answer
stringlengths
17
10.2M
package org.sipfoundry.sipxbridge; import gov.nist.javax.sip.DialogExt; import gov.nist.javax.sip.header.HeaderFactoryExt; import gov.nist.javax.sip.header.extensions.MinSE; import gov.nist.javax.sip.header.extensions.SessionExpiresHeader; import gov.nist.javax.sip.header.ims.PAssertedIdentityHeader; import gov.nist.javax.sip.message.SIPResponse; import java.text.ParseException; import java.util.ListIterator; import java.util.TimerTask; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javax.sdp.SessionDescription; import javax.sip.ClientTransaction; import javax.sip.Dialog; import javax.sip.DialogState; import javax.sip.InvalidArgumentException; import javax.sip.ObjectInUseException; import javax.sip.ServerTransaction; import javax.sip.SipException; import javax.sip.SipProvider; import javax.sip.Transaction; import javax.sip.TransactionDoesNotExistException; import javax.sip.address.Address; import javax.sip.header.AcceptHeader; import javax.sip.header.AllowHeader; import javax.sip.header.CSeqHeader; import javax.sip.header.CallIdHeader; import javax.sip.header.ContactHeader; import javax.sip.header.FromHeader; import javax.sip.header.Header; import javax.sip.header.ProxyAuthorizationHeader; import javax.sip.header.ReasonHeader; import javax.sip.header.RouteHeader; import javax.sip.header.SubjectHeader; import javax.sip.header.SupportedHeader; import javax.sip.header.ViaHeader; import javax.sip.message.Request; import javax.sip.message.Response; import org.apache.log4j.Logger; /** * Store information that is specific to a Dialog. This is a temporary holding place for dialog * specific data that is specific to the lifetime of a SIP Dialog. There is one of these * structures per dialog. * * @author M. Ranganathan * */ class DialogContext { private static Logger logger = Logger.getLogger(DialogContext.class); /* * Drives what to do for this dialog when a response is seen for an in-dialog response. */ private PendingDialogAction pendingAction = PendingDialogAction.NONE; /* * Dialog associated with this application data. */ private Dialog dialog; /* * The Peer Dialog of this Dialog. */ private Dialog peerDialog; /* * The request that originated the Dialog */ private Request request; /* * The transaction that created this DialogApplicationData */ Transaction dialogCreatingTransaction; /* * The last ACK. */ Request lastAck; /* * The last response seen by the dialog. */ private Response lastResponse; /* * The B2BUA associated with the dialog. The BackToBackUserAgent structure tracks call state. */ private BackToBackUserAgent backToBackUserAgent; /* * Account information for the associated dialog. There can be several ITSPs involved in a * single call ( each call leg can have its own ITSP). */ private ItspAccountInfo itspInfo; boolean isOriginatedBySipxbridge; /* * Stack trace to keep track of where this was created. */ private String creationPointStackTrace; /* * Stack trace where this was stored in the dialog table. */ private String insertionPointStackTrace; // Auxilliary data structures associated with dialog state machine. /* * Rtp session associated with this call leg. */ RtpSession rtpSession; /* * Session timer associated with this call leg. */ private SessionTimerTask sessionTimer; // The following are state variables associated with the Dialog State // machine. /* * Used by the session timer - to compute whether or not to send a session timer re-INVITE. */ long timeLastAckSent; /* * Session timer interval ( seconds ). */ int sessionExpires = Gateway.DEFAULT_SESSION_TIMER_INTERVAL; /* * Records whether or not an ACCEPTED has been sent for the REFER. This dictates what we need * to do when we see a BYE for this dialog. */ private boolean forwardByeToPeer = true; /* * The generated REFER request. */ private Request referRequest; /* * If this flag is set to true then the call dialog is torn down immediately after it is * CONFIRMed. */ private boolean terminateOnConfirm; private ProxyAuthorizationHeader proxyAuthorizationHeader; // Inner classes. /** * The session timer task -- sends Re-INVITE to the associated dialog at specific intervals. */ class SessionTimerTask extends TimerTask { String method; public SessionTimerTask(String method) { this.method = method; } @Override public void run() { if (dialog.getState() == DialogState.TERMINATED) { logger.debug("Dialog is terminated -- not firing the session timer"); this.cancel(); return; } try { Request request; logger.debug("Firing Session timer " ); logger.debug("DialogState = " + dialog.getState()); logger.debug("peerDialog " + DialogContext.this.getPeerDialog()); if (dialog.getState() == DialogState.CONFIRMED && DialogContext.get(dialog).getPeerDialog() != null) { if (method.equalsIgnoreCase(Request.INVITE)) { SipProvider provider = ((DialogExt) dialog).getSipProvider(); RtpSession rtpSession = getRtpSession(); if (rtpSession == null || rtpSession.getReceiver() == null) { return; } SessionDescription sd = rtpSession.getReceiver().getSessionDescription(); request = dialog.createRequest(Request.INVITE); if ( proxyAuthorizationHeader != null ) { request.setHeader(proxyAuthorizationHeader); } request.removeHeader(AllowHeader.NAME); SipUtilities.addWanAllowHeaders(request); AcceptHeader accept = ProtocolObjects.headerFactory.createAcceptHeader( "application", "sdp"); request.setHeader(accept); request.removeHeader(SupportedHeader.NAME); request.setContent(sd.toString(), ProtocolObjects.headerFactory .createContentTypeHeader("application", "sdp")); ContactHeader cth = SipUtilities.createContactHeader(provider, getItspInfo()); request.setHeader(cth); SessionExpiresHeader sexp = SipUtilities.createSessionExpires(DialogContext.this.sessionExpires); request.setHeader(sexp); MinSE minSe = new MinSE(); minSe.setExpires(Gateway.MIN_EXPIRES); request.setHeader(minSe); if (getItspInfo() != null && !getItspInfo().stripPrivateHeaders()) { SubjectHeader sh = ProtocolObjects.headerFactory .createSubjectHeader("SipxBridge Session Timer"); request.setHeader(sh); } else { SipUtilities.stripPrivateHeaders(request); } if (getItspInfo() == null || getItspInfo().isGlobalAddressingUsed()) { SipUtilities.setGlobalAddresses(request); } } else { /* * This is never used but keep it here for now. */ request = dialog.createRequest(Request.OPTIONS); } DialogExt dialogExt = (DialogExt) dialog; ClientTransaction ctx = dialogExt.getSipProvider().getNewClientTransaction( request); TransactionContext.attach(ctx, Operation.SESSION_TIMER); DialogContext.this.sendReInvite(ctx); } } catch (Exception ex) { logger.error("Unexpected exception sending Session Timer INVITE", ex); this.cancel(); } } public void terminate() { logger.debug("Terminating session Timer Task for " + dialog); this.cancel(); } } /** * Delays sending the INVITE to the park server. If a RE-INVITE is sent to the ITSP in that * interval, the INVITE to the park server is not sent. Instead, we ACK the incoming INVITE so * that the INVITE waiting for the ACK can proceed. * */ class MohTimer extends TimerTask { private ClientTransaction mohCtx; public MohTimer(ClientTransaction mohCtx) { this.mohCtx = mohCtx; } public void run() { try { if (!DialogContext.get(mohCtx.getDialog()).terminateOnConfirm) { logger.debug("Bridge sending INVITE to MOH server"); TransactionContext.get(mohCtx).setDialogPendingSdpAnswer(dialog); DialogContext mohDialogContext = DialogContext.get(mohCtx.getDialog()); mohDialogContext.setPendingAction( PendingDialogAction.PENDING_SDP_ANSWER_IN_ACK); mohDialogContext.setPeerDialog(dialog); mohDialogContext.setRtpSession(getPeerRtpSession(dialog)); mohCtx.sendRequest(); } else { logger.debug("Phone already sent INVITE - canceling MOH transaction"); mohCtx.terminate(); } } catch (Exception ex) { logger.error("Error sending moh request", ex); } finally { mohCtx = null; } } } public String getCallLegId() { return SipUtilities.getCallLegId(this.getRequest()); } public void startSessionTimer() { logger.debug("startSessionTimer() for " + this.dialog); this.startSessionTimer(this.sessionExpires); } public void startSessionTimer( int sessionTimeout ) { logger.debug(String.format("startSessionTimer(%d)",sessionTimeout) + " dialog " + dialog); this.sessionTimer = new SessionTimerTask(Gateway.getSessionTimerMethod()); this.sessionExpires = sessionTimeout; int time = (this.sessionExpires - Gateway.TIMER_ADVANCE) * 1000; Gateway.getTimer().schedule(this.sessionTimer,time,time); } public boolean isSessionTimerStarted() { return this.sessionTimer != null; } /* * Constructor. */ private DialogContext(Dialog dialog) { this.sessionExpires = Gateway.DEFAULT_SESSION_TIMER_INTERVAL; this.dialog = dialog; this.creationPointStackTrace = SipUtilities.getStackTrace(); } /** * Create a dialog to dialog association. * * @param dialog1 - first dialog. * @param dialog2 - second dialog. * */ static void pairDialogs(Dialog dialog1, Dialog dialog2) { logger.debug("pairDialogs dialogs = " + dialog1 + " " + dialog2); DialogContext dad1 = DialogContext.get(dialog1); DialogContext dad2 = DialogContext.get(dialog2); dad1.setPeerDialog(dialog2); dad2.setPeerDialog(dialog1); } static BackToBackUserAgent getBackToBackUserAgent(Dialog dialog) { if (dialog == null) { logger.debug("null dialog -- returning null "); return null; } else if (dialog.getApplicationData() == null) { logger.debug("null dialog application data -- returning null"); return null; } else { return ((DialogContext) dialog.getApplicationData()).getBackToBackUserAgent(); } } /** * Conveniance methods */ static Dialog getPeerDialog(Dialog dialog) { return ((DialogContext) dialog.getApplicationData()).peerDialog; } static RtpSession getPeerRtpSession(Dialog dialog) { return get(getPeerDialog(dialog)).rtpSession; } static RtpSession getRtpSession(Dialog dialog) { logger.debug("DialogApplicationData.getRtpSession " + dialog); return ((DialogContext) dialog.getApplicationData()).rtpSession; } static DialogContext attach(BackToBackUserAgent backToBackUserAgent, Dialog dialog, Transaction transaction, Request request) { if (backToBackUserAgent == null) throw new NullPointerException("Null back2back ua"); if (dialog.getApplicationData() != null) { logger.debug("DialogContext: Context Already set!!"); return (DialogContext) dialog.getApplicationData(); } DialogContext dialogContext = new DialogContext(dialog); dialogContext.dialogCreatingTransaction = transaction; dialogContext.request = request; dialogContext.setBackToBackUserAgent(backToBackUserAgent); dialog.setApplicationData(dialogContext); return dialogContext; } static DialogContext get(Dialog dialog) { return (DialogContext) dialog.getApplicationData(); } /** * Get the RTP session of my peer Dialog. * * @param dialog * @return */ static RtpSession getPeerTransmitter(Dialog dialog) { return DialogContext.get(DialogContext.getPeerDialog(dialog)).rtpSession; } /** * Convenience method to get the pending action for a dialog. * */ static PendingDialogAction getPendingAction(Dialog dialog) { return DialogContext.get(dialog).pendingAction; } /** * Convenience method to get the peer dialog context. */ static DialogContext getPeerDialogContext(Dialog dialog) { return DialogContext.get(DialogContext.getPeerDialog(dialog)); } /** * Get the transaction that created this dialog. */ Transaction getDialogCreatingTransaction() { return dialogCreatingTransaction; } /** * @param rtpSession the rtpSession to set */ void setRtpSession(RtpSession rtpSession) { if (rtpSession == null && this.rtpSession != null ) { logger.warn("Setting a Null RTP session!"); } this.rtpSession = rtpSession; } /** * @return the rtpSession */ RtpSession getRtpSession() { return rtpSession; } /** * Record the time when ACK was last sent ( for the session timer ). */ void recordLastAckTime() { this.timeLastAckSent = System.currentTimeMillis(); } /** * @param backToBackUserAgent the backToBackUserAgent to set */ void setBackToBackUserAgent(BackToBackUserAgent backToBackUserAgent) { this.backToBackUserAgent = backToBackUserAgent; } /** * @return the backToBackUserAgent */ BackToBackUserAgent getBackToBackUserAgent() { return backToBackUserAgent; } /** * @param itspInfo the itspInfo to set */ void setItspInfo(ItspAccountInfo itspInfo) { if (itspInfo == null ) { logger.warn("Setting ITSP info to null!!"); } else if ( this.itspInfo != null && this.itspInfo != itspInfo ) { logger.warn("Overriding ITSP info " + itspInfo + " This is probably a bug"); } this.itspInfo = itspInfo; if ( itspInfo != null ) { this.sessionExpires = itspInfo.getSessionTimerInterval(); } } /** * @return the itspInfo */ ItspAccountInfo getItspInfo() { return itspInfo; } /** * @return the provider */ SipProvider getSipProvider() { return ((DialogExt) dialog).getSipProvider(); } /** * Cancel the session timer. */ void cancelSessionTimer() { logger.debug("cancelSessionTimer " + this.dialog); if (this.sessionTimer != null) { this.sessionTimer.terminate(); this.sessionTimer = null; } } /** * Set the Expires time for session timer. * * @param expires */ void setSetExpires(int expires) { if ( expires != this.sessionExpires) { if ( this.sessionTimer != null ) { this.sessionTimer.terminate(); } this.startSessionTimer(expires); } } /** * Send ACK to the encapsulated dialog. * * @throws Exception */ void sendAck(SessionDescription sessionDescription) throws Exception { if (this.getLastResponse() == null) { Gateway.logInternalError("Method was called with lastResponse null"); throw new SipXbridgeException("sendAck : null last response"); } if ( this.lastResponse.getStatusCode() != 200 || !SipUtilities.getCSeqMethod(this.lastResponse).equals(Request.INVITE)) { Gateway.logInternalError("Method was called with lastResponse null"); throw new SipXbridgeException("sendAck : last response is not valid " + this.lastResponse); } if ( this.lastResponse.getHeader(ContactHeader.NAME) == null ) { logger.warn("ITSP sent a 200 OK WITHOUT Contact header - silently dropping 200 OK and sending BYE"); this.sendBye(true,"200 OK without Contact header sent. Dropping call leg."); return; } Request ackRequest = dialog.createAck(SipUtilities.getSeqNumber(this.getLastResponse())); if ( this.proxyAuthorizationHeader != null ) { ackRequest.setHeader(proxyAuthorizationHeader); } this.setLastResponse(null); this.recordLastAckTime(); SipUtilities.setSessionDescription(ackRequest, sessionDescription); /* * Compensate for the quirks of some ITSPs which will play MOH. */ SipUtilities.setDuplexity(sessionDescription, "sendrecv"); this.sendAck(ackRequest); setPendingAction(PendingDialogAction.NONE); } /** * Check to see if the ITSP allows a REFER request. * * @return true if REFER is allowed. */ @SuppressWarnings("unchecked") boolean isReferAllowed() { if (this.dialogCreatingTransaction instanceof ServerTransaction) { if (this.getRequest() == null) { return false; } ListIterator li = getRequest().getHeaders(AllowHeader.NAME); while (li != null && li.hasNext()) { AllowHeader ah = (AllowHeader) li.next(); if (ah.getMethod().equals(Request.REFER)) { return true; } } return false; } else { if (this.getLastResponse() == null) { return false; } ListIterator li = getLastResponse().getHeaders(AllowHeader.NAME); while (li != null && li.hasNext()) { AllowHeader ah = (AllowHeader) li.next(); if (ah.getMethod().equals(Request.REFER)) { return true; } } return false; } } /** * Send an INVITE with no SDP to the peer dialog. This solicits an SDP offer from the peer of * the given dialog. * * @param requestEvent -- the request event for which we have to solicit the offer. * @param continuationData -- context information so we can process the continuation. * * @return true if the offer is sent successfully. false if there is already an offer in * progress and hence we should not send an offer. */ boolean solicitSdpOfferFromPeerDialog(ContinuationData continuationData) throws Exception { try { Dialog peerDialog = DialogContext.getPeerDialog(dialog); /* * There is already a re-negotiation in progress so return silently */ if (peerDialog != null && peerDialog.getState() != DialogState.TERMINATED) { logger.debug("queryDialogFromPeer -- sending query to " + peerDialog + " continuationOperation = " + (continuationData != null ? continuationData.getOperation() : null)); Request reInvite = peerDialog.createRequest(Request.INVITE); DialogContext peerDialogContext = DialogContext.get(peerDialog); if ( peerDialogContext.proxyAuthorizationHeader != null ) { reInvite.setHeader(peerDialogContext.proxyAuthorizationHeader); } reInvite.removeHeader(SupportedHeader.NAME); reInvite.removeHeader("remote-party-Id"); if ( this.itspInfo != null ) { Address address = this.itspInfo.getCallerAlias(); PAssertedIdentityHeader passertedIdentityHeader = null; if (address != null) { passertedIdentityHeader = ((HeaderFactoryExt) ProtocolObjects.headerFactory) .createPAssertedIdentityHeader(address); reInvite.setHeader(passertedIdentityHeader); } } else { logger.warn("Could not find ITSP Information. Sending re-INVITE anyway."); } SipUtilities.addWanAllowHeaders(reInvite); SipProvider provider = ((DialogExt) peerDialog).getSipProvider(); ItspAccountInfo peerAccountInfo = DialogContext.getPeerDialogContext(dialog) .getItspInfo(); ViaHeader viaHeader = SipUtilities.createViaHeader(provider, peerAccountInfo); reInvite.setHeader(viaHeader); ContactHeader contactHeader = SipUtilities.createContactHeader(provider, peerAccountInfo); reInvite.setHeader(contactHeader); AcceptHeader acceptHeader = ProtocolObjects.headerFactory.createAcceptHeader( "application", "sdp"); reInvite.setHeader(acceptHeader); ClientTransaction ctx = provider.getNewClientTransaction(reInvite); TransactionContext tad = TransactionContext.attach(ctx, Operation.SOLICIT_SDP_OFFER_FROM_PEER_DIALOG); /* * Mark what we should do when we see the 200 OK response. This is what this * dialog expects to see. Mark this as the pending operation for this dialog. */ DialogContext.get(peerDialog).setPendingAction(PendingDialogAction.PENDING_SDP_ANSWER_IN_ACK); /* * The information we need to continue the operation when the Response comes in. */ tad.setContinuationData(continuationData); /* * Send the Re-INVITE and try to avoid the Glare Race condition. */ DialogContext.get(peerDialog).sendReInvite(ctx); } return true; } catch (Exception ex) { logger.error("Exception occured. tearing down call! ", ex); this.backToBackUserAgent.tearDown(); return true; } } /** * Sent the pending action ( to be performed when the next in-Dialog request or response * arrives ). * * @param pendingAction */ void setPendingAction(PendingDialogAction pendingAction) { logger.debug("setPendingAction " + this + " pendingAction = " + pendingAction); /* * A dialog can have only a single outstanding action. */ if (this.pendingAction != PendingDialogAction.NONE && pendingAction != PendingDialogAction.NONE && this.pendingAction != pendingAction) { logger.error("Replacing pending action " + this.pendingAction + " with " + pendingAction); throw new SipXbridgeException("Pending dialog action is " + this.pendingAction); } this.pendingAction = pendingAction; } /** * Get the pending action for this dialog. */ PendingDialogAction getPendingAction() { return pendingAction; } /** * Set the last seen response for this dialog. * * @param lastResponse */ void setLastResponse(Response lastResponse) { logger.debug("DialogContext.setLastResponse "); if (lastResponse == null) { logger.debug("lastResponse = " + null); } else { logger.debug("lastResponse = " + ((SIPResponse) lastResponse).getFirstLine()); } this.lastResponse = lastResponse; } /** * The last response that was seen for this dialog. * * @return */ Response getLastResponse() { return lastResponse; } /** * Send an SDP re-OFFER to the other side of the B2BUA. * * @param sdpOffer -- the sdp offer session description. * @throws Exception -- if could not send */ void sendSdpReOffer(SessionDescription sdpOffer) throws Exception { if (dialog.getState() == DialogState.TERMINATED) { logger.warn("Attempt to send SDP re-offer on a terminated dialog"); return; } Request sdpOfferInvite = dialog.createRequest(Request.INVITE); if ( proxyAuthorizationHeader != null ) { sdpOfferInvite.setHeader(proxyAuthorizationHeader); } /* * Set and fix up the sdp offer to send to the opposite side. */ this.getRtpSession().getReceiver().setSessionDescription(sdpOffer); SipUtilities.incrementSessionVersion(sdpOffer); SipUtilities.fixupOutboundRequest(dialog, sdpOfferInvite); sdpOfferInvite.setContent(sdpOffer.toString(), ProtocolObjects.headerFactory .createContentTypeHeader("application", "sdp")); ClientTransaction ctx = ((DialogExt) dialog).getSipProvider().getNewClientTransaction( sdpOfferInvite); TransactionContext.attach(ctx, Operation.SEND_SDP_RE_OFFER); this.sendReInvite(ctx); } /** * Send an ACK and record it. * * @param ack * @throws SipException */ void sendAck(Request ack) throws SipException { this.recordLastAckTime(); this.lastAck = ack; logger.debug("SendingAck ON " + dialog); if ( this.proxyAuthorizationHeader != null ) { ack.setHeader(proxyAuthorizationHeader); } dialog.sendAck(ack); if (terminateOnConfirm) { logger.debug("tearing down MOH dialog because of terminateOnConfirm."); Request byeRequest = dialog.createRequest(Request.BYE); ClientTransaction ctx = ((DialogExt) dialog).getSipProvider() .getNewClientTransaction(byeRequest); TransactionContext.attach(ctx, Operation.SEND_BYE_TO_MOH_SERVER); dialog.sendRequest(ctx); } } /** * Set the "terminate on confirm" flag which will send BYE to the dialog If the flag is set as * soon as the MOH server confirms the dialog, the flag is consulted and a BYE sent to the MOH * server. * */ void setTerminateOnConfirm() { this.terminateOnConfirm = true; logger.debug("setTerminateOnConfirm: " + this); /* * Fire off a timer to reap this guy if he does not die in 8 seconds. */ Gateway.getTimer().schedule(new TimerTask() { @Override public void run() { try { if (DialogContext.this.dialog.getState() != DialogState.TERMINATED) { logger.debug("terminating dialog " + dialog + " because no confirmation received and terminateOnConfirm is set"); DialogContext.this.dialog.delete(); } } catch (Exception ex) { logger.error("Terminate On Confirm processing", ex); } } }, 8000); } /** * return true if "terminate on confirm" flag is set. */ boolean isTerminateOnConfirm() { return this.terminateOnConfirm; } /** * Send a re-INVITE. The dialog layer will asynchronously send the re-INVITE */ void sendReInvite(ClientTransaction clientTransaction) { if ( this.proxyAuthorizationHeader != null ) { clientTransaction.getRequest().setHeader(this.proxyAuthorizationHeader); } if (dialog.getState() != DialogState.TERMINATED) { try { dialog.sendRequest(clientTransaction); } catch (SipException e) { logger.error("Exception sending re-INVITE",e); } } else { logger.warn("sendReInvite was called when the dialog is terminated - ignoring"); } } /** * Send INVITE to MOH server. */ void sendMohInvite(ClientTransaction mohClientTransaction) { Gateway.getTimer().schedule(new MohTimer(mohClientTransaction), Gateway.getMusicOnHoldDelayMiliseconds()); } /** * Set the peer dialog of this dialog. */ void setPeerDialog(Dialog peerDialog) { logger.debug("DialogContext.setPeerDialog: " + this.dialog + " peer = " + peerDialog); this.peerDialog = peerDialog; if (logger.isDebugEnabled() && peerDialog == null ) { SipUtilities.printStackTrace(); } } /** * Get the peer dialog of this dialog. */ Dialog getPeerDialog() { return peerDialog; } /** * Flag that controls whether or not BYE is forwarded to the peer dialog. */ void setForwardByeToPeer(boolean forwardByeToPeer) { logger.debug("setForwardByeToPeer " + forwardByeToPeer); this.forwardByeToPeer = forwardByeToPeer; } /** * Retuns true if we should forward the BYE for the peer. * * @return */ boolean isForwardByeToPeer() { return forwardByeToPeer; } /** * The pending REFER request that we are processing. * * @param referRequest */ void setReferRequest(Request referRequest) { this.referRequest = referRequest; } /** * The current REFER request being processed. * * @return */ Request getReferRequest() { return referRequest; } /** * Get the request that created the Dialog. * * @return the dialog creating request. */ Request getRequest() { return request; } /** * Send ACK for the dialog. * * @param response -- the 200 OK that we are ACKing. * * @throws Exception */ public void sendAck(Response response) throws Exception { this.lastResponse = response; if (this.getLastResponse() == null) { Gateway.logInternalError("Method was called with lastResponse null"); throw new SipXbridgeException("sendAck : null last response"); } if ( this.lastResponse.getStatusCode() != 200 || !SipUtilities.getCSeqMethod(this.lastResponse).equals(Request.INVITE)) { Gateway.logInternalError("Method was called with lastResponse null"); throw new SipXbridgeException("sendAck : last response is not valid " + this.lastResponse); } if ( this.lastResponse.getHeader(ContactHeader.NAME) == null ) { logger.warn("ITSP sent a 200 OK WITHOUT Contact header - silently dropping 200 OK and sending BYE"); this.sendBye(true,"200 OK without Contact header sent. Dropping call leg."); return; } Request ack = dialog.createAck(((CSeqHeader) response.getHeader(CSeqHeader.NAME)) .getSeqNumber()); if ( this.proxyAuthorizationHeader != null ) { ack.setHeader(proxyAuthorizationHeader); } this.sendAck(ack); } /** * Send bye for this dialog. * * @param forward - whether or not to forward this BYE to the other side of the B2BUA. * @param reason - text to place in the Reason header. * * @throws Exception */ void sendBye(boolean forward, String reason) throws SipException { try { Request bye = dialog.createRequest(Request.BYE); if ( getSipProvider() != Gateway.getLanProvider() ) { if ( itspInfo == null || itspInfo.isGlobalAddressingUsed()) { SipUtilities.setGlobalAddresses(bye); } } if ( this.proxyAuthorizationHeader != null ) { bye.setHeader(proxyAuthorizationHeader); } ViaHeader via = ((ViaHeader) bye.getHeader(ViaHeader.NAME)); if ( !forward ) via.setParameter("noforward", "true"); ClientTransaction clientTransaction = getSipProvider().getNewClientTransaction(bye); TransactionContext transactionContext = TransactionContext.attach( clientTransaction, Operation.PROCESS_BYE); transactionContext.setItspAccountInfo(this.itspInfo); dialog.sendRequest(clientTransaction); } catch (ParseException ex) { logger.error("Unexpected exception",ex); throw new SipXbridgeException("Unexpected exception",ex); } } /** * Send BYE for this dialog (no reason provided). * * @param forward -- whether or not to forward the BYE. */ void sendBye(boolean forward) throws SipException { sendBye(forward,null); } /** * Forward BYE. * * @throws SipException */ void forwardBye(ServerTransaction serverTransaction) throws SipException { Request bye = dialog.createRequest(Request.BYE); if ( this.proxyAuthorizationHeader != null ) { bye.setHeader(this.proxyAuthorizationHeader) ; } if ( getSipProvider() != Gateway.getLanProvider() ) { if ( itspInfo == null || itspInfo.isGlobalAddressingUsed()) { SipUtilities.setGlobalAddresses(bye); } } ClientTransaction clientTransaction = getSipProvider().getNewClientTransaction(bye); TransactionContext transactionContext = TransactionContext.attach( clientTransaction, Operation.PROCESS_BYE); transactionContext.setItspAccountInfo(this.itspInfo); TransactionContext.get(serverTransaction).setClientTransaction(clientTransaction); dialog.sendRequest(clientTransaction); } /** * Response sent to session timer so we can kill our own session timer. */ void setSessionTimerResponseSent() { if (this.sessionTimer != null) { logger.debug("setSessionTimerResponseSent()"); this.cancelSessionTimer(); this.startSessionTimer(); } } /** * Set the dialog pointer ( link this structure with a Dialog ). * * @param dialog */ public void setDialog(Dialog dialog) { this.dialog = dialog; dialog.setApplicationData(this); } /** * Set the dialog creating transaction. * * @param newTransaction */ public void setDialogCreatingTransaction(ClientTransaction dialogCreatingTransaction) { this.dialogCreatingTransaction = dialogCreatingTransaction; this.request = dialogCreatingTransaction.getRequest(); } /** * Detach this structure from the associated dialog. */ public void detach() { this.dialog.setApplicationData(null); this.dialog = null; this.pendingAction = PendingDialogAction.NONE; } /** * Debugging method that returns the stack trace corresponding to where the dialog was * created. * * @return */ public String getCreationPointStackTrace() { return this.creationPointStackTrace; } /** * Debugging method that returns where the structure was originally stored into the * dialog table. */ public String getInsertionPointStackTrace() { return this.insertionPointStackTrace; } /** * Debugging method that records when this is inserted into the dialog table. */ public void recordInsertionPoint() { this.insertionPointStackTrace = SipUtilities.getStackTrace(); } /** * Get the associated dialog. * * @return dialog associated with this dialog context. */ public Dialog getDialog() { return this.dialog; } public void setProxyAuthorizationHeader(ProxyAuthorizationHeader pah) { this.proxyAuthorizationHeader = pah; } }
package org.telegram.mtproto.secure; import org.telegram.mtproto.secure.aes.AESImplementation; import org.telegram.mtproto.secure.aes.DefaultAESImplementation; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.io.*; import java.math.BigInteger; import java.security.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.RSAPublicKeySpec; public class CryptoUtils { private static final ThreadLocal<MessageDigest> md5 = new ThreadLocal<MessageDigest>() { @Override protected MessageDigest initialValue() { MessageDigest crypt = null; try { crypt = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return crypt; } }; private static final ThreadLocal<MessageDigest> sha1 = new ThreadLocal<MessageDigest>() { @Override protected MessageDigest initialValue() { MessageDigest crypt = null; try { crypt = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return crypt; } }; private static AESImplementation currentImplementation = new DefaultAESImplementation(); public static void setAESImplementation(AESImplementation implementation) { currentImplementation = implementation; } public static byte[] RSA(byte[] src, BigInteger key, BigInteger exponent) { try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(new RSAPublicKeySpec(key, exponent)); Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(src); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } return null; } public static void AES256IGEDecryptBig(byte[] src, byte[] dest, int len, byte[] iv, byte[] key) { currentImplementation.AES256IGEDecrypt(src, dest, len, iv, key); } public static byte[] AES256IGEDecrypt(byte[] src, byte[] iv, byte[] key) { byte[] res = new byte[src.length]; currentImplementation.AES256IGEDecrypt(src, res, src.length, iv, key); return res; } public static void AES256IGEDecrypt(File src, File dest, byte[] iv, byte[] key) throws IOException { currentImplementation.AES256IGEDecrypt(src.getAbsolutePath(), dest.getAbsolutePath(), iv, key); } public static void AES256IGEEncrypt(File src, File dest, byte[] iv, byte[] key) throws IOException { currentImplementation.AES256IGEEncrypt(src.getAbsolutePath(), dest.getAbsolutePath(), iv, key); } public static byte[] AES256IGEEncrypt(byte[] src, byte[] iv, byte[] key) { byte[] res = new byte[src.length]; currentImplementation.AES256IGEEncrypt(src, res, src.length, iv, key); return res; } public static String MD5(byte[] src) { try { MessageDigest crypt = MessageDigest.getInstance("MD5"); crypt.reset(); crypt.update(src); return ToHex(crypt.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } public static String MD5(RandomAccessFile randomAccessFile) { try { MessageDigest crypt = md5.get(); crypt.reset(); byte[] block = new byte[8 * 1024]; for (int i = 0; i < randomAccessFile.length(); i += 8 * 1024) { int len = (int) Math.min(block.length, randomAccessFile.length() - i); randomAccessFile.readFully(block, 0, len); crypt.update(block, 0, len); } return ToHex(crypt.digest()); } catch (IOException e) { e.printStackTrace(); } return null; } public static byte[] MD5Raw(byte[] src) { MessageDigest crypt = md5.get(); crypt.reset(); crypt.update(src); return crypt.digest(); } public static String ToHex(byte[] src) { String res = ""; for (int i = 0; i < src.length; i++) { res += String.format("%02X", src[i] & 0xFF); } return res.toLowerCase(); } public static byte[] SHA1(InputStream in) throws IOException { MessageDigest crypt = sha1.get(); crypt.reset(); // Transfer bytes from in to out byte[] buf = new byte[4 * 1024]; int len; while ((len = in.read(buf)) > 0) { Thread.yield(); // out.write(buf, 0, len); crypt.update(buf, 0, len); } in.close(); return crypt.digest(); } public static byte[] SHA1(String fileName) throws IOException { MessageDigest crypt = sha1.get(); crypt.reset(); FileInputStream in = new FileInputStream(fileName); // Transfer bytes from in to out byte[] buf = new byte[4 * 1024]; int len; while ((len = in.read(buf)) > 0) { Thread.yield(); // out.write(buf, 0, len); crypt.update(buf, 0, len); } in.close(); return crypt.digest(); } public static byte[] SHA1(byte[] src) { MessageDigest crypt = sha1.get(); crypt.reset(); crypt.update(src); return crypt.digest(); } public static byte[] SHA1(byte[]... src1) { MessageDigest crypt = sha1.get(); crypt.reset(); for (int i = 0; i < src1.length; i++) { crypt.update(src1[i]); } return crypt.digest(); } public static boolean arrayEq(byte[] a, byte[] b) { if (a.length != b.length) { return false; } for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) return false; } return true; } public static byte[] concat(byte[]... v) { int len = 0; for (int i = 0; i < v.length; i++) { len += v[i].length; } byte[] res = new byte[len]; int offset = 0; for (int i = 0; i < v.length; i++) { System.arraycopy(v[i], 0, res, offset, v[i].length); offset += v[i].length; } return res; } public static byte[] substring(byte[] src, int start, int len) { byte[] res = new byte[len]; System.arraycopy(src, start, res, 0, len); return res; } public static byte[] align(byte[] src, int factor) { if (src.length % factor == 0) { return src; } int padding = factor - src.length % factor; return concat(src, Entropy.generateSeed(padding)); } public static byte[] alignKeyZero(byte[] src, int size) { if (src.length == size) { return src; } if (src.length > size) { return substring(src, src.length - size, size); } else { return concat(new byte[size - src.length], src); } } public static byte[] xor(byte[] a, byte[] b) { byte[] res = new byte[a.length]; for (int i = 0; i < a.length; i++) { res[i] = (byte) (a[i] ^ b[i]); } return res; } public static BigInteger loadBigInt(byte[] data) { return new BigInteger(1, data); } public static byte[] fromBigInt(BigInteger val) { byte[] res = val.toByteArray(); if (res[0] == 0) { byte[] res2 = new byte[res.length - 1]; System.arraycopy(res, 1, res2, 0, res2.length); return res2; } else { return res; } } public static boolean isZero(byte[] src) { for (int i = 0; i < src.length; i++) { if (src[i] != 0) { return false; } } return true; } }
package org.twuni.money.common; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class SimpleRepository<V> implements Repository<String, V> { protected final Map<Integer, V> map = new HashMap<Integer, V>(); @Override public V findById( String key ) { return map.get( Integer.valueOf( key.hashCode() ) ); } @Override public void save( V value ) { map.put( Integer.valueOf( value.hashCode() ), value ); } @Override public void delete( V value ) { map.put( Integer.valueOf( value.hashCode() ), null ); } @Override public List<V> list( int limit ) { ArrayList<V> list = new ArrayList<V>( map.values() ); return limit > list.size() ? list : list.subList( 0, limit ); } @Override public List<V> list() { return list( Integer.MAX_VALUE ); } }
package pl.asie.charset.wires; import net.minecraft.block.Block; import net.minecraft.block.BlockRedstoneDiode; import net.minecraft.block.BlockRedstoneWire; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.Packet; import net.minecraft.network.play.server.S35PacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.ITickable; import net.minecraftforge.common.property.IUnlistedProperty; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import pl.asie.charset.api.wires.IBundledEmitter; import pl.asie.charset.api.wires.IBundledUpdatable; import pl.asie.charset.api.wires.IConnectable; import pl.asie.charset.api.wires.IRedstoneEmitter; import pl.asie.charset.api.wires.IRedstoneUpdatable; import pl.asie.charset.api.wires.IWire; import pl.asie.charset.api.wires.WireFace; import pl.asie.charset.api.wires.WireType; import pl.asie.charset.wires.logic.Wire; import pl.asie.charset.wires.logic.WireBundled; import pl.asie.charset.wires.logic.WireInsulated; import pl.asie.charset.wires.logic.WireNormal; public class TileWireContainer extends TileEntity implements ITickable, IWire, IBundledEmitter, IBundledUpdatable, IRedstoneEmitter, IRedstoneUpdatable { public static final Property PROPERTY = new Property(); private static class Property implements IUnlistedProperty<TileWireContainer> { private Property() { } @Override public String getName() { return "wireTile"; } @Override public boolean isValid(TileWireContainer value) { return true; } @Override public Class<TileWireContainer> getType() { return TileWireContainer.class; } @Override public String valueToString(TileWireContainer value) { return "!?"; } } public WireKind getWireKind(WireFace side) { return wires[side.ordinal()] != null ? wires[side.ordinal()].type : WireKind.NORMAL; } public TileEntity getNeighbourTile(EnumFacing side) { return side != null ? worldObj.getTileEntity(pos.offset(side)) : null; } private final Wire[] wires = new Wire[7]; private boolean scheduledRenderUpdate, scheduledConnectionUpdate, scheduledNeighborUpdate, scheduledPropagationUpdate; @SideOnly(Side.CLIENT) public int getRenderColor(WireFace loc) { return wires[loc.ordinal()].getRenderColor(); } @Override public void validate() { super.validate(); scheduleConnectionUpdate(); schedulePropagationUpdate(); } @Override public void update() { if (scheduledConnectionUpdate) { scheduledConnectionUpdate = false; updateConnections(); } if (scheduledNeighborUpdate) { scheduledNeighborUpdate = false; worldObj.notifyNeighborsRespectDebug(pos, getBlockType()); for (EnumFacing facing : EnumFacing.VALUES) { worldObj.notifyNeighborsOfStateExcept(pos.offset(facing), getBlockType(), facing.getOpposite()); } } if (scheduledPropagationUpdate) { scheduledPropagationUpdate = false; onWireUpdate(null); } if (scheduledRenderUpdate) { scheduledRenderUpdate = false; if (!worldObj.isRemote) { getWorld().markBlockForUpdate(pos); } else { getWorld().markBlockRangeForRenderUpdate(pos, pos); } } } public boolean canProvideStrongPower(EnumFacing direction) { return hasWire(WireFace.get(direction), WireKind.NORMAL); } public boolean canProvideWeakPower(EnumFacing direction) { WireType onFaceType = getWireType(WireFace.get(direction)); if (onFaceType != null && onFaceType != WireType.NORMAL) { return false; } for (WireFace face : WireFace.VALUES) { if (face.facing() == direction.getOpposite()) { continue; } if (hasWire(face)) { if (getWireType(face) == WireType.NORMAL) { return true; } if (connects(face, direction)) { return true; } } } return false; } public int getItemMetadata(WireFace loc) { return ((wires[loc.ordinal()] != null ? wires[loc.ordinal()].type.ordinal() : 0) << 1) | (loc == WireFace.CENTER ? 1 : 0); } public boolean canConnectInternal(WireFace from, WireFace to) { return wires[to.ordinal()] != null && wires[to.ordinal()].type.connects(wires[from.ordinal()].type); } public boolean canConnectExternal(WireFace from, WireFace to) { EnumFacing direction = to.facing(); BlockPos connectingPos = pos.offset(direction); IBlockState connectingState = worldObj.getBlockState(connectingPos); Block connectingBlock = connectingState.getBlock(); TileEntity connectingTile = getNeighbourTile(direction); if (connectingTile instanceof TileWireContainer) { TileWireContainer wc = (TileWireContainer) connectingTile; if (wc.wires[from.ordinal()] != null && wc.wires[from.ordinal()].type.connects(wires[from.ordinal()].type)) { return true; } } else if (connectingTile instanceof IConnectable) { IConnectable tc = (IConnectable) connectingTile; if (tc.canConnect(getWireType(from), from, direction.getOpposite())) { return true; } } else if (getWireType(from) != WireType.BUNDLED) { if ((connectingBlock instanceof BlockRedstoneDiode || connectingBlock instanceof BlockRedstoneWire) && from != WireFace.DOWN) { return false; } if (from == WireFace.CENTER && !connectingBlock.isSideSolid(worldObj, connectingPos, direction.getOpposite())) { return false; } if (connectingBlock.canProvidePower() && connectingBlock.canConnectRedstone(worldObj, connectingPos, direction.getOpposite())) { return true; } } return false; } public int getInsulatedSignalLevel(WireFace side, int i) { if (wires[side.ordinal()] != null) { switch (wires[side.ordinal()].type.type()) { case BUNDLED: return wires[side.ordinal()].getBundledSignalLevel(i); default: return wires[side.ordinal()].getSignalLevel(); } } return 0; } public byte getInsulatedRedstoneLevel(WireFace side, int i) { if (wires[side.ordinal()] != null) { switch (wires[side.ordinal()].type.type()) { case BUNDLED: return wires[side.ordinal()].getBundledRedstoneLevel(i); default: return (byte) wires[side.ordinal()].getRedstoneLevel(); } } return 0; } public int getBundledSignalLevel(WireFace side, int i) { if (wires[side.ordinal()] != null) { if (wires[side.ordinal()].type.type() == WireType.INSULATED) { return wires[side.ordinal()].type.color() == i ? wires[side.ordinal()].getSignalLevel() : 0; } else { return wires[side.ordinal()].getBundledSignalLevel(i); } } return 0; } public byte getBundledRedstoneLevel(WireFace side, int i) { if (wires[side.ordinal()] != null) { if (wires[side.ordinal()].type.type() == WireType.INSULATED) { return wires[side.ordinal()].type.color() == i ? (byte) wires[side.ordinal()].getRedstoneLevel() : 0; } else { return wires[side.ordinal()].getBundledRedstoneLevel(i); } } return 0; } public int getSignalLevel(WireFace side) { return wires[side.ordinal()] != null ? wires[side.ordinal()].getSignalLevel() : 0; } public int getRedstoneLevel(WireFace side) { return wires[side.ordinal()] != null ? wires[side.ordinal()].getRedstoneLevel() : 0; } public int getStrongRedstoneLevel(EnumFacing direction) { return getRedstoneLevel(WireFace.get(direction)); } public int getWeakRedstoneLevel(EnumFacing direction) { int signal = getRedstoneLevel(WireFace.get(direction)); for (Wire w : wires) { if (w != null && (w.connects(direction) || (w.type == WireKind.NORMAL && w.location.facing() != direction.getOpposite()))) { signal = Math.max(signal, w.getRedstoneLevel()); } } return signal; } public boolean canConnectCorner(WireFace from, WireFace to) { EnumFacing side = from.facing(); EnumFacing direction = to.facing(); BlockPos middlePos = pos.offset(direction); if (worldObj.isSideSolid(middlePos, direction.getOpposite()) || worldObj.isSideSolid(middlePos, side.getOpposite())) { return false; } BlockPos cornerPos = middlePos.offset(side); TileEntity cornerTile = worldObj.getTileEntity(cornerPos); if (cornerTile instanceof TileWireContainer) { TileWireContainer wc = (TileWireContainer) cornerTile; EnumFacing wireSide = direction.getOpposite(); if (wc.wires[wireSide.ordinal()] != null && wc.wires[wireSide.ordinal()].type.connects(wires[from.ordinal()].type)) { return true; } } return false; } protected boolean dropWire(WireFace side, EntityPlayer player) { int wireMeta = getItemMetadata(side); if (removeWire(side)) { if (player == null || !player.capabilities.isCreativeMode) { Block.spawnAsEntity(worldObj, pos, new ItemStack(Item.getItemFromBlock(getBlockType()), 1, wireMeta)); } scheduleConnectionUpdate(); scheduleRenderUpdate(); return true; } else { return false; } } protected boolean hasWires() { for (int i = 0; i < wires.length; i++) { if (wires[i] != null) { return true; } } return false; } public void updateWireLocation(WireFace loc) { if (wires[loc.ordinal()] != null) { wires[loc.ordinal()].propagate(); } } public void onWireUpdate(EnumFacing side) { for (Wire w : wires) { if (w != null && (side == null || w.connects(side))) { w.propagate(); } } } private void updateConnections() { for (WireFace side : WireFace.VALUES) { if (wires[side.ordinal()] != null) { if (side != WireFace.CENTER && !WireUtils.canPlaceWire(worldObj, pos.offset(side.facing()), side.facing().getOpposite())) { dropWire(side, null); scheduleNeighborUpdate(); continue; } wires[side.ordinal()].updateConnections(); } } if (!hasWires()) { invalidate(); getBlockType().breakBlock(worldObj, pos, worldObj.getBlockState(pos)); worldObj.setBlockToAir(pos); return; } } public boolean providesSignal(EnumFacing direction) { for (Wire w : wires) { if (w != null && w.connects(direction)) { return true; } } return false; } public boolean hasWire(WireFace side, WireKind type) { return wires[side.ordinal()] != null && wires[side.ordinal()].type == type; } public boolean hasWire(WireFace side) { return wires[side.ordinal()] != null; } @Override public void readFromNBT(NBTTagCompound tag) { super.readFromNBT(tag); for (int i = 0; i < 7; i++) { wires[i] = null; if (tag.hasKey("wire" + i)) { NBTTagCompound cpd = tag.getCompoundTag("wire" + i); wires[i] = createWire(WireFace.VALUES[i], cpd.getByte("id")); wires[i].readFromNBT(cpd); } } } @Override public void writeToNBT(NBTTagCompound tag) { super.writeToNBT(tag); writeToNBT(tag, false); } private void writeToNBT(NBTTagCompound tag, boolean isPacket) { super.writeToNBT(tag); for (int i = 0; i < 7; i++) { if (wires[i] != null) { NBTTagCompound cpd = new NBTTagCompound(); cpd.setByte("id", (byte) wires[i].type.ordinal()); wires[i].writeToNBT(cpd, isPacket); tag.setTag("wire" + i, cpd); } } } @Override public Packet getDescriptionPacket() { NBTTagCompound tag = new NBTTagCompound(); writeToNBT(tag, true); return new S35PacketUpdateTileEntity(getPos(), getBlockMetadata(), tag); } @Override public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) { readFromNBT(pkt.getNbtCompound()); scheduleRenderUpdate(); } public boolean removeWire(WireFace side) { if (!hasWire(side)) { return false; } this.wires[side.ordinal()] = null; scheduleConnectionUpdate(); scheduleRenderUpdate(); return true; } public boolean addWire(WireFace side, int meta) { if (hasWire(side)) { return false; } if (side != WireFace.CENTER && !WireUtils.canPlaceWire(worldObj, pos.offset(side.facing()), side.facing().getOpposite())) { return false; } this.wires[side.ordinal()] = createWire(side, meta >> 1); scheduleConnectionUpdate(); scheduleRenderUpdate(); return true; } private Wire createWire(WireFace side, int meta) { if (meta >= 1 && meta < 17) { return new WireInsulated(WireKind.insulated(meta - 1), side, this); } else if (meta == 17) { return new WireBundled(WireKind.BUNDLED, side, this); } else { return new WireNormal(WireKind.NORMAL, side, this); } } public void scheduleNeighborUpdate() { scheduledNeighborUpdate = true; } public void onNeighborBlockChange() { scheduleConnectionUpdate(); schedulePropagationUpdate(); } public void schedulePropagationUpdate() { scheduledPropagationUpdate = true; } public void scheduleRenderUpdate() { scheduledRenderUpdate = true; } public void scheduleConnectionUpdate() { if (getWorld() != null && !getWorld().isRemote) { scheduledConnectionUpdate = true; } } public boolean connects(WireFace side, EnumFacing direction) { return wires[side.ordinal()] != null ? wires[side.ordinal()].connects(direction) : null; } public boolean connectsAny(WireFace side, EnumFacing direction) { return wires[side.ordinal()] != null ? wires[side.ordinal()].connectsAny(direction) : null; } public boolean connectsCorner(WireFace side, EnumFacing direction) { return wires[side.ordinal()] != null ? wires[side.ordinal()].connectsCorner(direction) : null; } // API @Override public WireType getWireType(WireFace location) { return hasWire(location) ? wires[location.ordinal()].type.type() : null; } @Override public int getInsulatedColor(WireFace location) { return getWireType(location) == WireType.INSULATED ? wires[location.ordinal()].type.color() : -1; } @Override public byte[] getBundledSignal(WireFace face, EnumFacing toDirection) { Wire wire = wires[face.ordinal()]; return wire instanceof WireBundled ? ((WireBundled) wire).getBundledSignal() : null; } @Override public void onBundledInputChanged(EnumFacing face) { schedulePropagationUpdate(); } @Override public int getRedstoneSignal(WireFace face, EnumFacing toDirection) { return connects(face, toDirection) ? getRedstoneLevel(face) : 0; } @Override public void onRedstoneInputChanged(EnumFacing face) { schedulePropagationUpdate(); } }
package main.java.ru.parallel.octotron.exec; import java.io.File; import main.java.ru.parallel.octotron.core.GraphService; import main.java.ru.parallel.octotron.impl.PersistenStorage; import main.java.ru.parallel.octotron.logic.ExecutionControler; import main.java.ru.parallel.octotron.neo4j.impl.Neo4jGraph; import main.java.ru.parallel.octotron.primitive.exception.ExceptionSystemError; import main.java.ru.parallel.utils.FileUtils; import main.java.ru.parallel.utils.JavaUtils; /** * main executable function<br> * */ public class StartOctotron { static private final int EXIT_ERROR = 1; private static final int PROCESS_CHUNK = 1024; // seems ok /** * main executable function<br> * uses one input parameter from args - path to the configuration file<br> * see documentation for details about config file<br> * */ public static void main(String[] args) { String fname = null; // insert your config file path here - for debug purpose if(fname == null) { if(args.length != 1) { System.err.println("specify the config file"); System.exit(EXIT_ERROR); } fname = args[0]; } System.out.println("statring octotron using config file: " + fname); GlobalSettings settings = null; try { String json_config = FileUtils.FileToString(fname); settings = new GlobalSettings(json_config); CheckConfig(settings); } catch(ExceptionSystemError e) { System.err.println(e.getMessage()); System.exit(EXIT_ERROR); } Run(settings); } /** * compare hashes to check if the new config does not match the old one<br> * */ private static void CheckConfig(GlobalSettings settings) throws NumberFormatException, ExceptionSystemError { String path = settings.GetDbPath() + settings.GetDbName(); int old_hash = Integer.parseInt(FileUtils.FileToString(path + DBCreator.HASH_FILE)); if(settings.GetHash() != old_hash) { System.err.println("**********************************************************"); System.err.println("* WARNING *"); System.err.println("**********************************************************"); System.err.println(); System.err.println("config file has been changed since database creation"); System.err.println("consistency is not guaranteed"); System.err.println(); System.err.println("**********************************************************"); } } /** * created db, start main loop and shutdown, when finished<br> * all errors are printed and may be reported by special scripts<br> * */ private static void Run(GlobalSettings settings) { Neo4jGraph graph = null; ExecutionControler exec_control = null; String path = settings.GetDbPath() + settings.GetDbName(); try { graph = new Neo4jGraph(path + "_neo4j", Neo4jGraph.Op.LOAD); exec_control = new ExecutionControler(graph, new GraphService(graph), settings); PersistenStorage.INSTANCE.Load(path); ProcessStart(settings); } catch(Exception start_exception) { ProcessCrash(settings, start_exception, "start"); return; } Exception loop_exception = MainLoop(settings, exec_control); if(loop_exception != null) { ProcessCrash(settings, loop_exception, "mainloop"); } Exception shutdown_exception = Shutdown(settings, graph, exec_control); if(shutdown_exception != null) { ProcessCrash(settings, shutdown_exception, "shutdown"); } } /** * run the main program loop<br> * if it crashes - returns exception, otherwise returns nothing<br> * @param exec_control * */ private static Exception MainLoop(GlobalSettings settings, ExecutionControler exec_control) { System.out.println("main loop started"); try { while(!exec_control.ShouldExit()) { exec_control.Process(PROCESS_CHUNK); // it may sleep inside } ProcessFinish(settings); } catch(Exception e) { return e; } return null; } /** * shutdown the graph and all execution processes<br> * */ public static Exception Shutdown(GlobalSettings settings, Neo4jGraph graph, ExecutionControler exec_control) { String path = settings.GetDbPath() + settings.GetDbName(); try { PersistenStorage.INSTANCE.Save(path); if(exec_control != null) exec_control.Finish(); if(graph != null) graph.Shutdown(); } catch(Exception e) { return e; } return null; } /** * reaction to normal execution start<br> * */ private static void ProcessStart(GlobalSettings settings) throws ExceptionSystemError { String script = settings.GetScriptByKey("on_start"); if(script != null) FileUtils.ExecSilent(true, script); } /** * reaction to normal execution finish<br> * */ private static void ProcessFinish(GlobalSettings settings) throws ExceptionSystemError { String script = settings.GetScriptByKey("on_finish"); if(script != null) FileUtils.ExecSilent(true, script); } /** * reaction to an exception<br> * creates the file with excpetion info<br> * */ private static void ProcessCrash(GlobalSettings settings, Exception catched_exception, String suffix) { String error = catched_exception.getLocalizedMessage() + System.lineSeparator(); for(StackTraceElement elem : catched_exception.getStackTrace()) error += elem.toString() + System.lineSeparator(); System.err.println(error); File error_file = new File("crash_" + JavaUtils.GetDate() + "_" + JavaUtils.GetTimestamp() + "_" + suffix + ".txt"); String error_fname = error_file.getAbsolutePath(); try { FileUtils.SaveToFile(error_fname, error); } catch (Exception e) // giving up now - exception during exception processing.. { System.err.println(e); } try { String script = settings.GetScriptByKey("on_crash"); if(script != null) FileUtils.ExecSilent(true, script, error_fname); } catch (ExceptionSystemError e) // giving up now - exception during exception processing.. { System.err.println(e); } } }
package ru.r2cloud.satellite.decoder; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.imageio.ImageIO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.r2cloud.jradio.Beacon; import ru.r2cloud.jradio.BeaconInputStream; import ru.r2cloud.jradio.BeaconSource; import ru.r2cloud.jradio.blocks.CorrelateAccessCodeTag; import ru.r2cloud.jradio.blocks.FixedLengthTagger; import ru.r2cloud.jradio.blocks.SoftToHard; import ru.r2cloud.jradio.blocks.TaggedStreamToPdu; import ru.r2cloud.jradio.fox.Fox1DBeacon; import ru.r2cloud.jradio.fox.FoxPictureDecoder; import ru.r2cloud.jradio.fox.HighSpeedFox; import ru.r2cloud.jradio.fox.PictureScanLine; import ru.r2cloud.model.ObservationRequest; import ru.r2cloud.model.ObservationResult; import ru.r2cloud.predict.PredictOreKit; import ru.r2cloud.util.Configuration; public class FoxDecoder<T extends Beacon> extends FoxSlowDecoder<T> { private static final Logger LOG = LoggerFactory.getLogger(FoxDecoder.class); private final Class<T> clazz; public FoxDecoder(PredictOreKit predict, Configuration config, Class<T> clazz) { super(predict, config, clazz); this.clazz = clazz; } @Override public List<BeaconSource<? extends Beacon>> createBeaconSources(File rawIq, ObservationRequest req) throws IOException { List<BeaconSource<? extends Beacon>> result = new ArrayList<>(); // slow fox DopplerCorrectedSource source = new DopplerCorrectedSource(predict, rawIq, req); result.add(createBeaconSource(source, req)); DopplerCorrectedSource source2 = new DopplerCorrectedSource(predict, rawIq, req); GmskDemodulator gmsk = new GmskDemodulator(source2, 9600, req.getBandwidth(), 0.175f * 3); SoftToHard s2h = new SoftToHard(gmsk); Set<String> codes = new HashSet<>(); codes.add("0011111010"); codes.add("1100000101"); CorrelateAccessCodeTag correlate = new CorrelateAccessCodeTag(s2h, 0, codes, false); TaggedStreamToPdu pdu = new TaggedStreamToPdu(new FixedLengthTagger(correlate, HighSpeedFox.HIGH_SPEED_FRAME_SIZE * 10)); result.add(new HighSpeedFox(pdu)); return result; } @Override public ObservationResult decode(File rawIq, ObservationRequest req) { ObservationResult result = super.decode(rawIq, req); if (result.getDataPath() != null) { try (BeaconInputStream<Fox1DBeacon> bis = new BeaconInputStream<>(new BufferedInputStream(new FileInputStream(result.getDataPath())), Fox1DBeacon.class)) { List<PictureScanLine> scanLines = new ArrayList<>(); while (bis.hasNext()) { Fox1DBeacon beacon = bis.next(); if (beacon.getPictureScanLines() == null) { continue; } scanLines.addAll(beacon.getPictureScanLines()); } FoxPictureDecoder pictureDecoder = new FoxPictureDecoder(scanLines); while (pictureDecoder.hasNext()) { BufferedImage cur = pictureDecoder.next(); if (cur == null) { continue; } File imageFile = saveImage("fox1d-" + req.getId() + ".jpg", cur); if (imageFile != null) { result.setaPath(imageFile); // interested only in the first image break; } } } catch (IOException e) { LOG.error("unable to read data", e); } } return result; } private File saveImage(String path, BufferedImage image) { File imageFile = new File(config.getTempDirectory(), path); try { ImageIO.write(image, "jpg", imageFile); return imageFile; } catch (IOException e) { LOG.error("unable to write image", e); return null; } } @Override public Class<? extends Beacon> getBeaconClass() { return clazz; } }
package sb.tasks.jobs.dailypress; import com.jcabi.http.Response; import com.jcabi.http.request.JdkRequest; import com.jcabi.http.wire.AutoRedirectingWire; import com.jcabi.http.wire.CookieOptimizingWire; import com.jcabi.http.wire.RetryWire; import com.jcabi.log.Logger; import org.bson.Document; import org.jsoup.Jsoup; import sb.tasks.jobs.Agent; import javax.ws.rs.core.HttpHeaders; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; import java.util.List; public final class AnSportExpress implements Agent<MagResult> { private final Document document; private final String phpSessId; private final String username; private final String selife; private final String userAgent; public AnSportExpress(Document document, String phpSessId, String username, String selife, String userAgent) { this.document = document; this.phpSessId = phpSessId; this.username = username; this.userAgent = userAgent; this.selife = selife; } @Override public List<MagResult> perform() throws IOException { String url = Jsoup.connect("http: .get() .getElementById("pdf_load") .attr("href"); Logger.info(this, String.format("Checking link: %s", url)); File out = new File( System.getProperty("java.io.tmpdir"), String.format("se%s.pdf", new SimpleDateFormat("yyyyMMdd").format(new Date())) ); if (!url.equals(document.get("vars", Document.class).getString("download_url"))) { Response response = new JdkRequest(url) .through(RetryWire.class) .through(CookieOptimizingWire.class) .through(AutoRedirectingWire.class) .header("Upgrade-Insecure-Requests", "0") .header(HttpHeaders.ACCEPT, "application/pdf") .header(HttpHeaders.USER_AGENT, userAgent) .header(HttpHeaders.COOKIE, String.format("PHPSESSID=%s", phpSessId)) .header(HttpHeaders.COOKIE, String.format("RealUserName=%s", username)) .header(HttpHeaders.COOKIE, String.format("SELIFE=%s", selife)) .fetch(); new PdfFromResponse(response).saveTo(out); } else Logger.info(this, String.format("%s already downloaded. Exiting", url)); return Collections.singletonList( new MagResult(out, url, document.get("params", Document.class).getString("text")) ); } }
package se.lth.cs.connect.modules; import se.lth.cs.connect.TrustLevel; import java.util.List; import java.security.SecureRandom; import java.time.ZoneId; import java.time.ZonedDateTime; import com.lambdaworks.crypto.SCryptUtil; import iot.jcypher.graph.GrNode; import iot.jcypher.graph.GrProperty; import iot.jcypher.query.JcQueryResult; import iot.jcypher.query.api.IClause; import iot.jcypher.query.values.JcNode; import iot.jcypher.query.values.JcRelation; import iot.jcypher.query.values.JcString; import iot.jcypher.query.values.JcBoolean; import iot.jcypher.query.factories.clause.MATCH; import iot.jcypher.query.factories.clause.CREATE; import iot.jcypher.query.factories.clause.RETURN; import iot.jcypher.query.factories.clause.WHERE; import iot.jcypher.query.factories.clause.DO; /** * An account must have a unique email. * Trust is elevated from 0-->1 (verify email) and 1-->2 (admin promotes). * Passwords are encrypted with scrypt. */ public class AccountSystem { // 2^14/8/1 ~ 100ms private static final int SCRYPT_N = 16384; private static final int SCRYPT_R = 8; private static final int SCRYPT_P = 1; // Must be reseeded from time to time private static final SecureRandom random = new SecureRandom(); /** * POJO representation of an account. Changes to the variables will not be * reflected in the database, use the methods "changeXYZ" further down. */ public static class Account { public String email; public String password; // bcrypt/scrypt hashed public int trust; // See TrustLevel public int defaultCollection; public Account(String email, String pwd, int trust) { this.email = email; this.password = pwd; this.trust = trust; } public Account(GrNode base) { for (GrProperty prop : base.getProperties()) { switch (prop.getName()) { case "email": email = prop.getValue().toString(); break; case "password": password = prop.getValue().toString(); break; case "trust": java.math.BigDecimal a = (java.math.BigDecimal)prop.getValue(); trust = a.intValue(); break; case "default": java.math.BigDecimal b = (java.math.BigDecimal)prop.getValue(); defaultCollection = b.intValue(); default: break; } } } public boolean authenticate(String email, String password) { // important to fail on email check first, otherwise very slow return email != null && password != null && this.email.equals(email) && SCryptUtil.check(password, this.password); } } /** * Get Account by email, or null if email doesn't exist. Use this method to * get trust level and username. Throws DatabaseException if query fails. */ public static Account findByEmail(String email) { JcNode node = new JcNode("user"); JcQueryResult res = Database.query(Database.access(), new IClause[]{ MATCH.node(node).label("user").property("email").value(email), RETURN.value(node) }); List<GrNode> entries = res.resultOf(node); // This is almost undefined behavior if (entries.size() > 1) {} if (entries.size() == 0) return null; // "Invalid username or password" return new Account(entries.get(0)); } /** * Try to logon email with plaintextPassword. Returns true on success (email * exists and password was correct) and false on any type of failure (email * doesn't exist, password was wrong). Throws database exceptions on error. */ public static boolean authenticate(String email, String plaintextPassword) { Account acc = findByEmail(email); // "Invalid email or password" if (acc == null) return false; return acc.authenticate(email, plaintextPassword); } /** * Try and create a user with the provided details. Email uniqueness is * enforced and if email is already in database, false will be returned. * * A database exception is thrown if the create query returns with errors. * * Synchronized due to uniqueness constraint not enabled in the community * edition, and email addresses must be unique. */ public static synchronized boolean createAccount(String email, String password, int trust) { Account acc = findByEmail(email); JcNode coll = new JcNode("c"); JcNode user = new JcNode("user"); ZonedDateTime currentTime = ZonedDateTime.now(ZoneId.of("Europe/Stockholm")); // "Email already exists" if (acc != null){ //email is already registered if(acc.trust!=TrustLevel.UNREGISTERED) return false; //email isn't registered, merge existing mail with the new registration info acc.password = SCryptUtil.scrypt(password, SCRYPT_N, SCRYPT_R, SCRYPT_P); Database.query(Database.access(), new IClause[]{ MATCH.node(user).label("user") .property("email").value(email), DO.SET(user.property("trust")).to(trust), DO.SET(user.property("password")).to(acc.password), DO.SET(user.property("signupdate")).to(currentTime) }); return true; } // Unless synchronized, email may or may not longer be unique acc = new Account(email, SCryptUtil.scrypt(password, SCRYPT_N, SCRYPT_R, SCRYPT_P), trust); Database.query(Database.access(), new IClause[]{ CREATE.node(coll).label("collection") .property("name").value("default"), CREATE.node().label("user") .property("email").value(email) .property("password").value(acc.password) .property("trust").value(trust) .property("signupdate").value(currentTime) .property("default").value(coll.id()) .relation().out().type("MEMBER_OF") .node(coll) }); return true; } /** * Try and remove the user from the database. The user and all relations * to entries will be deleted. Methods throws database exception on error. */ public static boolean deleteAccount(String email) { JcNode node = new JcNode("user"); JcQueryResult res = Database.query(Database.access(), new IClause[]{ MATCH.node(node).label("user").property("email").value(email), DO.DETACH_DELETE(node) }); return true; } /** * Generate 32 bytes of random data and encode it with base64. */ private static String generateToken() { byte[] entropy = new byte[32]; random.nextBytes(entropy); return java.util.Base64.getEncoder().encodeToString(entropy); } /** * Attempt to verify a token, removing it if possible and returning the * related email address. */ private static String verifyToken(String tokenType, String tokenStr) { JcNode user = new JcNode("user"); JcNode token = new JcNode("token"); JcString email = new JcString("email"); JcQueryResult res = Database.query(Database.access(), new IClause[]{ MATCH.node(token).label("token").property("token").value(tokenStr) .relation().type(tokenType) .node(user).label("user"), DO.DETACH_DELETE(token), RETURN.value(user.property("email")).AS(email) }); List<String> emails = res.resultOf(email); // Either 0 (no token-user match) or >1 (multiple token-user matches) if (emails.size() != 1) return null; return emails.get(0); } /** * Attaches a token to the specified email. Returns token. */ private static String attachToken(String tokenType, String email) { JcNode user = new JcNode("user"); JcNode token = new JcNode("token"); String tokenValue = generateToken(); JcQueryResult res = Database.query(Database.access(), new IClause[]{ MATCH.node(user).label("user").property("email").value(email), CREATE.node(token).label("token").property("token").value(tokenValue), CREATE.node(token).relation().out().type(tokenType).node(user) }); return tokenValue; } /** * Generate a password reset token that points to a user and returns it. */ public static String generatePasswordToken(String email) { return attachToken("RESET_TOKEN", email); } /** * Generate an email confirmation token that points to a user and returns it. */ public static String generateEmailToken(String email) { return attachToken("EMAIL_TOKEN", email); } /** * Attempt to use a token value to verify an email address. Returns email * if token was found and deletes token, otherwise method returns null. */ public static String verifyEmail(String hash) { String email = verifyToken("EMAIL_TOKEN", hash); if (email == null) return null; changeTrust(email, TrustLevel.USER); return email; } /** * Consumes the provided token and returns the email to continue * the reset password progress. Must check that email isn't null * when using this method. */ public static String verifyResetPasswordToken(String hash) { return verifyToken("RESET_TOKEN", hash); } /** * Helper method to set a user property. Pass in the IClause to carried out. */ private static void setUserProperty(JcNode node, String email, IClause property) { JcQueryResult res = Database.query(Database.access(), new IClause[]{ MATCH.node(node).label("user").property("email").value(email), property }); } /** * Set a user's trust level, see TrustLevel for (meaningful) values. */ public static void changeTrust(String email, int trust) { JcNode node = new JcNode("user"); setUserProperty(node, email, DO.SET(node.property("trust")).to(trust)); } /** * Set a user's email address. Should be verified before making this switch. */ public static void changeEmail(String current, String email) { JcNode node = new JcNode("user"); setUserProperty(node, current, DO.SET(node.property("email")).to(email)); } /** * Change password. Current password should be checked before calling this. */ public static void changePassword(String email, String plaintext) { JcNode node = new JcNode("user"); String hashed = SCryptUtil.scrypt(plaintext, SCRYPT_N, SCRYPT_R, SCRYPT_P); setUserProperty(node, email, DO.SET(node.property("password")).to(hashed)); } }
package seedu.task.logic.commands; import seedu.task.commons.core.LogsCenter; import seedu.task.commons.core.Messages; import seedu.task.commons.core.UnmodifiableObservableList; import seedu.task.commons.exceptions.IllegalValueException; import seedu.task.logic.parser.TaskParser; import seedu.task.logic.parser.UpdateTaskParser; import seedu.task.model.ModelManager; import seedu.task.model.task.ReadOnlyTask; import seedu.task.model.task.Task; import seedu.task.model.task.UniqueTaskList; import seedu.task.model.task.UniqueTaskList.DuplicateTaskException; import seedu.task.model.task.UniqueTaskList.TaskNotFoundException; public class UpdateCommand extends Command{ public static final String COMMAND_WORD = "update"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Updates the person identified by the index number used in the last person listing.\n" + "Parameters: INDEX (must be a positive integer)\n" + "Example: " + COMMAND_WORD + " 1 by Sunday"; public static final String MESSAGE_SUCCESS = "Updated task %1$s"; public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in the taskBook"; private final int taskIndex; private final String updateArgs; /** * Parameter: Task Index * * */ public UpdateCommand(int taskIndex, String updateArgs) { this.taskIndex = taskIndex; this.updateArgs = updateArgs; } @Override public CommandResult execute() { LogsCenter.getLogger(ModelManager.class).info("Task Index: " + taskIndex + " Args: " + updateArgs); UnmodifiableObservableList<ReadOnlyTask> lastShownList = model.getFilteredTaskList(); if (lastShownList.size() < taskIndex) { indicateAttemptToExecuteIncorrectCommand(); return new CommandResult(Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX); } assert model != null; try { TaskParser updateTaskParser = new UpdateTaskParser((Task)lastShownList.get(taskIndex - 1), updateArgs); model.deleteTask(lastShownList.get(taskIndex - 1)); model.addTask(updateTaskParser.parseInput()); } catch (TaskNotFoundException pnfe) { assert false : "The target person cannot be missing"; } catch (DuplicateTaskException e) { return new CommandResult(MESSAGE_DUPLICATE_TASK); } catch (IllegalValueException e) { new IncorrectCommand(e.getMessage()); } return new CommandResult(String.format(MESSAGE_SUCCESS, taskIndex)); } }
package team.creative.creativecore; import org.apache.commons.lang3.tuple.Pair; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import net.minecraft.util.ResourceLocation; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.fml.ExtensionPoint; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.fml.loading.FMLPaths; import net.minecraftforge.fml.network.FMLNetworkConstants; import team.creative.creativecore.client.CreativeCoreClient; import team.creative.creativecore.common.config.event.ConfigEventHandler; import team.creative.creativecore.common.config.sync.ConfigurationChangePacket; import team.creative.creativecore.common.config.sync.ConfigurationClientPacket; import team.creative.creativecore.common.config.sync.ConfigurationPacket; import team.creative.creativecore.common.network.CreativeNetwork; @Mod(value = CreativeCore.MODID) public class CreativeCore { public static final String MODID = "creativecore"; public static final Logger LOGGER = LogManager.getLogger(CreativeCore.MODID); public static final CreativeCoreConfig CONFIG = new CreativeCoreConfig(); public static final CreativeNetwork NETWORK = new CreativeNetwork("1.0", LOGGER, new ResourceLocation(CreativeCore.MODID, "main")); public static ConfigEventHandler CONFIG_HANDLER; public CreativeCore() { FMLJavaModLoadingContext.get().getModEventBus().addListener(this::init); DistExecutor.runWhenOn(Dist.CLIENT, () -> () -> FMLJavaModLoadingContext.get().getModEventBus().addListener(this::client)); } @OnlyIn(value = Dist.CLIENT) private void client(final FMLClientSetupEvent event) { MinecraftForge.EVENT_BUS.register(CreativeCoreClient.class); CreativeCoreClient.init(event); ModLoadingContext.get().registerExtensionPoint(ExtensionPoint.DISPLAYTEST, () -> Pair.of(() -> FMLNetworkConstants.IGNORESERVERONLY, (a, b) -> true)); } private void init(final FMLCommonSetupEvent event) { NETWORK.registerType(ConfigurationChangePacket.class); NETWORK.registerType(ConfigurationClientPacket.class); NETWORK.registerType(ConfigurationPacket.class); CONFIG_HANDLER = new ConfigEventHandler(FMLPaths.CONFIGDIR.get().toFile(), LOGGER); } }
package techreborn.compat.jei; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.annotation.Nonnull; import mezz.jei.api.recipe.BlankRecipeWrapper; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import techreborn.api.recipe.BaseRecipe; public abstract class BaseRecipeWrapper<T extends BaseRecipe> extends BlankRecipeWrapper { protected final T baseRecipe; @Nonnull private final List<List<ItemStack>> inputs; public BaseRecipeWrapper(T baseRecipe) { this.baseRecipe = baseRecipe; inputs = new ArrayList<>(); for (ItemStack input : baseRecipe.getInputs()) { if (baseRecipe.useOreDic()) { List<ItemStack> oreDictInputs = expandOreDict(input); inputs.add(oreDictInputs); } else { inputs.add(Collections.singletonList(input)); } } } private static List<ItemStack> expandOreDict(ItemStack itemStack) { int[] oreIds = OreDictionary.getOreIDs(itemStack); if (oreIds.length == 0) { return Collections.singletonList(itemStack); } Set<ItemStack> itemStackSet = new HashSet<>(); for (int oreId : oreIds) { String oreName = OreDictionary.getOreName(oreId); List<ItemStack> ores = OreDictionary.getOres(oreName); for (ItemStack ore : ores) { if (ore.stackSize != itemStack.stackSize) { ItemStack oreCopy = ore.copy(); oreCopy.stackSize = itemStack.stackSize; itemStackSet.add(oreCopy); } else { itemStackSet.add(ore); } } } return new ArrayList<>(itemStackSet); } @Nonnull @Override public List<List<ItemStack>> getInputs() { return inputs; } @Nonnull @Override public List<ItemStack> getOutputs() { return baseRecipe.getOutputs(); } }
package techreborn.utils; import com.google.common.collect.Maps; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.CraftingInventory; import net.minecraft.item.ItemStack; import net.minecraft.util.registry.Registry; import reborncore.api.events.ItemCraftCallback; import team.reborn.energy.Energy; import techreborn.TechReborn; import java.util.Map; import java.util.stream.IntStream; public final class PoweredCraftingHandler implements ItemCraftCallback { private PoweredCraftingHandler() { } public static void setup() { ItemCraftCallback.EVENT.register(new PoweredCraftingHandler()); } @Override public void onCraft(ItemStack stack, CraftingInventory craftingInventory, PlayerEntity playerEntity) { if (Energy.valid(stack)) { double totalEnergy = IntStream.range(0, craftingInventory.getInvSize()) .mapToObj(craftingInventory::getInvStack) .filter(s -> !s.isEmpty()) .filter(Energy::valid) .mapToDouble(s -> Energy.of(s).getEnergy()) .sum(); Energy.of(stack).set(totalEnergy); } if (!Registry.ITEM.getId(stack.getItem()).getNamespace().equalsIgnoreCase(TechReborn.MOD_ID)) { return; } Map<Enchantment, Integer> map = Maps.newLinkedHashMap(); for (int i = 0; i < craftingInventory.getInvSize(); i++){ ItemStack ingredient = craftingInventory.getInvStack(i); if (ingredient.isEmpty()){ continue; } EnchantmentHelper.getEnchantments(ingredient).forEach((key, value) -> map.merge(key, value, (v1, v2) -> v1 > v2 ? v1 : v2)); } if (!map.isEmpty()){ EnchantmentHelper.set(map, stack); } } }
package tigase.server.xmppclient; import tigase.util.TigaseStringprepException; import tigase.xmpp.BareJID; import tigase.db.DBInitException; import tigase.db.DataRepository; import tigase.db.RepositoryFactory; import tigase.db.UserNotFoundException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Map; import java.util.concurrent.ConcurrentSkipListMap; import java.util.logging.Level; import java.util.logging.Logger; /** * Extended implementation of SeeOtherHost using redirect information from * database * */ public class SeeOtherHostDB extends SeeOtherHostHashed { private static final Logger log = Logger.getLogger(SeeOtherHostDB.class.getName()); public static final String SEE_OTHER_HOST_TABLE = "tig_see_other_hosts"; public static final String SEE_OTHER_HOST_DB_URL_KEY = CM_SEE_OTHER_HOST_CLASS_PROP_KEY + "/" + "db-url"; public static final String SEE_OTHER_HOST_DB_QUERY_KEY = CM_SEE_OTHER_HOST_CLASS_PROP_KEY + "/" + "get-host-query"; public static final String DB_GET_ALL_DATA_DB_QUERY_KEY = CM_SEE_OTHER_HOST_CLASS_PROP_KEY + "/" + "get-all-data-query"; public static final String GET_ALL_QUERY_TIMEOUT_QUERY_KEY = CM_SEE_OTHER_HOST_CLASS_PROP_KEY + "/" + "get-all-query-timeout"; public static final String SERIAL_ID = "sid"; public static final String USER_ID = "uid"; public static final String NODE_ID = "node_id"; public static final String DEF_DB_GET_HOST_QUERY = " select * from tig_users, " + SEE_OTHER_HOST_TABLE + " where tig_users.uid = " + SEE_OTHER_HOST_TABLE + "." + USER_ID + " and user_id = ?"; private static final String DEF_DB_GET_ALL_DATA_QUERY = "select user_id, node_id from tig_users, " + SEE_OTHER_HOST_TABLE + " where tig_users.uid = " + SEE_OTHER_HOST_TABLE + "." + USER_ID; private static final String CREATE_STATS_TABLE = "create table " + SEE_OTHER_HOST_TABLE + " ( " + SERIAL_ID + " serial," + USER_ID + " bigint unsigned NOT NULL, " + NODE_ID + " varchar(2049) NOT NULL, " + " primary key (" + SERIAL_ID + "), " + " constraint tig_see_other_host_constr foreign key (" + USER_ID + ") references tig_users (" + USER_ID + ")" + ")"; private static final int DEF_QUERY_TIME_OUT = 0; private String get_host_query = DEF_DB_GET_HOST_QUERY; private String get_all_data_query = DEF_DB_GET_ALL_DATA_QUERY; private String get_host_DB_url = ""; private DataRepository data_repo = null; private Map<BareJID, BareJID> redirectsMap = new ConcurrentSkipListMap<BareJID, BareJID>(); // Methods @Override public BareJID findHostForJID(BareJID jid, BareJID host) { BareJID see_other_host = redirectsMap.get(jid); if (see_other_host != null) { return see_other_host; } else { see_other_host = host; } try { see_other_host = queryDB(jid); } catch (Exception ex) { see_other_host = super.findHostForJID(jid, host); log.log(Level.SEVERE, "DB lookup failed, fallback to SeeOtherHostHashed: ", ex); } return see_other_host; } @Override public void getDefaults(Map<String, Object> defs, Map<String, Object> params) { super.getDefaults(defs, params); if (params.containsKey("--user-db-uri")) { get_host_DB_url = (String) params.get("--user-db-uri"); } defs.put(SEE_OTHER_HOST_DB_URL_KEY, get_host_DB_url); defs.put(SEE_OTHER_HOST_DB_QUERY_KEY, get_host_query); defs.put(DB_GET_ALL_DATA_DB_QUERY_KEY, get_all_data_query); } @Override public void setProperties(Map<String, Object> props) { super.setProperties(props); if ((props.containsKey(SEE_OTHER_HOST_DB_URL_KEY)) && !props.get(SEE_OTHER_HOST_DB_URL_KEY).toString().trim().isEmpty()) { get_host_DB_url = props.get(SEE_OTHER_HOST_DB_URL_KEY).toString().trim(); } props.put(SEE_OTHER_HOST_DB_URL_KEY, get_host_DB_url); if ((props.containsKey(SEE_OTHER_HOST_DB_QUERY_KEY)) && !props.get(SEE_OTHER_HOST_DB_QUERY_KEY).toString().trim().isEmpty()) { get_host_query = props.get(SEE_OTHER_HOST_DB_QUERY_KEY).toString().trim(); } props.put(SEE_OTHER_HOST_DB_QUERY_KEY, get_host_query); if ((props.containsKey(DB_GET_ALL_DATA_DB_QUERY_KEY)) && !props.get(DB_GET_ALL_DATA_DB_QUERY_KEY).toString().trim().isEmpty()) { get_all_data_query = props.get(DB_GET_ALL_DATA_DB_QUERY_KEY).toString().trim(); } props.put(DB_GET_ALL_DATA_DB_QUERY_KEY, get_all_data_query); try { initRepository(get_host_DB_url, null); } catch (Exception ex) { log.log(Level.SEVERE, "Cannot initialize connection to database: ", ex); } } public void initRepository(String conn_str, Map<String, String> map) throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException, DBInitException { log.log(Level.INFO, "Initializing dbAccess for db connection url: {0}", conn_str); data_repo = RepositoryFactory.getDataRepository(null, conn_str, map); checkDB(); data_repo.initPreparedStatement(get_host_query, get_host_query); data_repo.initPreparedStatement(get_all_data_query, get_all_data_query); queryAllDB(); } private void checkDB() throws SQLException { data_repo.checkTable( SEE_OTHER_HOST_TABLE, CREATE_STATS_TABLE ); } private BareJID queryDB(BareJID user) throws UserNotFoundException, SQLException, TigaseStringprepException { PreparedStatement get_host = data_repo.getPreparedStatement(user, get_host_query); ResultSet rs = null; synchronized (get_host) { get_host.setString(1, user.toString()); rs = get_host.executeQuery(); if (rs.next()) { return BareJID.bareJIDInstance(rs.getString(NODE_ID)); } else { throw new UserNotFoundException("Item does not exist for user: " + user); } // end of if (isnext) else } } private void queryAllDB() throws SQLException { PreparedStatement get_all = data_repo.getPreparedStatement(null, get_all_data_query); get_all.setQueryTimeout(DEF_QUERY_TIME_OUT); ResultSet rs = null; synchronized (get_all) { rs = get_all.executeQuery(); while (rs.next()) { String user_jid = rs.getString("user_id"); String node_jid = rs.getString(NODE_ID); try { BareJID user = BareJID.bareJIDInstance(user_jid); BareJID node = BareJID.bareJIDInstance(node_jid); redirectsMap.put(user, node); } catch (TigaseStringprepException ex) { log.warning("Invalid user's or node's JID: " + user_jid + ", " + node_jid); } } // end of if (isnext) else } log.info("Loaded " + redirectsMap.size() + " redirect definitions from database."); } }
//@@author A0138493W package utask.logic.parser; import static utask.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import java.util.regex.Matcher; import java.util.regex.Pattern; import utask.logic.commands.Command; import utask.logic.commands.IncorrectCommand; import utask.logic.commands.UnaliasCommand; import utask.model.AliasCommandMap; /** * Parses input arguments and creates a new UnaliasCommand object */ public class UnaliasCommandParser { private static final Pattern UNALIAS_REGEX = Pattern.compile("[\\w]+"); public Command parse(AliasCommandMap aliasMap, String args) { final Matcher matcher = UNALIAS_REGEX.matcher(args.trim()); if (matcher.matches()) { System.out.println(args.trim()); return new UnaliasCommand(aliasMap, args.trim()); } return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, UnaliasCommand.MESSAGE_USAGE)); } }
package org.smoothbuild.lang.base; import static org.smoothbuild.lang.type.TestingTypes.blob; import static org.smoothbuild.lang.type.TestingTypes.string; import static org.smoothbuild.util.Lists.list; import static org.testory.Testory.given; import static org.testory.Testory.mock; import static org.testory.Testory.thenReturned; import static org.testory.Testory.thenThrown; import static org.testory.Testory.when; import org.junit.Test; import org.smoothbuild.util.Dag; public class SignatureTest { private Parameter parameter; private Parameter parameter2; @Test public void null_type_is_forbidden() { when(() -> new Signature(null, "name", list())); thenThrown(NullPointerException.class); } @Test public void null_name_is_forbidden() { when(() -> new Signature(string, null, list())); thenThrown(NullPointerException.class); } @Test public void null_param_is_forbidden() { when(() -> new Signature(string, "name", null)); thenThrown(NullPointerException.class); } @Test public void parameter_types() throws Exception { given(parameter = new Parameter(blob, "blob", mock(Dag.class))); given(parameter2 = new Parameter(string, "string", mock(Dag.class))); when(() -> new Signature(string, "name", list(parameter, parameter2)).parameterTypes()); thenReturned(list(blob, string)); } @Test public void to_string() throws Exception { given(parameter = new Parameter(blob, "blob", mock(Dag.class))); given(parameter2 = new Parameter(string, "string", mock(Dag.class))); when(() -> new Signature(string, "name", list(parameter, parameter2)).toString()); thenReturned(string.name() + " " + "name" + "(" + parameter.type().name() + " " + parameter.name() + ", " + parameter2.type().name() + " " + parameter2.name() + ")"); } }
package net.sf.odinms.server; import java.io.File; import java.util.*; import java.util.Map.Entry; import java.util.stream.Collectors; import net.sf.odinms.client.Equip; import net.sf.odinms.client.IItem; import net.sf.odinms.client.MapleClient; import net.sf.odinms.client.MapleInventoryType; import net.sf.odinms.client.MapleWeaponType; import net.sf.odinms.client.SkillFactory; import net.sf.odinms.net.channel.ChannelServer; import net.sf.odinms.provider.*; import net.sf.odinms.tools.Pair; public class MapleItemInformationProvider { private static MapleItemInformationProvider instance = null; protected final MapleDataProvider itemData; protected final MapleDataProvider equipData; protected final MapleDataProvider stringData; protected final MapleData cashStringData; protected final MapleData consumeStringData; protected final MapleData eqpStringData; protected final MapleData etcStringData; protected final MapleData insStringData; protected final MapleData petStringData; protected final Map<Integer, MapleInventoryType> inventoryTypeCache = new HashMap<>(); protected final Map<Integer, Short> slotMaxCache = new HashMap<>(); protected final Map<Integer, MapleStatEffect> itemEffects = new HashMap<>(); protected final Map<Integer, Map<String, Integer>> equipStatsCache = new HashMap<>(); protected final Map<Integer, Boolean> cashCache = new HashMap<>(); protected final Map<Integer, Equip> equipCache = new HashMap<>(); protected final Map<Integer, Double> priceCache = new HashMap<>(); protected final Map<Integer, Integer> wholePriceCache = new HashMap<>(); protected final Map<Integer, Integer> projectileWatkCache = new HashMap<>(); protected final Map<Integer, String> nameCache = new HashMap<>(); protected final Map<Integer, String> descCache = new HashMap<>(); protected final Map<Integer, String> msgCache = new HashMap<>(); protected final Map<Integer, Boolean> dropRestrictionCache = new HashMap<>(); protected final Map<Integer, Boolean> pickupRestrictionCache = new HashMap<>(); protected final List<Pair<Integer, String>> itemNameCache = new ArrayList<>(); protected final Map<Integer, Integer> getMesoCache = new HashMap<>(); protected final Map<Integer, Integer> getExpCache = new HashMap<>(); private static final Random rand = new Random(); private static final List<List<Integer>> maleFaceCache = new ArrayList<>(); private static final List<List<Integer>> femaleFaceCache = new ArrayList<>(); private static final List<List<Integer>> ungenderedFaceCache = new ArrayList<>(); private static final List<List<Integer>> maleHairCache = new ArrayList<>(); private static final List<List<Integer>> femaleHairCache = new ArrayList<>(); private static final List<List<Integer>> ungenderedHairCache = new ArrayList<>(); private static boolean facesCached = false; private static boolean hairsCached = false; private static final Map<String, Integer> cashEquips = new HashMap<>(); private static boolean cashEquipsCached = false; /** Creates a new instance of MapleItemInformationProvider */ protected MapleItemInformationProvider() { itemData = MapleDataProviderFactory.getDataProvider(new File(System.getProperty("net.sf.odinms.wzpath") + "/Item.wz")); equipData = MapleDataProviderFactory.getDataProvider(new File(System.getProperty("net.sf.odinms.wzpath") + "/Character.wz")); stringData = MapleDataProviderFactory.getDataProvider(new File(System.getProperty("net.sf.odinms.wzpath") + "/String.wz")); cashStringData = MapleDataProviderFactory.getDataProvider(new File(System.getProperty("net.sf.odinms.wzpath") + "/String.wz")).getData("Cash.img"); consumeStringData = MapleDataProviderFactory.getDataProvider(new File(System.getProperty("net.sf.odinms.wzpath") + "/String.wz")).getData("Consume.img"); eqpStringData = MapleDataProviderFactory.getDataProvider(new File(System.getProperty("net.sf.odinms.wzpath") + "/String.wz")).getData("Eqp.img"); etcStringData = MapleDataProviderFactory.getDataProvider(new File(System.getProperty("net.sf.odinms.wzpath") + "/String.wz")).getData("Etc.img"); insStringData = MapleDataProviderFactory.getDataProvider(new File(System.getProperty("net.sf.odinms.wzpath") + "/String.wz")).getData("Ins.img"); petStringData = MapleDataProviderFactory.getDataProvider(new File(System.getProperty("net.sf.odinms.wzpath") + "/String.wz")).getData("Pet.img"); } public static MapleItemInformationProvider getInstance() { if (instance == null) { instance = new MapleItemInformationProvider(); } return instance; } /* returns the inventory type for the specified item id */ public MapleInventoryType getInventoryType(int itemId) { if (inventoryTypeCache.containsKey(itemId)) { return inventoryTypeCache.get(itemId); } MapleInventoryType ret; String idStr = "0" + String.valueOf(itemId); // first look in items... MapleDataDirectoryEntry root = itemData.getRoot(); for (MapleDataDirectoryEntry topDir : root.getSubdirectories()) { // we should have .img files here beginning with the first 4 IID for (MapleDataFileEntry iFile : topDir.getFiles()) { if (iFile.getName().equals(idStr.substring(0, 4) + ".img")) { ret = MapleInventoryType.getByWZName(topDir.getName()); inventoryTypeCache.put(itemId, ret); return ret; } else if (iFile.getName().equals(idStr.substring(1) + ".img")) { ret = MapleInventoryType.getByWZName(topDir.getName()); inventoryTypeCache.put(itemId, ret); return ret; } } } // not found? maybe its equip... root = equipData.getRoot(); for (MapleDataDirectoryEntry topDir : root.getSubdirectories()) { for (MapleDataFileEntry iFile : topDir.getFiles()) { if (iFile.getName().equals(idStr + ".img")) { ret = MapleInventoryType.EQUIP; inventoryTypeCache.put(itemId, ret); return ret; } } } ret = MapleInventoryType.UNDEFINED; inventoryTypeCache.put(itemId, ret); return ret; } public List<Pair<Integer, String>> getAllConsume() { return getAllConsume('\0'); } public List<Pair<Integer, String>> getAllConsume(char initial) { List<Pair<Integer, String>> itemPairs = new ArrayList<>(); MapleData itemsData; itemsData = stringData.getData("Consume.img"); if (Character.isLetter(initial)) { initial = Character.toUpperCase(initial); for (MapleData itemFolder : itemsData.getChildren()) { boolean hasicon = false; String itemName = MapleDataTool.getString("name", itemFolder, "NO-NAME"); if (Character.toUpperCase(itemName.charAt(0)) == initial) { int itemId = Integer.parseInt(itemFolder.getName()); MapleData item = getItemData(itemId); if (item == null) { continue; } MapleData info = item.getChildByPath("info"); if (info == null) { continue; } for (MapleData data : info.getChildren()) { if (data.getName().equalsIgnoreCase("icon")) { hasicon = true; break; } } if (hasicon) { itemPairs.add(new Pair<>(itemId, itemName)); } } } } else if (initial == ' for (MapleData itemFolder : itemsData.getChildren()) { boolean hasicon = false; String itemName = MapleDataTool.getString("name", itemFolder, "NO-NAME"); if (!Character.isLetter(itemName.charAt(0))) { int itemId = Integer.parseInt(itemFolder.getName()); MapleData item = getItemData(itemId); if (item == null) { continue; } MapleData info = item.getChildByPath("info"); if (info == null) { continue; } for (MapleData data : info.getChildren()) { if (data.getName().equalsIgnoreCase("icon")) { hasicon = true; break; } } if (hasicon) { itemPairs.add(new Pair<>(itemId, itemName)); } } } } else { for (MapleData itemFolder : itemsData.getChildren()) { boolean hasicon = false; String itemName = MapleDataTool.getString("name", itemFolder, "NO-NAME"); int itemId = Integer.parseInt(itemFolder.getName()); MapleData item = getItemData(itemId); if (item == null) { continue; } MapleData info = item.getChildByPath("info"); if (info == null) { continue; } for (MapleData data : info.getChildren()) { if (data.getName().equalsIgnoreCase("icon")) { hasicon = true; break; } } if (hasicon) { itemPairs.add(new Pair<>(itemId, itemName)); } } } return itemPairs; } public Pair<Integer, String> getConsumeByName(String searchstring) { Pair<Integer, String> ret = null; MapleData itemsData; itemsData = stringData.getData("Consume.img"); if (searchstring.isEmpty()) { return ret; } searchstring = searchstring.toUpperCase(); for (MapleData itemFolder : itemsData.getChildren()) { boolean hasicon = false; String itemName = MapleDataTool.getString("name", itemFolder, "NO-NAME"); if (itemName.toUpperCase().startsWith(searchstring)) { int itemId = Integer.parseInt(itemFolder.getName()); MapleData item = getItemData(itemId); if (item == null) { continue; } MapleData info = item.getChildByPath("info"); if (info == null) { continue; } for (MapleData data : info.getChildren()) { if (data.getName().equalsIgnoreCase("icon")) { hasicon = true; break; } } if (hasicon) { if (ret == null) { ret = new Pair<>(itemId, itemName); } else if (ret.getRight().length() > itemName.length()) { ret = new Pair<>(itemId, itemName); } } } } return ret; } public List<Pair<Integer, String>> getAllEqp() { return getAllEqp('\0'); } public List<Pair<Integer, String>> getAllEqp(char initial) { List<Pair<Integer, String>> itemPairs = new ArrayList<>(); MapleData itemsData; itemsData = stringData.getData("Eqp.img").getChildByPath("Eqp"); if (Character.isLetter(initial)) { initial = Character.toUpperCase(initial); for (MapleData eqpType : itemsData.getChildren()) { for (MapleData itemFolder : eqpType.getChildren()) { boolean hasicon = false; String itemName = MapleDataTool.getString("name", itemFolder, "NO-NAME"); if (Character.toUpperCase(itemName.charAt(0)) == initial) { int itemId = Integer.parseInt(itemFolder.getName()); MapleData item = getItemData(itemId); if (item == null) { continue; } MapleData info = item.getChildByPath("info"); if (info == null) { continue; } for (MapleData data : info.getChildren()) { if (data.getName().equalsIgnoreCase("icon")) { hasicon = true; break; } } if (hasicon) { itemPairs.add(new Pair<>(itemId, itemName)); } } } } } else if (initial == ' for (MapleData eqpType : itemsData.getChildren()) { for (MapleData itemFolder : eqpType.getChildren()) { boolean hasicon = false; String itemName = MapleDataTool.getString("name", itemFolder, "NO-NAME"); if (!Character.isLetter(itemName.charAt(0))) { int itemId = Integer.parseInt(itemFolder.getName()); MapleData item = getItemData(itemId); if (item == null) { continue; } MapleData info = item.getChildByPath("info"); if (info == null) { continue; } for (MapleData data : info.getChildren()) { if (data.getName().equalsIgnoreCase("icon")) { hasicon = true; break; } } if (hasicon) { itemPairs.add(new Pair<>(itemId, itemName)); } } } } } else { for (MapleData eqpType : itemsData.getChildren()) { for (MapleData itemFolder : eqpType.getChildren()) { boolean hasicon = false; String itemName = MapleDataTool.getString("name", itemFolder, "NO-NAME"); int itemId = Integer.parseInt(itemFolder.getName()); MapleData item = getItemData(itemId); if (item == null) { continue; } MapleData info = item.getChildByPath("info"); if (info == null) { continue; } for (MapleData data : info.getChildren()) { if (data.getName().equalsIgnoreCase("icon")) { hasicon = true; break; } } if (hasicon) { itemPairs.add(new Pair<>(itemId, itemName)); } } } } return itemPairs; } public Pair<Integer, String> getEqpByName(String searchstring) { Pair<Integer, String> ret = null; MapleData itemsData; itemsData = stringData.getData("Eqp.img").getChildByPath("Eqp"); if (searchstring.isEmpty()) { return ret; } searchstring = searchstring.toUpperCase(); for (MapleData eqpType : itemsData.getChildren()) { for (MapleData itemFolder : eqpType.getChildren()) { boolean hasicon = false; String itemName = MapleDataTool.getString("name", itemFolder, "NO-NAME"); if (itemName.toUpperCase().startsWith(searchstring)) { int itemId = Integer.parseInt(itemFolder.getName()); MapleData item = getItemData(itemId); if (item == null) { continue; } MapleData info = item.getChildByPath("info"); if (info == null) { continue; } for (MapleData data : info.getChildren()) { if (data.getName().equalsIgnoreCase("icon")) { hasicon = true; break; } } if (hasicon) { if (ret == null) { ret = new Pair<>(itemId, itemName); } else if (ret.getRight().length() > itemName.length()) { ret = new Pair<>(itemId, itemName); } } } } } return ret; } public List<Pair<Integer, String>> getAllEtc() { return getAllEtc('\0'); } public List<Pair<Integer, String>> getAllEtc(char initial) { List<Pair<Integer, String>> itemPairs = new ArrayList<>(); MapleData itemsData; itemsData = stringData.getData("Etc.img").getChildByPath("Etc"); if (Character.isLetter(initial)) { initial = Character.toUpperCase(initial); for (MapleData itemFolder : itemsData.getChildren()) { boolean hasicon = false; String itemName = MapleDataTool.getString("name", itemFolder, "NO-NAME"); if (Character.toUpperCase(itemName.charAt(0)) == initial) { int itemId = Integer.parseInt(itemFolder.getName()); MapleData item = getItemData(itemId); if (item == null) { continue; } MapleData info = item.getChildByPath("info"); if (info == null) { continue; } for (MapleData data : info.getChildren()) { if (data.getName().equalsIgnoreCase("icon")) { hasicon = true; break; } } if (hasicon) { itemPairs.add(new Pair<>(itemId, itemName)); } } } } else if (initial == ' for (MapleData itemFolder : itemsData.getChildren()) { boolean hasicon = false; String itemName = MapleDataTool.getString("name", itemFolder, "NO-NAME"); if (!Character.isLetter(itemName.charAt(0))) { int itemId = Integer.parseInt(itemFolder.getName()); MapleData item = getItemData(itemId); if (item == null) { continue; } MapleData info = item.getChildByPath("info"); if (info == null) { continue; } for (MapleData data : info.getChildren()) { if (data.getName().equalsIgnoreCase("icon")) { hasicon = true; break; } } if (hasicon) { itemPairs.add(new Pair<>(itemId, itemName)); } } } } else { for (MapleData itemFolder : itemsData.getChildren()) { boolean hasicon = false; String itemName = MapleDataTool.getString("name", itemFolder, "NO-NAME"); int itemId = Integer.parseInt(itemFolder.getName()); MapleData item = getItemData(itemId); if (item == null) { continue; } MapleData info = item.getChildByPath("info"); if (info == null) { continue; } for (MapleData data : info.getChildren()) { if (data.getName().equalsIgnoreCase("icon")) { hasicon = true; break; } } if (hasicon) { itemPairs.add(new Pair<>(itemId, itemName)); } } } return itemPairs; } public Pair<Integer, String> getEtcByName(String searchstring) { Pair<Integer, String> ret = null; MapleData itemsData; itemsData = stringData.getData("Etc.img").getChildByPath("Etc"); if (searchstring.isEmpty()) { return ret; } searchstring = searchstring.toUpperCase(); for (MapleData itemFolder : itemsData.getChildren()) { boolean hasicon = false; String itemName = MapleDataTool.getString("name", itemFolder, "NO-NAME"); if (itemName.toUpperCase().startsWith(searchstring)) { int itemId = Integer.parseInt(itemFolder.getName()); MapleData item = getItemData(itemId); if (item == null) { continue; } MapleData info = item.getChildByPath("info"); if (info == null) { continue; } for (MapleData data : info.getChildren()) { if (data.getName().equalsIgnoreCase("icon")) { hasicon = true; break; } } if (hasicon) { if (ret == null) { ret = new Pair<>(itemId, itemName); } else if (ret.getRight().length() > itemName.length()) { ret = new Pair<>(itemId, itemName); } } } } return ret; } public List<Pair<Integer, String>> getAllItems() { if (!itemNameCache.isEmpty()) { return itemNameCache; } List<Pair<Integer, String>> itemPairs = new ArrayList<>(); MapleData itemsData; itemsData = stringData.getData("Cash.img"); for (MapleData itemFolder : itemsData.getChildren()) { int itemId = Integer.parseInt(itemFolder.getName()); String itemName = MapleDataTool.getString("name", itemFolder, "NO-NAME"); itemPairs.add(new Pair<>(itemId, itemName)); } itemsData = stringData.getData("Consume.img"); for (MapleData itemFolder : itemsData.getChildren()) { int itemId = Integer.parseInt(itemFolder.getName()); String itemName = MapleDataTool.getString("name", itemFolder, "NO-NAME"); itemPairs.add(new Pair<>(itemId, itemName)); } itemsData = stringData.getData("Eqp.img").getChildByPath("Eqp"); for (MapleData eqpType : itemsData.getChildren()) { for (MapleData itemFolder : eqpType.getChildren()) { int itemId = Integer.parseInt(itemFolder.getName()); String itemName = MapleDataTool.getString("name", itemFolder, "NO-NAME"); itemPairs.add(new Pair<>(itemId, itemName)); } } itemsData = stringData.getData("Etc.img").getChildByPath("Etc"); for (MapleData itemFolder : itemsData.getChildren()) { int itemId = Integer.parseInt(itemFolder.getName()); String itemName = MapleDataTool.getString("name", itemFolder, "NO-NAME"); itemPairs.add(new Pair<>(itemId, itemName)); } itemsData = stringData.getData("Ins.img"); for (MapleData itemFolder : itemsData.getChildren()) { int itemId = Integer.parseInt(itemFolder.getName()); String itemName = MapleDataTool.getString("name", itemFolder, "NO-NAME"); itemPairs.add(new Pair<>(itemId, itemName)); } itemsData = stringData.getData("Pet.img"); for (MapleData itemFolder : itemsData.getChildren()) { int itemId = Integer.parseInt(itemFolder.getName()); String itemName = MapleDataTool.getString("name", itemFolder, "NO-NAME"); itemPairs.add(new Pair<>(itemId, itemName)); } return itemPairs; } protected MapleData getStringData(int itemId) { String cat = "null"; MapleData theData; if (itemId >= 5010000) { theData = cashStringData; } else if (itemId >= 2000000 && itemId < 3000000) { theData = consumeStringData; } else if (itemId >= 1010000 && itemId < 1040000 || itemId >= 1122000 && itemId < 1123000) { theData = eqpStringData.getChildByPath("Eqp"); cat = "Accessory"; } else if (itemId >= 1000000 && itemId < 1010000) { theData = eqpStringData.getChildByPath("Eqp"); cat = "Cap"; } else if (itemId >= 1102000 && itemId < 1103000) { theData = eqpStringData.getChildByPath("Eqp"); cat = "Cape"; } else if (itemId >= 1040000 && itemId < 1050000) { theData = eqpStringData.getChildByPath("Eqp"); cat = "Coat"; } else if (itemId >= 20000 && itemId < 22000) { theData = eqpStringData.getChildByPath("Eqp"); cat = "Face"; } else if (itemId >= 1080000 && itemId < 1090000) { theData = eqpStringData.getChildByPath("Eqp"); cat = "Glove"; } else if (itemId >= 30000 && itemId < 32000) { theData = eqpStringData.getChildByPath("Eqp"); cat = "Hair"; } else if (itemId >= 1050000 && itemId < 1060000) { theData = eqpStringData.getChildByPath("Eqp"); cat = "Longcoat"; } else if (itemId >= 1060000 && itemId < 1070000) { theData = eqpStringData.getChildByPath("Eqp"); cat = "Pants"; } else if (itemId >= 1802000 && itemId < 1810000) { theData = eqpStringData.getChildByPath("Eqp"); cat = "PetEquip"; } else if (itemId >= 1112000 && itemId < 1120000) { theData = eqpStringData.getChildByPath("Eqp"); cat = "Ring"; } else if (itemId >= 1092000 && itemId < 1100000) { theData = eqpStringData.getChildByPath("Eqp"); cat = "Shield"; } else if (itemId >= 1070000 && itemId < 1080000) { theData = eqpStringData.getChildByPath("Eqp"); cat = "Shoes"; } else if (itemId >= 1900000 && itemId < 2000000) { theData = eqpStringData.getChildByPath("Eqp"); cat = "Taming"; } else if (itemId >= 1300000 && itemId < 1800000) { theData = eqpStringData.getChildByPath("Eqp"); cat = "Weapon"; } else if (itemId == 4280000 || itemId == 4280001) { theData = etcStringData; } else if (itemId >= 4000000 && itemId < 5000000) { theData = etcStringData.getChildByPath("Etc"); } else if (itemId >= 3000000 && itemId < 4000000) { theData = insStringData; } else if (itemId >= 5000000 && itemId < 5010000) { theData = petStringData; } else { return null; } if (cat.equalsIgnoreCase("null")) { return theData.getChildByPath(String.valueOf(itemId)); } else { return theData.getChildByPath(cat + "/" + itemId); } } protected MapleData getItemData(int itemId) { MapleData ret = null; String idStr = "0" + String.valueOf(itemId); MapleDataDirectoryEntry root = itemData.getRoot(); for (MapleDataDirectoryEntry topDir : root.getSubdirectories()) { // we should have .img files here beginning with the first 4 IID for (MapleDataFileEntry iFile : topDir.getFiles()) { if (iFile.getName().equals(idStr.substring(0, 4) + ".img")) { ret = itemData.getData(topDir.getName() + "/" + iFile.getName()); if (ret == null) { return null; } ret = ret.getChildByPath(idStr); return ret; } else if (iFile.getName().equals(idStr.substring(1) + ".img")) { return itemData.getData(topDir.getName() + "/" + iFile.getName()); } } } root = equipData.getRoot(); for (MapleDataDirectoryEntry topDir : root.getSubdirectories()) { for (MapleDataFileEntry iFile : topDir.getFiles()) { if (iFile.getName().equals(idStr + ".img")) { return equipData.getData(topDir.getName() + "/" + iFile.getName()); } } } return ret; } /** Called by Coco NPC the first time someone starts a conversation with them. */ public void cacheFaceData() { if (!facesCached) { MapleDataDirectoryEntry root = equipData.getRoot(); for (MapleDataDirectoryEntry topDir : root.getSubdirectories()) { if (topDir.getName().equals("Face")) { topDir.getFiles().stream().map(MapleDataEntry::getName).sorted().forEachOrdered((iFile) -> { Integer id = Integer.parseInt(iFile.substring(3, 8)); // Gets just the ID without leading zeroes. List<List<Integer>> faceLists; if (id >= 20000 && id < 30000) { // Just in case. if ((id / 1000) % 10 == 0) { faceLists = maleFaceCache; } else if ((id / 1000) % 10 == 1) { faceLists = femaleFaceCache; } else { faceLists = ungenderedFaceCache; } List<Integer> faceList = null; if (!faceLists.isEmpty()) { faceList = faceLists.get(faceLists.size() - 1); } // Match condition is that all decimal places EXCEPT for the hundreds place match. Simpler than it looks. if (faceList != null && (faceList.size() < 300 || faceList.stream().anyMatch(x -> Integer.valueOf(x - (x % 1000 / 100 * 100)).equals(id - (id % 1000 / 100 * 100))))) { faceList.add(id); } else { List<Integer> newFaceList = new ArrayList<>(); newFaceList.add(id); faceLists.add(newFaceList); } } }); break; } } facesCached = true; } } /** Called by Coco NPC the first time someone starts a conversation with them. */ public void cacheHairData() { if (!hairsCached) { MapleDataDirectoryEntry root = equipData.getRoot(); for (MapleDataDirectoryEntry topDir : root.getSubdirectories()) { if (topDir.getName().equals("Hair")) { topDir.getFiles().stream().map(MapleDataEntry::getName).sorted().forEachOrdered((iFile) -> { Integer id = Integer.parseInt(iFile.substring(3, 8)); // Gets just the ID without leading zeroes. List<List<Integer>> hairLists; if (id >= 30000 && id < 40000) { // Filtering out IDs that cannot be rendered by the client. if ((id / 1000) % 10 == 0) { hairLists = maleHairCache; } else if ((id / 1000) % 10 == 1) { hairLists = femaleHairCache; } else { hairLists = ungenderedHairCache; } List<Integer> hairList = null; if (!hairLists.isEmpty()) { hairList = hairLists.get(hairLists.size() - 1); } if (hairList != null && (hairList.size() < 300 || hairList.stream().anyMatch(x -> Integer.valueOf(x / 10).equals(id / 10)))) { hairList.add(id); } else { List<Integer> newHairList = new ArrayList<>(); newHairList.add(id); hairLists.add(newHairList); } } }); break; } } hairsCached = true; } } public List<List<Integer>> getFaceData(int gender) { switch (gender) { case 0: return maleFaceCache; case 1: return femaleFaceCache; default: return ungenderedFaceCache; } } public List<List<Integer>> getHairData(int gender) { switch (gender) { case 0: return maleHairCache; case 1: return femaleHairCache; default: return ungenderedHairCache; } } public List<Integer> getFaceData(int gender, int index) { switch (gender) { case 0: return maleFaceCache.get(index); case 1: return femaleFaceCache.get(index); default: return ungenderedFaceCache.get(index); } } public List<Integer> getHairData(int gender, int index) { switch (gender) { case 0: return maleHairCache.get(index); case 1: return femaleHairCache.get(index); default: return ungenderedHairCache.get(index); } } public int getFaceListCount(int gender) { switch (gender) { case 0: return maleFaceCache.size(); case 1: return femaleFaceCache.size(); default: return ungenderedFaceCache.size(); } } public int getHairListCount(int gender) { switch (gender) { case 0: return maleHairCache.size(); case 1: return femaleHairCache.size(); default: return ungenderedHairCache.size(); } } public List<Integer> getAllColors(int id) { List<Integer> ret = new ArrayList<>(); List<List<Integer>> cache; if (id >= 20000 && id < 30000) { // Face int match = id - (id % 1000 / 100 * 100); // Hundreds place set to zero. switch ((id / 1000) % 10) { case 0: cache = maleFaceCache; break; case 1: cache = femaleFaceCache; break; default: cache = ungenderedFaceCache; } for (List<Integer> faceList : cache) { if (faceList.contains(id)) { ret.addAll(faceList.stream().filter(x -> Integer.valueOf(x - (x % 1000 / 100 * 100)).equals(match)).collect(Collectors.toList())); break; } } } else { // Hair int match = id / 10; switch ((id / 1000) % 10) { case 0: cache = maleHairCache; break; case 1: cache = femaleHairCache; break; default: cache = ungenderedHairCache; } for (List<Integer> hairList : cache) { if (hairList.contains(id)) { ret.addAll(hairList.stream().filter(x -> Integer.valueOf(x / 10).equals(match)).collect(Collectors.toList())); break; } } } return ret; } /** returns the maximum of items in one slot * @param c * @param itemId * @return short */ public short getSlotMax(MapleClient c, int itemId) { if (slotMaxCache.containsKey(itemId)) { return slotMaxCache.get(itemId); } short ret = 0; MapleData item = getItemData(itemId); if (item != null) { MapleData smEntry = item.getChildByPath("info/slotMax"); if (smEntry == null) { if (getInventoryType(itemId).getType() == MapleInventoryType.EQUIP.getType()) { ret = 1; } else { ret = 100; } } else { if (isThrowingStar(itemId) || isBullet(itemId) || (MapleDataTool.getInt(smEntry) == 0)) { ret = 1; } ret = (short) MapleDataTool.getInt(smEntry); if (isThrowingStar(itemId)) { ret += c.getPlayer().getSkillLevel(SkillFactory.getSkill(4100000)) * 10; } else { ret += c.getPlayer().getSkillLevel(SkillFactory.getSkill(5200000)) * 10; } } } if (!isThrowingStar(itemId) && !isBullet(itemId)) { slotMaxCache.put(itemId, ret); } return ret; } public int getMeso(int itemId) { if (getMesoCache.containsKey(itemId)) { return getMesoCache.get(itemId); } MapleData item = getItemData(itemId); if (item == null) { return -1; } int pEntry; MapleData pData = item.getChildByPath("info/meso"); if (pData == null) { return -1; } pEntry = MapleDataTool.getInt(pData); getMesoCache.put(itemId, pEntry); return pEntry; } public int getExpCache(int itemId) { if (this.getExpCache.containsKey(itemId)) { return getExpCache.get(itemId); } MapleData item = getItemData(itemId); if (item == null) { return 0; } int pEntry; MapleData pData = item.getChildByPath("spec/exp"); if (pData == null) { return 0; } pEntry = MapleDataTool.getInt(pData); getExpCache.put(itemId, pEntry); return pEntry; } public int getWholePrice(int itemId) { if (wholePriceCache.containsKey(itemId)) { return wholePriceCache.get(itemId); } MapleData item = getItemData(itemId); if (item == null) { return -1; } int pEntry; MapleData pData = item.getChildByPath("info/price"); if (pData == null) { return -1; } pEntry = MapleDataTool.getInt(pData); wholePriceCache.put(itemId, pEntry); return pEntry; } public double getPrice(int itemId) { if (priceCache.containsKey(itemId)) { return priceCache.get(itemId); } MapleData item = getItemData(itemId); if (item == null) { return -1; } double pEntry; MapleData pData = item.getChildByPath("info/unitPrice"); if (pData != null) { try { pEntry = MapleDataTool.getDouble(pData); } catch (Exception e) { pEntry = (double) MapleDataTool.getInt(pData); } } else { pData = item.getChildByPath("info/price"); if (pData == null) { return -1; } pEntry = (double) MapleDataTool.getInt(pData); } priceCache.put(itemId, pEntry); return pEntry; } protected Map<String, Integer> getEquipStats(int itemId) { if (equipStatsCache.containsKey(itemId)) { return equipStatsCache.get(itemId); } Map<String, Integer> ret = new LinkedHashMap<>(); MapleData item = getItemData(itemId); if (item == null) { return null; } MapleData info = item.getChildByPath("info"); if (info == null) { return null; } for (MapleData data : info.getChildren()) { if (data.getName().startsWith("inc")) { ret.put(data.getName().substring(3), MapleDataTool.getIntConvert(data)); } } ret.put("tuc", MapleDataTool.getInt("tuc", info, 0)); ret.put("reqLevel", MapleDataTool.getInt("reqLevel", info, 0)); ret.put("cursed", MapleDataTool.getInt("cursed", info, 0)); ret.put("success", MapleDataTool.getInt("success", info, 0)); equipStatsCache.put(itemId, ret); return ret; } public boolean isCash(int itemId) { if (cashCache.containsKey(itemId)) { return cashCache.get(itemId); } MapleData item = getItemData(itemId); MapleData info = item.getChildByPath("info"); if (info == null) { cashCache.put(itemId, false); return false; } boolean cash = MapleDataTool.getInt("cash", info, 0) == 1; cashCache.put(itemId, cash); return cash; } public void cacheCashEquips() { if (!cashEquipsCached) { final List<String> excludes = Arrays.asList("Afterimage", "TamingMob", "Face", "Hair", "PetEquip"); MapleDataDirectoryEntry root = equipData.getRoot(); root.getSubdirectories().forEach((topDir) -> { if (!excludes.contains(topDir.getName())) { topDir.getFiles().forEach((iFile) -> { int id = Integer.parseInt(iFile.getName().substring(1, 8)); if (isCash(id)) { cashEquips.put(getName(id), id); } }); } }); cashEquipsCached = true; } } public List<Entry<String, Integer>> getCashEquipEntries(final int type) { return cashEquips.entrySet().stream().filter(e -> e.getValue() / 10000 == type).collect(Collectors.toList()); } public boolean cashEquipExists(int id) { return cashEquips.containsValue(id); } public int singleCashEquipSearch(String query) { if (query.length() < 1) return 0; query = query.toUpperCase(); Map.Entry<String, Integer> bestMatch = null; for (Map.Entry<String, Integer> e : cashEquips.entrySet()) { if (e.getKey() == null) continue; String newKey = e.getKey().toUpperCase(); String bestKey = bestMatch == null ? null : bestMatch.getKey().toUpperCase(); if ((bestKey == null && newKey.contains(query)) || (bestKey != null && newKey.contains(query) && (newKey.indexOf(query) < bestKey.indexOf(query) || (newKey.indexOf(query) == bestKey.indexOf(query) && newKey.length() < bestKey.length())))) { bestMatch = e; } } return bestMatch == null || !bestMatch.getKey().toUpperCase().contains(query) ? 0 : bestMatch.getValue(); } public List<Integer> cashEquipSearch(String query) { if (query.length() < 1) return new ArrayList<>(); query = query.toUpperCase(); final List<String> splitQuery = Arrays.stream(query.split("\\s+")) .distinct() .collect(Collectors.toList()); splitQuery.remove(""); if (splitQuery.isEmpty()) return new ArrayList<>(); return cashEquips .entrySet() .stream() .filter(e -> { if (e.getKey() == null || e.getValue() == null) return false; String name = e.getKey().toUpperCase(); for (String token : splitQuery) { if (name.contains(token)) return true; } return false; }) .sorted((e1, e2) -> { String name1 = e1.getKey().toUpperCase(); String name2 = e2.getKey().toUpperCase(); if (name1.equals(name2)) return 0; int tokenCount1 = 0; int tokenCount2 = 0; int combinedIndices1 = 0; int combinedIndices2 = 0; for (String token : splitQuery) { if (name1.contains(token)) { tokenCount1++; combinedIndices1 += name1.indexOf(token); } if (name2.contains(token)) { tokenCount2++; combinedIndices2 += name2.indexOf(token); } } if (tokenCount1 != tokenCount2) { return tokenCount2 - tokenCount1; } if (combinedIndices1 != combinedIndices2) { return combinedIndices1 - combinedIndices2; } if (name1.length() != name2.length()) { return name1.length() - name2.length(); } return name1.compareTo(name2); }) .map(Entry::getValue) .collect(Collectors.toList()); } public List<Integer> cashEquipsByType(final int type) { return cashEquips.values().stream().filter((id) -> { int t = id / 10000; return t == type; }).collect(Collectors.toList()); } public List<Integer> cashEquipsByType(final int lowerType, final int upperType) { return cashEquips.values().stream().filter((id) -> { int type = id / 10000; return type >= lowerType && type <= upperType; }).collect(Collectors.toList()); } public int getReqLevel(int itemId) { final Integer req = getEquipStats(itemId).get("reqLevel"); return req == null ? 0 : req; } public List<Integer> getScrollReqs(int itemId) { List<Integer> ret = new ArrayList<>(); MapleData data = getItemData(itemId); data = data.getChildByPath("req"); if (data == null) { return ret; } for (MapleData req : data.getChildren()) { ret.add(MapleDataTool.getInt(req)); } return ret; } public boolean isWeapon(int itemId) { return itemId >= 1302000 && itemId < 1492024; } public MapleWeaponType getWeaponType(int itemId) { int cat = itemId / 10000; cat = cat % 100; switch (cat) { case 30: return MapleWeaponType.SWORD1H; case 31: return MapleWeaponType.AXE1H; case 32: return MapleWeaponType.BLUNT1H; case 33: return MapleWeaponType.DAGGER; case 37: return MapleWeaponType.WAND; case 38: return MapleWeaponType.STAFF; case 40: return MapleWeaponType.SWORD2H; case 41: return MapleWeaponType.AXE2H; case 42: return MapleWeaponType.BLUNT2H; case 43: return MapleWeaponType.SPEAR; case 44: return MapleWeaponType.POLE_ARM; case 45: return MapleWeaponType.BOW; case 46: return MapleWeaponType.CROSSBOW; case 47: return MapleWeaponType.CLAW; case 48: return MapleWeaponType.KNUCKLE; case 49: return MapleWeaponType.GUN; } return MapleWeaponType.NOT_A_WEAPON; } public boolean isShield(int itemId) { int cat = itemId / 10000; cat = cat % 100; return cat == 9; } public boolean isEquip(int itemId) { return itemId / 1000000 == 1; } public boolean isCleanSlate(int scrollId) { switch (scrollId) { case 2049000: case 2049001: case 2049002: case 2049003: return true; } return false; } public IItem scrollEquipWithId(MapleClient c, IItem equip, int scrollId, boolean usingWhiteScroll) { boolean noFail = false; if (c.getPlayer().haveItem(2022118, 1, false, true)) { noFail = true; } boolean isGM = false; if (c.getPlayer().isGM()) { isGM = true; } if (equip instanceof Equip) { Equip nEquip = (Equip) equip; Map<String, Integer> stats = this.getEquipStats(scrollId); Map<String, Integer> eqstats = this.getEquipStats(equip.getItemId()); if ((nEquip.getUpgradeSlots() > 0 || isCleanSlate(scrollId)) && Math.ceil(Math.random() * 100.0) <= stats.get("success") || isGM || noFail) { switch (scrollId) { case 2049000: case 2049001: case 2049002: case 2049003: if (nEquip.getLevel() + nEquip.getUpgradeSlots() < eqstats.get("tuc")) { byte newSlots = (byte) (nEquip.getUpgradeSlots() + 1); nEquip.setUpgradeSlots(newSlots); } break; case 2049100: case 2049101: case 2049102: case 2049122: // Chaos Scroll of Goodness int increase = 1; if (Math.ceil(Math.random() * 100.0) <= 50 && scrollId != 2049122) { increase = increase * -1; } if (nEquip.getStr() > 0) { short newStat = (short) (nEquip.getStr() + Math.ceil(Math.random() * 5.0) * increase); nEquip.setStr(newStat); } if (nEquip.getDex() > 0) { short newStat = (short) (nEquip.getDex() + Math.ceil(Math.random() * 5.0) * increase); nEquip.setDex(newStat); } if (nEquip.getInt() > 0) { short newStat = (short) (nEquip.getInt() + Math.ceil(Math.random() * 5.0) * increase); nEquip.setInt(newStat); } if (nEquip.getLuk() > 0) { short newStat = (short) (nEquip.getLuk() + Math.ceil(Math.random() * 5.0) * increase); nEquip.setLuk(newStat); } if (nEquip.getWatk() > 0) { short newStat = (short) (nEquip.getWatk() + Math.ceil(Math.random() * 5.0) * increase); nEquip.setWatk(newStat); } if (nEquip.getWdef() > 0) { short newStat = (short) (nEquip.getWdef() + Math.ceil(Math.random() * 5.0) * increase); nEquip.setWdef(newStat); } if (nEquip.getMatk() > 0) { short newStat = (short) (nEquip.getMatk() + Math.ceil(Math.random() * 5.0) * increase); nEquip.setMatk(newStat); } if (nEquip.getMdef() > 0) { short newStat = (short) (nEquip.getMdef() + Math.ceil(Math.random() * 5.0) * increase); nEquip.setMdef(newStat); } if (nEquip.getAcc() > 0) { short newStat = (short) (nEquip.getAcc() + Math.ceil(Math.random() * 5.0) * increase); nEquip.setAcc(newStat); } if (nEquip.getAvoid() > 0) { short newStat = (short) (nEquip.getAvoid() + Math.ceil(Math.random() * 5.0) * increase); nEquip.setAvoid(newStat); } if (nEquip.getSpeed() > 0) { short newStat = (short) (nEquip.getSpeed() + Math.ceil(Math.random() * 5.0) * increase); nEquip.setSpeed(newStat); } if (nEquip.getJump() > 0) { short newStat = (short) (nEquip.getJump() + Math.ceil(Math.random() * 5.0) * increase); nEquip.setJump(newStat); } if (nEquip.getHp() > 0) { short newStat = (short) (nEquip.getHp() + Math.ceil(Math.random() * 5.0) * increase); nEquip.setHp(newStat); } if (nEquip.getMp() > 0) { short newStat = (short) (nEquip.getMp() + Math.ceil(Math.random() * 5.0) * increase); nEquip.setMp(newStat); } break; case 2049004: // Innocence Scroll 60% Map<String, Integer> innoStats = getEquipStats(nEquip.getItemId()); nEquip.setStr(innoStats.getOrDefault("STR", 0).shortValue()); nEquip.setDex(innoStats.getOrDefault("DEX", 0).shortValue()); nEquip.setInt(innoStats.getOrDefault("INT", 0).shortValue()); nEquip.setLuk(innoStats.getOrDefault("LUK", 0).shortValue()); nEquip.setWatk(innoStats.getOrDefault("PAD", 0).shortValue()); nEquip.setWdef(innoStats.getOrDefault("PDD", 0).shortValue()); nEquip.setMatk(innoStats.getOrDefault("MAD", 0).shortValue()); nEquip.setMdef(innoStats.getOrDefault("MDD", 0).shortValue()); nEquip.setAcc(innoStats.getOrDefault("ACC", 0).shortValue()); nEquip.setAvoid(innoStats.getOrDefault("EVA", 0).shortValue()); nEquip.setSpeed(innoStats.getOrDefault("Speed", 0).shortValue()); nEquip.setJump(innoStats.getOrDefault("Jump", 0).shortValue()); nEquip.setHp(innoStats.getOrDefault("MHP", 0).shortValue()); nEquip.setMp(innoStats.getOrDefault("MMP", 0).shortValue()); nEquip.setUpgradeSlots(innoStats.getOrDefault("tuc", 0).byteValue()); nEquip.setLevel((byte) 0); break; default: for (Entry<String, Integer> stat : stats.entrySet()) { if (stat.getKey().equals("STR")) { nEquip.setStr((short) (nEquip.getStr() + stat.getValue())); } else if (stat.getKey().equals("DEX")) { nEquip.setDex((short) (nEquip.getDex() + stat.getValue())); } else if (stat.getKey().equals("INT")) { nEquip.setInt((short) (nEquip.getInt() + stat.getValue())); } else if (stat.getKey().equals("LUK")) { nEquip.setLuk((short) (nEquip.getLuk() + stat.getValue())); } else if (stat.getKey().equals("PAD")) { nEquip.setWatk((short) (nEquip.getWatk() + stat.getValue())); } else if (stat.getKey().equals("PDD")) { nEquip.setWdef((short) (nEquip.getWdef() + stat.getValue())); } else if (stat.getKey().equals("MAD")) { nEquip.setMatk((short) (nEquip.getMatk() + stat.getValue())); } else if (stat.getKey().equals("MDD")) { nEquip.setMdef((short) (nEquip.getMdef() + stat.getValue())); } else if (stat.getKey().equals("ACC")) { nEquip.setAcc((short) (nEquip.getAcc() + stat.getValue())); } else if (stat.getKey().equals("EVA")) { nEquip.setAvoid((short) (nEquip.getAvoid() + stat.getValue())); } else if (stat.getKey().equals("Speed")) { nEquip.setSpeed((short) (nEquip.getSpeed() + stat.getValue())); } else if (stat.getKey().equals("Jump")) { nEquip.setJump((short) (nEquip.getJump() + stat.getValue())); } else if (stat.getKey().equals("MHP")) { nEquip.setHp((short) (nEquip.getHp() + stat.getValue())); } else if (stat.getKey().equals("MMP")) { nEquip.setMp((short) (nEquip.getMp() + stat.getValue())); } } break; } if (noFail && !isGM) { MapleInventoryManipulator.removeById(c, MapleInventoryType.USE, 2022118, 1, true, false); } if (!isCleanSlate(scrollId) && scrollId != 2049004) { if (!isGM) { nEquip.setUpgradeSlots((byte) (nEquip.getUpgradeSlots() - 1)); } nEquip.setLevel((byte) (nEquip.getLevel() + 1)); } } else { if (!usingWhiteScroll && !isCleanSlate(scrollId)) { nEquip.setUpgradeSlots((byte) (nEquip.getUpgradeSlots() - 1)); } if (Math.ceil(1.0 + Math.random() * 100.0) < stats.get("cursed")) { return null; } } } return equip; } public IItem getEquipById(int equipId) { return getEquipById(equipId, -1); } public IItem getEquipById(int equipId, int ringId) { Equip nEquip; nEquip = new Equip(equipId, (byte) 0, ringId); nEquip.setQuantity((short) 1); Map<String, Integer> stats = this.getEquipStats(equipId); if (stats != null) { for (Entry<String, Integer> stat : stats.entrySet()) { if (stat.getKey().equals("STR")) { nEquip.setStr((short) stat.getValue().intValue()); } else if (stat.getKey().equals("DEX")) { nEquip.setDex((short) stat.getValue().intValue()); } else if (stat.getKey().equals("INT")) { nEquip.setInt((short) stat.getValue().intValue()); } else if (stat.getKey().equals("LUK")) { nEquip.setLuk((short) stat.getValue().intValue()); } else if (stat.getKey().equals("PAD")) { nEquip.setWatk((short) stat.getValue().intValue()); } else if (stat.getKey().equals("PDD")) { nEquip.setWdef((short) stat.getValue().intValue()); } else if (stat.getKey().equals("MAD")) { nEquip.setMatk((short) stat.getValue().intValue()); } else if (stat.getKey().equals("MDD")) { nEquip.setMdef((short) stat.getValue().intValue()); } else if (stat.getKey().equals("ACC")) { nEquip.setAcc((short) stat.getValue().intValue()); } else if (stat.getKey().equals("EVA")) { nEquip.setAvoid((short) stat.getValue().intValue()); } else if (stat.getKey().equals("Speed")) { nEquip.setSpeed((short) stat.getValue().intValue()); } else if (stat.getKey().equals("Jump")) { nEquip.setJump((short) stat.getValue().intValue()); } else if (stat.getKey().equals("MHP")) { nEquip.setHp((short) stat.getValue().intValue()); } else if (stat.getKey().equals("MMP")) { nEquip.setMp((short) stat.getValue().intValue()); } else if (stat.getKey().equals("tuc")) { nEquip.setUpgradeSlots((byte) stat.getValue().intValue()); } else if (stat.getKey().equals("afterImage")) { } } } equipCache.put(equipId, nEquip); return nEquip.copy(); } private short getRandStat(short defaultValue, int maxRange, short additionalStats) { if (defaultValue == 0) { return 0; } // vary no more than ceil of 10% of stat int lMaxRange = (int) Math.min(Math.ceil(defaultValue * 0.1), maxRange); return (short) ((defaultValue - lMaxRange) + Math.floor(rand.nextDouble() * (lMaxRange * 2 + additionalStats))); } public Equip randomizeStats(MapleClient c, Equip equip) { short x = 1; ChannelServer cserv = c.getChannelServer(); if (cserv.isGodlyItems() && Math.ceil(Math.random() * 100.0) <= cserv.getGodlyItemRate()) { x = cserv.getItemMultiplier(); } equip.setStr(getRandStat(equip.getStr(), 5, x)); equip.setDex(getRandStat(equip.getDex(), 5, x)); equip.setInt(getRandStat(equip.getInt(), 5, x)); equip.setLuk(getRandStat(equip.getLuk(), 5, x)); equip.setMatk(getRandStat(equip.getMatk(), 5, x)); equip.setWatk(getRandStat(equip.getWatk(), 5, x)); equip.setAcc(getRandStat(equip.getAcc(), 5, x)); equip.setAvoid(getRandStat(equip.getAvoid(), 5, x)); equip.setJump(getRandStat(equip.getJump(), 5, x)); equip.setSpeed(getRandStat(equip.getSpeed(), 5, x)); equip.setWdef(getRandStat(equip.getWdef(), 10, x)); equip.setMdef(getRandStat(equip.getMdef(), 10, x)); equip.setHp(getRandStat(equip.getHp(), 10, x)); equip.setMp(getRandStat(equip.getMp(), 10, x)); return equip; } public Equip hardcoreItem(Equip equip, short stat) { equip.setStr(stat); equip.setDex(stat); equip.setInt(stat); equip.setLuk(stat); equip.setMatk(stat); equip.setWatk(stat); equip.setAcc(stat); equip.setAvoid(stat); equip.setJump(stat); equip.setSpeed(stat); equip.setWdef(stat); equip.setMdef(stat); equip.setHp(stat); equip.setMp(stat); return equip; } public MapleStatEffect getItemEffect(int itemId) { MapleStatEffect ret = itemEffects.get(itemId); if (ret == null) { MapleData item = getItemData(itemId); if (item == null) { return null; } MapleData spec = item.getChildByPath("spec"); ret = MapleStatEffect.loadItemEffectFromData(spec, itemId); itemEffects.put(itemId, ret); } return ret; } public int[][] getSummonMobs(int itemId) { MapleData data = getItemData(itemId); int theInt = data.getChildByPath("mob").getChildren().size(); int[][] mobs2spawn = new int[theInt][2]; for (int x = 0; x < theInt; ++x) { mobs2spawn[x][0] = MapleDataTool.getIntConvert("mob/" + x + "/id", data); mobs2spawn[x][1] = MapleDataTool.getIntConvert("mob/" + x + "/prob", data); } return mobs2spawn; } public boolean isThrowingStar(int itemId) { return (itemId >= 2070000 && itemId < 2080000); } public boolean isBullet(int itemId) { int id = itemId / 10000; return id == 233; } public boolean isRechargable(int itemId) { int id = itemId / 10000; return id == 233 || id == 207; } public boolean isOverall(int itemId) { return itemId >= 1050000 && itemId < 1060000; } public boolean isPet(int itemId) { return itemId >= 5000000 && itemId <= 5000100; } public boolean isArrowForCrossBow(int itemId) { return itemId >= 2061000 && itemId < 2062000; } public boolean isArrowForBow(int itemId) { return itemId >= 2060000 && itemId < 2061000; } public boolean isTwoHanded(int itemId) { switch (getWeaponType(itemId)) { case AXE2H: case BLUNT2H: case BOW: case CLAW: case CROSSBOW: case POLE_ARM: case SPEAR: case SWORD2H: case GUN: case KNUCKLE: return true; default: return false; } } public boolean isTownScroll(int itemId) { return (itemId >= 2030000 && itemId < 2030020); } public boolean isGun(int itemId) { return itemId >= 1492000 && itemId <= 1492024; } public int getWatkForProjectile(int itemId) { Integer atk = projectileWatkCache.get(itemId); if (atk != null) { return atk; } MapleData data = getItemData(itemId); atk = MapleDataTool.getInt("info/incPAD", data, 0); projectileWatkCache.put(itemId, atk); return atk; } public boolean canScroll(int scrollid, int itemid) { int scrollCategoryQualifier = (scrollid / 100) % 100; int itemCategoryQualifier = (itemid / 10000) % 100; return scrollCategoryQualifier == itemCategoryQualifier; } public String getName(int itemId) { if (nameCache.containsKey(itemId)) { return nameCache.get(itemId); } MapleData strings = getStringData(itemId); if (strings == null) { return null; } String ret = MapleDataTool.getString("name", strings, null); nameCache.put(itemId, ret); return ret; } public String getDesc(int itemId) { if (descCache.containsKey(itemId)) { return descCache.get(itemId); } MapleData strings = getStringData(itemId); if (strings == null) { return null; } String ret = MapleDataTool.getString("desc", strings, null); descCache.put(itemId, ret); return ret; } public String getMsg(int itemId) { if (msgCache.containsKey(itemId)) { return msgCache.get(itemId); } MapleData strings = getStringData(itemId); if (strings == null) { return null; } String ret = MapleDataTool.getString("msg", strings, null); msgCache.put(itemId, ret); return ret; } public boolean isDropRestricted(int itemId) { if (dropRestrictionCache.containsKey(itemId)) { return dropRestrictionCache.get(itemId); } MapleData data = getItemData(itemId); boolean bRestricted = MapleDataTool.getIntConvert("info/tradeBlock", data, 0) == 1; if (!bRestricted) { bRestricted = MapleDataTool.getIntConvert("info/quest", data, 0) == 1; } dropRestrictionCache.put(itemId, bRestricted); return bRestricted; } public boolean isPickupRestricted(int itemId) { if (pickupRestrictionCache.containsKey(itemId)) { return pickupRestrictionCache.get(itemId); } MapleData data = getItemData(itemId); boolean bRestricted = MapleDataTool.getIntConvert("info/only", data, 0) == 1; pickupRestrictionCache.put(itemId, bRestricted); return bRestricted; } public Map<String, Integer> getSkillStats(int itemId, double playerJob) { Map<String, Integer> ret = new LinkedHashMap<>(); MapleData item = getItemData(itemId); if (item == null) { return null; } MapleData info = item.getChildByPath("info"); if (info == null) { return null; } for (MapleData data : info.getChildren()) { if (data.getName().startsWith("inc")) { ret.put(data.getName().substring(3), MapleDataTool.getIntConvert(data)); } } ret.put("masterLevel", MapleDataTool.getInt("masterLevel", info, 0)); ret.put("reqSkillLevel", MapleDataTool.getInt("reqSkillLevel", info, 0)); ret.put("success", MapleDataTool.getInt("success", info, 0)); MapleData skill = info.getChildByPath("skill"); int curskill = 1; int size = skill.getChildren().size(); for (int i = 0; i < size; ++i) { curskill = MapleDataTool.getInt(Integer.toString(i), skill, 0); if (curskill == 0) { break; } double skillJob = Math.floor(curskill / 10000); if (skillJob == playerJob) { ret.put("skillid", curskill); break; } } ret.putIfAbsent("skillid", 0); return ret; } public List<Integer> petsCanConsume(int itemId) { List<Integer> ret = new ArrayList<>(); MapleData data = getItemData(itemId); int curPetId = 0; int size = data.getChildren().size(); for (int i = 0; i < size; ++i) { curPetId = MapleDataTool.getInt("spec/" + Integer.toString(i), data, 0); if (curPetId == 0) { break; } ret.add(curPetId); } return ret; } protected final Map<Integer, Boolean> isQuestItemCache = new HashMap<>(); public boolean isQuestItem(int itemId) { if (isQuestItemCache.containsKey(itemId)) { return isQuestItemCache.get(itemId); } MapleData data = getItemData(itemId); boolean questItem = MapleDataTool.getIntConvert("info/quest", data, 0) == 1; isQuestItemCache.put(itemId, questItem); return questItem; } }
package org.apache.james.transport.mailets; import java.io.*; import java.util.*; import java.net.*; import org.apache.avalon.*; import org.apache.james.*; import org.apache.james.core.*; import org.apache.james.mailrepository.*; import org.apache.james.transport.*; import org.apache.mailet.*; import org.apache.avalon.blocks.*; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.URLName; import javax.mail.internet.*; /** * Receive a MessageContainer from JamesSpoolManager and takes care of delivery * the message to remote hosts. If for some reason mail can't be delivered * store it in the "outgoing" Repository and set an Alarm. After "delayTime" the * Alarm will wake the servlet that will try to send it again. After "maxRetries" * the mail will be considered underiverable and will be returned to sender. * * @author Serge Knystautas <sergek@lokitech.com> * @author Federico Barbieri <scoobie@pop.systemy.it> */ public class RemoteDelivery extends GenericMailet implements Runnable { private SpoolRepository outgoing; private long delayTime = 21600000; // default is 6*60*60*1000 millis (6 hours) private int maxRetries = 5; // default number of retries private int deliveryThreadCount = 1; // default number of delivery threads private Collection deliveryThreads = new Vector(); private MailServer mailServer; public void init() throws MessagingException { try { delayTime = Long.parseLong(getInitParameter("delayTime")); } catch (Exception e) { } try { maxRetries = Integer.parseInt(getInitParameter("maxRetries")); } catch (Exception e) { } ComponentManager comp = (ComponentManager)getMailetContext().getAttribute(Constants.AVALON_COMPONENT_MANAGER); // Instantiate the a MailRepository for outgoing mails Store store = (Store) comp.getComponent(Interfaces.STORE); String outgoingPath = getInitParameter("outgoing"); if (outgoingPath == null) { outgoingPath = "file:///../var/mail/outgoing"; } outgoing = (SpoolRepository) store.getPrivateRepository(outgoingPath, SpoolRepository.SPOOL, Store.ASYNCHRONOUS); //Start up a number of threads try { deliveryThreadCount = Integer.parseInt(getInitParameter("deliveryThreads")); } catch (Exception e) { } for (int i = 0; i < deliveryThreadCount; i++) { Thread t = new Thread(this, "Remote delivery thread (" + i + ")"); t.start(); deliveryThreads.add(t); } } private void deliver(MailImpl mail) { try { log("attempting to deliver " + mail.getName()); MimeMessage message = mail.getMessage(); Collection recipients = mail.getRecipients(); MailAddress rcpt = (MailAddress) recipients.iterator().next(); String host = rcpt.getHost(); InternetAddress addr[] = new InternetAddress[recipients.size()]; int j = 0; for (Iterator i = recipients.iterator(); i.hasNext(); j++) { rcpt = (MailAddress)i.next(); addr[j] = rcpt.toInternetAddress(); } if (addr.length > 0) { //Lookup the possible targets for (Iterator i = getMailetContext().getMailServers(host).iterator(); i.hasNext();) { try { String outgoingmailserver = i.next().toString (); log("attempting delivery of " + mail.getName() + " to host " + outgoingmailserver); URLName urlname = new URLName("smtp://" + outgoingmailserver); Transport transport = Session.getDefaultInstance(System.getProperties(), null).getTransport(urlname); transport.connect(); transport.sendMessage(message, addr); transport.close(); log("mail (" + mail.getName() + ") sent successfully to " + outgoingmailserver); return; } catch (MessagingException me) { if (!i.hasNext()) { throw me; } } } throw new MessagingException("No route found to " + host); } else { log("no recipients specified... not sure how this could have happened."); } } catch (Exception ex) { //We should do a better job checking this... if the failure is a general //connect exception, this is less descriptive than more specific SMTP command //failure... have to lookup and see what are the various Exception //possibilities //Unable to deliver message after numerous tries... fail accordingly failMessage(mail, "Delivery failure: " + ex.toString(), ex); } } private void failMessage(MailImpl mail, String reason, Exception ex) { log("Exception delivering mail (" + mail.getName() + ": " + ex.toString()); if (!mail.getState().equals(Mail.ERROR)) { mail.setState(Mail.ERROR); mail.setErrorMessage("0"); } int retries = Integer.parseInt(mail.getErrorMessage()); if (retries >= maxRetries) { log("Sending back message " + mail.getName() + " after max (" + retries + ") retries reached"); try { getMailetContext().bounce(mail, reason); } catch (MessagingException me) { log("encountered unexpected messaging exception while bouncing message: " + me.getMessage()); } } else { //Change the name (unique identifier) of this message... we want to save a new copy // of it, so change the unique idea for restoring mail.setName(mail.getName() + retries); log("Storing message " + mail.getName() + " into outgoing after " + retries + " retries"); ++retries; mail.setErrorMessage(retries + ""); outgoing.store(mail); } } public String getMailetInfo() { return "RemoteDelivery Mailet"; } /** * For this message, we take the list of recipients, organize these into distinct * servers, and duplicate the message for each of these servers, and then call * the deliver (messagecontainer) method for each server-specific * messagecontainer ... that will handle storing it in the outgoing queue if needed. * * @param mail org.apache.mailet.Mail * @return org.apache.mailet.MessageContainer */ public void service(Mail genericmail) throws AddressException { MailImpl mail = (MailImpl)genericmail; //Do I want to give the internal key, or the message's Message ID log("Remotely delivering mail " + mail.getName()); Collection recipients = mail.getRecipients(); //Must first organize the recipients into distinct servers (name made case insensitive) Hashtable targets = new Hashtable(); for (Iterator i = recipients.iterator(); i.hasNext();) { MailAddress target = (MailAddress)i.next(); String targetServer = target.getHost().toLowerCase(); Collection temp = (Collection)targets.get(targetServer); if (temp == null) { temp = new Vector(); targets.put(targetServer, temp); } temp.add(target); } //We have the recipients organized into distinct servers... put them into the //delivery store organized like this... this is ultra inefficient I think... //store the new message containers, organized by server, in the outgoing mail repository String name = mail.getName(); for (Iterator i = targets.keySet().iterator(); i.hasNext(); ) { String host = (String) i.next(); Collection rec = (Collection)targets.get(host); log("sending mail to " + rec + " on " + host); mail.setRecipients(rec); mail.setName(name + "-to-" + host); outgoing.store(mail); //Set it to try to deliver (in a separate thread) immediately (triggered by storage) } mail.setState(Mail.GHOST); } public void destroy() { //Wake up all threads from waiting for an accept notifyAll(); for (Iterator i = deliveryThreads.iterator(); i.hasNext(); ) { Thread t = (Thread)i.next(); t.interrupt(); } } public void wake(String name, String memo) { log("waking for " + name + " with memo: " + memo); MailImpl mail = outgoing.retrieve(name); deliver(mail); outgoing.remove(name); } /** * Handles checking the outgoing spool for new mail and delivering them if * there are any */ public void run() { //Checks the pool and delivers a mail message while (!Thread.currentThread().interrupted()) { try { String key = outgoing.accept(delayTime); log(Thread.currentThread().getName() + " will process mail " + key); MailImpl mail = outgoing.retrieve(key); deliver(mail); outgoing.remove(key); } catch (Exception e) { } } } }
package org.ensembl.healthcheck.testcase.variation; import java.sql.Connection; import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.Species; /** * Checks the source table to make sure it is OK. Only for mouse databse, to check external sources * */ public class Source extends SingleDatabaseTestCase { /** * Creates a new instance of CheckSourceDataTableTestCase */ public Source() { /*addToGroup("variation"); addToGroup("release");*/ setDescription("Check that the source table contains the right entries for mouse"); } /** * Check various aspects of the meta table. * * @param dbre The database to check. * @return True if the test passed. */ public boolean run(final DatabaseRegistryEntry dbre) { boolean result = true; Connection con = dbre.getConnection(); if (dbre.getSpecies() == Species.MUS_MUSCULUS){ String source = "Sanger"; int mc = getRowCount(con,"SELECT COUNT(*) FROM source WHERE name = '" + source + "' AND version IS NULL"); if (mc == 0){ ReportManager.problem(this, con, "No entry for source " + source + " or has a not NULL version in Source table"); result = false; } else{ ReportManager.correct(this, con, "Source table correct in mouse"); } } return result; } // run }
package org.nschmidt.ldparteditor.data; import java.util.ArrayList; import java.util.HashMap; import org.lwjgl.util.vector.Matrix4f; import org.lwjgl.util.vector.Vector3f; import org.lwjgl.util.vector.Vector4f; import org.nschmidt.ldparteditor.enums.View; import org.nschmidt.ldparteditor.opengl.GL33Helper; import org.nschmidt.ldparteditor.opengl.GLShader; import org.nschmidt.ldparteditor.opengl.OpenGLRenderer; public enum GL33TexmapRenderer { INSTANCE; public static void render(ArrayList<GDataAndTexture> texmapData, GLShader mainShader, OpenGLRenderer renderer, HashMap<GData, Vector3f[]> normalMap, HashMap<GData, Vertex[]> vertexMap, boolean smoothShading) { GTexture lastTexture = null; float[] uv; float[] triVertices = new float[36]; float[] quadVertices = new float[48]; final Vector4f Nv = new Vector4f(0, 0, 0, 1f); final HashMap<GData1, Matrix4f> matrixMap = new HashMap<>(); int[] triIndices = new int[]{0, 1, 2}; int[] quadIndices = new int[]{0, 1, 2, 2, 3, 0}; int[] triIndicesNOCLIP = new int[]{0, 2, 1}; int[] quadIndicesNOCLIP = new int[]{0, 3, 2, 2, 1, 0}; boolean texmap = true; for (GDataAndTexture gw : texmapData) { final GTexture tex = gw.texture; final GData gd = gw.data; if (tex != GTexture.NO_TEXTURE && tex != lastTexture) { lastTexture = tex; lastTexture.refreshCache(); lastTexture.bindGL33(renderer, mainShader); } if (texmap && tex == GTexture.NO_TEXTURE) { mainShader.texmapOff(); texmap = false; } else if (!texmap && tex != GTexture.NO_TEXTURE){ mainShader.texmapOn(); texmap = true; } switch (gd.type()) { case 3: GData3 gd3 = (GData3) gd; Vertex[] v = vertexMap.get(gd); Vector3f[] n = normalMap.get(gd); if (n == null) { Nv.x = gd3.xn; Nv.y = gd3.yn; Nv.z = gd3.zn; Nv.w = 1f; Matrix4f loc = matrixMap.get(gd3.parent); if (loc == null) { final Matrix4f rotation = new Matrix4f(gd3.parent.productMatrix); rotation.m30 = 0f; rotation.m31 = 0f; rotation.m32 = 0f; rotation.invert(); rotation.transpose(); matrixMap.put(gd3.parent, rotation); loc = rotation; } Matrix4f.transform(loc, Nv, Nv); n = new Vector3f[3]; n[0] = new Vector3f(Nv.x, Nv.y, Nv.z); n[1] = n[0]; n[2] = n[0]; } if (lastTexture != null && v != null) { lastTexture.calcUVcoords1(gd3.x1, gd3.y1, gd3.z1, gd3.parent, gd); lastTexture.calcUVcoords2(gd3.x2, gd3.y2, gd3.z2, gd3.parent); lastTexture.calcUVcoords3(gd3.x3, gd3.y3, gd3.z3, gd3.parent); uv = lastTexture.getUVcoords(true, gd); GColour c = View.getLDConfigColour(View.getLDConfigIndex(gd3.r, gd3.g, gd3.b)); GColourType ct = c.getType(); boolean hasColourType = ct != null; if (hasColourType) { switch (ct.type()) { case CHROME: colourise(3, gd3.r, gd3.g, gd3.b, 2f, triVertices); break; case MATTE_METALLIC: colourise(3, gd3.r, gd3.g, gd3.b, 4.2f, triVertices); break; case METAL: colourise(3, gd3.r, gd3.g, gd3.b, 3.2f, triVertices); break; case RUBBER: colourise(3, gd3.r, gd3.g, gd3.b, 5.2f, triVertices); break; default: colourise(3, gd3.r, gd3.g, gd3.b, gd3.a, triVertices); break; } } else { colourise(3, gd3.r, gd3.g, gd3.b, gd3.a, triVertices); } switch (gw.winding) { case BFC.CW: if (smoothShading) { if (gw.invertNext ^ gw.negativeDeterminant) { normal(0, n[0].x, n[0].y, n[0].z, triVertices); normal(1, n[2].x, n[2].y, n[2].z, triVertices); normal(2, n[1].x, n[1].y, n[1].z, triVertices); } else { normal(0, n[0].x, n[0].y, n[0].z, triVertices); normal(1, n[1].x, n[1].y, n[1].z, triVertices); normal(2, n[2].x, n[2].y, n[2].z, triVertices); } } else { if (gw.invertNext) { normal(0, n[0].x, n[0].y, n[0].z, triVertices); normal(1, n[1].x, n[1].y, n[1].z, triVertices); normal(2, n[2].x, n[2].y, n[2].z, triVertices); } else { normal(0, -n[0].x, -n[0].y, -n[0].z, triVertices); normal(1, -n[1].x, -n[1].y, -n[1].z, triVertices); normal(2, -n[2].x, -n[2].y, -n[2].z, triVertices); } } if (gw.negativeDeterminant ^ gw.invertNext) { pointAt(0, v[0].x, v[0].y, v[0].z, triVertices); pointAt(1, v[2].x, v[2].y, v[2].z, triVertices); pointAt(2, v[1].x, v[1].y, v[1].z, triVertices); uv(0, uv[0], uv[1], triVertices); uv(1, uv[4], uv[5], triVertices); uv(2, uv[2], uv[3], triVertices); } else { pointAt(0, v[0].x, v[0].y, v[0].z, triVertices); pointAt(1, v[1].x, v[1].y, v[1].z, triVertices); pointAt(2, v[2].x, v[2].y, v[2].z, triVertices); uv(0, uv[0], uv[1], triVertices); uv(1, uv[2], uv[3], triVertices); uv(2, uv[4], uv[5], triVertices); } break; case BFC.CCW: if (smoothShading) { if (gw.invertNext ^ gw.negativeDeterminant) { normal(0, n[0].x, n[0].y, n[0].z, triVertices); normal(1, n[1].x, n[1].y, n[1].z, triVertices); normal(2, n[2].x, n[2].y, n[2].z, triVertices); } else { normal(0, n[0].x, n[0].y, n[0].z, triVertices); normal(1, n[2].x, n[2].y, n[2].z, triVertices); normal(2, n[1].x, n[1].y, n[1].z, triVertices); } } else { if (gw.invertNext) { normal(0, -n[0].x, -n[0].y, -n[0].z, triVertices); normal(1, -n[1].x, -n[1].y, -n[1].z, triVertices); normal(2, -n[2].x, -n[2].y, -n[2].z, triVertices); } else { normal(0, n[0].x, n[0].y, n[0].z, triVertices); normal(1, n[1].x, n[1].y, n[1].z, triVertices); normal(2, n[2].x, n[2].y, n[2].z, triVertices); } } if (gw.negativeDeterminant ^ gw.invertNext) { pointAt(0, v[0].x, v[0].y, v[0].z, triVertices); pointAt(1, v[1].x, v[1].y, v[1].z, triVertices); pointAt(2, v[2].x, v[2].y, v[2].z, triVertices); uv(0, uv[0], uv[1], triVertices); uv(1, uv[2], uv[3], triVertices); uv(2, uv[4], uv[5], triVertices); } else { pointAt(0, v[0].x, v[0].y, v[0].z, triVertices); pointAt(1, v[2].x, v[2].y, v[2].z, triVertices); pointAt(2, v[1].x, v[1].y, v[1].z, triVertices); uv(0, uv[0], uv[1], triVertices); uv(1, uv[4], uv[5], triVertices); uv(2, uv[2], uv[3], triVertices); } break; case BFC.NOCERTIFY: default: colourise(3, 0f, 0f, 0f, 0f, triVertices); continue; } GL33Helper.drawTrianglesIndexedTextured_GeneralSlow(triVertices, triIndices); if (gw.noclip || gd3.a < 1f) { flipnormals(3, triVertices); GL33Helper.drawTrianglesIndexedTextured_GeneralSlow(triVertices, triIndicesNOCLIP); } } continue; case 4: GData4 gd4 = (GData4) gd; v = vertexMap.get(gd); n = normalMap.get(gd); if (n == null) { Nv.x = gd4.xn; Nv.y = gd4.yn; Nv.z = gd4.zn; Nv.w = 1f; Matrix4f loc = matrixMap.get(gd4.parent); if (loc == null) { final Matrix4f rotation = new Matrix4f(gd4.parent.productMatrix); rotation.m30 = 0f; rotation.m31 = 0f; rotation.m32 = 0f; rotation.invert(); rotation.transpose(); matrixMap.put(gd4.parent, rotation); loc = rotation; } Matrix4f.transform(loc, Nv, Nv); n = new Vector3f[4]; n[0] = new Vector3f(Nv.x, Nv.y, Nv.z); n[1] = n[0]; n[2] = n[0]; n[3] = n[0]; } if (lastTexture != null && v != null) { lastTexture.calcUVcoords1(gd4.x1, gd4.y1, gd4.z1, gd4.parent, gd); lastTexture.calcUVcoords2(gd4.x2, gd4.y2, gd4.z2, gd4.parent); lastTexture.calcUVcoords3(gd4.x3, gd4.y3, gd4.z3, gd4.parent); lastTexture.calcUVcoords4(gd4.x4, gd4.y4, gd4.z4, gd4.parent); uv = lastTexture.getUVcoords(false, gd); GColour c = View.getLDConfigColour(View.getLDConfigIndex(gd4.r, gd4.g, gd4.b)); GColourType ct = c.getType(); boolean hasColourType = ct != null; if (hasColourType) { switch (ct.type()) { case CHROME: colourise(4, gd4.r, gd4.g, gd4.b, 2f, quadVertices); break; case MATTE_METALLIC: colourise(4, gd4.r, gd4.g, gd4.b, 4.2f, quadVertices); break; case METAL: colourise(4, gd4.r, gd4.g, gd4.b, 3.2f, quadVertices); break; case RUBBER: colourise(4, gd4.r, gd4.g, gd4.b, 5.2f, quadVertices); break; default: colourise(4, gd4.r, gd4.g, gd4.b, gd4.a, quadVertices); break; } } else { colourise(4, gd4.r, gd4.g, gd4.b, gd4.a, quadVertices); } switch (gw.winding) { case BFC.CW: if (smoothShading) { if (gw.invertNext ^ gw.negativeDeterminant) { normal(0, n[0].x, n[0].y, n[0].z, quadVertices); normal(1, n[3].x, n[3].y, n[3].z, quadVertices); normal(2, n[2].x, n[2].y, n[2].z, quadVertices); normal(3, n[1].x, n[1].y, n[1].z, quadVertices); } else { normal(0, n[0].x, n[0].y, n[0].z, quadVertices); normal(1, n[1].x, n[1].y, n[1].z, quadVertices); normal(2, n[2].x, n[2].y, n[2].z, quadVertices); normal(3, n[3].x, n[3].y, n[3].z, quadVertices); } } else { if (gw.invertNext) { normal(0, n[0].x, n[0].y, n[0].z, quadVertices); normal(1, n[1].x, n[1].y, n[1].z, quadVertices); normal(2, n[2].x, n[2].y, n[2].z, quadVertices); normal(3, n[3].x, n[3].y, n[3].z, quadVertices); } else { normal(0, -n[0].x, -n[0].y, -n[0].z, quadVertices); normal(1, -n[1].x, -n[1].y, -n[1].z, quadVertices); normal(2, -n[2].x, -n[2].y, -n[2].z, quadVertices); normal(3, -n[3].x, -n[3].y, -n[3].z, quadVertices); } } if (gw.negativeDeterminant ^ gw.invertNext) { pointAt(0, v[0].x, v[0].y, v[0].z, quadVertices); pointAt(1, v[3].x, v[3].y, v[3].z, quadVertices); pointAt(2, v[2].x, v[2].y, v[2].z, quadVertices); pointAt(3, v[1].x, v[1].y, v[1].z, quadVertices); uv(0, uv[0], uv[1], quadVertices); uv(1, uv[6], uv[7], quadVertices); uv(2, uv[4], uv[5], quadVertices); uv(3, uv[2], uv[3], quadVertices); } else { pointAt(0, v[0].x, v[0].y, v[0].z, quadVertices); pointAt(1, v[1].x, v[1].y, v[1].z, quadVertices); pointAt(2, v[2].x, v[2].y, v[2].z, quadVertices); pointAt(3, v[3].x, v[3].y, v[3].z, quadVertices); uv(0, uv[0], uv[1], quadVertices); uv(1, uv[2], uv[3], quadVertices); uv(2, uv[4], uv[5], quadVertices); uv(3, uv[6], uv[7], quadVertices); } break; case BFC.CCW: if (smoothShading) { if (gw.invertNext ^ gw.negativeDeterminant) { normal(0, n[0].x, n[0].y, n[0].z, quadVertices); normal(1, n[1].x, n[1].y, n[1].z, quadVertices); normal(2, n[2].x, n[2].y, n[2].z, quadVertices); normal(3, n[3].x, n[3].y, n[3].z, quadVertices); } else { normal(0, n[0].x, n[0].y, n[0].z, quadVertices); normal(1, n[3].x, n[3].y, n[3].z, quadVertices); normal(2, n[2].x, n[2].y, n[2].z, quadVertices); normal(3, n[1].x, n[1].y, n[1].z, quadVertices); } } else { if (gw.invertNext) { normal(0, -n[0].x, -n[0].y, -n[0].z, quadVertices); normal(1, -n[1].x, -n[1].y, -n[1].z, quadVertices); normal(2, -n[2].x, -n[2].y, -n[2].z, quadVertices); normal(3, -n[3].x, -n[3].y, -n[3].z, quadVertices); } else { normal(0, n[0].x, n[0].y, n[0].z, quadVertices); normal(1, n[1].x, n[1].y, n[1].z, quadVertices); normal(2, n[2].x, n[2].y, n[2].z, quadVertices); normal(3, n[3].x, n[3].y, n[3].z, quadVertices); } } if (gw.negativeDeterminant ^ gw.invertNext) { pointAt(0, v[0].x, v[0].y, v[0].z, quadVertices); pointAt(1, v[1].x, v[1].y, v[1].z, quadVertices); pointAt(2, v[2].x, v[2].y, v[2].z, quadVertices); pointAt(3, v[3].x, v[3].y, v[3].z, quadVertices); uv(0, uv[0], uv[1], quadVertices); uv(1, uv[2], uv[3], quadVertices); uv(2, uv[4], uv[5], quadVertices); uv(3, uv[6], uv[7], quadVertices); } else { pointAt(0, v[0].x, v[0].y, v[0].z, quadVertices); pointAt(1, v[3].x, v[3].y, v[3].z, quadVertices); pointAt(2, v[2].x, v[2].y, v[2].z, quadVertices); pointAt(3, v[1].x, v[1].y, v[1].z, quadVertices); uv(0, uv[0], uv[1], quadVertices); uv(1, uv[6], uv[7], quadVertices); uv(2, uv[4], uv[5], quadVertices); uv(3, uv[2], uv[3], quadVertices); } break; case BFC.NOCERTIFY: default: colourise(4, 0f, 0f, 0f, 0f, quadVertices); continue; } GL33Helper.drawTrianglesIndexedTextured_GeneralSlow(quadVertices, quadIndices); if (gw.noclip || gd4.a < 1f) { flipnormals(4, quadVertices); GL33Helper.drawTrianglesIndexedTextured_GeneralSlow(quadVertices, quadIndicesNOCLIP); } } continue; default: } } } private static void flipnormals(int i, float[] data) { for (int j = 0; j < i; j++) { int k = j * 12; data[k + 3] = -data[k + 3]; data[k + 4] = -data[k + 4]; data[k + 5] = -data[k + 5]; } } private static void pointAt(int i, float x, float y, float z, float[] data) { int j = i * 12; data[j] = x; data[j + 1] = y; data[j + 2] = z; } private static void normal(int i, float x, float y, float z, float[] data) { int j = i * 12; data[j + 3] = x; data[j + 4] = y; data[j + 5] = z; } private static void colourise(int i, float r, float g, float b, float a, float[] data) { for (int j = 0; j < i; j++) { int k = j * 12; data[k + 6] = r; data[k + 7] = g; data[k + 8] = b; data[k + 9] = a; } } private static void uv(int i, float u, float v, float[] data) { int j = i * 12; data[j + 10] = u; data[j + 11] = v; } }
package org.pentaho.di.cluster.dialog; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.pentaho.di.cluster.ClusterSchema; import org.pentaho.di.cluster.SlaveServer; import org.pentaho.di.core.Props; import org.pentaho.di.core.dialog.EnterSelectionDialog; import org.pentaho.di.core.gui.GUIResource; import org.pentaho.di.trans.step.BaseStepDialog; import org.pentaho.di.core.widget.ColumnInfo; import org.pentaho.di.core.Const; import org.pentaho.di.core.gui.WindowProperty; import org.pentaho.di.core.widget.TableView; import org.pentaho.di.core.widget.TextVar; /** * * Dialog that allows you to edit the settings of the cluster schema * * @see ClusterSchema * @author Matt * @since 17-11-2006 * */ public class ClusterSchemaDialog extends Dialog { private ClusterSchema clusterSchema; private Shell shell; // Name private Text wName; // Servers private TableView wServers; private Button wOK, wCancel; private ModifyListener lsMod; private Props props; private int middle; private int margin; private ClusterSchema originalSchema; private boolean ok; private Button wSelect; private TextVar wPort; private TextVar wBufferSize; private TextVar wFlushInterval; private Button wCompressed; private List slaveServers; public ClusterSchemaDialog(Shell par, ClusterSchema clusterSchema, List slaveServers) { super(par, SWT.NONE); this.clusterSchema=(ClusterSchema) clusterSchema.clone(); this.originalSchema=clusterSchema; this.slaveServers = slaveServers; props=Props.getInstance(); ok=false; } public boolean open() { Shell parent = getParent(); shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN ); props.setLook(shell); shell.setImage( GUIResource.getInstance().getImageConnection()); lsMod = new ModifyListener() { public void modifyText(ModifyEvent e) { clusterSchema.setChanged(); } }; middle = props.getMiddlePct(); margin = Const.MARGIN; FormLayout formLayout = new FormLayout (); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setText(Messages.getString("ClusterSchemaDialog.Shell.Title")); shell.setLayout (formLayout); // First, add the buttons... // Buttons wOK = new Button(shell, SWT.PUSH); wOK.setText(" &OK "); wCancel = new Button(shell, SWT.PUSH); wCancel.setText(" &Cancel "); Button[] buttons = new Button[] { wOK, wCancel }; BaseStepDialog.positionBottomButtons(shell, buttons, margin, null); // The rest stays above the buttons, so we added those first... // What's the schema name?? Label wlName = new Label(shell, SWT.RIGHT); props.setLook(wlName); wlName.setText(Messages.getString("ClusterSchemaDialog.Schema.Label")); FormData fdlName = new FormData(); fdlName.top = new FormAttachment(0, 0); fdlName.left = new FormAttachment(0, 0); // First one in the left top corner fdlName.right = new FormAttachment(middle, 0); wlName.setLayoutData(fdlName); wName = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook(wName); wName.addModifyListener(lsMod); FormData fdName = new FormData(); fdName.top = new FormAttachment(0, 0); fdName.left = new FormAttachment(middle, margin); // To the right of the label fdName.right= new FormAttachment(95, 0); wName.setLayoutData(fdName); // What's the base port?? Label wlPort = new Label(shell, SWT.RIGHT); props.setLook(wlPort); wlPort.setText(Messages.getString("ClusterSchemaDialog.Port.Label")); FormData fdlPort = new FormData(); fdlPort.top = new FormAttachment(wName, margin); fdlPort.left = new FormAttachment(0, 0); // First one in the left top corner fdlPort.right = new FormAttachment(middle, 0); wlPort.setLayoutData(fdlPort); wPort = new TextVar(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook(wPort); wPort.addModifyListener(lsMod); FormData fdPort = new FormData(); fdPort.top = new FormAttachment(wName, margin); fdPort.left = new FormAttachment(middle, margin); // To the right of the label fdPort.right= new FormAttachment(95, 0); wPort.setLayoutData(fdPort); // What are the sockets buffer sizes?? Label wlBufferSize = new Label(shell, SWT.RIGHT); props.setLook(wlBufferSize); wlBufferSize.setText(Messages.getString("ClusterSchemaDialog.SocketBufferSize.Label")); FormData fdlBufferSize = new FormData(); fdlBufferSize.top = new FormAttachment(wPort, margin); fdlBufferSize.left = new FormAttachment(0, 0); // First one in the left top corner fdlBufferSize.right = new FormAttachment(middle, 0); wlBufferSize.setLayoutData(fdlBufferSize); wBufferSize = new TextVar(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook(wBufferSize); wBufferSize.addModifyListener(lsMod); FormData fdBufferSize = new FormData(); fdBufferSize.top = new FormAttachment(wPort, margin); fdBufferSize.left = new FormAttachment(middle, margin); // To the right of the label fdBufferSize.right= new FormAttachment(95, 0); wBufferSize.setLayoutData(fdBufferSize); // What are the sockets buffer sizes?? Label wlFlushInterval = new Label(shell, SWT.RIGHT); props.setLook(wlFlushInterval); wlFlushInterval.setText(Messages.getString("ClusterSchemaDialog.SocketFlushRows.Label")); FormData fdlFlushInterval = new FormData(); fdlFlushInterval.top = new FormAttachment(wBufferSize, margin); fdlFlushInterval.left = new FormAttachment(0, 0); // First one in the left top corner fdlFlushInterval.right = new FormAttachment(middle, 0); wlFlushInterval.setLayoutData(fdlFlushInterval); wFlushInterval = new TextVar(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook(wFlushInterval); wFlushInterval.addModifyListener(lsMod); FormData fdFlushInterval = new FormData(); fdFlushInterval.top = new FormAttachment(wBufferSize, margin); fdFlushInterval.left = new FormAttachment(middle, margin); // To the right of the label fdFlushInterval.right= new FormAttachment(95, 0); wFlushInterval.setLayoutData(fdFlushInterval); // What are the sockets buffer sizes?? Label wlCompressed = new Label(shell, SWT.RIGHT); props.setLook(wlCompressed); wlCompressed.setText(Messages.getString("ClusterSchemaDialog.SocketDataCompressed.Label")); FormData fdlCompressed = new FormData(); fdlCompressed.top = new FormAttachment(wFlushInterval, margin); fdlCompressed.left = new FormAttachment(0, 0); // First one in the left top corner fdlCompressed.right = new FormAttachment(middle, 0); wlCompressed.setLayoutData(fdlCompressed); wCompressed = new Button(shell, SWT.CHECK ); props.setLook(wCompressed); FormData fdCompressed = new FormData(); fdCompressed.top = new FormAttachment(wFlushInterval, margin); fdCompressed.left = new FormAttachment(middle, margin); // To the right of the label fdCompressed.right= new FormAttachment(95, 0); wCompressed.setLayoutData(fdCompressed); // Schema servers: Label wlServers = new Label(shell, SWT.RIGHT); wlServers.setText(Messages.getString("ClusterSchemaDialog.SlaveServers.Label")); props.setLook(wlServers); FormData fdlServers=new FormData(); fdlServers.left = new FormAttachment(0, 0); fdlServers.right = new FormAttachment(middle, 0); fdlServers.top = new FormAttachment(wCompressed, margin); wlServers.setLayoutData(fdlServers); // Some buttons to manage... wSelect = new Button(shell, SWT.PUSH); wSelect.setText(Messages.getString("ClusterSchemaDialog.SelectSlaveServers.Label")); props.setLook(wSelect); FormData fdSelect=new FormData(); fdSelect.right= new FormAttachment(100, 0); fdSelect.top = new FormAttachment(wlServers, 5*margin); wSelect.setLayoutData(fdSelect); wSelect.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { selectSlaveServers(); }}); ColumnInfo[] partitionColumns = new ColumnInfo[] { new ColumnInfo( Messages.getString("ClusterSchemaDialog.ColumnInfoName.Label"), ColumnInfo.COLUMN_TYPE_TEXT, true, false), //$NON-NLS-1$ new ColumnInfo( Messages.getString("ClusterSchemaDialog.ColumnInfoServiceURL.Label"), ColumnInfo.COLUMN_TYPE_TEXT, true, true), //$NON-NLS-1$ new ColumnInfo( Messages.getString("ClusterSchemaDialog.ColumnInfoMaster.Label"), ColumnInfo.COLUMN_TYPE_TEXT, true, true), //$NON-NLS-1$ }; wServers = new TableView(shell, SWT.BORDER | SWT.FULL_SELECTION | SWT.SINGLE, partitionColumns, 1, lsMod, props); wServers.setReadonly(false); props.setLook(wServers); FormData fdServers = new FormData(); fdServers.left = new FormAttachment(middle, margin ); fdServers.right = new FormAttachment(wSelect, -2*margin); fdServers.top = new FormAttachment(wCompressed, margin); fdServers.bottom = new FormAttachment(wOK, -margin * 2); wServers.setLayoutData(fdServers); wServers.table.addSelectionListener(new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { editSlaveServer(); }}); // Add listeners wOK.addListener(SWT.Selection, new Listener () { public void handleEvent (Event e) { ok(); } } ); wCancel.addListener(SWT.Selection, new Listener () { public void handleEvent (Event e) { cancel(); } } ); SelectionAdapter selAdapter=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } }; wName.addSelectionListener(selAdapter); wPort.addSelectionListener(selAdapter); wBufferSize.addSelectionListener(selAdapter); wFlushInterval.addSelectionListener(selAdapter); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } ); getData(); BaseStepDialog.setSize(shell); shell.open(); Display display = parent.getDisplay(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return ok; } private void editSlaveServer() { int idx = wServers.getSelectionIndex(); if (idx>=0) { SlaveServer slaveServer = clusterSchema.findSlaveServer(wServers.getItems(0)[idx]); if (slaveServer!=null) { SlaveServerDialog dialog = new SlaveServerDialog(shell, slaveServer); if (dialog.open()) { refreshSlaveServers(); } } } } private void selectSlaveServers() { String[] names = SlaveServer.getSlaveServerNames(slaveServers); int idx[] = Const.indexsOfFoundStrings(wServers.getItems(0), names); EnterSelectionDialog dialog = new EnterSelectionDialog(shell, names, Messages.getString("ClusterSchemaDialog.SelectServers.Label"), Messages.getString("ClusterSchemaDialog.SelectServersCluster.Label")); dialog.setSelectedNrs(idx); dialog.setMulti(true); if (dialog.open()!=null) { clusterSchema.getSlaveServers().clear(); int[] indeces = dialog.getSelectionIndeces(); for (int i=0;i<indeces.length;i++) { SlaveServer slaveServer = SlaveServer.findSlaveServer(slaveServers, names[indeces[i]]); clusterSchema.getSlaveServers().add(slaveServer); } refreshSlaveServers(); } } public void dispose() { props.setScreen(new WindowProperty(shell)); shell.dispose(); } public void getData() { wName.setText( Const.NVL(clusterSchema.getName(), "") ); wPort.setText( Const.NVL(clusterSchema.getBasePort(), "")); wBufferSize.setText( Const.NVL(clusterSchema.getSocketsBufferSize(), "")); wFlushInterval.setText( Const.NVL(clusterSchema.getSocketsFlushInterval(), "")); wCompressed.setSelection( clusterSchema.isSocketsCompressed()); refreshSlaveServers(); wName.setFocus(); } private void refreshSlaveServers() { wServers.clearAll(false); List slaveServers = clusterSchema.getSlaveServers(); for (int i=0;i<slaveServers.size();i++) { TableItem item = new TableItem(wServers.table, SWT.NONE); SlaveServer slaveServer = (SlaveServer)slaveServers.get(i); item.setText(1, Const.NVL(slaveServer.getName(), "")); item.setText(2, Const.NVL(slaveServer.toString(), "")); item.setText(3, slaveServer.isMaster()?"Y":"N"); } wServers.removeEmptyRows(); wServers.setRowNums(); wServers.optWidth(true); } private void cancel() { originalSchema = null; dispose(); } public void ok() { getInfo(); originalSchema.setName(clusterSchema.getName()); originalSchema.setBasePort(clusterSchema.getBasePort()); originalSchema.setSocketsBufferSize(clusterSchema.getSocketsBufferSize()); originalSchema.setSocketsFlushInterval(clusterSchema.getSocketsFlushInterval()); originalSchema.setSocketsCompressed(clusterSchema.isSocketsCompressed()); originalSchema.setSlaveServers(clusterSchema.getSlaveServers()); originalSchema.setChanged(); ok=true; dispose(); } private void getInfo() { clusterSchema.setName(wName.getText()); clusterSchema.setBasePort(wPort.getText()); clusterSchema.setSocketsBufferSize(wBufferSize.getText()); clusterSchema.setSocketsFlushInterval(wFlushInterval.getText()); clusterSchema.setSocketsCompressed(wCompressed.getSelection()); String[] names = SlaveServer.getSlaveServerNames(slaveServers); int idx[] = Const.indexsOfFoundStrings(wServers.getItems(0), names); clusterSchema.getSlaveServers().clear(); for (int i=0;i<idx.length;i++) { SlaveServer slaveServer = SlaveServer.findSlaveServer(slaveServers, names[idx[i]]); clusterSchema.getSlaveServers().add(slaveServer); } } }
package org.spurint.android.viewcontroller; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; public abstract class ViewController { private final int layoutId; private final Activity activity; private final View contentView; private NavigationController navigationController; public ViewController(Activity activity, int layoutId) { if (activity == null) throw new IllegalArgumentException("Activity cannot be null"); if (layoutId == 0) throw new IllegalArgumentException("Layout ID cannot be 0"); this.activity = activity; this.layoutId = layoutId; this.contentView = LayoutInflater.from(activity).inflate(this.layoutId, null); } public void attachContentView() { activity.setContentView(contentView); } protected void _setNavigationController(NavigationController navigationController) { this.navigationController = navigationController; } protected NavigationController getNavigationController() { return navigationController; } protected int getLayoutId() { return layoutId; } protected Activity getActivity() { return activity; } protected View getContentView() { return contentView; } }
package org.usfirst.frc.team910.robot.Functions; import org.usfirst.frc.team910.robot.IO.Inputs; import org.usfirst.frc.team910.robot.IO.Outputs; import org.usfirst.frc.team910.robot.IO.Sensors; import org.usfirst.frc.team910.robot.Subsystems.Climber; import org.usfirst.frc.team910.robot.Subsystems.DriveTrain; import org.usfirst.frc.team910.robot.Vision.Target; import edu.wpi.first.wpilibj.Timer; public class AutoClimb { private static final double DRIVE_POWER = 0.2; private static final double ALLOWABLE_ANGLE_ERROR = .5; private static final double LAG_TIME = 0.1; private static final double ALLOWABLE_DISTANCE_ERROR = 1; private static final double CLIMB_POWER = 0.9; private static final double DRIVE_TIME = 0.5; private Inputs in; private Outputs out; private Sensors sense; private DriveTrain drive; private Climber climb; public AutoClimb(Inputs in, Sensors sense, DriveTrain drive, Climber climb) { this.in = in; this.sense = sense; this.drive = drive; this.climb = climb; } private enum ClimbState { CAM_CHECK, DRIVE, DRIVE2, CLIMB }; private ClimbState climbState = ClimbState.values()[0]; private Target currentTarget; private double endTime = 0; public void run() { if (in.autoClimb) { currentTarget = sense.camera.rope.getCurrentTarget(); switch (climbState) { case CAM_CHECK: if (Timer.getFPGATimestamp() - currentTarget.time < LAG_TIME) { climbState = ClimbState.DRIVE; } break; case DRIVE: drive.originAngle.set(sense.robotAngle.get() + sense.cameraAngle.get()); drive.driveStraightNavX(false, DRIVE_POWER, 0); if ((currentTarget.distance) < ALLOWABLE_DISTANCE_ERROR) { climbState = ClimbState.DRIVE2; endTime = Timer.getFPGATimestamp() + DRIVE_TIME; } break; case DRIVE2: drive.originAngle.set(sense.robotAngle.get() + sense.cameraAngle.get()); drive.driveStraightNavX(false, DRIVE_POWER, 0); climb.forward(CLIMB_POWER); if(Timer.getFPGATimestamp() > endTime) { climbState = climbState.CLIMB; } break; case CLIMB: climb.forward(CLIMB_POWER); } } } }
package swift.application; import swift.client.SwiftImpl; import swift.crdt.CRDTIdentifier; import swift.crdt.IntegerTxnLocal; import swift.crdt.interfaces.CachePolicy; import swift.crdt.interfaces.IsolationLevel; import swift.crdt.interfaces.TxnHandle; import swift.dc.DCConstants; import swift.dc.DCSequencerServer; import swift.dc.DCServer; import sys.Sys; /** * Manual test client that stresses the system correctness by issuing mixed * workload of transactions with different isolation levels. * * @author mzawirski */ public class ClientIsolationLevelsStressTest { private static final int TRANSACTIONS_PER_CLIENT = 100; private static final int CLIENTS_NUMBER = 10; static String sequencerName = "localhost"; public static void main(String[] args) { // start sequencer server DCSequencerServer sequencer = new DCSequencerServer(sequencerName); sequencer.start(); // start DC server DCServer.main(new String[] { sequencerName }); Sys.init(); final Thread[] clientThreads = new Thread[CLIENTS_NUMBER]; for (int i = 0; i < clientThreads.length; i++) { final int portId = i + 2000; Thread clientThread = new Thread("client" + i) { public void run() { SwiftImpl client = SwiftImpl.newInstance(portId, "localhost", DCConstants.SURROGATE_PORT); runTransactions(client, portId); client.stop(true); } }; clientThreads[i] = clientThread; clientThread.start(); } for (int i = 0; i < clientThreads.length; i++) { try { clientThreads[i].join(); } catch (InterruptedException e) { } } System.out.println("clients done with processing, stopping gracefully"); System.exit(0); } private static void runTransactions(SwiftImpl client, final int clientId) { try { for (int i = 0; i < TRANSACTIONS_PER_CLIENT; i++) { TxnHandle txn = client.beginTxn(i % 2 == 0 ? IsolationLevel.SNAPSHOT_ISOLATION : IsolationLevel.REPEATABLE_READS, CachePolicy.STRICTLY_MOST_RECENT, false); IntegerTxnLocal i1 = txn.get(new CRDTIdentifier("tests", "1"), true, swift.crdt.IntegerVersioned.class, TxnHandle.DUMMY_UPDATES_SUBSCRIBER); IntegerTxnLocal i2 = txn.get(new CRDTIdentifier("tests", "2"), true, swift.crdt.IntegerVersioned.class, TxnHandle.DUMMY_UPDATES_SUBSCRIBER); // Play with 2 integer counters a bit. final int i1OldValue = i1.getValue(); final int i2OldValue = i2.getValue(); if (clientId % 2 == 0) { i1.add(i2.getValue() - i1OldValue + 1); } else { i2.add(i1.getValue() - i2OldValue + 1); } System.out.printf("client%d: i1.old=%d, i2.old=%d, i1.new=%d, i2.new=%d\n", clientId, i1OldValue, i2OldValue, i1.getValue(), i2.getValue()); txn.commitAsync(null); } System.out.printf("client%d done\n", clientId); } catch (Exception e) { e.printStackTrace(); } } }
package ch.bind.philib.conf; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertSame; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.Test; public class LoggingListenerTest { @Test public void defaultConstructor() { LoggingListener ll = new LoggingListener(); assertNotNull(ll.getLogger()); assertSame(ll.getLogger(), LoggerFactory.getLogger(LoggingListener.class)); } @Test public void added() { Logger log = mock(Logger.class); LoggingListener ll = new LoggingListener(log); ll.added("key", "value"); verify(log).info("added '%s': '%s'", "key", "value"); verifyNoMoreInteractions(log); } @Test public void changed() { Logger log = mock(Logger.class); LoggingListener ll = new LoggingListener(log); ll.changed("key", "oldValue", "newValue"); verify(log).info("changed '%s': '%s' -> '%s'", "key", "oldValue", "newValue"); verifyNoMoreInteractions(log); } @Test public void removed() { Logger log = mock(Logger.class); LoggingListener ll = new LoggingListener(log); ll.removed("key", "oldValue"); verify(log).info("removed '%s': '%s'", "key", "oldValue"); verifyNoMoreInteractions(log); } }
package com.annimon.ownlang.parser; import com.annimon.ownlang.Console; import com.annimon.ownlang.lib.FunctionValue; import com.annimon.ownlang.lib.Functions; import com.annimon.ownlang.lib.NumberValue; import com.annimon.ownlang.lib.Variables; import com.annimon.ownlang.outputsettings.OutputSettings; import com.annimon.ownlang.outputsettings.StringOutputSettings; import com.annimon.ownlang.parser.ast.FunctionDefineStatement; import com.annimon.ownlang.parser.ast.Statement; import com.annimon.ownlang.parser.ast.Visitor; import com.annimon.ownlang.parser.visitors.AbstractVisitor; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Assert; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class ProgramsTest { private static final String RES_DIR = "src/test/resources"; private final String programPath; public ProgramsTest(String programPath) { this.programPath = programPath; } @Parameters(name = "{index}: {0}") public static Collection<String> data() { final File resDir = new File(RES_DIR); return scanDirectory(resDir) .map(File::getPath) .collect(Collectors.toList()); } private static Stream<File> scanDirectory(File dir) { final File[] files = dir.listFiles(); if (files == null || files.length == 0) { return Stream.empty(); } return Arrays.stream(files) .flatMap(file -> { if (file.isDirectory()) { return scanDirectory(file); } return Stream.of(file); }) .filter(f -> f.getName().endsWith(".own")); } @Before public void initialize() { Variables.clear(); Functions.clear(); // Let's mock junit methods as ounit functions Functions.set("assertEquals", (args) -> { assertEquals(args[0], args[1]); return NumberValue.ONE; }); Functions.set("assertNotEquals", (args) -> { assertNotEquals(args[0], args[1]); return NumberValue.ONE; }); Functions.set("assertSameType", (args) -> { assertEquals(args[0].type(), args[1].type()); return NumberValue.ONE; }); Functions.set("assertTrue", (args) -> { assertTrue(args[0].asInt() != 0); return NumberValue.ONE; }); Functions.set("assertFalse", (args) -> { assertFalse(args[0].asInt() != 0); return NumberValue.ONE; }); Functions.set("assertFail", (args) -> { try { ((FunctionValue) args[0]).getValue().execute(); fail("Function should fail"); } catch (Throwable thr) { } return NumberValue.ONE; }); } @Test public void testProgram() throws IOException { final String source = SourceLoader.readSource(programPath); final Statement s = Parser.parse(Lexer.tokenize(source)); try { s.execute(); s.accept(testFunctionsExecutor); } catch (Exception oae) { Assert.fail(oae.toString()); } } @Test public void testOutput() throws IOException { OutputSettings oldSettings = Console.getSettings(); Console.useSettings(new StringOutputSettings()); String source = "for i = 0, i <= 5, i++\n print i"; final Statement s = Parser.parse(Lexer.tokenize(source)); try { s.execute(); assertEquals("012345", Console.text()); } catch (Exception oae) { Assert.fail(oae.toString()); } finally { Console.useSettings(oldSettings); } } private static Visitor testFunctionsExecutor = new AbstractVisitor() { @Override public void visit(FunctionDefineStatement s) { if (s.name.startsWith("test")) { try { Functions.get(s.name).execute(); } catch (AssertionError err) { throw new AssertionError(s.name + ": " + err.getMessage(), err); } } } }; }
package com.github.fakemongo; import com.github.fakemongo.junit.FongoRule; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MapReduceCommand; import com.mongodb.MapReduceOutput; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import com.mongodb.util.JSON; import org.assertj.core.api.Assertions; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.RuleChain; import org.junit.rules.TestRule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FongoMapReduceTest { private static final Logger LOG = LoggerFactory.getLogger(FongoMapReduceTest.class); public final FongoRule fongoRule = new FongoRule(false); public final ExpectedException exception = ExpectedException.none(); @Rule public TestRule rules = RuleChain.outerRule(exception).around(fongoRule); @Test public void testMapReduceSimple() { DBCollection coll = fongoRule.newCollection(); fongoRule.insertJSON(coll, "[{url: \"www.google.com\", date: 1, trash_data: 5 },\n" + " {url: \"www.no-fucking-idea.com\", date: 1, trash_data: 13 },\n" + " {url: \"www.google.com\", date: 1, trash_data: 1 },\n" + " {url: \"www.no-fucking-idea.com\", date: 2, trash_data: 69 },\n" + " {url: \"www.no-fucking-idea.com\", date: 2, trash_data: 256 }]"); String map = "function(){ emit(this.url, 1); };"; String reduce = "function(key, values){ var res = 0; values.forEach(function(v){ res += 1}); return {count: res}; };"; coll.mapReduce(map, reduce, "result", new BasicDBObject()); List<DBObject> results = fongoRule.newCollection("result").find().toArray(); assertEquals(fongoRule.parse("[{ \"_id\" : \"www.google.com\" , \"value\" : { \"count\" : 2.0}}, { \"_id\" : \"www.no-fucking-idea.com\" , \"value\" : { \"count\" : 3.0}}]"), results); } @Test public void testMapReduceEmitObject() { DBCollection coll = fongoRule.newCollection(); fongoRule.insertJSON(coll, "[{url: \"www.google.com\", date: 1, trash_data: 5 },\n" + " {url: \"www.no-fucking-idea.com\", date: 1, trash_data: 13 },\n" + " {url: \"www.google.com\", date: 1, trash_data: 1 },\n" + " {url: \"www.no-fucking-idea.com\", date: 2, trash_data: 69 },\n" + " {url: \"www.no-fucking-idea.com\", date: 2, trash_data: 256 }]"); String map = "function(){ emit({url: this.url}, 1); };"; String reduce = "function(key, values){ var res = 0; values.forEach(function(v){ res += 1}); return {count: res}; };"; coll.mapReduce(map, reduce, "result", new BasicDBObject()); List<DBObject> results = fongoRule.newCollection("result").find().toArray(); assertEquals(fongoRule.parse("[{\"_id\" : {url: \"www.google.com\"} , \"value\" : { \"count\" : 2.0}}, { \"_id\" : {url: \"www.no-fucking-idea.com\"} , \"value\" : { \"count\" : 3.0}}]"), results); } @Test public void testMapReduceJoinOneToMany() { DBCollection trash = fongoRule.newCollection(); DBCollection dates = fongoRule.newCollection(); fongoRule.insertJSON(trash, "[" + " {date: \"1\", trash_data: \"13\" },\n" + " {date: \"1\", trash_data: \"1\" },\n" + " {date: \"2\", trash_data: \"100\" },\n" + " {date: \"2\", trash_data: \"256\" }]"); fongoRule.insertJSON(dates, "[{date: \"1\", dateval: \"10\"}, {date:\"2\", dateval: \"20\"}]"); String mapTrash = "function() { emit({date: this.date}, {value : [{dateval: null, trash_data:this.trash_data, date:this.date}]});};"; String mapDates = "function() { emit({date:this.date}, {value : [{dateval:this.dateval}]});};"; String reduce = "function(key, values){" + " var dateval = null;\n" + " for (var j in values) {\n" + " var valArr = values[j].value;\n" + " for (var jj in valArr) {\n" + " var value = valArr[jj];\n" + " if (value.dateval !== null) {\n" + " dateval = value.dateval;\n" + " }\n" + " }\n" + " }" + " var outValues = [];\n" + " for (var j in values) {\n" + " var valArr = values[j].value;\n" + " for (var jj in valArr) {\n" + " var orig = valArr[jj];\n" + " var copy = {};\n" + " for (var jjj in orig) {\n" + " copy[jjj] = orig[jjj];\n" + " }\n" + " if (dateval !== null) {\n" + " copy[\"dateval\"] = dateval;\n" + " }\n" + " outValues.push(copy);\n" + " }\n" + " }\n" + " return {value:outValues};" + "};"; trash.mapReduce(mapTrash, reduce, "result", MapReduceCommand.OutputType.REDUCE, new BasicDBObject()); dates.mapReduce(mapDates, reduce, "result", MapReduceCommand.OutputType.REDUCE, new BasicDBObject()); List<DBObject> results = fongoRule.newCollection("result").find().toArray(); Map<String, DBObject> byId = new HashMap<String, DBObject>(); for (DBObject res : results) { byId.put(JSON.serialize(res.get("_id")), res); } List<DBObject> expected = fongoRule.parse("[" + "{\"_id\":{\"date\":\"1\"}, \"value\":" + "{\"value\":[{\"dateval\":\"10\"}, {\"trash_data\":\"13\", \"date\":\"1\", \"dateval\":\"10\"}, " + "{\"trash_data\":\"1\", \"date\":\"1\", \"dateval\":\"10\"}]}}, " + "{\"_id\":{\"date\":\"2\"}, \"value\":" + "{\"value\":[{\"dateval\":\"20\"}, {\"trash_data\":\"100\", \"date\":\"2\", \"dateval\":\"20\"}, " + "{\"trash_data\":\"256\", \"date\":\"2\", \"dateval\":\"20\"}]}}]"); for (DBObject e : expected) { List<DBObject> values = (List<DBObject>)(((DBObject) e.get("value")).get("value")); DBObject id = (DBObject) e.get("_id"); DBObject actual = byId.get(JSON.serialize(id)); List<DBObject> actualValues = (List<DBObject>)(((DBObject) actual.get("value")).get("value")); Assertions.assertThat(actualValues).containsAll(values); Assertions.assertThat(actualValues.size()).isEqualTo(values.size()); } Assertions.assertThat(expected.size()).isEqualTo(results.size()); } @Test public void testMapReduceWithArray() { DBCollection coll = fongoRule.newCollection(); fongoRule.insertJSON(coll, "[{url: \"www.google.com\", date: 1, trash_data: 5, arr: ['a',2] },\n" + " {url: \"www.no-fucking-idea.com\", date: 1, trash_data: 13, arr: ['b',4] },\n" + " {url: \"www.google.com\", date: 1, trash_data: 1, arr: ['c',6] },\n" + " {url: \"www.no-fucking-idea.com\", date: 2, trash_data: 69, arr: ['d',8] },\n" + " {url: \"www.no-fucking-idea.com\", date: 2, trash_data: 256, arr: ['e',10] }]"); String map = "function(){ emit(this.url, this.arr); };"; String reduce = "function(key, values){ var res = []; values.forEach(function(v){ res = res.concat(v); }); return {mergedArray: res}; };"; coll.mapReduce(map, reduce, "result", new BasicDBObject()); List<DBObject> results = fongoRule.newCollection("result").find().toArray(); assertEquals(fongoRule.parse("[{ \"_id\" : \"www.google.com\" , \"value\" : { \"mergedArray\" : [\"a\",2,\"c\",6]}}, { \"_id\" : \"www.no-fucking-idea.com\" , \"value\" : { \"mergedArray\" : [\"b\",4,\"d\",8,\"e\",10]}}]"), results); } @Test public void should_use_outputdb() { DBCollection coll = fongoRule.newCollection(); fongoRule.insertJSON(coll, "[{url: \"www.google.com\", date: 1, trash_data: 5 },\n" + " {url: \"www.no-fucking-idea.com\", date: 1, trash_data: 13 },\n" + " {url: \"www.google.com\", date: 1, trash_data: 1 },\n" + " {url: \"www.no-fucking-idea.com\", date: 2, trash_data: 69 },\n" + " {url: \"www.no-fucking-idea.com\", date: 2, trash_data: 256 }]"); String map = "function(){ emit(this.url, 1); };"; String reduce = "function(key, values){ var res = 0; values.forEach(function(v){ res += 1}); return {count: res}; };"; MapReduceCommand mapReduceCommand = new MapReduceCommand(coll, map, reduce, "result", MapReduceCommand.OutputType.MERGE, new BasicDBObject()); mapReduceCommand.setOutputDB("otherColl"); coll.mapReduce(mapReduceCommand); List<DBObject> results = fongoRule.getDb("otherColl").getCollection("result").find().toArray(); assertEquals(fongoRule.parse("[{ \"_id\" : \"www.google.com\" , \"value\" : { \"count\" : 2.0}}, { \"_id\" : \"www.no-fucking-idea.com\" , \"value\" : { \"count\" : 3.0}}]"), results); } @Test public void testZipMapReduce() throws IOException { DBCollection coll = fongoRule.newCollection(); fongoRule.insertFile(coll, "/zips.json"); String map = "function () {\n" + " var pitt = [-80.064879, 40.612044];\n" + " var phil = [-74.978052, 40.089738];\n" + "\n" + " function distance(a, b) {\n" + " var dx = a[0] - b[0];\n" + " var dy = a[1] - b[1];\n" + " return Math.sqrt(dx * dx + dy * dy);\n" + " }\n" + "\n" + " if (distance(this.loc, pitt) < distance(this.loc, phil)) {\n" + " emit(\"pitt\",1);\n" + " } else {\n" + " emit(\"phil\",1);\n" + " }\n" + "}\n"; String reduce = "function(name, values) { return Array.sum(values); };"; MapReduceOutput output = coll.mapReduce(map, reduce, "resultF", new BasicDBObject("state", "MA")); List<DBObject> results = output.getOutputCollection().find().toArray(); assertEquals(fongoRule.parse("[{ \"_id\" : \"phil\" , \"value\" : 474.0}]"), results); } /** * Inline output = in memory. */ @Test public void testMapReduceInline() { // Given DBCollection coll = fongoRule.newCollection(); fongoRule.insertJSON(coll, "[{url: \"www.google.com\", date: 1, trash_data: 5 },\n" + " {url: \"www.no-fucking-idea.com\", date: 1, trash_data: 13 },\n" + " {url: \"www.google.com\", date: 1, trash_data: 1 },\n" + " {url: \"www.no-fucking-idea.com\", date: 2, trash_data: 69 },\n" + " {url: \"www.no-fucking-idea.com\", date: 2, trash_data: 256 }]"); // When String map = "function(){ emit(this.url, 1); };"; String reduce = "function(key, values){ var res = 0; values.forEach(function(v){ res += 1}); return {count: res}; };"; MapReduceOutput output = coll.mapReduce(map, reduce, null, MapReduceCommand.OutputType.INLINE, new BasicDBObject()); // Then assertEquals(fongoRule.parse("[{ \"_id\" : \"www.google.com\" , \"value\" : { \"count\" : 2.0}}, { \"_id\" : \"www.no-fucking-idea.com\" , \"value\" : { \"count\" : 3.0}}]"), output.results()); } @Test public void testMapReduceMapInError() { ExpectedMongoException.expectCommandFailure(exception, 16722); DBCollection coll = fongoRule.newCollection(); fongoRule.insertJSON(coll, "[{url: \"www.google.com\", date: 1, trash_data: 5 },\n" + " {url: \"www.no-fucking-idea.com\", date: 1, trash_data: 13 },\n" + " {url: \"www.google.com\", date: 1, trash_data: 1 },\n" + " {url: \"www.no-fucking-idea.com\", date: 2, trash_data: 69 },\n" + " {url: \"www.no-fucking-idea.com\", date: 2, trash_data: 256 }]"); String map = "function(){ ;"; String reduce = "function(key, values){ var res = 0; values.forEach(function(v){ res += 1}); return {count: res}; };"; coll.mapReduce(map, reduce, "result", new BasicDBObject()); } @Test public void testMapReduceReduceInError() { ExpectedMongoException.expectCommandFailure(exception, 16722); DBCollection coll = fongoRule.newCollection(); fongoRule.insertJSON(coll, "[{url: \"www.google.com\", date: 1, trash_data: 5 },\n" + " {url: \"www.no-fucking-idea.com\", date: 1, trash_data: 13 },\n" + " {url: \"www.google.com\", date: 1, trash_data: 1 },\n" + " {url: \"www.no-fucking-idea.com\", date: 2, trash_data: 69 },\n" + " {url: \"www.no-fucking-idea.com\", date: 2, trash_data: 256 }]"); String map = "function(){ emit(this.url, 1); };"; String reduce = "function(key, values){ values.forEach(function(v){ res += 1}); return {count: res}; };"; coll.mapReduce(map, reduce, "result", new BasicDBObject()); } }
package com.microsoft.graph.core; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; /** * Tests for Multipart functionality */ public class MultipartTests { private Multipart multipart; @Before public void setUp() { multipart = new Multipart(); } @Test public void testCreatePartHeaderWithNameContenttypeFilename() { String actual = multipart.createPartHeader("hamilton", "image/jpg", "hamilton.jpg"); String expected = "--"+multipart.getBoundary()+"\r\nContent-Disposition: form-data; name=\"hamilton\"; filename=\"hamilton.jpg\"\r\nContent-Type: image/jpg\r\n\r\n"; assertEquals(expected, actual); } @Test public void testCreatePartHeaderWithContenttypeFilename() { String actual = multipart.createPartHeader(null, "image/jpg", "hamilton.jpg"); String expected = "--"+multipart.getBoundary()+"\r\nContent-Disposition: form-data; filename=\"hamilton.jpg\"\r\nContent-Type: image/jpg\r\n\r\n"; assertEquals(expected, actual); } @Test public void testCreatePartHeaderWithNameContenttype() { String actual = multipart.createPartHeader("hamilton", "image/jpg", null); String expected = "--"+multipart.getBoundary()+"\r\nContent-Disposition: form-data; name=\"hamilton\"\r\nContent-Type: image/jpg\r\n\r\n"; assertEquals(expected, actual); } @Test public void testCreatePartHeaderWithContenttype() { String actual = multipart.createPartHeader(null, "image/jpg", null); String expected = "--"+multipart.getBoundary()+"\r\nContent-Disposition: form-data\r\nContent-Type: image/jpg\r\n\r\n"; assertEquals(expected, actual); } @Test public void testCreatePartHeader() { String actual = multipart.createPartHeader(null, null, null); String expected = "--"+multipart.getBoundary()+"\r\nContent-Disposition: form-data\r\n\r\n"; assertEquals(expected, actual); } @Test public void testCreatePartHeaderWithNameFilename() { String actual = multipart.createPartHeader("hamilton", null, "hamilton.jpg"); String expected = "--"+multipart.getBoundary()+"\r\nContent-Disposition: form-data; name=\"hamilton\"; filename=\"hamilton.jpg\"\r\n\r\n"; assertEquals(expected, actual); } @Test public void testCreatePartHeaderWithName() { String actual = multipart.createPartHeader("hamilton", null, null); String expected = "--"+multipart.getBoundary()+"\r\nContent-Disposition: form-data; name=\"hamilton\"\r\n\r\n"; assertEquals(expected, actual); } @Test public void testCreatePartHeaderWithFilename() { String actual = multipart.createPartHeader(null, null, "hamilton.jpg"); String expected = "--"+multipart.getBoundary()+"\r\nContent-Disposition: form-data; filename=\"hamilton.jpg\"\r\n\r\n"; assertEquals(expected, actual); } }
package com.pengrad.telegrambot; import com.pengrad.telegrambot.model.Message; import com.pengrad.telegrambot.model.Update; import com.pengrad.telegrambot.model.User; import com.pengrad.telegrambot.model.request.*; import com.pengrad.telegrambot.response.*; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Files; import java.util.List; import java.util.Properties; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** * stas * 10/20/15. */ public class TelegramBotTest { TelegramBot bot; Integer chatId, forwardMessageId; String channelName = "@bottest"; Long channelId = -1001002720332L; String stickerId; String imagefile = getClass().getClassLoader().getResource("image.png").getFile(); String audioFile = getClass().getClassLoader().getResource("beep.mp3").getFile(); String docFile = getClass().getClassLoader().getResource("doc.txt").getFile(); String videoFile = getClass().getClassLoader().getResource("tabs.mp4").getFile(); public TelegramBotTest() throws IOException { Properties properties = new Properties(); properties.load(new FileInputStream("local.properties")); bot = TelegramBotAdapter.buildDebug(properties.getProperty("TEST_TOKEN")); chatId = Integer.parseInt(properties.getProperty("CHAT_ID")); forwardMessageId = Integer.parseInt(properties.getProperty("FORWARD_MESSAGE")); stickerId = properties.getProperty("STICKER_FILE_ID"); } @Test public void testGetFullFilePath() throws Exception { String path1 = bot.getFullFilePath(bot.getFile(stickerId).file()); String path2 = bot.getFullFilePath(stickerId); assertNotNull(path1); assertEquals(path1, path2); } @Test public void testGetMe() throws Exception { GetMeResponse getMeResponse = bot.getMe(); User user = getMeResponse.user(); UserTest.checkUser(user); } @Test public void testForwardMessage() throws Exception { SendResponse sendResponse = bot.forwardMessage(chatId, chatId, forwardMessageId); Message message = sendResponse.message(); MessageTest.checkForwardedMessage(message); } @Test public void testSendMessage() throws Exception { SendResponse sendResponse = bot.sendMessage(chatId, "short message sending with emoji \uD83D\uDE4C"); MessageTest.checkTextdMessage(sendResponse.message()); sendResponse = bot.sendMessage(chatId, "sendMessage _italic_ *markdown*", ParseMode.Markdown, null, forwardMessageId, new ReplyKeyboardMarkup(new String[]{"ok", "test"}).oneTimeKeyboard(true)); MessageTest.checkTextdMessage(sendResponse.message()); sendResponse = bot.sendMessage(channelName, "to channel _italic_ *markdown*", ParseMode.Markdown, false, null, new ForceReply()); MessageTest.checkTextdMessage(sendResponse.message()); sendResponse = bot.sendMessage(channelId, "explicit to channel id _italic_ *markdown*", ParseMode.Markdown, false, null, new ReplyKeyboardHide()); MessageTest.checkTextdMessage(sendResponse.message()); } @Test public void testSendPhoto() throws Exception { InputFile inputFile = InputFile.photo(new File(imagefile)); SendResponse sendResponse = bot.sendPhoto(chatId, inputFile, "caption", null, null); Message message = sendResponse.message(); MessageTest.checkPhotoMessage(message); } @Test public void testSendAudio() throws Exception { InputFile inputFile = InputFile.audio(new File(audioFile)); SendResponse sendResponse = bot.sendAudio(chatId, inputFile, null, null, null, null, null); Message message = sendResponse.message(); MessageTest.checkAudioMessage(message); } @Test public void testSendDocument() throws Exception { InputFile inputFile = new InputFile("text/plain", new File(docFile)); SendResponse sendResponse = bot.sendDocument(chatId, inputFile, null, null); Message message = sendResponse.message(); MessageTest.checkDocumentMessage(message); } @Test public void testSendSticker() throws Exception { SendResponse sendResponse = bot.sendSticker(chatId, stickerId, null, null); Message message = sendResponse.message(); MessageTest.checkStickerMessage(message); } @Test public void testSendVideo() throws Exception { InputFile inputFile = InputFile.video(new File(videoFile)); SendResponse sendResponse = bot.sendVideo(chatId, inputFile, null, "caption", null, null); Message message = sendResponse.message(); MessageTest.checkVideoMessage(message); } @Test public void testSendVoice() throws Exception { byte[] array = Files.readAllBytes(new File(audioFile).toPath()); InputFileBytes inputFileBytes = InputFileBytes.voice(array); SendResponse sendResponse = bot.sendVoice(chatId, inputFileBytes, null, null, null); Message message = sendResponse.message(); MessageTest.checkVoiceMessage(message); } @Test public void testSendLocation() throws Exception { SendResponse sendResponse = bot.sendLocation(chatId, 55.1f, 38.2f, null, null); MessageTest.checkLocationMessage(sendResponse.message()); } @Test public void testSendChatAction() throws Exception { bot.sendChatAction(chatId, ChatAction.find_location); bot.sendChatAction(chatId, ChatAction.typing); bot.sendChatAction(chatId, ChatAction.record_audio); bot.sendChatAction(chatId, ChatAction.record_video); bot.sendChatAction(channelName, ChatAction.upload_audio); bot.sendChatAction(channelName, ChatAction.upload_document); bot.sendChatAction(channelName, ChatAction.upload_photo); bot.sendChatAction(channelName, ChatAction.upload_video); } @Test public void testGetUserProfilePhotos() throws Exception { GetUserProfilePhotosResponse userProfilePhotosResponse = bot.getUserProfilePhotos(chatId, 0, 5); UserProfilePhotosTest.check(userProfilePhotosResponse.photos()); } @Test public void testGetUpdates() throws Exception { GetUpdatesResponse updatesResponse = bot.getUpdates(0, 10, 0); List<Update> update = updatesResponse.updates(); UpdateTest.check(update); } @Test public void testSetWebhook() throws Exception { SetWebhookResponse webhookResponse = bot.setWebhook(""); assertNotNull(webhookResponse.description()); } @Test public void testGetFile() throws Exception { GetFileResponse fileResponse = bot.getFile(stickerId); FileTest.check(fileResponse.file()); } }
package com.qiniu.testing; import java.net.SocketTimeoutException; import junit.framework.TestCase; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ConnectTimeoutException; import com.qiniu.api.config.Config; import com.qiniu.api.net.Http; public class HttpClientTimeOutTest extends TestCase { private int CONNECTION_TIMEOUT; private int SO_TIMEOUT; @Override public void setUp() { CONNECTION_TIMEOUT = Config.CONNECTION_TIMEOUT; SO_TIMEOUT = Config.SO_TIMEOUT; Http.setClient(null); } @Override public void tearDown() { Config.CONNECTION_TIMEOUT = CONNECTION_TIMEOUT; Config.SO_TIMEOUT = SO_TIMEOUT; Http.setClient(null); } public void testCONNECTION_TIMEOUT() { Throwable tx = null; long s = 0; try { Config.CONNECTION_TIMEOUT = 5; Config.SO_TIMEOUT = 20 * 1000; HttpClient client = Http.getClient(); HttpGet httpget = new HttpGet("http: s = System.currentTimeMillis(); HttpResponse ret = client.execute(httpget); fail(" ConnectTimeoutException"); } catch (Exception e) { long end = System.currentTimeMillis(); System.out.println("CONNECTION_TIMEOUT test : " + (end - s)); tx = e; } assertNotNull(tx.getMessage()); assertEquals(ConnectTimeoutException.class, tx.getClass()); } public void testSO_TIMEOUT() { Throwable tx = null; long s = 0; try { Config.CONNECTION_TIMEOUT = 20 * 1000; Config.SO_TIMEOUT = 5; HttpClient client = Http.getClient(); HttpGet httpget = new HttpGet("http: s = System.currentTimeMillis(); HttpResponse ret = client.execute(httpget); fail(" SocketTimeoutException"); } catch (Exception e) { long end = System.currentTimeMillis(); System.out.println("SO_TIMEOUT test : " + (end - s)); tx = e; } assertNotNull(tx.getMessage()); assertEquals(SocketTimeoutException.class, tx.getClass()); } }
package edu.harvard.iq.dataverse.api; import com.jayway.restassured.RestAssured; import static com.jayway.restassured.RestAssured.given; import com.jayway.restassured.http.ContentType; import com.jayway.restassured.response.Response; import java.util.logging.Logger; import org.junit.BeforeClass; import org.junit.Test; import com.jayway.restassured.path.json.JsonPath; import java.util.List; import java.util.Map; import javax.json.JsonObject; import static javax.ws.rs.core.Response.Status.CREATED; import static javax.ws.rs.core.Response.Status.FORBIDDEN; import static javax.ws.rs.core.Response.Status.OK; import static javax.ws.rs.core.Response.Status.UNAUTHORIZED; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.Status.METHOD_NOT_ALLOWED; import edu.harvard.iq.dataverse.DataFile; import static edu.harvard.iq.dataverse.api.UtilIT.API_TOKEN_HTTP_HEADER; import edu.harvard.iq.dataverse.authorization.DataverseRole; import edu.harvard.iq.dataverse.authorization.users.PrivateUrlUser; import edu.harvard.iq.dataverse.settings.SettingsServiceBean; import java.util.UUID; import static javax.ws.rs.core.Response.Status.NO_CONTENT; import org.apache.commons.lang.StringUtils; import com.jayway.restassured.parsing.Parser; import static com.jayway.restassured.path.json.JsonPath.with; import com.jayway.restassured.path.xml.XmlPath; import static edu.harvard.iq.dataverse.api.UtilIT.equalToCI; import edu.harvard.iq.dataverse.util.SystemConfig; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import javax.json.Json; import javax.json.JsonObjectBuilder; import static junit.framework.Assert.assertEquals; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import org.junit.AfterClass; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class DatasetsIT { private static final Logger logger = Logger.getLogger(DatasetsIT.class.getCanonicalName()); @BeforeClass public static void setUpClass() { RestAssured.baseURI = UtilIT.getRestAssuredBaseUri(); Response removeIdentifierGenerationStyle = UtilIT.deleteSetting(SettingsServiceBean.Key.IdentifierGenerationStyle); removeIdentifierGenerationStyle.then().assertThat() .statusCode(200); Response removeExcludeEmail = UtilIT.deleteSetting(SettingsServiceBean.Key.ExcludeEmailFromExport); removeExcludeEmail.then().assertThat() .statusCode(200); /* With Dual mode, we can no longer mess with upload methods since native is now required for anything to work Response removeDcmUrl = UtilIT.deleteSetting(SettingsServiceBean.Key.DataCaptureModuleUrl); removeDcmUrl.then().assertThat() .statusCode(200); Response removeUploadMethods = UtilIT.deleteSetting(SettingsServiceBean.Key.UploadMethods); removeUploadMethods.then().assertThat() .statusCode(200); */ } @AfterClass public static void afterClass() { Response removeIdentifierGenerationStyle = UtilIT.deleteSetting(SettingsServiceBean.Key.IdentifierGenerationStyle); removeIdentifierGenerationStyle.then().assertThat() .statusCode(200); Response removeExcludeEmail = UtilIT.deleteSetting(SettingsServiceBean.Key.ExcludeEmailFromExport); removeExcludeEmail.then().assertThat() .statusCode(200); /* See above Response removeDcmUrl = UtilIT.deleteSetting(SettingsServiceBean.Key.DataCaptureModuleUrl); removeDcmUrl.then().assertThat() .statusCode(200); Response removeUploadMethods = UtilIT.deleteSetting(SettingsServiceBean.Key.UploadMethods); removeUploadMethods.then().assertThat() .statusCode(200); */ } @Test public void testCreateDataset() { Response createUser = UtilIT.createRandomUser(); createUser.prettyPrint(); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); createDatasetResponse.prettyPrint(); Integer datasetId = UtilIT.getDatasetIdFromResponse(createDatasetResponse); Response datasetAsJson = UtilIT.nativeGet(datasetId, apiToken); datasetAsJson.then().assertThat() .statusCode(OK.getStatusCode()); String identifier = JsonPath.from(datasetAsJson.getBody().asString()).getString("data.identifier"); assertEquals(10, identifier.length()); Response deleteDatasetResponse = UtilIT.deleteDatasetViaNativeApi(datasetId, apiToken); deleteDatasetResponse.prettyPrint(); assertEquals(200, deleteDatasetResponse.getStatusCode()); Response deleteDataverseResponse = UtilIT.deleteDataverse(dataverseAlias, apiToken); deleteDataverseResponse.prettyPrint(); assertEquals(200, deleteDataverseResponse.getStatusCode()); Response deleteUserResponse = UtilIT.deleteUser(username); deleteUserResponse.prettyPrint(); assertEquals(200, deleteUserResponse.getStatusCode()); } @Test public void testAddUpdateDatasetViaNativeAPI() { Response createUser = UtilIT.createRandomUser(); createUser.prettyPrint(); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); createDatasetResponse.prettyPrint(); Integer datasetId = UtilIT.getDatasetIdFromResponse(createDatasetResponse); Response datasetAsJson = UtilIT.nativeGet(datasetId, apiToken); datasetAsJson.then().assertThat() .statusCode(OK.getStatusCode()); String identifier = JsonPath.from(datasetAsJson.getBody().asString()).getString("data.identifier"); //Test Add Data Response getDatasetJsonBeforePublishing = UtilIT.nativeGet(datasetId, apiToken); getDatasetJsonBeforePublishing.prettyPrint(); String protocol = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.protocol"); String authority = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.authority"); String datasetPersistentId = protocol + ":" + authority + "/" + identifier; String pathToJsonFile = "doc/sphinx-guides/source/_static/api/dataset-add-metadata.json"; Response addSubjectViaNative = UtilIT.addDatasetMetadataViaNative(datasetPersistentId, pathToJsonFile, apiToken); addSubjectViaNative.prettyPrint(); addSubjectViaNative.then().assertThat() .statusCode(OK.getStatusCode()); RestAssured.registerParser("text/plain", Parser.JSON); Response exportDatasetAsJson = UtilIT.exportDataset(datasetPersistentId, "dataverse_json", apiToken); exportDatasetAsJson.prettyPrint(); pathToJsonFile = "doc/sphinx-guides/source/_static/api/dataset-add-subject-metadata.json"; addSubjectViaNative = UtilIT.addDatasetMetadataViaNative(datasetPersistentId, pathToJsonFile, apiToken); addSubjectViaNative.prettyPrint(); addSubjectViaNative.then().assertThat() .statusCode(OK.getStatusCode()); String pathToJsonFileSingle = "doc/sphinx-guides/source/_static/api/dataset-simple-update-metadata.json"; Response addSubjectSingleViaNative = UtilIT.updateFieldLevelDatasetMetadataViaNative(datasetPersistentId, pathToJsonFileSingle, apiToken); addSubjectSingleViaNative.prettyPrint(); addSubjectSingleViaNative.then().assertThat() .statusCode(OK.getStatusCode()); //Trying to blank out required field should fail... String pathToJsonFileBadData = "doc/sphinx-guides/source/_static/api/dataset-update-with-blank-metadata.json"; Response deleteTitleViaNative = UtilIT.updateFieldLevelDatasetMetadataViaNative(datasetPersistentId, pathToJsonFileBadData, apiToken); deleteTitleViaNative.prettyPrint(); deleteTitleViaNative.then().assertThat().body("message", equalTo("Error parsing dataset update: Empty value for field: Title ")); Response publishDataverse = UtilIT.publishDataverseViaSword(dataverseAlias, apiToken); Response publishDataset = UtilIT.publishDatasetViaNativeApi(datasetPersistentId, "major", apiToken); assertEquals(200, publishDataset.getStatusCode()); //post publish update String pathToJsonFilePostPub= "doc/sphinx-guides/source/_static/api/dataset-add-metadata-after-pub.json"; Response addDataToPublishedVersion = UtilIT.addDatasetMetadataViaNative(datasetPersistentId, pathToJsonFilePostPub, apiToken); addDataToPublishedVersion.prettyPrint(); addDataToPublishedVersion.then().assertThat().statusCode(OK.getStatusCode()); publishDataset = UtilIT.publishDatasetViaNativeApi(datasetPersistentId, "major", apiToken); //post publish update String pathToJsonFileBadDataSubtitle = "doc/sphinx-guides/source/_static/api/dataset-edit-metadata-subtitle.json"; Response addDataToBadData = UtilIT.updateFieldLevelDatasetMetadataViaNative(datasetPersistentId, pathToJsonFileBadDataSubtitle, apiToken); addDataToBadData.prettyPrint(); addDataToBadData.then().assertThat() .body("message", equalToCI("Error parsing dataset update: Invalid value submitted for Subtitle. It should be a single value.")) .statusCode(400); addSubjectViaNative = UtilIT.addDatasetMetadataViaNative(datasetPersistentId, pathToJsonFile, apiToken); addSubjectViaNative.prettyPrint(); addSubjectViaNative.then().assertThat() .statusCode(OK.getStatusCode()); String pathToJsonDeleteFile = "doc/sphinx-guides/source/_static/api/dataset-delete-subject-metadata.json"; addSubjectViaNative = UtilIT.deleteDatasetMetadataViaNative(datasetPersistentId, pathToJsonDeleteFile, apiToken); addSubjectViaNative.prettyPrint(); addSubjectViaNative.then().assertThat() .statusCode(OK.getStatusCode()); pathToJsonDeleteFile = "doc/sphinx-guides/source/_static/api/dataset-delete-author-metadata.json"; addSubjectViaNative = UtilIT.deleteDatasetMetadataViaNative(datasetPersistentId, pathToJsonDeleteFile, apiToken); addSubjectViaNative.prettyPrint(); addSubjectViaNative.then().assertThat() .statusCode(OK.getStatusCode()); pathToJsonDeleteFile = "doc/sphinx-guides/source/_static/api/dataset-delete-author-no-match.json"; addSubjectViaNative = UtilIT.deleteDatasetMetadataViaNative(datasetPersistentId, pathToJsonDeleteFile, apiToken); addSubjectViaNative.prettyPrint(); addSubjectViaNative.then().assertThat().body("message", equalTo("Delete metadata failed: Author: Spruce, Sabrina not found.")) .statusCode(400); //"Delete metadata failed: " + updateField.getDatasetFieldType().getDisplayName() + ": " + displayValue + " not found." } /** * This test requires the root dataverse to be published to pass. */ @Test public void testCreatePublishDestroyDataset() { Response createUser = UtilIT.createRandomUser(); createUser.prettyPrint(); assertEquals(200, createUser.getStatusCode()); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); Response makeSuperUser = UtilIT.makeSuperUser(username); assertEquals(200, makeSuperUser.getStatusCode()); Response createNoAccessUser = UtilIT.createRandomUser(); createNoAccessUser.prettyPrint(); String apiTokenNoAccess= UtilIT.getApiTokenFromResponse(createNoAccessUser); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); createDatasetResponse.prettyPrint(); Integer datasetId = JsonPath.from(createDatasetResponse.body().asString()).getInt("data.id"); Response getDatasetJsonBeforePublishing = UtilIT.nativeGet(datasetId, apiToken); getDatasetJsonBeforePublishing.prettyPrint(); String protocol = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.protocol"); String authority = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.authority"); String identifier = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.identifier"); String datasetPersistentId = protocol + ":" + authority + "/" + identifier; Response datasetAsJsonNoAccess = UtilIT.nativeGet(datasetId, apiTokenNoAccess); datasetAsJsonNoAccess.then().assertThat() .statusCode(UNAUTHORIZED.getStatusCode()); Response publishDataverse = UtilIT.publishDataverseViaSword(dataverseAlias, apiToken); assertEquals(200, publishDataverse.getStatusCode()); Response attemptToPublishZeroDotOne = UtilIT.publishDatasetViaNativeApiDeprecated(datasetPersistentId, "minor", apiToken); attemptToPublishZeroDotOne.prettyPrint(); attemptToPublishZeroDotOne.then().assertThat() .body("message", equalTo("Cannot publish as minor version. Re-try as major release.")) .statusCode(403); Response publishDataset = UtilIT.publishDatasetViaNativeApi(datasetPersistentId, "major", apiToken); assertEquals(200, publishDataset.getStatusCode()); Response getDatasetJsonAfterPublishing = UtilIT.nativeGet(datasetId, apiToken); getDatasetJsonAfterPublishing.prettyPrint(); getDatasetJsonAfterPublishing.then().assertThat() .body("data.latestVersion.versionNumber", equalTo(1)) .body("data.latestVersion.versionMinorNumber", equalTo(0)) // FIXME: make this less brittle by removing "2" and "0". See also test below. .body("data.latestVersion.metadataBlocks.citation.fields[2].value[0].datasetContactEmail.value", equalTo("finch@mailinator.com")) .statusCode(OK.getStatusCode()); Response datasetAsJsonNoAccessPostPublish = UtilIT.nativeGet(datasetId, apiTokenNoAccess); datasetAsJsonNoAccessPostPublish.then().assertThat() .statusCode(OK.getStatusCode()); assertTrue(datasetAsJsonNoAccessPostPublish.body().asString().contains(identifier)); List<JsonObject> datasetContactsFromNativeGet = with(getDatasetJsonAfterPublishing.body().asString()).param("datasetContact", "datasetContact") .getJsonObject("data.latestVersion.metadataBlocks.citation.fields.findAll { fields -> fields.typeName == datasetContact }"); Map firstDatasetContactFromNativeGet = datasetContactsFromNativeGet.get(0); assertTrue(firstDatasetContactFromNativeGet.toString().contains("finch@mailinator.com")); RestAssured.registerParser("text/plain", Parser.JSON); Response exportDatasetAsJson = UtilIT.exportDataset(datasetPersistentId, "dataverse_json", apiToken); exportDatasetAsJson.prettyPrint(); exportDatasetAsJson.then().assertThat() .body("datasetVersion.metadataBlocks.citation.fields[2].value[0].datasetContactEmail.value", equalTo("finch@mailinator.com")) .statusCode(OK.getStatusCode()); RestAssured.unregisterParser("text/plain"); // FIXME: It would be awesome if we could just get a JSON object back instead. :( Map<String, Object> datasetContactFromExport = with(exportDatasetAsJson.body().asString()).param("datasetContact", "datasetContact") .getJsonObject("datasetVersion.metadataBlocks.citation.fields.find { fields -> fields.typeName == datasetContact }"); System.out.println("datasetContactFromExport: " + datasetContactFromExport); assertEquals("datasetContact", datasetContactFromExport.get("typeName")); List valuesArray = (ArrayList) datasetContactFromExport.get("value"); // FIXME: it's brittle to rely on the first value but what else can we do, given our API? Map<String, Object> firstValue = (Map<String, Object>) valuesArray.get(0); // System.out.println("firstValue: " + firstValue); Map firstValueMap = (HashMap) firstValue.get("datasetContactEmail"); // System.out.println("firstValueMap: " + firstValueMap); assertEquals("finch@mailinator.com", firstValueMap.get("value")); assertTrue(datasetContactFromExport.toString().contains("finch@mailinator.com")); assertTrue(firstValue.toString().contains("finch@mailinator.com")); Response citationBlock = UtilIT.getMetadataBlockFromDatasetVersion(datasetPersistentId, null, null, apiToken); citationBlock.prettyPrint(); citationBlock.then().assertThat() .body("data.fields[2].value[0].datasetContactEmail.value", equalTo("finch@mailinator.com")) .statusCode(OK.getStatusCode()); Response exportFail = UtilIT.exportDataset(datasetPersistentId, "noSuchExporter", apiToken); exportFail.prettyPrint(); exportFail.then().assertThat() .body("message", equalTo("Export Failed")) .statusCode(FORBIDDEN.getStatusCode()); Response exportDatasetAsDublinCore = UtilIT.exportDataset(datasetPersistentId, "oai_dc", apiToken); exportDatasetAsDublinCore.prettyPrint(); exportDatasetAsDublinCore.then().assertThat() // FIXME: Get this working. See https://github.com/rest-assured/rest-assured/wiki/Usage // .body("oai_dc:dc.find { it == 'dc:title' }.item", hasItems("Darwin's Finches")) .statusCode(OK.getStatusCode()); Response exportDatasetAsDdi = UtilIT.exportDataset(datasetPersistentId, "ddi", apiToken); exportDatasetAsDdi.prettyPrint(); exportDatasetAsDdi.then().assertThat() .statusCode(OK.getStatusCode()); /** * The Native API allows you to create a dataset contact with an email * but no name. The email should appear in the DDI export. SWORD may * have the same behavior. Untested. This smells like a bug. */ boolean nameRequiredForContactToAppear = true; if (nameRequiredForContactToAppear) { assertEquals("Finch, Fiona", XmlPath.from(exportDatasetAsDdi.body().asString()).getString("codeBook.stdyDscr.stdyInfo.contact")); } else { assertEquals("finch@mailinator.com", XmlPath.from(exportDatasetAsDdi.body().asString()).getString("codeBook.stdyDscr.stdyInfo.contact.@email")); } assertEquals(datasetPersistentId, XmlPath.from(exportDatasetAsDdi.body().asString()).getString("codeBook.docDscr.citation.titlStmt.IDNo")); Response deleteDatasetResponse = UtilIT.destroyDataset(datasetId, apiToken); deleteDatasetResponse.prettyPrint(); assertEquals(200, deleteDatasetResponse.getStatusCode()); Response deleteDataverseResponse = UtilIT.deleteDataverse(dataverseAlias, apiToken); deleteDataverseResponse.prettyPrint(); assertEquals(200, deleteDataverseResponse.getStatusCode()); Response deleteUserResponse = UtilIT.deleteUser(username); deleteUserResponse.prettyPrint(); assertEquals(200, deleteUserResponse.getStatusCode()); } /** * This test requires the root dataverse to be published to pass. */ @Test public void testExport() { Response createUser = UtilIT.createRandomUser(); createUser.prettyPrint(); assertEquals(200, createUser.getStatusCode()); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); Response makeSuperUser = UtilIT.makeSuperUser(username); assertEquals(200, makeSuperUser.getStatusCode()); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); String pathToJsonFile = "scripts/api/data/dataset-create-new.json"; Response createDatasetResponse = UtilIT.createDatasetViaNativeApi(dataverseAlias, pathToJsonFile, apiToken); createDatasetResponse.prettyPrint(); Integer datasetId = JsonPath.from(createDatasetResponse.body().asString()).getInt("data.id"); Response getDatasetJsonBeforePublishing = UtilIT.nativeGet(datasetId, apiToken); getDatasetJsonBeforePublishing.prettyPrint(); String protocol = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.protocol"); String authority = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.authority"); String identifier = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.identifier"); String datasetPersistentId = protocol + ":" + authority + "/" + identifier; Response publishDataverse = UtilIT.publishDataverseViaSword(dataverseAlias, apiToken); assertEquals(200, publishDataverse.getStatusCode()); Response attemptToPublishZeroDotOne = UtilIT.publishDatasetViaNativeApiDeprecated(datasetPersistentId, "minor", apiToken); attemptToPublishZeroDotOne.prettyPrint(); attemptToPublishZeroDotOne.then().assertThat() .body("message", equalTo("Cannot publish as minor version. Re-try as major release.")) .statusCode(403); Response publishDataset = UtilIT.publishDatasetViaNativeApi(datasetPersistentId, "major", apiToken); assertEquals(200, publishDataset.getStatusCode()); Response getDatasetJsonAfterPublishing = UtilIT.nativeGet(datasetId, apiToken); getDatasetJsonAfterPublishing.prettyPrint(); getDatasetJsonAfterPublishing.then().assertThat() .body("data.latestVersion.versionNumber", equalTo(1)) .body("data.latestVersion.versionMinorNumber", equalTo(0)) // FIXME: make this less brittle by removing "2" and "0". See also test below. .body("data.latestVersion.metadataBlocks.citation.fields[2].value[0].datasetContactEmail.value", equalTo("sammi@sample.com")) .statusCode(OK.getStatusCode()); List<JsonObject> datasetContactsFromNativeGet = with(getDatasetJsonAfterPublishing.body().asString()).param("datasetContact", "datasetContact") .getJsonObject("data.latestVersion.metadataBlocks.citation.fields.findAll { fields -> fields.typeName == datasetContact }"); Map firstDatasetContactFromNativeGet = datasetContactsFromNativeGet.get(0); assertTrue(firstDatasetContactFromNativeGet.toString().contains("sammi@sample.com")); RestAssured.registerParser("text/plain", Parser.JSON); Response exportDatasetAsJson = UtilIT.exportDataset(datasetPersistentId, "dataverse_json", apiToken); exportDatasetAsJson.prettyPrint(); exportDatasetAsJson.then().assertThat() .body("datasetVersion.metadataBlocks.citation.fields[2].value[0].datasetContactEmail.value", equalTo("sammi@sample.com")) .statusCode(OK.getStatusCode()); RestAssured.unregisterParser("text/plain"); // FIXME: It would be awesome if we could just get a JSON object back instead. :( Map<String, Object> datasetContactFromExport = with(exportDatasetAsJson.body().asString()).param("datasetContact", "datasetContact") .getJsonObject("datasetVersion.metadataBlocks.citation.fields.find { fields -> fields.typeName == datasetContact }"); System.out.println("datasetContactFromExport: " + datasetContactFromExport); assertEquals("datasetContact", datasetContactFromExport.get("typeName")); List valuesArray = (ArrayList) datasetContactFromExport.get("value"); // FIXME: it's brittle to rely on the first value but what else can we do, given our API? Map<String, Object> firstValue = (Map<String, Object>) valuesArray.get(0); // System.out.println("firstValue: " + firstValue); Map firstValueMap = (HashMap) firstValue.get("datasetContactEmail"); // System.out.println("firstValueMap: " + firstValueMap); assertEquals("sammi@sample.com", firstValueMap.get("value")); assertTrue(datasetContactFromExport.toString().contains("sammi@sample.com")); assertTrue(firstValue.toString().contains("sammi@sample.com")); Response citationBlock = UtilIT.getMetadataBlockFromDatasetVersion(datasetPersistentId, null, null, apiToken); citationBlock.prettyPrint(); citationBlock.then().assertThat() .body("data.fields[2].value[0].datasetContactEmail.value", equalTo("sammi@sample.com")) .statusCode(OK.getStatusCode()); Response exportFail = UtilIT.exportDataset(datasetPersistentId, "noSuchExporter", apiToken); exportFail.prettyPrint(); exportFail.then().assertThat() .body("message", equalTo("Export Failed")) .statusCode(FORBIDDEN.getStatusCode()); Response exportDatasetAsDublinCore = UtilIT.exportDataset(datasetPersistentId, "oai_dc", apiToken); exportDatasetAsDublinCore.prettyPrint(); exportDatasetAsDublinCore.then().assertThat() // FIXME: Get this working. See https://github.com/rest-assured/rest-assured/wiki/Usage // .body("oai_dc:dc.find { it == 'dc:title' }.item", hasItems("Darwin's Finches")) .statusCode(OK.getStatusCode()); Response exportDatasetAsDdi = UtilIT.exportDataset(datasetPersistentId, "ddi", apiToken); exportDatasetAsDdi.prettyPrint(); exportDatasetAsDdi.then().assertThat() .statusCode(OK.getStatusCode()); assertEquals("sammi@sample.com", XmlPath.from(exportDatasetAsDdi.body().asString()).getString("codeBook.stdyDscr.stdyInfo.contact.@email")); assertEquals(datasetPersistentId, XmlPath.from(exportDatasetAsDdi.body().asString()).getString("codeBook.docDscr.citation.titlStmt.IDNo")); Response deleteDatasetResponse = UtilIT.destroyDataset(datasetId, apiToken); deleteDatasetResponse.prettyPrint(); assertEquals(200, deleteDatasetResponse.getStatusCode()); Response deleteDataverseResponse = UtilIT.deleteDataverse(dataverseAlias, apiToken); deleteDataverseResponse.prettyPrint(); assertEquals(200, deleteDataverseResponse.getStatusCode()); Response deleteUserResponse = UtilIT.deleteUser(username); deleteUserResponse.prettyPrint(); assertEquals(200, deleteUserResponse.getStatusCode()); } /** * This test requires the root dataverse to be published to pass. */ @Test public void testExcludeEmail() { Response createUser = UtilIT.createRandomUser(); createUser.prettyPrint(); assertEquals(200, createUser.getStatusCode()); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); Response makeSuperUser = UtilIT.makeSuperUser(username); assertEquals(200, makeSuperUser.getStatusCode()); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); String pathToJsonFile = "scripts/api/data/dataset-create-new.json"; Response createDatasetResponse = UtilIT.createDatasetViaNativeApi(dataverseAlias, pathToJsonFile, apiToken); createDatasetResponse.prettyPrint(); Integer datasetId = JsonPath.from(createDatasetResponse.body().asString()).getInt("data.id"); Response getDatasetJsonBeforePublishing = UtilIT.nativeGet(datasetId, apiToken); getDatasetJsonBeforePublishing.prettyPrint(); String protocol = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.protocol"); String authority = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.authority"); String identifier = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.identifier"); String datasetPersistentId = protocol + ":" + authority + "/" + identifier; Response publishDataverse = UtilIT.publishDataverseViaSword(dataverseAlias, apiToken); assertEquals(200, publishDataverse.getStatusCode()); Response attemptToPublishZeroDotOne = UtilIT.publishDatasetViaNativeApiDeprecated(datasetPersistentId, "minor", apiToken); attemptToPublishZeroDotOne.prettyPrint(); attemptToPublishZeroDotOne.then().assertThat() .body("message", equalTo("Cannot publish as minor version. Re-try as major release.")) .statusCode(403); Response setToExcludeEmailFromExport = UtilIT.setSetting(SettingsServiceBean.Key.ExcludeEmailFromExport, "true"); setToExcludeEmailFromExport.then().assertThat() .statusCode(OK.getStatusCode()); Response publishDataset = UtilIT.publishDatasetViaNativeApi(datasetPersistentId, "major", apiToken); assertEquals(200, publishDataset.getStatusCode()); Response getDatasetJsonAfterPublishing = UtilIT.nativeGet(datasetId, apiToken); getDatasetJsonAfterPublishing.prettyPrint(); getDatasetJsonAfterPublishing.then().assertThat() .body("data.latestVersion.versionNumber", equalTo(1)) .body("data.latestVersion.versionMinorNumber", equalTo(0)) .statusCode(OK.getStatusCode()); Response exportDatasetAsDdi = UtilIT.exportDataset(datasetPersistentId, "ddi", apiToken); exportDatasetAsDdi.prettyPrint(); exportDatasetAsDdi.then().assertThat() .statusCode(OK.getStatusCode()); assertEquals("Dataverse, Admin", XmlPath.from(exportDatasetAsDdi.body().asString()).getString("codeBook.stdyDscr.stdyInfo.contact")); assertEquals("[]", XmlPath.from(exportDatasetAsDdi.body().asString()).getString("codeBook.stdyDscr.stdyInfo.contact.@email")); assertEquals("Sample Datasets, inc.", XmlPath.from(exportDatasetAsDdi.body().asString()).getString("codeBook.stdyDscr.stdyInfo.contact.@affiliation")); assertEquals(datasetPersistentId, XmlPath.from(exportDatasetAsDdi.body().asString()).getString("codeBook.docDscr.citation.titlStmt.IDNo")); List<JsonObject> datasetContactsFromNativeGet = with(getDatasetJsonAfterPublishing.body().asString()).param("datasetContact", "datasetContact") .getJsonObject("data.latestVersion.metadataBlocks.citation.fields.findAll { fields -> fields.typeName == datasetContact }"); // TODO: Assert that email can't be found. assertEquals(1, datasetContactsFromNativeGet.size()); // TODO: Write test for DDI too. Response exportDatasetAsJson = UtilIT.exportDataset(datasetPersistentId, "dataverse_json", apiToken); exportDatasetAsJson.prettyPrint(); exportDatasetAsJson.then().assertThat() .statusCode(OK.getStatusCode()); RestAssured.unregisterParser("text/plain"); List<JsonObject> datasetContactsFromExport = with(exportDatasetAsJson.body().asString()).param("datasetContact", "datasetContact") .getJsonObject("datasetVersion.metadataBlocks.citation.fields.findAll { fields -> fields.typeName == datasetContact }"); // TODO: Assert that email can't be found. assertEquals(1, datasetContactsFromExport.size()); Response citationBlock = UtilIT.getMetadataBlockFromDatasetVersion(datasetPersistentId, null, null, apiToken); citationBlock.prettyPrint(); citationBlock.then().assertThat() .statusCode(OK.getStatusCode()); List<JsonObject> datasetContactsFromCitationBlock = with(citationBlock.body().asString()).param("datasetContact", "datasetContact") .getJsonObject("data.fields.findAll { fields -> fields.typeName == datasetContact }"); // TODO: Assert that email can't be found. assertEquals(1, datasetContactsFromCitationBlock.size()); Response deleteDatasetResponse = UtilIT.destroyDataset(datasetId, apiToken); deleteDatasetResponse.prettyPrint(); assertEquals(200, deleteDatasetResponse.getStatusCode()); Response deleteDataverseResponse = UtilIT.deleteDataverse(dataverseAlias, apiToken); deleteDataverseResponse.prettyPrint(); assertEquals(200, deleteDataverseResponse.getStatusCode()); Response deleteUserResponse = UtilIT.deleteUser(username); deleteUserResponse.prettyPrint(); assertEquals(200, deleteUserResponse.getStatusCode()); Response removeExcludeEmail = UtilIT.deleteSetting(SettingsServiceBean.Key.ExcludeEmailFromExport); removeExcludeEmail.then().assertThat() .statusCode(200); } @Test public void testSequentialNumberAsIdentifierGenerationStyle() { Response createUser = UtilIT.createRandomUser(); createUser.prettyPrint(); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); Response setSequentialNumberAsIdentifierGenerationStyle = UtilIT.setSetting(SettingsServiceBean.Key.IdentifierGenerationStyle, "sequentialNumber"); setSequentialNumberAsIdentifierGenerationStyle.then().assertThat() .statusCode(OK.getStatusCode()); Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); createDatasetResponse.prettyPrint(); Integer datasetId = UtilIT.getDatasetIdFromResponse(createDatasetResponse); Response datasetAsJson = UtilIT.nativeGet(datasetId, apiToken); datasetAsJson.then().assertThat() .statusCode(OK.getStatusCode()); String identifier = JsonPath.from(datasetAsJson.getBody().asString()).getString("data.identifier"); System.out.println("identifier: " + identifier); String numericPart = identifier.replace("FK2/", ""); //remove shoulder from identifier assertTrue(StringUtils.isNumeric(numericPart)); Response deleteDatasetResponse = UtilIT.deleteDatasetViaNativeApi(datasetId, apiToken); deleteDatasetResponse.prettyPrint(); assertEquals(200, deleteDatasetResponse.getStatusCode()); Response deleteDataverseResponse = UtilIT.deleteDataverse(dataverseAlias, apiToken); deleteDataverseResponse.prettyPrint(); assertEquals(200, deleteDataverseResponse.getStatusCode()); Response deleteUserResponse = UtilIT.deleteUser(username); deleteUserResponse.prettyPrint(); assertEquals(200, deleteUserResponse.getStatusCode()); Response remove = UtilIT.deleteSetting(SettingsServiceBean.Key.IdentifierGenerationStyle); remove.then().assertThat() .statusCode(200); } /** * This test requires the root dataverse to be published to pass. */ @Test public void testPrivateUrl() { Response createUser = UtilIT.createRandomUser(); // createUser.prettyPrint(); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); Response failToCreateWhenDatasetIdNotFound = UtilIT.privateUrlCreate(Integer.MAX_VALUE, apiToken); failToCreateWhenDatasetIdNotFound.prettyPrint(); assertEquals(NOT_FOUND.getStatusCode(), failToCreateWhenDatasetIdNotFound.getStatusCode()); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); createDatasetResponse.prettyPrint(); Integer datasetId = JsonPath.from(createDatasetResponse.body().asString()).getInt("data.id"); System.out.println("dataset id: " + datasetId); Response createContributorResponse = UtilIT.createRandomUser(); String contributorUsername = UtilIT.getUsernameFromResponse(createContributorResponse); String contributorApiToken = UtilIT.getApiTokenFromResponse(createContributorResponse); UtilIT.getRoleAssignmentsOnDataverse(dataverseAlias, apiToken).prettyPrint(); Response grantRoleShouldFail = UtilIT.grantRoleOnDataverse(dataverseAlias, DataverseRole.EDITOR.toString(), "doesNotExist", apiToken); grantRoleShouldFail.then().assertThat() .statusCode(BAD_REQUEST.getStatusCode()) .body("message", equalTo("Assignee not found")); /** * editor (a.k.a. Contributor) has "ViewUnpublishedDataset", * "EditDataset", "DownloadFile", and "DeleteDatasetDraft" per * scripts/api/data/role-editor.json */ Response grantRole = UtilIT.grantRoleOnDataverse(dataverseAlias, DataverseRole.EDITOR.toString(), "@" + contributorUsername, apiToken); grantRole.prettyPrint(); assertEquals(OK.getStatusCode(), grantRole.getStatusCode()); UtilIT.getRoleAssignmentsOnDataverse(dataverseAlias, apiToken).prettyPrint(); Response contributorDoesNotHavePermissionToCreatePrivateUrl = UtilIT.privateUrlCreate(datasetId, contributorApiToken); contributorDoesNotHavePermissionToCreatePrivateUrl.prettyPrint(); assertEquals(UNAUTHORIZED.getStatusCode(), contributorDoesNotHavePermissionToCreatePrivateUrl.getStatusCode()); Response getDatasetJson = UtilIT.nativeGet(datasetId, apiToken); getDatasetJson.prettyPrint(); String protocol1 = JsonPath.from(getDatasetJson.getBody().asString()).getString("data.protocol"); String authority1 = JsonPath.from(getDatasetJson.getBody().asString()).getString("data.authority"); String identifier1 = JsonPath.from(getDatasetJson.getBody().asString()).getString("data.identifier"); String dataset1PersistentId = protocol1 + ":" + authority1 + "/" + identifier1; Response uploadFileResponse = UtilIT.uploadRandomFile(dataset1PersistentId, apiToken); uploadFileResponse.prettyPrint(); assertEquals(CREATED.getStatusCode(), uploadFileResponse.getStatusCode()); Response badApiKeyEmptyString = UtilIT.privateUrlGet(datasetId, ""); badApiKeyEmptyString.prettyPrint(); assertEquals(UNAUTHORIZED.getStatusCode(), badApiKeyEmptyString.getStatusCode()); Response badApiKeyDoesNotExist = UtilIT.privateUrlGet(datasetId, "junk"); badApiKeyDoesNotExist.prettyPrint(); assertEquals(UNAUTHORIZED.getStatusCode(), badApiKeyDoesNotExist.getStatusCode()); Response badDatasetId = UtilIT.privateUrlGet(Integer.MAX_VALUE, apiToken); badDatasetId.prettyPrint(); assertEquals(NOT_FOUND.getStatusCode(), badDatasetId.getStatusCode()); Response pristine = UtilIT.privateUrlGet(datasetId, apiToken); pristine.prettyPrint(); assertEquals(NOT_FOUND.getStatusCode(), pristine.getStatusCode()); Response createPrivateUrl = UtilIT.privateUrlCreate(datasetId, apiToken); createPrivateUrl.prettyPrint(); assertEquals(OK.getStatusCode(), createPrivateUrl.getStatusCode()); Response userWithNoRoles = UtilIT.createRandomUser(); String userWithNoRolesApiToken = UtilIT.getApiTokenFromResponse(userWithNoRoles); Response unAuth = UtilIT.privateUrlGet(datasetId, userWithNoRolesApiToken); unAuth.prettyPrint(); assertEquals(UNAUTHORIZED.getStatusCode(), unAuth.getStatusCode()); Response shouldExist = UtilIT.privateUrlGet(datasetId, apiToken); shouldExist.prettyPrint(); assertEquals(OK.getStatusCode(), shouldExist.getStatusCode()); String tokenForPrivateUrlUser = JsonPath.from(shouldExist.body().asString()).getString("data.token"); logger.info("privateUrlToken: " + tokenForPrivateUrlUser); String urlWithToken = JsonPath.from(shouldExist.body().asString()).getString("data.link"); logger.info("URL with token: " + urlWithToken); assertEquals(tokenForPrivateUrlUser, urlWithToken.substring(urlWithToken.length() - UUID.randomUUID().toString().length())); /** * If you're getting a crazy error like this... * * javax.net.ssl.SSLHandshakeException: * sun.security.validator.ValidatorException: PKIX path building failed: * sun.security.provider.certpath.SunCertPathBuilderException: unable to * find valid certification path to requested target * * ... you might do well to set "siteUrl" to localhost:8080 like this: * * asadmin create-jvm-options * "-Ddataverse.siteUrl=http\://localhost\:8080" */ Response getDatasetAsUserWhoClicksPrivateUrl = given() .header(API_TOKEN_HTTP_HEADER, apiToken) .get(urlWithToken); String title = getDatasetAsUserWhoClicksPrivateUrl.getBody().htmlPath().getString("html.head.title"); assertEquals("Darwin's Finches - " + dataverseAlias, title); assertEquals(OK.getStatusCode(), getDatasetAsUserWhoClicksPrivateUrl.getStatusCode()); Response junkPrivateUrlToken = given() .header(API_TOKEN_HTTP_HEADER, apiToken) .get("/privateurl.xhtml?token=" + "junk"); assertEquals("404 Not Found", junkPrivateUrlToken.getBody().htmlPath().getString("html.head.title").substring(0, 13)); long roleAssignmentIdFromCreate = JsonPath.from(createPrivateUrl.body().asString()).getLong("data.roleAssignment.id"); logger.info("roleAssignmentIdFromCreate: " + roleAssignmentIdFromCreate); Response badAnonLinkTokenEmptyString = UtilIT.nativeGet(datasetId, ""); badAnonLinkTokenEmptyString.prettyPrint(); assertEquals(UNAUTHORIZED.getStatusCode(), badAnonLinkTokenEmptyString.getStatusCode()); Response getWithPrivateUrlToken = UtilIT.nativeGet(datasetId, tokenForPrivateUrlUser); assertEquals(OK.getStatusCode(), getWithPrivateUrlToken.getStatusCode()); // getWithPrivateUrlToken.prettyPrint(); logger.info("http://localhost:8080/privateurl.xhtml?token=" + tokenForPrivateUrlUser); Response swordStatement = UtilIT.getSwordStatement(dataset1PersistentId, apiToken); assertEquals(OK.getStatusCode(), swordStatement.getStatusCode()); Integer fileId = UtilIT.getFileIdFromSwordStatementResponse(swordStatement); Response downloadFile = UtilIT.downloadFile(fileId, tokenForPrivateUrlUser); assertEquals(OK.getStatusCode(), downloadFile.getStatusCode()); Response downloadFileBadToken = UtilIT.downloadFile(fileId, "junk"); assertEquals(FORBIDDEN.getStatusCode(), downloadFileBadToken.getStatusCode()); Response notPermittedToListRoleAssignment = UtilIT.getRoleAssignmentsOnDataset(datasetId.toString(), null, userWithNoRolesApiToken); assertEquals(UNAUTHORIZED.getStatusCode(), notPermittedToListRoleAssignment.getStatusCode()); Response roleAssignments = UtilIT.getRoleAssignmentsOnDataset(datasetId.toString(), null, apiToken); roleAssignments.prettyPrint(); assertEquals(OK.getStatusCode(), roleAssignments.getStatusCode()); List<JsonObject> assignments = with(roleAssignments.body().asString()).param("member", "member").getJsonObject("data.findAll { data -> data._roleAlias == member }"); assertEquals(1, assignments.size()); PrivateUrlUser privateUrlUser = new PrivateUrlUser(datasetId); assertEquals("Private URL Enabled", privateUrlUser.getDisplayInfo().getTitle()); List<JsonObject> assigneeShouldExistForPrivateUrlUser = with(roleAssignments.body().asString()).param("assigneeString", privateUrlUser.getIdentifier()).getJsonObject("data.findAll { data -> data.assignee == assigneeString }"); logger.info(assigneeShouldExistForPrivateUrlUser + " found for " + privateUrlUser.getIdentifier()); assertEquals(1, assigneeShouldExistForPrivateUrlUser.size()); Map roleAssignment = assignments.get(0); int roleAssignmentId = (int) roleAssignment.get("id"); logger.info("role assignment id: " + roleAssignmentId); assertEquals(roleAssignmentIdFromCreate, roleAssignmentId); Response revoke = UtilIT.revokeRole(dataverseAlias, roleAssignmentId, apiToken); revoke.prettyPrint(); assertEquals(OK.getStatusCode(), revoke.getStatusCode()); Response shouldNoLongerExist = UtilIT.privateUrlGet(datasetId, apiToken); shouldNoLongerExist.prettyPrint(); assertEquals(NOT_FOUND.getStatusCode(), shouldNoLongerExist.getStatusCode()); Response createPrivateUrlUnauth = UtilIT.privateUrlCreate(datasetId, userWithNoRolesApiToken); createPrivateUrlUnauth.prettyPrint(); assertEquals(UNAUTHORIZED.getStatusCode(), createPrivateUrlUnauth.getStatusCode()); Response createPrivateUrlAgain = UtilIT.privateUrlCreate(datasetId, apiToken); createPrivateUrlAgain.prettyPrint(); assertEquals(OK.getStatusCode(), createPrivateUrlAgain.getStatusCode()); Response shouldNotDeletePrivateUrl = UtilIT.privateUrlDelete(datasetId, userWithNoRolesApiToken); shouldNotDeletePrivateUrl.prettyPrint(); assertEquals(UNAUTHORIZED.getStatusCode(), shouldNotDeletePrivateUrl.getStatusCode()); Response deletePrivateUrlResponse = UtilIT.privateUrlDelete(datasetId, apiToken); deletePrivateUrlResponse.prettyPrint(); assertEquals(OK.getStatusCode(), deletePrivateUrlResponse.getStatusCode()); Response tryToDeleteAlreadyDeletedPrivateUrl = UtilIT.privateUrlDelete(datasetId, apiToken); tryToDeleteAlreadyDeletedPrivateUrl.prettyPrint(); assertEquals(NOT_FOUND.getStatusCode(), tryToDeleteAlreadyDeletedPrivateUrl.getStatusCode()); Response createPrivateUrlOnceAgain = UtilIT.privateUrlCreate(datasetId, apiToken); createPrivateUrlOnceAgain.prettyPrint(); assertEquals(OK.getStatusCode(), createPrivateUrlOnceAgain.getStatusCode()); Response tryToCreatePrivateUrlWhenExisting = UtilIT.privateUrlCreate(datasetId, apiToken); tryToCreatePrivateUrlWhenExisting.prettyPrint(); assertEquals(FORBIDDEN.getStatusCode(), tryToCreatePrivateUrlWhenExisting.getStatusCode()); Response publishDataverse = UtilIT.publishDataverseViaSword(dataverseAlias, apiToken); assertEquals(OK.getStatusCode(), publishDataverse.getStatusCode()); Response publishDataset = UtilIT.publishDatasetViaSword(dataset1PersistentId, apiToken); assertEquals(OK.getStatusCode(), publishDataset.getStatusCode()); Response privateUrlTokenShouldBeDeletedOnPublish = UtilIT.privateUrlGet(datasetId, apiToken); privateUrlTokenShouldBeDeletedOnPublish.prettyPrint(); assertEquals(NOT_FOUND.getStatusCode(), privateUrlTokenShouldBeDeletedOnPublish.getStatusCode()); Response getRoleAssignmentsOnDatasetShouldFailUnauthorized = UtilIT.getRoleAssignmentsOnDataset(datasetId.toString(), null, userWithNoRolesApiToken); assertEquals(UNAUTHORIZED.getStatusCode(), getRoleAssignmentsOnDatasetShouldFailUnauthorized.getStatusCode()); Response publishingShouldHaveRemovedRoleAssignmentForPrivateUrlUser = UtilIT.getRoleAssignmentsOnDataset(datasetId.toString(), null, apiToken); publishingShouldHaveRemovedRoleAssignmentForPrivateUrlUser.prettyPrint(); List<JsonObject> noAssignmentsForPrivateUrlUser = with(publishingShouldHaveRemovedRoleAssignmentForPrivateUrlUser.body().asString()).param("member", "member").getJsonObject("data.findAll { data -> data._roleAlias == member }"); assertEquals(0, noAssignmentsForPrivateUrlUser.size()); Response tryToCreatePrivateUrlToPublishedVersion = UtilIT.privateUrlCreate(datasetId, apiToken); tryToCreatePrivateUrlToPublishedVersion.prettyPrint(); assertEquals(FORBIDDEN.getStatusCode(), tryToCreatePrivateUrlToPublishedVersion.getStatusCode()); String newTitle = "I am changing the title"; Response updatedMetadataResponse = UtilIT.updateDatasetTitleViaSword(dataset1PersistentId, newTitle, apiToken); updatedMetadataResponse.prettyPrint(); assertEquals(OK.getStatusCode(), updatedMetadataResponse.getStatusCode()); Response createPrivateUrlForPostVersionOneDraft = UtilIT.privateUrlCreate(datasetId, apiToken); createPrivateUrlForPostVersionOneDraft.prettyPrint(); assertEquals(OK.getStatusCode(), createPrivateUrlForPostVersionOneDraft.getStatusCode()); // A Contributor has DeleteDatasetDraft Response deleteDraftVersionAsContributor = UtilIT.deleteDatasetVersionViaNativeApi(datasetId, ":draft", contributorApiToken); deleteDraftVersionAsContributor.prettyPrint(); deleteDraftVersionAsContributor.then().assertThat() .statusCode(OK.getStatusCode()) .body("data.message", equalTo("Draft version of dataset " + datasetId + " deleted")); Response privateUrlRoleAssignmentShouldBeGoneAfterDraftDeleted = UtilIT.getRoleAssignmentsOnDataset(datasetId.toString(), null, apiToken); privateUrlRoleAssignmentShouldBeGoneAfterDraftDeleted.prettyPrint(); assertEquals(false, privateUrlRoleAssignmentShouldBeGoneAfterDraftDeleted.body().asString().contains(privateUrlUser.getIdentifier())); String newTitleAgain = "I am changing the title again"; Response draftCreatedAgainPostPub = UtilIT.updateDatasetTitleViaSword(dataset1PersistentId, newTitleAgain, apiToken); draftCreatedAgainPostPub.prettyPrint(); assertEquals(OK.getStatusCode(), draftCreatedAgainPostPub.getStatusCode()); /** * Making sure the Private URL is deleted when a dataset is destroyed is * less of an issue now that a Private URL is now effectively only a * specialized role assignment which is already known to be deleted when * a dataset is destroy. Still, we'll keep this test in here in case we * switch Private URL back to being its own table in the future. */ Response createPrivateUrlToMakeSureItIsDeletedWithDestructionOfDataset = UtilIT.privateUrlCreate(datasetId, apiToken); createPrivateUrlToMakeSureItIsDeletedWithDestructionOfDataset.prettyPrint(); assertEquals(OK.getStatusCode(), createPrivateUrlToMakeSureItIsDeletedWithDestructionOfDataset.getStatusCode()); Response makeSuperUser = UtilIT.makeSuperUser(username); assertEquals(200, makeSuperUser.getStatusCode()); Response destroyDatasetResponse = UtilIT.destroyDataset(datasetId, apiToken); destroyDatasetResponse.prettyPrint(); assertEquals(200, destroyDatasetResponse.getStatusCode()); Response deleteDataverseResponse = UtilIT.deleteDataverse(dataverseAlias, apiToken); deleteDataverseResponse.prettyPrint(); assertEquals(200, deleteDataverseResponse.getStatusCode()); Response deleteUserResponse = UtilIT.deleteUser(username); deleteUserResponse.prettyPrint(); assertEquals(200, deleteUserResponse.getStatusCode()); /** * @todo Should the Search API work with the Private URL token? */ } @Test public void testFileChecksum() { Response createUser = UtilIT.createRandomUser(); // createUser.prettyPrint(); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); createDatasetResponse.prettyPrint(); Integer datasetId = JsonPath.from(createDatasetResponse.body().asString()).getInt("data.id"); System.out.println("dataset id: " + datasetId); Response getDatasetJsonNoFiles = UtilIT.nativeGet(datasetId, apiToken); getDatasetJsonNoFiles.prettyPrint(); String protocol1 = JsonPath.from(getDatasetJsonNoFiles.getBody().asString()).getString("data.protocol"); String authority1 = JsonPath.from(getDatasetJsonNoFiles.getBody().asString()).getString("data.authority"); String identifier1 = JsonPath.from(getDatasetJsonNoFiles.getBody().asString()).getString("data.identifier"); String dataset1PersistentId = protocol1 + ":" + authority1 + "/" + identifier1; Response makeSureSettingIsDefault = UtilIT.deleteSetting(SettingsServiceBean.Key.FileFixityChecksumAlgorithm); makeSureSettingIsDefault.prettyPrint(); makeSureSettingIsDefault.then().assertThat() .statusCode(OK.getStatusCode()) .body("data.message", equalTo("Setting :FileFixityChecksumAlgorithm deleted.")); Response getDefaultSetting = UtilIT.getSetting(SettingsServiceBean.Key.FileFixityChecksumAlgorithm); getDefaultSetting.prettyPrint(); getDefaultSetting.then().assertThat() .body("message", equalTo("Setting :FileFixityChecksumAlgorithm not found")); Response uploadMd5File = UtilIT.uploadRandomFile(dataset1PersistentId, apiToken); uploadMd5File.prettyPrint(); assertEquals(CREATED.getStatusCode(), uploadMd5File.getStatusCode()); Response getDatasetJsonAfterMd5File = UtilIT.nativeGet(datasetId, apiToken); getDatasetJsonAfterMd5File.prettyPrint(); getDatasetJsonAfterMd5File.then().assertThat() .body("data.latestVersion.files[0].dataFile.md5", equalTo("0386269a5acb2c57b4eade587ff4db64")) .body("data.latestVersion.files[0].dataFile.checksum.type", equalTo("MD5")) .body("data.latestVersion.files[0].dataFile.checksum.value", equalTo("0386269a5acb2c57b4eade587ff4db64")); int fileId = JsonPath.from(getDatasetJsonAfterMd5File.getBody().asString()).getInt("data.latestVersion.files[0].dataFile.id"); Response deleteFile = UtilIT.deleteFile(fileId, apiToken); deleteFile.prettyPrint(); deleteFile.then().assertThat() .statusCode(NO_CONTENT.getStatusCode()); Response setToSha1 = UtilIT.setSetting(SettingsServiceBean.Key.FileFixityChecksumAlgorithm, DataFile.ChecksumType.SHA1.toString()); setToSha1.prettyPrint(); setToSha1.then().assertThat() .statusCode(OK.getStatusCode()); Response getNonDefaultSetting = UtilIT.getSetting(SettingsServiceBean.Key.FileFixityChecksumAlgorithm); getNonDefaultSetting.prettyPrint(); getNonDefaultSetting.then().assertThat() .body("data.message", equalTo("SHA-1")) .statusCode(OK.getStatusCode()); Response uploadSha1File = UtilIT.uploadRandomFile(dataset1PersistentId, apiToken); uploadSha1File.prettyPrint(); assertEquals(CREATED.getStatusCode(), uploadSha1File.getStatusCode()); Response getDatasetJsonAfterSha1File = UtilIT.nativeGet(datasetId, apiToken); getDatasetJsonAfterSha1File.prettyPrint(); getDatasetJsonAfterSha1File.then().assertThat() .body("data.latestVersion.files[0].dataFile.md5", nullValue()) .body("data.latestVersion.files[0].dataFile.checksum.type", equalTo("SHA-1")) .body("data.latestVersion.files[0].dataFile.checksum.value", equalTo("17ea9225aa0e96ae6ff61c256237d6add6c197d1")) .statusCode(OK.getStatusCode()); } @Test public void testDeleteDatasetWhileFileIngesting() { Response createUser = UtilIT.createRandomUser(); createUser.then().assertThat() .statusCode(OK.getStatusCode()); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); createDataverseResponse.then().assertThat() .statusCode(CREATED.getStatusCode()); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); createDatasetResponse.prettyPrint(); createDatasetResponse.then().assertThat() .statusCode(CREATED.getStatusCode()); Integer datasetId = JsonPath.from(createDatasetResponse.body().asString()).getInt("data.id"); String persistentId = JsonPath.from(createDatasetResponse.body().asString()).getString("data.persistentId"); logger.info("Dataset created with id " + datasetId + " and persistent id " + persistentId); String pathToFileThatGoesThroughIngest = "scripts/search/data/tabular/50by1000.dta"; Response uploadIngestableFile = UtilIT.uploadFileViaNative(datasetId.toString(), pathToFileThatGoesThroughIngest, apiToken); uploadIngestableFile.then().assertThat() .statusCode(OK.getStatusCode()); Response deleteDataset = UtilIT.deleteDatasetViaNativeApi(datasetId, apiToken); deleteDataset.prettyPrint(); deleteDataset.then().assertThat() .body("message", equalTo("Dataset cannot be edited due to dataset lock.")) .statusCode(FORBIDDEN.getStatusCode()); } @Test public void testCreateDatasetWithDcmDependency() { boolean disabled = true; if (disabled) { return; } // TODO: Test this with a value like "junk" rather than a valid URL which would give `java.net.MalformedURLException: no protocol`. String dcmVagrantUrl = "http://localhost:8888"; String dcmMockUrl = "http://localhost:5000"; String dcmUrl = dcmMockUrl; Response setDcmUrl = UtilIT.setSetting(SettingsServiceBean.Key.DataCaptureModuleUrl, dcmUrl); setDcmUrl.then().assertThat() .statusCode(OK.getStatusCode()); Response setUploadMethods = UtilIT.setSetting(SettingsServiceBean.Key.UploadMethods, SystemConfig.FileUploadMethods.RSYNC.toString()); setUploadMethods.then().assertThat() .statusCode(OK.getStatusCode()); Response urlConfigured = given() // .header(UtilIT.API_TOKEN_HTTP_HEADER, apiToken) .get("/api/admin/settings/" + SettingsServiceBean.Key.DataCaptureModuleUrl.toString()); if (urlConfigured.getStatusCode() != 200) { fail(SettingsServiceBean.Key.DataCaptureModuleUrl + " has not been not configured. This test cannot run without it."); } Response createUser = UtilIT.createRandomUser(); createUser.prettyPrint(); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); long userId = JsonPath.from(createUser.body().asString()).getLong("data.authenticatedUser.id"); /** * @todo Query system to see which file upload mechanisms are available. */ // String dataverseAlias = "dv" + UtilIT.getRandomIdentifier(); // List<String> fileUploadMechanismsEnabled = Arrays.asList(Dataset.FileUploadMechanism.RSYNC.toString()); // Response createDataverseResponse = UtilIT.createDataverse(dataverseAlias, fileUploadMechanismsEnabled, apiToken); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); createDataverseResponse.then().assertThat() // .body("data.alias", equalTo(dataverseAlias)) // .body("data.fileUploadMechanismsEnabled[0]", equalTo(Dataset.FileUploadMechanism.RSYNC.toString())) .statusCode(201); /** * @todo Make this configurable at runtime similar to * UtilIT.getRestAssuredBaseUri */ // Response createDatasetResponse = UtilIT.createDatasetWithDcmDependency(dataverseAlias, apiToken); // Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); createDatasetResponse.prettyPrint(); Integer datasetId = UtilIT.getDatasetIdFromResponse(createDatasetResponse); Response getDatasetJson = UtilIT.nativeGet(datasetId, apiToken); getDatasetJson.prettyPrint(); String protocol1 = JsonPath.from(getDatasetJson.getBody().asString()).getString("data.protocol"); String authority1 = JsonPath.from(getDatasetJson.getBody().asString()).getString("data.authority"); String identifier1 = JsonPath.from(getDatasetJson.getBody().asString()).getString("data.identifier"); String datasetPersistentId = protocol1 + ":" + authority1 + "/" + identifier1; Response getDatasetResponse = given() .header(UtilIT.API_TOKEN_HTTP_HEADER, apiToken) .get("/api/datasets/" + datasetId); getDatasetResponse.prettyPrint(); getDatasetResponse.then().assertThat() .statusCode(200); // final List<Map<String, ?>> dataTypeField = JsonPath.with(getDatasetResponse.body().asString()) // .get("data.latestVersion.metadataBlocks.citation.fields.findAll { it.typeName == 'dataType' }"); // logger.fine("dataTypeField: " + dataTypeField); // assertThat(dataTypeField.size(), equalTo(1)); // assertEquals("dataType", dataTypeField.get(0).get("typeName")); // assertEquals("controlledVocabulary", dataTypeField.get(0).get("typeClass")); // assertEquals("X-Ray Diffraction", dataTypeField.get(0).get("value")); // assertTrue(dataTypeField.get(0).get("multiple").equals(false)); String nullTokenToIndicateGuest = null; Response getRsyncScriptPermErrorGuest = UtilIT.getRsyncScript(datasetPersistentId, nullTokenToIndicateGuest); getRsyncScriptPermErrorGuest.prettyPrint(); getRsyncScriptPermErrorGuest.then().assertThat() .contentType(ContentType.JSON) .body("message", equalTo("User :guest is not permitted to perform requested action.")) .statusCode(UNAUTHORIZED.getStatusCode()); Response createNoPermsUser = UtilIT.createRandomUser(); String noPermsUsername = UtilIT.getUsernameFromResponse(createNoPermsUser); String noPermsApiToken = UtilIT.getApiTokenFromResponse(createNoPermsUser); Response getRsyncScriptPermErrorNonGuest = UtilIT.getRsyncScript(datasetPersistentId, noPermsApiToken); getRsyncScriptPermErrorNonGuest.then().assertThat() .contentType(ContentType.JSON) .body("message", equalTo("User @" + noPermsUsername + " is not permitted to perform requested action.")) .statusCode(UNAUTHORIZED.getStatusCode()); boolean stopEarlyBecauseYouDoNotHaveDcmInstalled = true; if (stopEarlyBecauseYouDoNotHaveDcmInstalled) { return; } boolean stopEarlyToVerifyTheScriptWasCreated = false; if (stopEarlyToVerifyTheScriptWasCreated) { logger.info("On the DCM, does /deposit/gen/upload-" + datasetId + ".bash exist? It should! Creating the dataset should be enough to create it."); return; } Response getRsyncScript = UtilIT.getRsyncScript(datasetPersistentId, apiToken); getRsyncScript.prettyPrint(); System.out.println("content type: " + getRsyncScript.getContentType()); // text/html;charset=ISO-8859-1 getRsyncScript.then().assertThat() .contentType(ContentType.TEXT) .statusCode(200); String rsyncScript = getRsyncScript.body().asString(); System.out.println("script:\n" + rsyncScript); assertTrue(rsyncScript.startsWith("#!")); assertTrue(rsyncScript.contains("placeholder")); // The DCM mock script has the word "placeholder" in it. Response removeUploadMethods = UtilIT.deleteSetting(SettingsServiceBean.Key.UploadMethods); removeUploadMethods.then().assertThat() .statusCode(200); Response createUser2 = UtilIT.createRandomUser(); String username2 = UtilIT.getUsernameFromResponse(createUser2); String apiToken2 = UtilIT.getApiTokenFromResponse(createUser2); Response createDataverseResponse2 = UtilIT.createRandomDataverse(apiToken2); createDataverseResponse2.prettyPrint(); String dataverseAlias2 = UtilIT.getAliasFromResponse(createDataverseResponse2); Response createDatasetResponse2 = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias2, apiToken2); createDatasetResponse2.prettyPrint(); Integer datasetId2 = JsonPath.from(createDatasetResponse2.body().asString()).getInt("data.id"); System.out.println("dataset id: " + datasetId); Response attemptToGetRsyncScriptForNonRsyncDataset = given() .header(UtilIT.API_TOKEN_HTTP_HEADER, apiToken2) .get("/api/datasets/" + datasetId2 + "/dataCaptureModule/rsync"); attemptToGetRsyncScriptForNonRsyncDataset.prettyPrint(); attemptToGetRsyncScriptForNonRsyncDataset.then().assertThat() .body("message", equalTo(":UploadMethods does not contain dcm/rsync+ssh.")) .statusCode(METHOD_NOT_ALLOWED.getStatusCode()); } /** * This test is just a test of notifications so a fully implemented dcm is * not necessary */ @Test public void testDcmChecksumValidationMessages() throws IOException, InterruptedException { /*SEK 3/28/2018 This test needs more work Currently it is failing at around line 1114 Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); the CreateDatasetCommand is not getting the rsync script so the dataset is not being created so the whole test is failing */ boolean disabled = true; if (disabled) { return; } String dcmVagrantUrl = "http://localhost:8888"; String dcmMockUrl = "http://localhost:5000"; String dcmUrl = dcmMockUrl; Response setDcmUrl = UtilIT.setSetting(SettingsServiceBean.Key.DataCaptureModuleUrl, dcmUrl); setDcmUrl.then().assertThat() .statusCode(OK.getStatusCode()); Response setUploadMethods = UtilIT.setSetting(SettingsServiceBean.Key.UploadMethods, SystemConfig.FileUploadMethods.RSYNC.toString()); setUploadMethods.then().assertThat() .statusCode(OK.getStatusCode()); Response urlConfigured = given() .get("/api/admin/settings/" + SettingsServiceBean.Key.DataCaptureModuleUrl.toString()); if (urlConfigured.getStatusCode() != 200) { fail(SettingsServiceBean.Key.DataCaptureModuleUrl + " has not been not configured. This test cannot run without it."); } Response createUser = UtilIT.createRandomUser(); createUser.prettyPrint(); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); long userId = JsonPath.from(createUser.body().asString()).getLong("data.authenticatedUser.id"); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); createDataverseResponse.then().assertThat() .statusCode(201); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); createDatasetResponse.prettyPrint(); Integer datasetId = UtilIT.getDatasetIdFromResponse(createDatasetResponse); Response getDatasetJson = UtilIT.nativeGet(datasetId, apiToken); getDatasetJson.prettyPrint(); Response getDatasetResponse = given() .header(UtilIT.API_TOKEN_HTTP_HEADER, apiToken) .get("/api/datasets/" + datasetId); getDatasetResponse.prettyPrint(); getDatasetResponse.then().assertThat() .statusCode(200); boolean stopEarlyToVerifyTheScriptWasCreated = false; if (stopEarlyToVerifyTheScriptWasCreated) { logger.info("On the DCM, does /deposit/gen/upload-" + datasetId + ".bash exist? It should! Creating the dataset should be enough to create it."); return; } Response createUser2 = UtilIT.createRandomUser(); String apiToken2 = UtilIT.getApiTokenFromResponse(createUser2); Response createDataverseResponse2 = UtilIT.createRandomDataverse(apiToken2); createDataverseResponse2.prettyPrint(); String dataverseAlias2 = UtilIT.getAliasFromResponse(createDataverseResponse2); Response createDatasetResponse2 = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias2, apiToken2); createDatasetResponse2.prettyPrint(); Integer datasetId2 = JsonPath.from(createDatasetResponse2.body().asString()).getInt("data.id"); Response getDatasetJsonBeforePublishing = UtilIT.nativeGet(datasetId, apiToken); getDatasetJsonBeforePublishing.prettyPrint(); String protocol = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.protocol"); String authority = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.authority"); String identifier = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.identifier"); String datasetPersistentId = protocol + ":" + authority + "/" + identifier; /** * Here we are pretending to be the Data Capture Module reporting on if * checksum validation success or failure. Don't notify the user on * success (too chatty) but do notify on failure. * * @todo On success a process should be kicked off to crawl the files so * they are imported into Dataverse. Once the crawling and importing is * complete, notify the user. * * @todo What authentication should be used here? The API token of the * user? (If so, pass the token in the initial upload request payload.) * This is suboptimal because of the security risk of having the Data * Capture Module store the API token. Or should Dataverse be able to be * configured so that it only will receive these messages from trusted * IP addresses? Should there be a shared secret that's used for *all* * requests from the Data Capture Module to Dataverse? */ /* Can't find dataset - give bad dataset ID */ JsonObjectBuilder wrongDataset = Json.createObjectBuilder(); String fakeDatasetId = "78921457982457921"; wrongDataset.add("status", "validation passed"); Response createSuperuser = UtilIT.createRandomUser(); String superuserApiToken = UtilIT.getApiTokenFromResponse(createSuperuser); String superuserUsername = UtilIT.getUsernameFromResponse(createSuperuser); UtilIT.makeSuperUser(superuserUsername); Response datasetNotFound = UtilIT.dataCaptureModuleChecksumValidation(fakeDatasetId, wrongDataset.build(), superuserApiToken); datasetNotFound.prettyPrint(); datasetNotFound.then().assertThat() .statusCode(404) .body("message", equalTo("Dataset with ID " + fakeDatasetId + " not found.")); JsonObjectBuilder badNews = Json.createObjectBuilder(); // Status options are documented at https://github.com/sbgrid/data-capture-module/blob/master/doc/api.md#post-upload badNews.add("status", "validation failed"); Response uploadFailed = UtilIT.dataCaptureModuleChecksumValidation(datasetPersistentId, badNews.build(), superuserApiToken); uploadFailed.prettyPrint(); uploadFailed.then().assertThat() /** * @todo Double check that we're ok with 200 here. We're saying * "Ok, the bad news was delivered." We had a success of * informing the user of bad news. */ .statusCode(200) .body("data.message", equalTo("User notified about checksum validation failure.")); Response authorsGetsBadNews = UtilIT.getNotifications(apiToken); authorsGetsBadNews.prettyPrint(); authorsGetsBadNews.then().assertThat() .body("data.notifications[0].type", equalTo("CHECKSUMFAIL")) .statusCode(OK.getStatusCode()); Response removeUploadMethods = UtilIT.deleteSetting(SettingsServiceBean.Key.UploadMethods); removeUploadMethods.then().assertThat() .statusCode(200); String uploadFolder = identifier; /** * The "extra testing" involves having this REST Assured test do two * jobs done by the rsync script and the DCM. The rsync script creates * "files.sha" and (if checksum validation succeeds) the DCM moves the * files and the "files.sha" file into the uploadFolder. */ boolean doExtraTesting = false; if (doExtraTesting) { String SEP = java.io.File.separator; // Set this to where you keep your files in dev. It might be nice to have an API to query to get this location from Dataverse. String dsDir = "/Users/pdurbin/dataverse/files/10.5072/FK2"; java.nio.file.Files.createDirectories(java.nio.file.Paths.get(dsDir + SEP + identifier)); java.nio.file.Files.createDirectories(java.nio.file.Paths.get(dsDir + SEP + identifier + SEP + uploadFolder)); String checksumFilename = "files.sha"; String filename1 = "file1.txt"; String fileContent1 = "big data!"; java.nio.file.Files.write(java.nio.file.Paths.get(dsDir + SEP + identifier + SEP + uploadFolder + SEP + checksumFilename), fileContent1.getBytes()); // // This is actually the SHA-1 of a zero byte file. It doesn't seem to matter what you send to the DCM? String checksumFileContent = "da39a3ee5e6b4b0d3255bfef95601890afd80709 " + filename1; java.nio.file.Files.createFile(java.nio.file.Paths.get(dsDir + SEP + identifier + SEP + uploadFolder + SEP + filename1)); java.nio.file.Files.write(java.nio.file.Paths.get(dsDir + SEP + identifier + SEP + uploadFolder + SEP + checksumFilename), checksumFileContent.getBytes()); } int totalSize = 1234567890; /** * @todo How can we test what the checksum validation notification looks * like in the GUI? There is no API for retrieving notifications. * * @todo How can we test that the email notification looks ok? */ JsonObjectBuilder goodNews = Json.createObjectBuilder(); goodNews.add("status", "validation passed"); goodNews.add("uploadFolder", uploadFolder); goodNews.add("totalSize", totalSize); Response uploadSuccessful = UtilIT.dataCaptureModuleChecksumValidation(datasetPersistentId, goodNews.build(), superuserApiToken); /** * Errors here are expected unless you've set doExtraTesting to true to * do the jobs of the rsync script and the DCM to create the files.sha * file and put it and the data files in place. You might see stuff * like: "message": "Uploaded files have passed checksum validation but * something went wrong while attempting to put the files into * Dataverse. Status code was 400 and message was 'Dataset directory is * invalid.'." */ uploadSuccessful.prettyPrint(); if (doExtraTesting) { uploadSuccessful.then().assertThat() .body("data.message", equalTo("FileSystemImportJob in progress")) .statusCode(200); if (doExtraTesting) { long millisecondsNeededForFileSystemImportJobToFinish = 1000; Thread.sleep(millisecondsNeededForFileSystemImportJobToFinish); Response datasetAsJson2 = UtilIT.nativeGet(datasetId, apiToken); datasetAsJson2.prettyPrint(); datasetAsJson2.then().assertThat() .body("data.latestVersion.files[0].dataFile.filename", equalTo(identifier)) .body("data.latestVersion.files[0].dataFile.contentType", equalTo("application/vnd.dataverse.file-package")) .body("data.latestVersion.files[0].dataFile.filesize", equalTo(totalSize)) .body("data.latestVersion.files[0].dataFile.checksum.type", equalTo("SHA-1")) .statusCode(OK.getStatusCode()); } } logger.info("username/password: " + username); } @Test public void testCreateDeleteDatasetLink() { Response createUser = UtilIT.createRandomUser(); createUser.prettyPrint(); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); Response superuserResponse = UtilIT.makeSuperUser(username); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); createDatasetResponse.prettyPrint(); Integer datasetId = UtilIT.getDatasetIdFromResponse(createDatasetResponse); // This should fail, because we are attempting to link the dataset // to its own dataverse: Response createLinkingDatasetResponse = UtilIT.createDatasetLink(datasetId.longValue(), dataverseAlias, apiToken); createLinkingDatasetResponse.prettyPrint(); createLinkingDatasetResponse.then().assertThat() .body("message", equalTo("Can't link a dataset to its dataverse")) .statusCode(FORBIDDEN.getStatusCode()); // OK, let's create a different random dataverse: createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); // And link the dataset to this new dataverse: createLinkingDatasetResponse = UtilIT.createDatasetLink(datasetId.longValue(), dataverseAlias, apiToken); createLinkingDatasetResponse.prettyPrint(); createLinkingDatasetResponse.then().assertThat() .body("data.message", equalTo("Dataset " + datasetId +" linked successfully to " + dataverseAlias)) .statusCode(200); // And now test deleting it: Response deleteLinkingDatasetResponse = UtilIT.deleteDatasetLink(datasetId.longValue(), dataverseAlias, apiToken); deleteLinkingDatasetResponse.prettyPrint(); deleteLinkingDatasetResponse.then().assertThat() .body("data.message", equalTo("Link from Dataset " + datasetId + " to linked Dataverse " + dataverseAlias + " deleted")) .statusCode(200); } }
package ihk.report.generator.util; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.Arrays; import java.util.List; import org.junit.Test; /** * The Class FileUtilsTest. */ public class FileUtilsTest { /** * Tests cover the following cases: * - get all files with given format * - given format is an empty string * - given format is null * - list must not be null * - list is empty on invalid param */ @Test public void testGetFilesByFormat() { assertThat(new FileUtils().getFilesByFormat(getTestDirectory(false), ".txt").isEmpty(), is(false)); assertThat(new FileUtils().getFilesByFormat(getTestDirectory(false), ".txt").size(), is(2)); assertThat(new FileUtils().getFilesByFormat(getTestDirectory(false), "").isEmpty(), is(true)); assertThat(new FileUtils().getFilesByFormat(getTestDirectory(false), "").size(), is(0)); assertThat(new FileUtils().getFilesByFormat(getTestDirectory(false), null).isEmpty(), is(true)); } /** * Tests cover the following cases: * - given format list is empty or null * - multiple files of the same format exist * - directory is empty * - only return the matched formats */ @Test public void testGetExistingFormatsInDirByFormats() { List<String> nullFormats = null; List<String> formats = Arrays.asList(".txt", ".xls", ".bak", "lala"); List<String> expectedFormats = Arrays.asList(".txt", ".xls"); assertTrue(new FileUtils().getExistingFormatsInDirByFormats(getTestDirectory(false), nullFormats) == null); assertThat(new FileUtils().getExistingFormatsInDirByFormats(getTestDirectory(false), formats), is(expectedFormats)); assertTrue(new FileUtils().getExistingFormatsInDirByFormats(getTestDirectory(true), formats) == null); } /** * Gets the test directory. * * @param empty the empty * @return the test directory */ private File getTestDirectory(boolean empty) { if (empty) { return new File(getClass().getClassLoader().getResource("file-utils-test/directory-empty").getFile()); } else { return new File(getClass().getClassLoader().getResource("file-utils-test/directory").getFile()); } } }
package nom.bdezonia.zorbage.algorithm; import static org.junit.Assert.assertEquals; import org.junit.Test; import nom.bdezonia.zorbage.groups.G; import nom.bdezonia.zorbage.procedure.Ramp; import nom.bdezonia.zorbage.type.data.float64.real.Float64Group; import nom.bdezonia.zorbage.type.data.float64.real.Float64Member; import nom.bdezonia.zorbage.type.storage.IndexedDataSource; import nom.bdezonia.zorbage.type.storage.Storage; /** * * @author Barry DeZonia * */ public class TestFill { @Test public void test() { long size = 10000; Float64Member type = new Float64Member(); IndexedDataSource<?, Float64Member> data = Storage.allocate(size, type); assertEquals(size, data.size()); Ramp<Float64Group, Float64Member> ramp1 = new Ramp<Float64Group, Float64Member>(G.DBL, new Float64Member(-25), new Float64Member(3)); Fill.compute(G.DBL, data, ramp1); for (long i = 0; i < size; i++) { data.get(i, type); assertEquals(-25+3*i, type.v(), 0); } Ramp<Float64Group, Float64Member> ramp2 = new Ramp<Float64Group, Float64Member>(G.DBL, new Float64Member(300), new Float64Member(-6)); Fill.compute(G.DBL, data, ramp2); for (long i = 0; i < size; i++) { data.get(i, type); assertEquals(300-6*i, type.v(), 0); } } }
package org.animotron.statement.math; import org.animotron.ATest; import org.animotron.expression.AbstractExpression; import org.animotron.expression.AnimoExpression; import org.animotron.expression.Expression; import org.animotron.statement.operator.AN; import org.animotron.statement.operator.REF; import org.junit.Test; import org.neo4j.graphdb.Relationship; import static java.lang.System.currentTimeMillis; /** * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> * */ public class SUM500Test extends ATest { @Test public void test_00() throws Throwable { long t; t = currentTimeMillis(); Relationship e = AnimoExpression.__(new AbstractExpression() { @Override public void build() throws Throwable { builder.start(AN._); builder._(REF._, SUM._.name()); for (int i = 0; i < 500; i++) { builder._(i); } builder.end(); } }); System.out.println("Build expression in " + (currentTimeMillis() - t)); t = currentTimeMillis(); assertAnimoResult(e, "124750."); System.out.println("Eval expression in " + (currentTimeMillis() - t)); } @Test public void test_01() throws Throwable { long t; t = currentTimeMillis(); for (int i = 0; i < 500; i++) { __("def a" + i + " (a) (b '" + i + "')."); } Expression e = new AnimoExpression("+ get b all a"); System.out.println("Build expressions in " + (currentTimeMillis() - t)); t = currentTimeMillis(); assertAnimoResult(e, "124750."); System.out.println("Eval expression in " + (currentTimeMillis() - t)); } }
package org.jabref.model.strings; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Optional; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; class StringUtilTest { @Test void StringUtilClassIsSmall() throws Exception { Path path = Path.of("src", "main", "java", StringUtil.class.getName().replace('.', '/') + ".java"); int lineCount = Files.readAllLines(path, StandardCharsets.UTF_8).size(); assertTrue(lineCount <= 761, "StringUtil increased in size to " + lineCount + ". " + "We try to keep this class as small as possible. " + "Thus think twice if you add something to StringUtil."); } @Test void testBooleanToBinaryString() { assertEquals("0", StringUtil.booleanToBinaryString(false)); assertEquals("1", StringUtil.booleanToBinaryString(true)); } @Test void testQuoteSimple() { assertEquals("a::", StringUtil.quote("a:", "", ':')); } @Test void testQuoteNullQuotation() { assertEquals("a::", StringUtil.quote("a:", null, ':')); } @Test void testQuoteNullString() { assertEquals("", StringUtil.quote(null, ";", ':')); } @Test void testQuoteQuotationCharacter() { assertEquals("a:::;", StringUtil.quote("a:;", ";", ':')); } @Test void testQuoteMoreComplicated() { assertEquals("a::b:%c:;", StringUtil.quote("a:b%c;", "%;", ':')); } @Test void testUnifyLineBreaks() { // Mac < v9 String result = StringUtil.unifyLineBreaks("\r", "newline"); assertEquals("newline", result); // Windows result = StringUtil.unifyLineBreaks("\r\n", "newline"); assertEquals("newline", result); // Unix result = StringUtil.unifyLineBreaks("\n", "newline"); assertEquals("newline", result); } @Test void testGetCorrectFileName() { assertEquals("aa.bib", StringUtil.getCorrectFileName("aa", "bib")); assertEquals(".login.bib", StringUtil.getCorrectFileName(".login", "bib")); assertEquals("a.bib", StringUtil.getCorrectFileName("a.bib", "bib")); assertEquals("a.bib", StringUtil.getCorrectFileName("a.bib", "BIB")); assertEquals("a.bib", StringUtil.getCorrectFileName("a", "bib")); assertEquals("a.bb", StringUtil.getCorrectFileName("a.bb", "bib")); assertEquals("", StringUtil.getCorrectFileName(null, "bib")); } @Test void testQuoteForHTML() { assertEquals("&#33;", StringUtil.quoteForHTML("!")); assertEquals("&#33;&#33;&#33;", StringUtil.quoteForHTML("!!!")); } @Test void testRemoveBracesAroundCapitals() { assertEquals("ABC", StringUtil.removeBracesAroundCapitals("{ABC}")); assertEquals("ABC", StringUtil.removeBracesAroundCapitals("{{ABC}}")); assertEquals("{abc}", StringUtil.removeBracesAroundCapitals("{abc}")); assertEquals("ABCDEF", StringUtil.removeBracesAroundCapitals("{ABC}{DEF}")); } @Test void testPutBracesAroundCapitals() { assertEquals("{ABC}", StringUtil.putBracesAroundCapitals("ABC")); assertEquals("{ABC}", StringUtil.putBracesAroundCapitals("{ABC}")); assertEquals("abc", StringUtil.putBracesAroundCapitals("abc")); assertEquals("#ABC#", StringUtil.putBracesAroundCapitals("#ABC#")); assertEquals("{ABC} def {EFG}", StringUtil.putBracesAroundCapitals("ABC def EFG")); } @Test void testShaveString() { assertEquals("", StringUtil.shaveString(null)); assertEquals("", StringUtil.shaveString("")); assertEquals("aaa", StringUtil.shaveString(" aaa\t\t\n\r")); assertEquals("a", StringUtil.shaveString(" {a} ")); assertEquals("a", StringUtil.shaveString(" \"a\" ")); assertEquals("{a}", StringUtil.shaveString(" {{a}} ")); assertEquals("{a}", StringUtil.shaveString(" \"{a}\" ")); assertEquals("\"{a\"}", StringUtil.shaveString(" \"{a\"} ")); } @Test void testJoin() { String[] s = {"ab", "cd", "ed"}; assertEquals("ab\\cd\\ed", StringUtil.join(s, "\\", 0, s.length)); assertEquals("cd\\ed", StringUtil.join(s, "\\", 1, s.length)); assertEquals("ed", StringUtil.join(s, "\\", 2, s.length)); assertEquals("", StringUtil.join(s, "\\", 3, s.length)); assertEquals("", StringUtil.join(new String[]{}, "\\", 0, 0)); } @Test void testStripBrackets() { assertEquals("foo", StringUtil.stripBrackets("[foo]")); assertEquals("[foo]", StringUtil.stripBrackets("[[foo]]")); assertEquals("", StringUtil.stripBrackets("")); assertEquals("[foo", StringUtil.stripBrackets("[foo")); assertEquals("]", StringUtil.stripBrackets("]")); assertEquals("", StringUtil.stripBrackets("[]")); assertEquals("f[]f", StringUtil.stripBrackets("f[]f")); assertEquals(null, StringUtil.stripBrackets(null)); } @Test void testGetPart() { assertEquals("{roupa}", StringUtil.getPart("O rato roeu a {roupa} do rei de roma", 13, false)); assertEquals("", StringUtil.getPart("", 0, false)); assertEquals("", StringUtil.getPart("Um passo por }dia}", 12, false)); assertEquals("dia", StringUtil.getPart("Um passo por dia", 12, true)); } @Test void testFindEncodingsForString() { // Unused in JabRef, but should be added in case it finds some use } @Test void testWrap() { String newline = "newline"; assertEquals("aaaaa" + newline + "\tbbbbb" + newline + "\tccccc", StringUtil.wrap("aaaaa bbbbb ccccc", 5, newline)); assertEquals("aaaaa bbbbb" + newline + "\tccccc", StringUtil.wrap("aaaaa bbbbb ccccc", 8, newline)); assertEquals("aaaaa bbbbb" + newline + "\tccccc", StringUtil.wrap("aaaaa bbbbb ccccc", 11, newline)); assertEquals("aaaaa bbbbb ccccc", StringUtil.wrap("aaaaa bbbbb ccccc", 12, newline)); assertEquals("aaaaa" + newline + "\t" + newline + "\tbbbbb" + newline + "\t" + newline + "\tccccc", StringUtil.wrap("aaaaa\nbbbbb\nccccc", 12, newline)); assertEquals( "aaaaa" + newline + "\t" + newline + "\t" + newline + "\tbbbbb" + newline + "\t" + newline + "\tccccc", StringUtil.wrap("aaaaa\n\nbbbbb\nccccc", 12, newline)); assertEquals("aaaaa" + newline + "\t" + newline + "\tbbbbb" + newline + "\t" + newline + "\tccccc", StringUtil.wrap("aaaaa\r\nbbbbb\r\nccccc", 12, newline)); } @Test void testDecodeStringDoubleArray() { assertArrayEquals(new String[][]{{"a", "b"}, {"c", "d"}}, StringUtil.decodeStringDoubleArray("a:b;c:d")); assertArrayEquals(new String[][]{{"a", ""}, {"c", "d"}}, StringUtil.decodeStringDoubleArray("a:;c:d")); // arrays first differed at element [0][1]; expected: null<null> but was: java.lang.String<null> // assertArrayEquals(stringArray2res, StringUtil.decodeStringDoubleArray(encStringArray2)); assertArrayEquals(new String[][]{{"a", ":b"}, {"c;", "d"}}, StringUtil.decodeStringDoubleArray("a:\\:b;c\\;:d")); } @Test void testIsInCurlyBrackets() { assertFalse(StringUtil.isInCurlyBrackets("")); assertFalse(StringUtil.isInCurlyBrackets(null)); assertTrue(StringUtil.isInCurlyBrackets("{}")); assertTrue(StringUtil.isInCurlyBrackets("{a}")); assertTrue(StringUtil.isInCurlyBrackets("{a{a}}")); assertTrue(StringUtil.isInCurlyBrackets("{{\\AA}sa {\\AA}Stor{\\aa}}")); assertFalse(StringUtil.isInCurlyBrackets("{")); assertFalse(StringUtil.isInCurlyBrackets("}")); assertFalse(StringUtil.isInCurlyBrackets("a{}a")); assertFalse(StringUtil.isInCurlyBrackets("{\\AA}sa {\\AA}Stor{\\aa}")); } @Test void testIsInSquareBrackets() { assertFalse(StringUtil.isInSquareBrackets("")); assertFalse(StringUtil.isInSquareBrackets(null)); assertTrue(StringUtil.isInSquareBrackets("[]")); assertTrue(StringUtil.isInSquareBrackets("[a]")); assertFalse(StringUtil.isInSquareBrackets("[")); assertFalse(StringUtil.isInSquareBrackets("]")); assertFalse(StringUtil.isInSquareBrackets("a[]a")); } @Test void testIsInCitationMarks() { assertFalse(StringUtil.isInCitationMarks("")); assertFalse(StringUtil.isInCitationMarks(null)); assertTrue(StringUtil.isInCitationMarks("\"\"")); assertTrue(StringUtil.isInCitationMarks("\"a\"")); assertFalse(StringUtil.isInCitationMarks("\"")); assertFalse(StringUtil.isInCitationMarks("a\"\"a")); } @Test void testIntValueOfSingleDigit() { assertEquals(1, StringUtil.intValueOf("1")); assertEquals(2, StringUtil.intValueOf("2")); assertEquals(8, StringUtil.intValueOf("8")); } @Test void testIntValueOfLongString() { assertEquals(1234567890, StringUtil.intValueOf("1234567890")); } @Test void testIntValueOfStartWithZeros() { assertEquals(1234, StringUtil.intValueOf("001234")); } @Test void testIntValueOfExceptionIfStringContainsLetter() { assertThrows(NumberFormatException.class, () -> StringUtil.intValueOf("12A2")); } @Test void testIntValueOfExceptionIfStringNull() { assertThrows(NumberFormatException.class, () -> StringUtil.intValueOf(null)); } @Test void testIntValueOfExceptionfIfStringEmpty() { assertThrows(NumberFormatException.class, () -> StringUtil.intValueOf("")); } @Test void testIntValueOfWithNullSingleDigit() { assertEquals(Optional.of(1), StringUtil.intValueOfOptional("1")); assertEquals(Optional.of(2), StringUtil.intValueOfOptional("2")); assertEquals(Optional.of(8), StringUtil.intValueOfOptional("8")); } @Test void testIntValueOfWithNullLongString() { assertEquals(Optional.of(1234567890), StringUtil.intValueOfOptional("1234567890")); } @Test void testIntValueOfWithNullStartWithZeros() { assertEquals(Optional.of(1234), StringUtil.intValueOfOptional("001234")); } @Test void testIntValueOfWithNullExceptionIfStringContainsLetter() { assertEquals(Optional.empty(), StringUtil.intValueOfOptional("12A2")); } @Test void testIntValueOfWithNullExceptionIfStringNull() { assertEquals(Optional.empty(), StringUtil.intValueOfOptional(null)); } @Test void testIntValueOfWithNullExceptionfIfStringEmpty() { assertEquals(Optional.empty(), StringUtil.intValueOfOptional("")); } @Test void testLimitStringLengthShort() { assertEquals("Test", StringUtil.limitStringLength("Test", 20)); } @Test void testLimitStringLengthLimiting() { assertEquals("TestTes...", StringUtil.limitStringLength("TestTestTestTestTest", 10)); assertEquals(10, StringUtil.limitStringLength("TestTestTestTestTest", 10).length()); } @Test void testLimitStringLengthNullInput() { assertEquals("", StringUtil.limitStringLength(null, 10)); } @Test void testReplaceSpecialCharacters() { assertEquals("Hallo Arger", StringUtil.replaceSpecialCharacters("Hallo Arger")); assertEquals("aaAeoeeee", StringUtil.replaceSpecialCharacters("åÄöéèë")); } @Test void replaceSpecialCharactersWithNonNormalizedUnicode() { assertEquals("Modele", StringUtil.replaceSpecialCharacters("Modèle")); } static Stream<Arguments> testRepeatSpacesData() { return Stream.of( Arguments.of("", -1), Arguments.of("", 0), Arguments.of(" ", 1), Arguments.of(" ", 7) ); } @ParameterizedTest @MethodSource("testRepeatSpacesData") void testRepeatSpaces(String result, int count) { assertEquals(result, StringUtil.repeatSpaces(count)); } @Test void testRepeat() { assertEquals("", StringUtil.repeat(0, 'a')); assertEquals("a", StringUtil.repeat(1, 'a')); assertEquals("aaaaaaa", StringUtil.repeat(7, 'a')); } @Test void testBoldHTML() { assertEquals("<b>AA</b>", StringUtil.boldHTML("AA")); } @Test void testBoldHTMLReturnsOriginalTextIfNonNull() { assertEquals("<b>AA</b>", StringUtil.boldHTML("AA", "BB")); } @Test void testBoldHTMLReturnsAlternativeTextIfNull() { assertEquals("<b>BB</b>", StringUtil.boldHTML(null, "BB")); } @Test void testUnquote() { assertEquals("a:", StringUtil.unquote("a::", ':')); assertEquals("a:;", StringUtil.unquote("a:::;", ':')); assertEquals("a:b%c;", StringUtil.unquote("a::b:%c:;", ':')); } @Test void testCapitalizeFirst() { assertEquals("", StringUtil.capitalizeFirst("")); assertEquals("Hello world", StringUtil.capitalizeFirst("Hello World")); assertEquals("A", StringUtil.capitalizeFirst("a")); assertEquals("Aa", StringUtil.capitalizeFirst("AA")); } private static Stream<Arguments> getQuoteStringIfSpaceIsContainedData() { return Stream.of( Arguments.of("", ""), Arguments.of("\" \"", " "), Arguments.of("world", "world"), Arguments.of("\"hello world\"", "hello world") ); } @ParameterizedTest @MethodSource("getQuoteStringIfSpaceIsContainedData") void testGuoteStringIfSpaceIsContained(String expected, String source) { assertEquals(expected, StringUtil.quoteStringIfSpaceIsContained(source)); } }
package org.sfm.reflect; import org.junit.Test; import org.sfm.beans.*; import org.sfm.reflect.asm.AsmFactory; import org.sfm.reflect.impl.FieldGetter; import org.sfm.reflect.impl.MethodGetter; import org.sfm.reflect.primitive.*; import static org.junit.Assert.*; public class ObjectGetterFactoryTest { private ObjectGetterFactory asm = new ObjectGetterFactory(new AsmFactory(getClass().getClassLoader())); private ObjectGetterFactory noAsm = new ObjectGetterFactory(null); private DbObject dbo = new DbObject(); { dbo.setName("v1"); } private DbFinalObject dbfo = new DbFinalObject(0, "v1", null, null, null, null); private DbPublicObject dbpo = new DbPublicObject(); { dbpo.name = "v1"; } private DbFinalPrimitiveObject dbFinalPrimitiveObject = new DbFinalPrimitiveObject(true, (byte)1, (char)2, (short)3, 4, 5l, 6.0f, 7.0); @Test public void testObjectGetterNoAsm() throws Exception { assertEquals(dbo.getName(), noAsm.getGetter(DbObject.class, "name").get(dbo)); assertEquals(dbfo.getName(), noAsm.getGetter(DbFinalObject.class, "name").get(dbfo)); assertEquals(dbpo.name, noAsm.getGetter(DbPublicObject.class, "name").get(dbpo)); } @Test public void testObjectGetterAsm() throws Exception { assertEquals(dbo.getName(), asm.getGetter(DbObject.class, "name").get(dbo)); assertFalse(asm.getGetter(DbObject.class, "name") instanceof MethodGetter); assertEquals(dbfo.getName(), asm.getGetter(DbFinalObject.class, "name").get(dbfo)); assertFalse(asm.getGetter(DbFinalObject.class, "name") instanceof MethodGetter); } @Test public void testBytePrimitiveAsmIsByteGetter() throws Exception { final Getter<DbFinalPrimitiveObject, ?> getter = asm.getGetter(DbFinalPrimitiveObject.class, "pByte"); assertTrue(getter instanceof ByteGetter); assertSame(getter, ObjectGetterFactory.toByteGetter(getter)); assertEquals(dbFinalPrimitiveObject.getpByte(), ((ByteGetter)getter).getByte(dbFinalPrimitiveObject)); } @Test public void testBytePrimitiveNoAsmIsByteGetter() throws Exception { final Getter<DbFinalPrimitiveObject, ?> getter = noAsm.getGetter(DbFinalPrimitiveObject.class, "pByte"); assertFalse(getter instanceof ByteGetter); final ByteGetter<DbFinalPrimitiveObject> byteGetter = ObjectGetterFactory.toByteGetter(getter); assertTrue(byteGetter instanceof ByteGetter); assertEquals(dbFinalPrimitiveObject.getpByte(), byteGetter.getByte(dbFinalPrimitiveObject)); } @Test public void testCharPrimitiveAsmIsCharGetter() throws Exception { final Getter<DbFinalPrimitiveObject, ?> getter = asm.getGetter(DbFinalPrimitiveObject.class, "pChar"); assertTrue(getter instanceof CharacterGetter); assertSame(getter, ObjectGetterFactory.toCharGetter(getter)); assertEquals(dbFinalPrimitiveObject.getpCharacter(), ((CharacterGetter)getter).getCharacter(dbFinalPrimitiveObject)); } @Test public void testCharPrimitiveNoAsmIsCharGetter() throws Exception { final Getter<DbFinalPrimitiveObject, ?> getter = noAsm.getGetter(DbFinalPrimitiveObject.class, "pChar"); assertFalse(getter instanceof CharacterGetter); final CharacterGetter<DbFinalPrimitiveObject> charGetter = ObjectGetterFactory.toCharGetter(getter); assertTrue(charGetter instanceof CharacterGetter); assertEquals(dbFinalPrimitiveObject.getpCharacter(), charGetter.getCharacter(dbFinalPrimitiveObject)); } @Test public void testShortPrimitiveAsmIsShortGetter() throws Exception { final Getter<DbFinalPrimitiveObject, ?> getter = asm.getGetter(DbFinalPrimitiveObject.class, "pShort"); assertTrue(getter instanceof ShortGetter); assertSame(getter, ObjectGetterFactory.toShortGetter(getter)); assertEquals(dbFinalPrimitiveObject.getpShort(), ((ShortGetter)getter).getShort(dbFinalPrimitiveObject)); } @Test public void testShortPrimitiveNoAsmIsShortGetter() throws Exception { final Getter<DbFinalPrimitiveObject, ?> getter = noAsm.getGetter(DbFinalPrimitiveObject.class, "pShort"); assertFalse(getter instanceof ShortGetter); final ShortGetter<DbFinalPrimitiveObject> shortGetter = ObjectGetterFactory.toShortGetter(getter); assertTrue(shortGetter instanceof ShortGetter); assertEquals(3, shortGetter.getShort(dbFinalPrimitiveObject)); assertEquals(dbFinalPrimitiveObject.getpShort(), shortGetter.getShort(dbFinalPrimitiveObject)); } @Test public void testIntPrimitiveAsmIsIntGetter() throws Exception { final Getter<DbFinalPrimitiveObject, ?> getter = asm.getGetter(DbFinalPrimitiveObject.class, "pInt"); assertTrue(getter instanceof IntGetter); assertSame(getter, ObjectGetterFactory.toIntGetter(getter)); assertEquals(dbFinalPrimitiveObject.getpInt(), ((IntGetter)getter).getInt(dbFinalPrimitiveObject)); } @Test public void testIntPrimitiveNoAsmIsIntGetter() throws Exception { final Getter<DbFinalPrimitiveObject, ?> getter = noAsm.getGetter(DbFinalPrimitiveObject.class, "pInt"); assertFalse(getter instanceof IntGetter); final IntGetter<DbFinalPrimitiveObject> intGetter = ObjectGetterFactory.toIntGetter(getter); assertTrue(intGetter instanceof IntGetter); assertEquals(dbFinalPrimitiveObject.getpInt(), intGetter.getInt(dbFinalPrimitiveObject)); } @Test public void testLongPrimitiveAsmIsLongGetter() throws Exception { final Getter<DbFinalPrimitiveObject, ?> getter = asm.getGetter(DbFinalPrimitiveObject.class, "pLong"); assertTrue(getter instanceof LongGetter); assertSame(getter, ObjectGetterFactory.toLongGetter(getter)); assertEquals(dbFinalPrimitiveObject.getpLong(), ((LongGetter)getter).getLong(dbFinalPrimitiveObject)); } @Test public void testLongPrimitiveNoAsmIsLongGetter() throws Exception { final Getter<DbFinalPrimitiveObject, ?> getter = noAsm.getGetter(DbFinalPrimitiveObject.class, "pLong"); assertFalse(getter instanceof LongGetter); final LongGetter<DbFinalPrimitiveObject> longGetter = ObjectGetterFactory.toLongGetter(getter); assertTrue(longGetter instanceof LongGetter); assertEquals(dbFinalPrimitiveObject.getpLong(), longGetter.getLong(dbFinalPrimitiveObject)); } @Test public void testFloatPrimitiveAsmIsFloatGetter() throws Exception { final Getter<DbFinalPrimitiveObject, ?> getter = asm.getGetter(DbFinalPrimitiveObject.class, "pFloat"); assertTrue(getter instanceof FloatGetter); assertSame(getter, ObjectGetterFactory.toFloatGetter(getter)); assertEquals(dbFinalPrimitiveObject.getpFloat(), ((FloatGetter)getter).getFloat(dbFinalPrimitiveObject), 0.0001); } @Test public void testFloatPrimitiveNoAsmIsFloatGetter() throws Exception { final Getter<DbFinalPrimitiveObject, ?> getter = noAsm.getGetter(DbFinalPrimitiveObject.class, "pFloat"); assertFalse(getter instanceof FloatGetter); final FloatGetter<DbFinalPrimitiveObject> longGetter = ObjectGetterFactory.toFloatGetter(getter); assertTrue(longGetter instanceof FloatGetter); assertEquals(dbFinalPrimitiveObject.getpFloat(), longGetter.getFloat(dbFinalPrimitiveObject), 0.0001); } @Test public void testDoublePrimitiveAsmIsDoubleGetter() throws Exception { final Getter<DbFinalPrimitiveObject, ?> getter = asm.getGetter(DbFinalPrimitiveObject.class, "pDouble"); assertTrue(getter instanceof DoubleGetter); assertSame(getter, ObjectGetterFactory.toDoubleGetter(getter)); assertEquals(dbFinalPrimitiveObject.getpDouble(), ((DoubleGetter)getter).getDouble(dbFinalPrimitiveObject), 0.0001); } @Test public void testDoublePrimitiveNoAsmIsDoubleGetter() throws Exception { final Getter<DbFinalPrimitiveObject, ?> getter = noAsm.getGetter(DbFinalPrimitiveObject.class, "pDouble"); assertFalse(getter instanceof DoubleGetter); final DoubleGetter<DbFinalPrimitiveObject> longGetter = ObjectGetterFactory.toDoubleGetter(getter); assertTrue(longGetter instanceof DoubleGetter); assertEquals(dbFinalPrimitiveObject.getpDouble(), longGetter.getDouble(dbFinalPrimitiveObject), 0.0001); } @Test public void testBooleanPrimitiveAsmIsBooleanGetter() throws Exception { final Getter<DbFinalPrimitiveObject, ?> getter = asm.getGetter(DbFinalPrimitiveObject.class, "pBoolean"); assertTrue(getter instanceof BooleanGetter); assertSame(getter, ObjectGetterFactory.toBooleanGetter(getter)); assertEquals(dbFinalPrimitiveObject.ispBoolean(), ((BooleanGetter)getter).getBoolean(dbFinalPrimitiveObject)); } @Test public void testBooleanPrimitiveNoAsmIsBooleanGetter() throws Exception { final Getter<DbFinalPrimitiveObject, ?> getter = noAsm.getGetter(DbFinalPrimitiveObject.class, "pBoolean"); assertFalse(getter instanceof BooleanGetter); final BooleanGetter<DbFinalPrimitiveObject> longGetter = ObjectGetterFactory.toBooleanGetter(getter); assertTrue(longGetter instanceof BooleanGetter); assertEquals(dbFinalPrimitiveObject.ispBoolean(), longGetter.getBoolean(dbFinalPrimitiveObject)); } @Test public void testBoxedBooleanAsm() throws Exception { final Getter<DbBoxed, ?> getter = asm.getGetter(DbBoxed.class, "propBoolean"); assertFalse(getter instanceof BooleanGetter); final BooleanGetter<DbBoxed> pGetter = ObjectGetterFactory.toBooleanGetter(getter); assertTrue(pGetter instanceof BooleanGetter); assertEquals(false, pGetter.getBoolean(new DbBoxed())); } @Test public void testBoxedBooleanNoAsm() throws Exception { final Getter<DbBoxed, ?> getter = asm.getGetter(DbBoxed.class, "propBoolean"); assertFalse(getter instanceof BooleanGetter); final BooleanGetter<DbBoxed> pGetter = ObjectGetterFactory.toBooleanGetter(getter); assertTrue(pGetter instanceof BooleanGetter); assertEquals(false, pGetter.getBoolean(new DbBoxed())); } @Test public void testBoxedByteAsm() throws Exception { final Getter<DbBoxed, ?> getter = asm.getGetter(DbBoxed.class, "propByte"); assertFalse(getter instanceof ByteGetter); final ByteGetter<DbBoxed> pGetter = ObjectGetterFactory.toByteGetter(getter); assertTrue(pGetter instanceof ByteGetter); assertEquals(0, pGetter.getByte(new DbBoxed())); } @Test public void testBoxedByteNoAsm() throws Exception { final Getter<DbBoxed, ?> getter = asm.getGetter(DbBoxed.class, "propByte"); assertFalse(getter instanceof ByteGetter); final ByteGetter<DbBoxed> pGetter = ObjectGetterFactory.toByteGetter(getter); assertTrue(pGetter instanceof ByteGetter); assertEquals(0, pGetter.getByte(new DbBoxed())); } @Test public void testBoxedCharacterAsm() throws Exception { final Getter<DbBoxed, ?> getter = asm.getGetter(DbBoxed.class, "propCharacter"); assertFalse(getter instanceof CharacterGetter); final CharacterGetter<DbBoxed> pGetter = ObjectGetterFactory.toCharGetter(getter); assertTrue(pGetter instanceof CharacterGetter); assertEquals(0, pGetter.getCharacter(new DbBoxed())); } @Test public void testBoxedCharacterNoAsm() throws Exception { final Getter<DbBoxed, ?> getter = asm.getGetter(DbBoxed.class, "propCharacter"); assertFalse(getter instanceof CharacterGetter); final CharacterGetter<DbBoxed> pGetter = ObjectGetterFactory.toCharGetter(getter); assertTrue(pGetter instanceof CharacterGetter); assertEquals(0, pGetter.getCharacter(new DbBoxed())); } @Test public void testBoxedShortAsm() throws Exception { final Getter<DbBoxed, ?> getter = asm.getGetter(DbBoxed.class, "propShort"); assertFalse(getter instanceof ShortGetter); final ShortGetter<DbBoxed> pGetter = ObjectGetterFactory.toShortGetter(getter); assertTrue(pGetter instanceof ShortGetter); assertEquals(0, pGetter.getShort(new DbBoxed())); } @Test public void testBoxedShortNoAsm() throws Exception { final Getter<DbBoxed, ?> getter = asm.getGetter(DbBoxed.class, "propShort"); assertFalse(getter instanceof ShortGetter); final ShortGetter<DbBoxed> pGetter = ObjectGetterFactory.toShortGetter(getter); assertTrue(pGetter instanceof ShortGetter); assertEquals(0, pGetter.getShort(new DbBoxed())); } @Test public void testBoxedIntegerAsm() throws Exception { final Getter<DbBoxed, ?> getter = asm.getGetter(DbBoxed.class, "propInt"); assertFalse(getter instanceof IntGetter); final IntGetter<DbBoxed> intGetter = ObjectGetterFactory.toIntGetter(getter); assertTrue(intGetter instanceof IntGetter); assertEquals(0, intGetter.getInt(new DbBoxed())); } @Test public void testBoxedIntegerNoAsm() throws Exception { final Getter<DbBoxed, ?> getter = asm.getGetter(DbBoxed.class, "propInt"); assertFalse(getter instanceof IntGetter); final IntGetter<DbBoxed> intGetter = ObjectGetterFactory.toIntGetter(getter); assertTrue(intGetter instanceof IntGetter); assertEquals(0, intGetter.getInt(new DbBoxed())); } @Test public void testBoxedLongAsm() throws Exception { final Getter<DbBoxed, ?> getter = asm.getGetter(DbBoxed.class, "propLong"); assertFalse(getter instanceof LongGetter); final LongGetter<DbBoxed> pGetter = ObjectGetterFactory.toLongGetter(getter); assertTrue(pGetter instanceof LongGetter); assertEquals(0, pGetter.getLong(new DbBoxed())); } @Test public void testBoxedLongNoAsm() throws Exception { final Getter<DbBoxed, ?> getter = asm.getGetter(DbBoxed.class, "propLong"); assertFalse(getter instanceof LongGetter); final LongGetter<DbBoxed> pGetter = ObjectGetterFactory.toLongGetter(getter); assertTrue(pGetter instanceof LongGetter); assertEquals(0, pGetter.getLong(new DbBoxed())); } @Test public void testBoxedFloatAsm() throws Exception { final Getter<DbBoxed, ?> getter = asm.getGetter(DbBoxed.class, "propFloat"); assertFalse(getter instanceof FloatGetter); final FloatGetter<DbBoxed> pGetter = ObjectGetterFactory.toFloatGetter(getter); assertTrue(pGetter instanceof FloatGetter); assertEquals(0.00, pGetter.getFloat(new DbBoxed()), 0.00001); } @Test public void testBoxedFloatNoAsm() throws Exception { final Getter<DbBoxed, ?> getter = asm.getGetter(DbBoxed.class, "propFloat"); assertFalse(getter instanceof FloatGetter); final FloatGetter<DbBoxed> pGetter = ObjectGetterFactory.toFloatGetter(getter); assertTrue(pGetter instanceof FloatGetter); assertEquals(0.0, pGetter.getFloat(new DbBoxed()), 0.00001); } @Test public void testBoxedDoubleAsm() throws Exception { final Getter<DbBoxed, ?> getter = asm.getGetter(DbBoxed.class, "propDouble"); assertFalse(getter instanceof DoubleGetter); final DoubleGetter<DbBoxed> pGetter = ObjectGetterFactory.toDoubleGetter(getter); assertTrue(pGetter instanceof DoubleGetter); assertEquals(0.0, pGetter.getDouble(new DbBoxed()), 0.0001); } @Test public void testBoxedDoubleNoAsm() throws Exception { final Getter<DbBoxed, ?> getter = asm.getGetter(DbBoxed.class, "propDouble"); assertFalse(getter instanceof DoubleGetter); final DoubleGetter<DbBoxed> pGetter = ObjectGetterFactory.toDoubleGetter(getter); assertTrue(pGetter instanceof DoubleGetter); assertEquals(0.0, pGetter.getDouble(new DbBoxed()), 0.00001); } public static class DbBoxed { Boolean propBoolean; Byte propByte; Character propCharacter; Short propShort; Integer propInt; Long propLong; Float propFloat; Double propDouble; public Integer getPropInt() { return propInt; } public void setPropInt(Integer propInt) { this.propInt = propInt; } public Long getPropLong() { return propLong; } public void setPropLong(Long propLong) { this.propLong = propLong; } public Boolean getPropBoolean() { return propBoolean; } public void setPropBoolean(Boolean propBoolean) { this.propBoolean = propBoolean; } public Byte getPropByte() { return propByte; } public void setPropByte(Byte propByte) { this.propByte = propByte; } public Character getPropCharacter() { return propCharacter; } public void setPropCharacter(Character propCharacter) { this.propCharacter = propCharacter; } public Short getPropShort() { return propShort; } public void setPropShort(Short propShort) { this.propShort = propShort; } public Float getPropFloat() { return propFloat; } public void setPropFloat(Float propFloat) { this.propFloat = propFloat; } public Double getPropDouble() { return propDouble; } public void setPropDouble(Double propDouble) { this.propDouble = propDouble; } } @Test public void testObjectFieldGetterAsm() throws Exception { Getter<FooField, Object> getter = asm.getGetter(FooField.class, "foo"); assertFalse(getter instanceof FieldGetter); FooField ff = new FooField(); ff.foo = "foo1"; assertEquals("foo1", getter.get(ff)); } @Test public void testExtension() throws Exception { Foo foo = new Foo(); new ObjectSetterFactory(null).getSetter(Foo.class, "bar").set(foo, "bar"); assertEquals("bar", noAsm.getGetter(Foo.class, "bar").get(foo)); } }
package seedu.todo.guitests; import static org.junit.Assert.*; import static seedu.todo.testutil.AssertUtil.assertSameDate; import java.time.LocalDate; import java.time.LocalDateTime; import org.junit.Before; import org.junit.Test; import seedu.todo.commons.util.DateUtil; import seedu.todo.guitests.guihandles.TaskListDateItemHandle; import seedu.todo.guitests.guihandles.TaskListEventItemHandle; import seedu.todo.guitests.guihandles.TaskListTaskItemHandle; import seedu.todo.models.Task; import seedu.todo.models.TodoListDB; /** * @@author A0093907W */ public class UndoRedoCommandTest extends GuiTest { private final LocalDateTime oneDayFromNow = LocalDateTime.now().plusDays(1); private final String oneDayFromNowString = DateUtil.formatDate(oneDayFromNow); private final String oneDayFromNowIsoString = DateUtil.formatIsoDate(oneDayFromNow); private final LocalDateTime twoDaysFromNow = LocalDateTime.now().plusDays(2); private final String twoDaysFromNowString = DateUtil.formatDate(twoDaysFromNow); private final String twoDaysFromNowIsoString = DateUtil.formatIsoDate(twoDaysFromNow); String commandAdd1 = String.format("add task Buy KOI by \"%s 8pm\"", oneDayFromNowString); Task task1 = new Task(); String commandAdd2 = String.format("add task Buy Milk by \"%s 9pm\"", twoDaysFromNowString); Task task2 = new Task(); public UndoRedoCommandTest() { task1.setName("Buy KOI"); task1.setCalendarDateTime(DateUtil.parseDateTime(String.format("%s 20:00:00", oneDayFromNowIsoString))); task2.setName("Buy Milk"); task2.setDueDate(DateUtil.parseDateTime(String.format("%s 21:00:00", twoDaysFromNowIsoString))); } @Before public void resetDB() { TodoListDB db = TodoListDB.getInstance(); db.destroyAllEvent(); db.destroyAllTask(); } @Test public void undo_single() { console.runCommand("clear"); assertTaskVisibleAfterCmd(commandAdd1, task1); assertTaskVisibleAfterCmd(commandAdd2, task2); assertTaskNotVisibleAfterCmd("undo", task2); } @Test public void undo_multiple() { console.runCommand("clear"); assertTaskVisibleAfterCmd(commandAdd1, task1); assertTaskVisibleAfterCmd(commandAdd2, task2); assertTaskNotVisibleAfterCmd("undo 2", task1); assertTaskNotVisibleAfterCmd("list", task2); // A li'l hacky but oh well } @Test public void redo_single() { console.runCommand("clear"); assertTaskVisibleAfterCmd(commandAdd1, task1); assertTaskNotVisibleAfterCmd("undo", task1); assertTaskVisibleAfterCmd("redo", task1); } @Test public void redo_multiple() { console.runCommand("clear"); assertTaskVisibleAfterCmd(commandAdd1, task1); assertTaskVisibleAfterCmd(commandAdd2, task2); assertTaskNotVisibleAfterCmd("undo 2", task1); assertTaskNotVisibleAfterCmd("list", task2); assertTaskVisibleAfterCmd("redo 2", task1); assertTaskVisibleAfterCmd("list", task2); } }
package com.vangent.hieos.xutil.xconfig; import com.vangent.hieos.xutil.exception.XMLParserException; import com.vangent.hieos.xutil.xml.XMLParser; import com.vangent.hieos.xutil.exception.XConfigException; import com.vangent.hieos.xutil.iosupport.Io; // Third-party. import java.util.ArrayList; import java.util.Iterator; import java.util.HashMap; import org.apache.axiom.om.OMElement; import java.io.File; import java.io.FileInputStream; import java.util.List; import org.apache.log4j.Logger; /** * Maintains system configuration parameters for IHE XDS.b and XCA profiles. Acts as a Singleton. * * @author Bernie Thuman * */ public class XConfig { public enum ConfigItem { CONFIG_DIR, XCONFIG_FILE, SCHEMA_DIR, CODES_FILE, XDSBRIDGE_DIR, POLICY_DIR }; // HIEOS environment variables (would like to rename but remaining backward compatible). public final static String ENV_HIEOS_CONFIG_DIR = "HIEOSxConfigDir"; public final static String ENV_HIEOS_XCONFIG_FILE = "HIEOSxConfigFile"; public final static String ENV_HIEOS_SCHEMA_DIR = "HIEOSxSchemaDir"; public final static String ENV_HIEOS_XDSBRIDGE_DIR = "HIEOSxXDSBridgeDir"; public final static String ENV_HIEOS_POLICY_DIR = "HIEOSxPolicyDir"; public final static String ENV_HIEOS_CODES_FILE = "HIEOSxCodesFile"; // HIEOS system properties (would like to rename but remaining backward compatible). public final static String SYSPROP_HIEOS_CONFIG_DIR = "com.vangent.hieos.configdir"; public final static String SYSPROP_HIEOS_XCONFIG_FILE = "com.vangent.hieos.xconfig"; public final static String SYSPROP_HIEOS_SCHEMA_DIR = "com.vangent.hieos.schemadir"; public final static String SYSPROP_HIEOS_XDSBRIDGE_DIR = "com.vangent.hieos.xdsbridgedir"; public final static String SYSPROP_HIEOS_POLICY_DIR = "com.vangent.hieos.policydir"; public final static String SYSPROP_HIEOS_CODES_FILE = "com.vangent.hieos.codesfile"; private final static Logger logger = Logger.getLogger(XConfig.class); // Location of XDS.b / XCA configuration file (looks in environment variable first. static private XConfig _instance = null; // Singleton instance. static private String _configLocation = null; // Location of xconfig.xml file // Internal data structure starts here. private List<XConfigObject> objects = new ArrayList<XConfigObject>(); private HashMap<String, XConfigObject> objectByNameMap = new HashMap<String, XConfigObject>(); private HashMap<String, XConfigObject> objectByIdMap = new HashMap<String, XConfigObject>(); private List<XConfigObject> assigningAuthorities = new ArrayList<XConfigObject>(); // Kept as strings versus enum to allow extension without XConfig code modification. static final public String HOME_COMMUNITY_TYPE = "HomeCommunityType"; static final public String XDSB_DOCUMENT_REGISTRY_TYPE = "DocumentRegistryType"; static final public String XDSB_DOCUMENT_REPOSITORY_TYPE = "DocumentRepositoryType"; static final public String XCA_INITIATING_GATEWAY_TYPE = "InitiatingGatewayType"; static final public String XCA_RESPONDING_GATEWAY_TYPE = "RespondingGatewayType"; static final public String XUA_PROPERTIES_TYPE = "XUAPropertiesType"; static final public String ASSIGNING_AUTHORITY_TYPE = "AssigningAuthorityType"; static final public String PDS_TYPE = "PDSType"; static final public String PIX_MANAGER_TYPE = "PIXManagerType"; static final public String XDR_DOCUMENT_RECIPIENT_TYPE = "DocumentRecipientType"; /** * * @param configItem * @return */ static public String getConfigLocation(ConfigItem configItem) { String configLocation = null; switch (configItem) { case CONFIG_DIR: configLocation = getConfigDir(); break; case XCONFIG_FILE: configLocation = getConfigLocation(configItem, XConfig.SYSPROP_HIEOS_XCONFIG_FILE, XConfig.ENV_HIEOS_XCONFIG_FILE); break; case SCHEMA_DIR: configLocation = getConfigLocation(configItem, XConfig.SYSPROP_HIEOS_SCHEMA_DIR, XConfig.ENV_HIEOS_SCHEMA_DIR); break; case CODES_FILE: configLocation = getConfigLocation(configItem, XConfig.SYSPROP_HIEOS_CODES_FILE, XConfig.ENV_HIEOS_CODES_FILE); break; case XDSBRIDGE_DIR: configLocation = getConfigLocation(configItem, XConfig.SYSPROP_HIEOS_XDSBRIDGE_DIR, XConfig.ENV_HIEOS_XDSBRIDGE_DIR); break; case POLICY_DIR: configLocation = getConfigLocation(configItem, XConfig.SYSPROP_HIEOS_POLICY_DIR, XConfig.ENV_HIEOS_POLICY_DIR); break; } return configLocation; } /** * * @return */ static public String getConfigDir() { // First look at system property. String configDir = System.getProperty(XConfig.SYSPROP_HIEOS_CONFIG_DIR); if (configDir == null) { // Look in environment variable next. configDir = System.getenv(XConfig.ENV_HIEOS_CONFIG_DIR); } return configDir; } /** * * @param sysPropName * @param envName * @return */ static private String getConfigLocation(ConfigItem configItem, String sysPropName, String envName) { // First look at system property. String configLocation = System.getProperty(sysPropName); if (configLocation == null) { // Look in environment variable next. configLocation = System.getenv(envName); } if (configLocation == null) { String configDir = XConfig.getConfigDir(); switch (configItem) { case XCONFIG_FILE: configLocation = configDir + "/xconfig.xml"; break; case SCHEMA_DIR: configLocation = configDir + "/schema"; break; case CODES_FILE: configLocation = configDir + "/codes/codes.xml"; break; case XDSBRIDGE_DIR: configLocation = configDir + "/xdsbridge"; break; case POLICY_DIR: configLocation = configDir + "/policy"; break; } } return configLocation; } /** * * @param configLocation */ static public synchronized void setConfigLocation(String configLocation) { _configLocation = configLocation; } /** * Returns Singleton instance of XConfig. * * @return Singleton instance of XConfig * @throws XConfigException */ static public synchronized XConfig getInstance() throws XConfigException { if (_instance == null) { _instance = new XConfig(); } return _instance; } /** * Private constructor responsible for loading configuration file into memory. */ private XConfig() throws XConfigException { loadConfiguration(); } /** * Returns the global configuration for the Home Community. * * @return XConfigObject */ public XConfigObject getHomeCommunityConfig() { String key = this.getKey("home", XConfig.HOME_COMMUNITY_TYPE); return this.objectByNameMap.get(key); } /** * Returns an XConfigActor (RespondingGatewayType) based on a homeCommunityId. * * @param homeCommunityId * @return An instance of XConfigActor or null (if not found). */ public XConfigActor getRespondingGatewayConfigForHomeCommunityId(String homeCommunityId) { return this.getXConfigActorById(homeCommunityId, XConfig.XCA_RESPONDING_GATEWAY_TYPE); } /** * Return an XConfigActor (RespondingGatewayType) given a gateway name. * * @param gatewayName Name of responding gateway. * @return XConfigActor */ protected XConfigActor getRespondingGatewayConfigByName(String gatewayName) { return this.getXConfigActorByName(gatewayName, XConfig.XCA_RESPONDING_GATEWAY_TYPE); } /** * Return an XConfigActor (RepositoryType) given a repository id. * * @param repositoryId * @return XConfigActor */ public XConfigActor getRepositoryConfigById(String repositoryId) { return this.getXConfigActorById(repositoryId, XConfig.XDSB_DOCUMENT_REPOSITORY_TYPE); } /** * Returns an XConfigObject for a given "name" and "type". * * @param name Name of the object. * @param type Type of the object. * @return XConfigObject */ public XConfigObject getXConfigObjectByName(String name, String type) { XConfigObject configObject = null; String key = this.getKey(name, type); if (this.objectByNameMap.containsKey(key)) { configObject = this.objectByNameMap.get(key); } return configObject; } /** * Returns an XConfigObject for a given "id" and "type". * * @param id Identifier for the object. * @param type Type of the object. * @return XConfigObject */ public XConfigObject getXConfigObjectById(String id, String type) { XConfigObject configObject = null; String key = this.getKey(id, type); if (this.objectByIdMap.containsKey(key)) { configObject = this.objectByIdMap.get(key); } return configObject; } /** * Returns all XConfigObject instances of the specific type. * * @param type The type of XConfigObject to locate. * @return List<XConfigObject> */ public List<XConfigObject> getXConfigObjectsOfType(String type) { List<XConfigObject> configObjects = new ArrayList<XConfigObject>(); for (XConfigObject object : objects) { if (object.getType().equalsIgnoreCase(type)) { configObjects.add(object); } } return configObjects; } /** * Returns an XConfigActor for a give "name" and "type". * * @param name Name of the Actor. * @param type Type of the Actor. * @return XConfigActor. */ public XConfigActor getXConfigActorByName(String name, String type) { return (XConfigActor) this.getXConfigObjectByName(name, type); } /** * Returns an XConfigActor for a give "id" and "type". * * @param id Identifier of the Actor. * @param type Type of the Actor. * @return XConfigActor. */ public XConfigActor getXConfigActorById(String id, String type) { return (XConfigActor) this.getXConfigObjectById(id, type); } /** * Returns an XConfigActor (RepositoryType) for a given repository "name". * * @param repositoryName * @return XConfigActor */ public XConfigActor getRepositoryConfigByName(String repositoryName) { return this.getXConfigActorByName(repositoryName, XConfig.XDSB_DOCUMENT_REPOSITORY_TYPE); } /** * Returns an XConfigActor (RegistryType) for a given registry "name". * * @param registryName * @return XConfigActor */ public XConfigActor getRegistryConfigByName(String registryName) { return this.getXConfigActorByName(registryName, XConfig.XDSB_DOCUMENT_REGISTRY_TYPE); } /** * Returns list of available assigning authority configurations. * * @return List<XConfigObject> List of assigning authority configurations. */ public List<XConfigObject> getAssigningAuthorityConfigs() { return this.assigningAuthorities; } /** * Returns an XConfigObject (AssigningAuthorityType) for a given "unique id". * * @param uniqueId * @return XConfigObject */ public XConfigObject getAssigningAuthorityConfigById(String uniqueId) { return this.getXConfigObjectById(uniqueId, XConfig.ASSIGNING_AUTHORITY_TYPE); } /** * Returns list of XConfigActors (of RespondingGatewayType) for a given assigning authority. * * @param uniqueId * @return List<XConfigActor> */ public List<XConfigActor> getRespondingGatewayConfigsForAssigningAuthorityId(String uniqueId) { XConfigObject aa = this.getAssigningAuthorityConfigById(uniqueId); List<XConfigActor> gateways = new ArrayList<XConfigActor>(); if (aa != null) { List<XConfigObject> configObjects = aa.getXConfigObjectsWithType(XConfig.XCA_RESPONDING_GATEWAY_TYPE); for (XConfigObject configObject : configObjects) { gateways.add((XConfigActor) configObject); } } return gateways; } /** * Returns XConfigActor (RegistryType) for a given assigning authority. * * @param uniqueId * @return XConfigActor */ public XConfigActor getRegistryConfigForAssigningAuthorityId(String uniqueId) { XConfigObject aa = this.getAssigningAuthorityConfigById(uniqueId); XConfigActor registry = null; if (aa != null) { List<XConfigObject> configObjects = aa.getXConfigObjectsWithType(XConfig.XDSB_DOCUMENT_REGISTRY_TYPE); if (configObjects.size() > 0) { registry = (XConfigActor) configObjects.get(0); // Should only have one. } } return registry; } /** * Return property value given a property key (scoped to home community). * * @param propKey Property key. * @return String Property value. */ public String getHomeCommunityConfigProperty(String propKey) { XConfigObject homeCommunityConfig = this.getHomeCommunityConfig(); return homeCommunityConfig.getProperty(propKey); } /** * Return boolean property value given a property key (scoped to home community). * * @param propKey Property key. * @return String Property value. */ public boolean getHomeCommunityConfigPropertyAsBoolean(String propKey) { XConfigObject homeCommunityConfig = this.getHomeCommunityConfig(); return homeCommunityConfig.getPropertyAsBoolean(propKey); } /** * Return boolean property value given a property key (scoped to home community). * * @param propKey Property key. * @param defaultValue Returned as value if "propKey" does not exist. * @return String Property value. */ public boolean getHomeCommunityConfigPropertyAsBoolean(String propKey, boolean defaultValue) { XConfigObject homeCommunityConfig = this.getHomeCommunityConfig(); return homeCommunityConfig.getPropertyAsBoolean(propKey, defaultValue); } /** * Return "long" property value given a property key (scoped to home community). * * @param propKey Property key. * @return long Property value. */ public long getHomeCommunityConfigPropertyAsLong(String propKey) { String longVal = this.getHomeCommunityConfigProperty(propKey); return (new Long(longVal)).longValue(); } /** * Return true if property "key" exists in home community configuration. * * @param propKey Property key. * @return boolean True if exists. False, otherwise. */ public boolean containsHomeCommunityConfigProperty(String propKey) { XConfigObject homeCommunityConfig = this.getHomeCommunityConfig(); return homeCommunityConfig.containsProperty(propKey); } /** * Retrieves XML configuration file, parses and places into an easily accessible data structure. */ private void loadConfiguration() throws XConfigException { String configLocation = _configLocation; // May be set. if (configLocation == null) { configLocation = XConfig.getConfigLocation(ConfigItem.XCONFIG_FILE); } String configXML = null; if (configLocation != null) { try { logger.info("Loading XConfig from: " + configLocation); // Get the configuration file from the file system. configXML = Io.getStringFromInputStream(new FileInputStream(new File(configLocation))); } catch (Exception e) { throw new XConfigException( "XConfig: Could not load configuration from " + configLocation + " " + e.getMessage()); } } else { throw new XConfigException( "XConfig: Unable to get location of xconfig file"); } // Parse the XML file. OMElement configXMLRoot; try { configXMLRoot = XMLParser.stringToOM(configXML); } catch (XMLParserException ex) { throw new XConfigException(ex.getMessage()); } if (configXMLRoot == null) { throw new XConfigException( "XConfig: Could not parse configuration from " + configLocation); } buildInternalStructure(configXMLRoot); } /** * Builds internal data structures for quick access. * * @param rootNode Holds root node of parsed configuration file. */ private void buildInternalStructure(OMElement rootNode) { parseObjects(rootNode); parseActors(rootNode); resolveObjectReferences(); } /** * Parses all "Object" XML nodes. * * @param rootNode Starting point. */ private void parseObjects(OMElement rootNode) { List<OMElement> nodes = XConfig.parseLevelOneNode(rootNode, "Object"); for (OMElement currentNode : nodes) { XConfigObject configObject = new XConfigObject(); configObject.parse(currentNode, this); this.addConfigObjectToMaps(configObject); } } /** * Parses all "Actor" XML nodes. * * @param rootNode Starting point. */ private void parseActors(OMElement rootNode) { List<OMElement> nodes = XConfig.parseLevelOneNode(rootNode, "Actor"); for (OMElement currentNode : nodes) { XConfigActor configObject = new XConfigActor(); configObject.parse(currentNode, this); this.addConfigObjectToMaps(configObject); } } /** * Add XConfigObject to internal data structures. * * @param configObject XConfigObject */ private void addConfigObjectToMaps(XConfigObject configObject) { if (configObject.getType().equals(XConfig.ASSIGNING_AUTHORITY_TYPE)) { this.assigningAuthorities.add(configObject); } this.objectByNameMap.put(this.getNameKey(configObject), configObject); if (configObject.getUniqueId() != null) { this.objectByIdMap.put(this.getIdKey(configObject), configObject); } this.objects.add(configObject); } /** * Formulate a "name based" key to use for lookups. * * @param configObject * @return String Formatted key. */ private String getNameKey(XConfigObject configObject) { return configObject.getName() + ":" + configObject.getType(); } /** * Formulate a key to use for lookups. * * @param name * @param key * @return String Formatted key. */ private String getKey(String name, String type) { return name + ":" + type; } /** * Formulate a "name based" key to use for lookups. * * @param configObjectRef * @return String Formatted key. */ private String getNameKey(XConfigObjectRef configObjectRef) { return configObjectRef.getRefName() + ":" + configObjectRef.getRefType(); } /** * Formulate an "id based" key to use for lookups. * * @param configObject * @return String Formatted key. */ private String getIdKey(XConfigObject configObject) { return configObject.getUniqueId() + ":" + configObject.getType(); } /** * Go through list of objects and resolve references to each other. */ private void resolveObjectReferences() { for (XConfigObject configObject : this.objects) { for (XConfigObjectRef objRef : configObject.getObjectRefs()) { // See if already resolved. if (objRef.getXConfigObject() == null) { // Find reference (by refname). String refKey = this.getNameKey(objRef); if (this.objectByNameMap.containsKey(refKey) == true) { XConfigObject referencedObject = objectByNameMap.get(refKey); objRef.setXConfigObject(referencedObject); } } } } } /** * Return property value for XUA configuration. * * @param propKey Property key. * @return String Property value. */ public String getXUAConfigProperty(String propKey) { XConfigObject configObject = this.getXUAConfigProperties(); return configObject.getProperty(propKey); } /** * Return boolean property value for XUA configuration. * * @param propKey Property key. * @return String Property value. */ public boolean getXUAConfigPropertyAsBoolean(String propKey) { XConfigObject configObject = this.getXUAConfigProperties(); return configObject.getPropertyAsBoolean(propKey); } /** * Return "XUAProperties" object. * * @return XConfigObject */ public XConfigObject getXUAConfigProperties() { return this.getXConfigObjectByName("XUAProperties", XConfig.XUA_PROPERTIES_TYPE); } /** * Helper method to find all AXIOM nodes given a "root node" and "local name". * * @param rootNode Starting point. * @param localName Local name to find. * @return List<OMElement> */ protected static List<OMElement> parseLevelOneNode(OMElement rootNode, String localName) { ArrayList<OMElement> al = new ArrayList<OMElement>(); for (Iterator it = rootNode.getChildElements(); it.hasNext();) { OMElement child = (OMElement) it.next(); if (child.getLocalName().equals(localName)) { al.add(child); } } return al; } /** * Just a test driver to exercise XConfig operations. * * @param args the command line arguments */ }
package com.eqt.ssc.tools; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.GZIPInputStream; import org.apache.commons.io.IOUtils; import com.amazonaws.auth.ClasspathPropertiesFileCredentialsProvider; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectInputStream; import com.amazonaws.services.s3.model.S3ObjectSummary; /*** * utility that will take an s3 bucket and mirror it locally. * * @author gman * */ public class S3Downloader { public static void main(String[] args) { if (args.length < 2) { System.out.println("USAGE: localPath bucketname <bucketPrefix>"); System.exit(1); } String localPath = args[0]; String bucketName = args[1]; String bucketPrefix = ""; //add on extra slash if(!localPath.endsWith("/")) localPath += "/"; if (args.length == 3) bucketPrefix = args[2]; //check local dir, make if it does not exist File localDir = new File(localPath); if(!localDir.exists()) localDir.mkdirs(); if(!localDir.isDirectory()) { System.out.println("Local Dir is not a dir: " + localPath); System.exit(1); } long totalBytes = 0; long start = System.currentTimeMillis(); AmazonS3 s3 = new AmazonS3Client( new ClasspathPropertiesFileCredentialsProvider()); ObjectListing listObjects = s3.listObjects(bucketName, bucketPrefix); do { for (S3ObjectSummary objectSummary : listObjects.getObjectSummaries()) { S3Object object = s3.getObject(bucketName, objectSummary.getKey()); S3ObjectInputStream inputStream = object.getObjectContent(); if("gzip".equals(object.getObjectMetadata().getContentEncoding())) { InputStream in = null; try { totalBytes += object.getObjectMetadata().getContentLength(); in = new GZIPInputStream(inputStream); //write this sucker out String path = localPath + object.getKey(); //have to take the gz off since this is not downloading compressed! if(path.endsWith(".gz")) path = path.substring(0,path.length() - 3); System.out.print("Writing file: " + path); File check = new File(path); File parentFile = check.getParentFile(); if(!parentFile.exists()) parentFile.mkdirs(); FileOutputStream out = new FileOutputStream(path); IOUtils.copy(in, out); System.out.println(" written."); } catch (IOException e) { System.out.println("crap"); e.printStackTrace(); throw new IllegalStateException("files are too hard",e); } finally { IOUtils.closeQuietly(in); } } else { System.out.println("unhandled content encoding: " + object.getObjectMetadata().getContentEncoding()); } } listObjects = s3.listNextBatchOfObjects(listObjects); } while (listObjects.isTruncated()); long now = System.currentTimeMillis(); System.out.println((totalBytes / 1000.0/ 1000.0) + " mb downloaded in " + ((now -start)/1000) + " seconds."); } }
package cn.cerc.mis.core; import java.io.IOException; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import cn.cerc.core.ClassConfig; import cn.cerc.core.ClassResource; import cn.cerc.core.ISession; import cn.cerc.core.LanguageResource; import cn.cerc.db.core.IAppConfig; import cn.cerc.db.core.IHandle; import cn.cerc.db.core.ISessionOwner; import cn.cerc.db.core.ITokenManage; import cn.cerc.db.core.ServerConfig; import cn.cerc.mis.SummerMIS; import lombok.extern.slf4j.Slf4j; @Slf4j public class Application { private static final ClassResource res = new ClassResource(Application.class, SummerMIS.ID); private static final ClassConfig config = new ClassConfig(Application.class, SummerMIS.ID); // tomcat JSESSION.ID public static final String sessionId = "sessionId"; // FIXME 5ISession public static final String TOKEN = ISession.TOKEN; public static final String bookNo = ISession.CORP_NO; public static final String userCode = ISession.USER_CODE; public static final String userName = ISession.USER_NAME; public static final String deviceLanguage = ISession.LANGUAGE_ID; @Deprecated public static final String userId = "UserID"; @Deprecated public static final String roleCode = "RoleCode"; public static final String ProxyUsers = "ProxyUsers"; public static final String clientIP = "clientIP"; public static final String loginTime = "loginTime"; public static final String webclient = "webclient"; // FIXME: 2019/12/7 public static final String App_Language = getAppLanguage(); // cn/en public static final String PATH_FORMS = "application.pathForms"; public static final String PATH_SERVICES = "application.pathServices"; public static final String FORM_WELCOME = "application.formWelcome"; public static final String FORM_DEFAULT = "application.formDefault"; public static final String FORM_LOGOUT = "application.formLogout"; public static final String FORM_VERIFY_DEVICE = "application.formVerifyDevice"; public static final String JSPFILE_LOGIN = "application.jspLoginFile"; public static final String FORM_ID = "formId"; private static ApplicationContext context; private static String staticPath; static { staticPath = config.getString("app.static.path", ""); } public static void init(String packageId) { if (context != null) return; String xmlFile = String.format("%s-spring.xml", packageId); if (packageId == null) xmlFile = "application.xml"; ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(xmlFile); context = ctx; } public static ApplicationContext getContext() { return context; } private static String getAppLanguage() { return LanguageResource.appLanguage; } public static void setContext(ApplicationContext applicationContext) { if (context != applicationContext) { if (context == null) { } else { log.warn("applicationContext overload!"); } context = applicationContext; } } public static ApplicationContext get(ServletContext servletContext) { setContext(WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)); return context; } public static ApplicationContext get(ServletRequest request) { setContext(WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext())); return context; } @Deprecated public static <T> T getBean(String beanId, Class<T> requiredType) { return context.getBean(beanId, requiredType); } public static <T> T getBean(Class<T> requiredType, String... beans) { for (String key : beans) { if (!context.containsBean(key)) { continue; } return context.getBean(key, requiredType); } return null; } /** * ISessionOwner session * * ITokenManage tokenManage, tokenManageDefault * * @param <T> * @param requiredType * @param session * @return */ public static <T> T getBeanDefault(Class<T> requiredType, ISession session) { String[] items = requiredType.getName().split("\\."); String itemId = items[items.length - 1]; String classId = itemId; if (itemId.substring(0, 2).toUpperCase().equals(itemId.substring(0, 2))) { classId = itemId.substring(1); } String beanId = classId.substring(0, 1).toLowerCase() + classId.substring(1); T result = getBean(requiredType, beanId, beanId + "Default"); // session if ((session != null) && (result instanceof ISessionOwner)) { ((ISessionOwner) result).setSession(session); } return result; } public static <T> T getBean(Class<T> requiredType) { String[] items = requiredType.getName().split("\\."); String itemId = items[items.length - 1]; String beanId; if (itemId.substring(0, 2).toUpperCase().equals(itemId.substring(0, 2))) { beanId = itemId; } else { beanId = itemId.substring(0, 1).toLowerCase() + itemId.substring(1); } return context.getBean(beanId, requiredType); } @Deprecated public static IHandle getHandle() { return new Handle(createSession()); } public static ISession createSession() { return getBeanDefault(ISession.class, null); } /** * ClassResourceAppConfigDefault * * @return */ @Deprecated public static IAppConfig getAppConfig() { return getBeanDefault(IAppConfig.class, null); } @Deprecated // getBean public static <T> T get(IHandle handle, Class<T> requiredType) { return getBean(handle, requiredType); } public static <T> T getBean(IHandle handle, Class<T> requiredType) { T bean = getBean(requiredType); if (bean != null && handle != null) { if (bean instanceof IHandle) { ((IHandle) bean).setSession(handle.getSession()); } } return bean; } public static IService getService(IHandle handle, String serviceCode) { IService bean = context.getBean(serviceCode, IService.class); if (bean != null && handle != null) { bean.setHandle(handle); } return bean; } public static IPassport getPassport(ISession session) { return getBeanDefault(IPassport.class, session); } public static IPassport getPassport(ISessionOwner owner) { return getBeanDefault(IPassport.class, owner.getSession()); } public static ISystemTable getSystemTable() { return getBeanDefault(ISystemTable.class, null); } public static IForm getForm(HttpServletRequest req, HttpServletResponse resp, String formId) { if (formId == null || "".equals(formId) || "service".equals(formId)) { return null; } setContext(WebApplicationContextUtils.getRequiredWebApplicationContext(req.getServletContext())); if (!context.containsBean(formId)) { throw new RuntimeException(String.format("form %s not find!", formId)); } IForm form = context.getBean(formId, IForm.class); if (form != null) { form.setRequest(req); form.setResponse(resp); } return form; } public static String getLanguage() { String lang = ServerConfig.getInstance().getProperty(deviceLanguage); if (lang == null || "".equals(lang) || App_Language.equals(lang)) { return App_Language; } else if (LanguageResource.LANGUAGE_EN.equals(lang)) { return lang; } else { throw new RuntimeException("not support language: " + lang); } } public static String getFormView(HttpServletRequest req, HttpServletResponse resp, String formId, String funcCode, String... pathVariables) { req.setAttribute("logon", false); IFormFilter formFilter = Application.getBean(IFormFilter.class, "AppFormFilter"); if (formFilter != null) { try { if (formFilter.doFilter(resp, formId, funcCode)) { return null; } } catch (IOException e) { log.error(e.getMessage()); e.printStackTrace(); } } ISession session = null; try { IForm form = Application.getForm(req, resp, formId); if (form == null) { outputErrorPage(req, resp, new RuntimeException("error servlet:" + req.getServletPath())); return null; } AppClient client = new AppClient(); client.setRequest(req); req.setAttribute("_showMenu_", !AppClient.ee.equals(client.getDevice())); form.setClient(client); session = Application.createSession(); ITokenManage manage = Application.getBeanDefault(ITokenManage.class, session); manage.resumeToken((String) req.getSession().getAttribute(RequestData.TOKEN)); session.setProperty(Application.sessionId, req.getSession().getId()); session.setProperty(Application.deviceLanguage, client.getLanguage()); session.setProperty(Application.TOKEN, req.getSession().getAttribute(RequestData.TOKEN)); IHandle handle = new Handle(session); req.setAttribute("myappHandle", handle); form.setId(formId); form.setHandle(handle); form.setPathVariables(pathVariables); // Form if (form.allowGuestUser()) { return form.getView(funcCode); } if (session.logon()) { if (!Application.getPassport(session).pass(form)) { resp.setContentType("text/html;charset=UTF-8"); JsonPage output = new JsonPage(form); output.setResultMessage(false, res.getString(1, "")); output.execute(); return null; } } else { IAppLogin appLogin = Application.getBeanDefault(IAppLogin.class, session); if (!appLogin.pass(form)) { return appLogin.getJspFile(); } } if (form.isSecurityDevice()) { return form.getView(funcCode); } ISecurityDeviceCheck deviceCheck = Application.getBeanDefault(ISecurityDeviceCheck.class, session); switch (deviceCheck.pass(form)) { case PASS: return form.getView(funcCode); case CHECK: return "redirect:" + config.getString(Application.FORM_VERIFY_DEVICE, "VerifyDevice"); default: resp.setContentType("text/html;charset=UTF-8"); JsonPage output = new JsonPage(form); output.setResultMessage(false, res.getString(2, "")); output.execute(); return null; } } catch (Exception e) { outputErrorPage(req, resp, e); return null; } finally { if (session != null) { session.close(); } } } public static void outputView(HttpServletRequest request, HttpServletResponse response, String url) throws IOException, ServletException { if (url == null) return; if (url.startsWith("redirect:")) { String redirect = url.substring(9); redirect = response.encodeRedirectURL(redirect); response.sendRedirect(redirect); return; } // jsp String jspFile = String.format("/WEB-INF/%s/%s", config.getString(Application.PATH_FORMS, "forms"), url); request.getServletContext().getRequestDispatcher(jspFile).forward(request, response); } public static void outputErrorPage(HttpServletRequest request, HttpServletResponse response, Throwable e) { Throwable err = e.getCause(); if (err == null) { err = e; } IAppErrorPage errorPage = Application.getBeanDefault(IAppErrorPage.class, null); if (errorPage != null) { String result = errorPage.getErrorPage(request, response, err); if (result != null) { String url = String.format("/WEB-INF/%s/%s", config.getString(Application.PATH_FORMS, "forms"), result); try { request.getServletContext().getRequestDispatcher(url).forward(request, response); } catch (ServletException | IOException e1) { log.error(e1.getMessage()); e1.printStackTrace(); } } } else { log.warn("not define bean: errorPage"); log.error(err.getMessage()); err.printStackTrace(); } } /** * token * * @param handle * @return */ public static String getToken(IHandle handle) { return (String) handle.getProperty(Application.TOKEN); } public static String getStaticPath() { return staticPath; } public static ITokenManage getTokenManage(ISession session) { return getBeanDefault(ITokenManage.class, session); } public static String getHomePage() { return config.getString(Application.FORM_DEFAULT, "default"); } }
package com.googlecode.totallylazy.template; import com.googlecode.totallylazy.template.ast.Grammar; import org.hamcrest.Matchers; import org.junit.Test; import java.util.Map; import static com.googlecode.totallylazy.Lists.list; import static com.googlecode.totallylazy.Maps.map; import static com.googlecode.totallylazy.matchers.Matchers.is; import static com.googlecode.totallylazy.template.Template.template; import static org.hamcrest.MatcherAssert.assertThat; public class TemplateTest { @Test public void subTemplatesCanHaveDotsInTheirNames() throws Exception { Templates templates = Templates.templates(). add("a.txt", ignore -> "..."). add("b.txt", context -> "Your last name is " + ((Map<?, ?>)context).get("name")); Template template = template("Hello $first$ $('a.txt')()$ $('b.txt')(name=last)$", templates); String result = template.render(map( "first", "Dan", "last", "Bodart")); assertThat(result, Matchers.is("Hello Dan ... Your last name is Bodart")); } @Test public void canParseATemplateWithDifferentDelimiters() throws Exception { Template template = template("Hello ~first~ ~last~", Grammar.parser('~')); String result = template.render(map("first", "Dan", "last", "Bodart")); assertThat(result, Matchers.is("Hello Dan Bodart")); } @Test public void canParseATemplate() throws Exception { Template template = template("Hello $first$ $last$"); String result = template.render(map("first", "Dan", "last", "Bodart")); assertThat(result, Matchers.is("Hello Dan Bodart")); } @Test public void canCallSubTemplates() throws Exception { Templates templates = Templates.templates(). add("subTemplateA", ignore -> "..."). add("subTemplateB", context -> "Your last name is " + ((Map<?, ?>)context).get("name")); Template template = template("Hello $first$ $subTemplateA()$ $subTemplateB(name=last)$", templates); String result = template.render(map( "first", "Dan", "last", "Bodart")); assertThat(result, Matchers.is("Hello Dan ... Your last name is Bodart")); } @Test public void supportsMappingList() throws Exception { Template template = template("$users:{ user | Hello $user$ }$"); String result = template.render(map("users", list("Dan", "Bob"))); assertThat(result, is("Hello Dan Hello Bob ")); } @Test public void supportsMappingSingleValues() throws Exception { Template template = template("$users:{ user | Hello $user$ }$"); String result = template.render(map("users", "Dan")); assertThat(result, is("Hello Dan ")); } @Test public void supportsMappingListWithIndex() throws Exception { Template template = template("$users:{ user, index | Hello $user$ you are number $index$!\n}$"); String result = template.render(map("users", list("Dan", "Bob"))); assertThat(result, is("Hello Dan you are number 0!\n" + "Hello Bob you are number 1!\n")); } @Test public void supportsMappingMaps() throws Exception { Template template = template("$user:{ value, key | $key$ $value$, }$"); String result = template.render(map("user", map("name", "Dan", "age", 12))); assertThat(result, is("name Dan, age 12, ")); } @Test public void supportsMappingMapValues() throws Exception { Template template = template("$user:{ value | $value$ }$"); String result = template.render(map("user", map("name","Dan", "age", 12))); assertThat(result, is("Dan 12 ")); } @Test public void supportsIndirection() throws Exception { Template template = template("$(method)$"); String result = template.render(map("method", "PUT", "PUT", "Indirect")); assertThat(result, is("Indirect")); } @Test public void supportsIndirectionWithAnonymousTemplate() throws Exception { Template template = template("$({a-$name$-c})$"); String result = template.render(map("name", "b", "a-b-c", "Indirect")); assertThat(result, is("Indirect")); } @Test public void supportsIndirectionWithNestedMaps() throws Exception { Template template = template("$root.('parent').child$"); String result = template.render(map("root", map("parent", map("child", "Hello")))); assertThat(result, is("Hello")); } @Test public void doesntBlowWithMissingChildren() throws Exception { Template template = template("$root.parent.child$"); String result = template.render(map("root", null)); assertThat(result, is("")); } }
package com.splunk.shep.customsearch; import org.apache.hadoop.fs.FSDataInputStream; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class OutputHdfsTest extends SplunkHdfsTest { String testuri = null; @Parameters({ "splunk.username", "splunk.password", "splunk.home" }) @Test(groups = { "super-slow" }) public void fileCheck(String username, String password, String splunkhome) { System.out.println("Running OutputHdfs Test"); System.out.println("splunkhome " + splunkhome); try { Runtime rt = Runtime.getRuntime(); String cmdarray[] = { splunkhome + "/bin/splunk", "search", "* | head 1 | outputhdfs file=" + testuri, "-auth", username + ":" + password }; Process proc = rt.exec(cmdarray); proc.waitFor(); FSDataInputStream is = getFileinHDFS(testuri); if (is == null) { Assert.fail("File not created by outputhdfs in HDFS"); } } catch (Throwable t) { t.printStackTrace(); Assert.fail(t.getMessage()); } } @Parameters({ "outputhdfstesturi" }) @BeforeMethod(groups = { "super-slow" }) public void beforeTest(String uri) { System.out.println("uri: " + uri); this.testuri = uri; try { mkdirsinHDFS(this.testuri); } catch (Exception e) { Assert.fail(e.getMessage()); } } @AfterMethod(groups = { "super-slow" }) public void afterTest() { try { deleteFileinHDFS(this.testuri); } catch (Exception e) { Assert.fail(e.getMessage()); } } }
package ch.usi.dag.disl.test.processor; import ch.usi.dag.disl.annotation.ArgsProcessor; import ch.usi.dag.disl.annotation.ProcessAlso; import ch.usi.dag.disl.annotation.ProcessAlso.Type; import ch.usi.dag.disl.annotation.SyntheticLocal; import ch.usi.dag.disl.dynamiccontext.DynamicContext; import ch.usi.dag.disl.processor.ArgumentContext; import ch.usi.dag.disl.staticcontext.MethodSC; @ArgsProcessor public class ProcessorTest { @SyntheticLocal public static String flag; public static void objPM(Object c, ArgumentContext ac, MethodSC msc) { System.out.println("processor for object in method " + msc.thisMethodFullName()); System.out.println(ac.position()); System.out.println(ac.totalCount()); System.out.println(ac.typeDescriptor()); System.out.println(c); System.out.println(" DiSLClass.flag = "OMG this is for the End"; } @ProcessAlso(types={Type.SHORT, Type.BYTE, Type.BOOLEAN}) public static void intPM(int c, ArgumentContext ac, DynamicContext dc) { System.out.println("processor for int"); System.out.println(ac.position()); System.out.println(ac.totalCount()); System.out.println(ac.typeDescriptor()); System.out.println(dc.thisValue()); System.out.println(" flag = "Processor flag for the End"; } public static void longPM(long c, ArgumentContext ac) { System.out.println("processor for long"); System.out.println(ac.position()); System.out.println(ac.totalCount()); System.out.println(ac.typeDescriptor()); System.out.println(" } public static void doublePM(double c, ArgumentContext ac) { System.out.println("processor for double"); System.out.println(ac.position()); System.out.println(ac.totalCount()); System.out.println(ac.typeDescriptor()); System.out.println(" } }
package org.sikuli.ide; import java.io.*; import java.awt.*; import java.awt.datatransfer.*; import java.awt.image.*; import java.awt.event.*; import java.util.regex.Pattern; import java.util.regex.Matcher; import javax.swing.*; import javax.swing.text.*; import javax.swing.filechooser.FileFilter; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; //import javax.swing.undo.*; import javax.imageio.*; import org.python.util.PythonInterpreter; import org.python.core.*; import org.sikuli.ide.indentation.PythonIndentation; import org.sikuli.script.ImageLocator; import org.sikuli.script.ScriptRunner; import org.sikuli.script.Debug; import org.sikuli.script.Location; public class SikuliPane extends JTextPane implements KeyListener, CaretListener{ private String _editingFilename; private String _srcBundlePath = null; private boolean _dirty = false; private Class _historyBtnClass; private CurrentLineHighlighter _highlighter; private ImageLocator _imgLocator; private String _tabString = " "; private Pattern _lastSearchPattern = null; private String _lastSearchString = null; private Matcher _lastSearchMatcher; private UndoManager _undo = new UndoManager(); // TODO: move to SikuliDocument private PythonIndentation _indentationLogic; public SikuliPane(){ UserPreferences pref = UserPreferences.getInstance(); setEditorKitForContentType("text/python", new SikuliEditorKit()); setContentType("text/python"); initKeyMap(); addKeyListener(this); setTransferHandler(new MyTransferHandler()); _highlighter = new CurrentLineHighlighter(this); addCaretListener(_highlighter); addCaretListener(this); setFont(new Font(pref.getFontName(), Font.PLAIN, pref.getFontSize())); setMargin( new Insets( 3, 3, 3, 3 ) ); //setTabSize(4); setBackground(Color.WHITE); if(!Utils.isMacOSX()) setSelectionColor(new Color(170, 200, 255)); updateDocumentListeners(); _indentationLogic = new PythonIndentation(); } private void updateDocumentListeners(){ getDocument().addDocumentListener(new DirtyHandler()); getDocument().addUndoableEditListener(_undo); } public UndoManager getUndoManager(){ return _undo; } public PythonIndentation getIndentationLogic(){ return _indentationLogic; } private void initKeyMap(){ InputMap map = this.getInputMap(); int shift = InputEvent.SHIFT_MASK; map.put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, shift), SikuliEditorKit.sklDeindentAction); } public void setTabSize(int charactersPerTab) { FontMetrics fm = this.getFontMetrics( this.getFont() ); int charWidth = fm.charWidth( 'w' ); int tabWidth = charWidth * charactersPerTab; TabStop[] tabs = new TabStop[10]; for (int j = 0; j < tabs.length; j++) { int tab = j + 1; tabs[j] = new TabStop( tab * tabWidth ); } TabSet tabSet = new TabSet(tabs); SimpleAttributeSet attributes = new SimpleAttributeSet(); StyleConstants.setFontSize(attributes, 18); StyleConstants.setFontFamily(attributes, "Osaka-Mono"); StyleConstants.setTabSet(attributes, tabSet); int length = getDocument().getLength(); getStyledDocument().setParagraphAttributes(0, length, attributes, true); } public void setTabs(int spaceForTab) { String t = ""; for(int i=0;i<spaceForTab;i++) t += " "; _tabString = t; } public boolean isDirty(){ return _dirty; } public void setDirty(boolean flag){ if(_dirty == flag) return; _dirty = flag; if(flag) getRootPane().putClientProperty("Window.documentModified", true); else SikuliIDE.getInstance().checkDirtyPanes(); } public int getLineAtCaret(int caretPosition) { Element root = getDocument().getDefaultRootElement(); return root.getElementIndex( caretPosition ) + 1; } public int getLineAtCaret() { int caretPosition = getCaretPosition(); Element root = getDocument().getDefaultRootElement(); return root.getElementIndex( caretPosition ) + 1; } public int getColumnAtCaret() { int offset = getCaretPosition(); int column; try { column = offset - Utilities.getRowStart(this, offset); } catch (BadLocationException e) { column = -1; } return column+1; } void setSrcBundle(String newBundlePath){ _srcBundlePath = newBundlePath; _imgLocator = new ImageLocator(_srcBundlePath); } public String getSrcBundle(){ if( _srcBundlePath == null ){ File tmp = Utils.createTempDir(); setSrcBundle(Utils.slashify(tmp.getAbsolutePath(),true)); } return _srcBundlePath; } public void setErrorHighlight(int lineNo){ _highlighter.setErrorLine(lineNo); try{ if(lineNo>0) jumpTo(lineNo); } catch(Exception e){ e.printStackTrace(); } repaint(); } public void setHistoryCaptureButton(CaptureButton btn){ _historyBtnClass = btn.getClass(); } public boolean close() throws IOException{ if( isDirty() ){ Object[] options = {I18N._I("yes"), I18N._I("no"), I18N._I("cancel")}; int ans = JOptionPane.showOptionDialog(this, I18N._I("msgAskSaveChanges", getCurrentShortFilename()), I18N._I("dlgAskCloseTab"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); if( ans == JOptionPane.CANCEL_OPTION || ans == JOptionPane.CLOSED_OPTION ) return false; else if( ans == JOptionPane.YES_OPTION ) saveFile(); setDirty(false); } return true; } public String getCurrentShortFilename(){ if(_srcBundlePath != null){ File f = new File(_srcBundlePath); return f.getName(); } return "Untitled"; } public String getCurrentFilename(){ if(_editingFilename==null){ try{ saveAsFile(); return _editingFilename; } catch(IOException e){ e.printStackTrace(); } } return _editingFilename; } static InputStream SikuliToHtmlConverter = SikuliIDE.class.getResourceAsStream("/scripts/sikuli2html.py"); static String pyConverter = Utils.convertStreamToString(SikuliToHtmlConverter); static InputStream SikuliBundleCleaner= SikuliIDE.class.getResourceAsStream("/scripts/clean-dot-sikuli.py"); static String pyBundleCleaner = Utils.convertStreamToString(SikuliBundleCleaner); private void convertSrcToHtml(String bundle){ PythonInterpreter py = ScriptRunner.getInstance(null).getPythonInterpreter(); Debug.log(2, "Convert Sikuli source code " + bundle + " to HTML"); py.set("local_convert", true); py.set("sikuli_src", bundle); py.exec(pyConverter); } private void writeFile(String filename) throws IOException{ this.write( new BufferedWriter(new OutputStreamWriter( new FileOutputStream(filename), "UTF8"))); } private void cleanBundle(String bundle){ PythonInterpreter py = ScriptRunner.getInstance(null).getPythonInterpreter(); Debug.log(2, "Clear source bundle " + bundle); py.set("bundle_path", bundle); py.exec(pyBundleCleaner); } private void writeSrcFile(boolean writeHTML) throws IOException{ this.write( new BufferedWriter(new OutputStreamWriter( new FileOutputStream(_editingFilename), "UTF8"))); if(writeHTML) convertSrcToHtml(getSrcBundle()); cleanBundle(getSrcBundle()); setDirty(false); } public String saveFile() throws IOException{ if(_editingFilename==null) return saveAsFile(); else{ writeSrcFile(true); return getCurrentShortFilename(); } } public String saveAsFile() throws IOException{ File file = new FileChooser(SikuliIDE.getInstance()).save(); if(file == null) return null; String bundlePath = file.getAbsolutePath(); if( !file.getAbsolutePath().endsWith(".sikuli") ) bundlePath += ".sikuli"; if(Utils.exists(bundlePath)){ int res = JOptionPane.showConfirmDialog( null, I18N._I("msgFileExists", bundlePath), I18N._I("dlgFileExists"), JOptionPane.YES_NO_OPTION); if(res != JOptionPane.YES_OPTION) return null; } saveAsBundle(bundlePath); return getCurrentShortFilename(); } public String exportAsZip() throws IOException, FileNotFoundException{ File file = new FileChooser(SikuliIDE.getInstance()).export(); if(file == null) return null; String zipPath = file.getAbsolutePath(); String srcName = file.getName(); if( !file.getAbsolutePath().endsWith(".skl") ){ zipPath += ".skl"; } else{ srcName = srcName.substring(0, srcName.lastIndexOf('.')); } writeFile(getSrcBundle() + srcName + ".py"); Utils.zip(getSrcBundle(), zipPath); Debug.log(1, "export to executable file: " + zipPath); return zipPath; } private void saveAsBundle(String bundlePath) throws IOException{ bundlePath = Utils.slashify(bundlePath, true); if(_srcBundlePath != null) Utils.xcopy( _srcBundlePath, bundlePath ); else Utils.mkdir(bundlePath); setSrcBundle(bundlePath); _editingFilename = getSourceFilename(bundlePath); Debug.log(1, "save to bundle: " + getSrcBundle()); writeSrcFile(true); //TODO: update all bundle references in ImageButtons //BUG: if save and rename images, the images will be gone.. } private String getSourceFilename(String filename){ if( filename.endsWith(".sikuli") || filename.endsWith(".sikuli" + "/") ){ File f = new File(filename); String dest = f.getName(); dest = dest.replace(".sikuli", ".py"); return getSrcBundle() + dest; } return filename; } public void loadFile(String filename) throws IOException{ if( filename.endsWith("/") ) filename = filename.substring(0, filename.length()-1); setSrcBundle(filename+"/"); _editingFilename = getSourceFilename(filename); this.read( new BufferedReader(new InputStreamReader( new FileInputStream(_editingFilename), "UTF8")), null); updateDocumentListeners(); setDirty(false); } public String loadFile() throws IOException{ File file = new FileChooser(SikuliIDE.getInstance()).load(); if(file == null) return null; String fname = Utils.slashify(file.getAbsolutePath(),false); loadFile(fname); return fname; } int _caret_last_x = -1; boolean _can_update_caret_last_x = true; public void caretUpdate(CaretEvent evt){ if(_can_update_caret_last_x) _caret_last_x = -1; else _can_update_caret_last_x = true; } public void keyPressed(java.awt.event.KeyEvent ke) { } public void keyReleased(java.awt.event.KeyEvent ke) { } private void expandTab() throws BadLocationException{ int pos = getCaretPosition(); Document doc = getDocument(); doc.remove(pos-1, 1); doc.insertString(pos-1, _tabString, null); } public void keyTyped(java.awt.event.KeyEvent ke) { /* try{ //if(ke.getKeyChar() == '\t') expandTab(); checkCompletion(ke); } catch(BadLocationException e){ e.printStackTrace(); } */ } @Override public void read(Reader in, Object desc) throws IOException{ super.read(in, desc); Document doc = getDocument(); Element root = doc.getDefaultRootElement(); parse(root); setCaretPosition(0); } public void jumpTo(int lineNo, int column) throws BadLocationException{ Debug.log(6, "jumpTo: " + lineNo+","+column); int off = getLineStartOffset(lineNo-1)+column-1; int lineCount= getDocument().getDefaultRootElement().getElementCount(); if( lineNo < lineCount ){ int nextLine = getLineStartOffset(lineNo); if( off >= nextLine ) off = nextLine-1; } if(off < 0) off = 0; setCaretPosition( off ); } public void jumpTo(int lineNo) throws BadLocationException{ Debug.log(6,"jumpTo: " + lineNo); setCaretPosition( getLineStartOffset(lineNo-1) ); } public void jumpTo(String funcName) throws BadLocationException{ Debug.log(6, "jumpTo: " + funcName); Element root = getDocument().getDefaultRootElement(); int pos = getFunctionStartOffset(funcName, root); if(pos>=0) setCaretPosition(pos); else throw new BadLocationException("Can't find function " + funcName,-1); } private int getFunctionStartOffset(String func, Element node) throws BadLocationException{ Document doc = getDocument(); int count = node.getElementCount(); Pattern patDef = Pattern.compile("def\\s+"+func+"\\s*\\("); for(int i=0;i<count;i++){ Element elm = node.getElement(i); if( elm.isLeaf() ){ int start = elm.getStartOffset(), end = elm.getEndOffset(); String line = doc.getText(start, end-start); Matcher matcher = patDef.matcher(line); if(matcher.find()) return start; } else{ int p = getFunctionStartOffset(func, elm); if(p>=0) return p; } } return -1; } public int getNumLines(){ Document doc = getDocument(); Element root = doc.getDefaultRootElement(); int lineIdx = root.getElementIndex(doc.getLength()-1); return lineIdx+1; } public void indent(int startLine, int endLine, int level){ Document doc = getDocument(); String strIndent = ""; if(level>0){ for(int i=0;i<level;i++) strIndent += " "; } else{ Debug.error("negative indentation not supported yet!!"); } for(int i=startLine;i<endLine;i++){ try{ int off = getLineStartOffset(i); if(level>0) doc.insertString(off, strIndent, null); } catch(Exception e){ e.printStackTrace(); } } } // line starting from 0 int getLineStartOffset(int line) throws BadLocationException { Element map = getDocument().getDefaultRootElement(); if (line < 0) { throw new BadLocationException("Negative line", -1); } else if (line >= map.getElementCount()) { throw new BadLocationException("No such line", getDocument().getLength()+1); } else { Element lineElem = map.getElement(line); return lineElem.getStartOffset(); } } int parseRange(int start, int end){ try{ end = parseLine(start, end, patPatternStr); end = parseLine(start, end, patSubregionStr); end = parseLine(start, end, patPngStr); } catch(BadLocationException e){ e.printStackTrace(); } return end; } void parse(Element node){ int count = node.getElementCount(); for(int i=0;i<count;i++){ Element elm = node.getElement(i); Debug.log(8, elm.toString() ); if( elm.isLeaf() ){ int start = elm.getStartOffset(), end = elm.getEndOffset(); parseRange(start, end); } else parse(elm); } } static Pattern patPngStr = Pattern.compile("(\"[^\"]+?\\.(?i)png\")"); static Pattern patHistoryBtnStr = Pattern.compile("(\"\\[SIKULI-(CAPTURE|DIFF)\\]\")"); static Pattern patPatternStr = Pattern.compile( "\\b(Pattern\\s*\\(\".*?\"\\)(\\.\\w+\\([^)]*\\))*)"); static Pattern patSubregionStr = Pattern.compile( "\\b(Region\\s*\\([\\d\\s,]+\\))"); int parseLine(int startOff, int endOff, Pattern ptn) throws BadLocationException{ //System.out.println(startOff + " " + endOff); if(endOff >= startOff) return endOff; Document doc = getDocument(); while(true){ String line = doc.getText(startOff, endOff-startOff); Matcher m = ptn.matcher(line); //System.out.println("["+line+"]"); if( m.find() ){ int len = m.end() - m.start(); if(replaceWithImage(startOff+m.start(), startOff+m.end())){ startOff += m.start()+1; endOff -= len-1; } else startOff += m.end()+1; } else break; } return endOff; } public File copyFileToBundle(String filename){ File f = new File(filename); String bundlePath = getSrcBundle(); if(f.exists()){ try{ Utils.xcopy(filename, bundlePath); filename = f.getName(); } catch(IOException e){ e.printStackTrace(); return f; } } filename = bundlePath + "/" + filename; f = new File(filename); if(f.exists()) return f; return null; } public File getFileInBundle(String filename){ if(_imgLocator == null) return null; try{ String fullpath = _imgLocator.locate(filename); return new File(fullpath); } catch(IOException e){ return null; } } boolean replaceWithImage(int startOff, int endOff) throws BadLocationException{ Document doc = getDocument(); String imgStr = doc.getText(startOff, endOff - startOff); String filename = imgStr.substring(1,endOff-startOff-1);; boolean useParameters = false; boolean exact = false; int numMatches = -1; float similarity = -1f; Location offset = null; //Debug.log("imgStr: " + imgStr); //Debug.log("filename " + filename); if( imgStr.startsWith("Pattern") ){ useParameters = true; String[] tokens = imgStr.split("\\)\\s*\\.?"); for(String str : tokens){ //System.out.println("token: " + str); if( str.startsWith("exact") ) exact = true; if( str.startsWith("Pattern") ) filename = str.substring( str.indexOf("\"")+1,str.lastIndexOf("\"")); if( str.startsWith("similar") ){ String strArg = str.substring(str.lastIndexOf("(")+1); try{ similarity = Float.valueOf(strArg); } catch(NumberFormatException e){ return false; } } if( str.startsWith("firstN") ){ String strArg = str.substring(str.lastIndexOf("(")+1); numMatches = Integer.valueOf(strArg); } if( str.startsWith("targetOffset") ){ String strArg = str.substring(str.lastIndexOf("(")+1); String[] args = strArg.split(","); try{ offset = new Location(0,0); offset.x = Integer.valueOf(args[0]); offset.y = Integer.valueOf(args[1]); } catch(NumberFormatException e){ return false; } } } } else if( imgStr.startsWith("Region") ){ String[] tokens = imgStr.split("[(),]"); try{ int x = Integer.valueOf(tokens[1]), y = Integer.valueOf(tokens[2]), w = Integer.valueOf(tokens[3]), h = Integer.valueOf(tokens[4]); this.select(startOff, endOff); RegionButton icon = new RegionButton(this, x, y, w, h); this.insertComponent(icon); return true; } catch(NumberFormatException e){ return false; } catch(Exception e){ e.printStackTrace(); return false; } } else if( patHistoryBtnStr.matcher(imgStr).matches() ){ Element root = doc.getDefaultRootElement(); int lineIdx = root.getElementIndex(startOff); Element line = root.getElement(lineIdx); try{ CaptureButton btnCapture = (CaptureButton)_historyBtnClass.newInstance(); if( imgStr.indexOf("DIFF") >= 0 ) btnCapture.setDiffMode(true); btnCapture.setSrcElement(line); btnCapture.setParentPane(this); //System.out.println("new btn: " + btnCapture.getSrcElement()); this.select(startOff, endOff); if( btnCapture.hasNext() ){ int pos = startOff; doc.insertString(pos++, "[", null); this.insertComponent(btnCapture); pos++; while(btnCapture.hasNext()){ CaptureButton btn = btnCapture.getNextDiffButton(); doc.insertString(pos++, ",", null); this.insertComponent(btn); pos++; } doc.insertString(pos, "]", null); } else this.insertComponent(btnCapture); } catch(Exception e){ e.printStackTrace(); } return true; } File f = getFileInBundle(filename); Debug.log(7,"replaceWithImage: " + filename); if( f != null && f.exists() ){ this.select(startOff, endOff); ImageButton icon = new ImageButton(this, f.getAbsolutePath()); if(useParameters){ icon.setParameters(exact, similarity, numMatches); if(offset != null) icon.setTargetOffset(offset); } this.insertComponent(icon); return true; } return false; } void checkCompletion(java.awt.event.KeyEvent ke) throws BadLocationException{ Document doc = getDocument(); Element root = doc.getDefaultRootElement(); int pos = getCaretPosition(); int lineIdx = root.getElementIndex(pos); Element line = root.getElement(lineIdx); int start = line.getStartOffset(), len = line.getEndOffset() - start; String strLine = doc.getText(start, len-1); Debug.log(9,"["+strLine+"]"); if( strLine.endsWith("find") && ke.getKeyChar()=='(' ){ ke.consume(); doc.insertString( pos, "(", null); CaptureButton btnCapture = new CaptureButton(this, line); insertComponent(btnCapture); doc.insertString( pos+2, ")", null); } } void insertString(String str){ int sel_start = getSelectionStart(); int sel_end = getSelectionEnd(); if(sel_end != sel_start){ try{ getDocument().remove(sel_start, sel_end-sel_start); } catch(BadLocationException e){ e.printStackTrace(); } } int pos = getCaretPosition(); insertString(pos, str); int new_pos = getCaretPosition(); int end = parseRange(pos, new_pos); setCaretPosition(end); } void insertString(int pos, String str){ Document doc = getDocument(); try{ doc.insertString( pos, str, null ); } catch(Exception e){ e.printStackTrace(); } } void appendString(String str){ Document doc = getDocument(); try{ int start = doc.getLength(); doc.insertString( doc.getLength(), str, null ); int end = doc.getLength(); end = parseLine(start, end, patHistoryBtnStr); } catch(Exception e){ e.printStackTrace(); } } // search forward /* public int search(Pattern pattern){ return search(pattern, true); } public int search(Pattern pattern, boolean forward){ if(!pattern.equals(_lastSearchPattern)){ _lastSearchPattern = pattern; Document doc = getDocument(); int pos = getCaretPosition(); Debug.log("caret: " + pos); try{ String body = doc.getText(pos, doc.getLength()-pos); _lastSearchMatcher = pattern.matcher(body); } catch(BadLocationException e){ e.printStackTrace(); } } return continueSearch(forward); } */ /* public int search(String str){ return search(str, true); } */ public int search(String str, int pos, boolean forward){ int ret = -1; Document doc = getDocument(); Debug.log(9, "search caret: " + pos + ", " + doc.getLength()); try{ String body; int begin; if(forward){ int len = doc.getLength()-pos; body = doc.getText(pos, len>0?len:0); begin = pos; } else{ body = doc.getText(0, pos); begin = 0; } Pattern pattern = Pattern.compile(str); Matcher matcher = pattern.matcher(body); ret = continueSearch(matcher, begin, forward); if(ret < 0){ if(forward && pos != 0) // search from beginning return search(str, 0, forward); if(!forward && pos != doc.getLength()) // search from end return search(str, doc.getLength(), forward); } } catch(BadLocationException e){ Debug.log(7, "search caret: " + pos + ", " + doc.getLength() + e.getStackTrace()); } return ret; } protected int continueSearch(Matcher matcher, int pos, boolean forward){ boolean hasNext = false; int start=0, end=0; if(!forward){ while(matcher.find()){ hasNext = true; start = matcher.start(); end = matcher.end(); } } else{ hasNext = matcher.find(); if(!hasNext) return -1; start = matcher.start(); end = matcher.end(); } if(hasNext){ Document doc = getDocument(); getCaret().setDot(pos+end); getCaret().moveDot(pos+start); getCaret().setSelectionVisible(true); return pos+start; } return -1; } private class DirtyHandler implements DocumentListener { public void changedUpdate(DocumentEvent ev) { Debug.log(9, "change update"); //setDirty(true); } public void insertUpdate(DocumentEvent ev) { Debug.log(9, "insert update"); setDirty(true); } public void removeUpdate(DocumentEvent ev) { Debug.log(9, "remove update"); setDirty(true); } } } class MyTransferHandler extends TransferHandler{ public MyTransferHandler(){ } public void exportToClipboard(JComponent comp, Clipboard clip, int action) { super.exportToClipboard(comp, clip, action); } public int getSourceActions(JComponent c) { return COPY_OR_MOVE; } protected Transferable createTransferable(JComponent c){ JTextPane aTextPane = (JTextPane)c; SikuliEditorKit kit = ((SikuliEditorKit)aTextPane.getEditorKit()); Document doc = aTextPane.getDocument(); int sel_start = aTextPane.getSelectionStart(); int sel_end = aTextPane.getSelectionEnd(); StringWriter writer = new StringWriter(); try{ kit.write(writer, doc, sel_start, sel_end - sel_start ); return new StringSelection(writer.toString()); } catch(Exception e){ e.printStackTrace(); } return null; } public boolean canImport(JComponent comp, DataFlavor[] transferFlavors){ for(int i=0; i<transferFlavors.length; i++){ //System.out.println(transferFlavors[i]); if(transferFlavors[i].equals(DataFlavor.stringFlavor)) return true; } return false; } public boolean importData(JComponent comp, Transferable t){ DataFlavor htmlFlavor = DataFlavor.stringFlavor; if(canImport(comp, t.getTransferDataFlavors())){ try{ String transferString = (String)t.getTransferData(htmlFlavor); SikuliPane targetTextPane = (SikuliPane)comp; targetTextPane.insertString(transferString); }catch (Exception e){ Debug.error("Can't transfer: " + t.toString()); } return true; } return false; } }
package com.example.helloworld; import com.appnexus.opensdk.BannerAdView; import com.appnexus.opensdk.InterstitialAdView; import com.appnexus.opensdk.AdListener; import com.google.ads.AdRequest; import com.google.ads.AdSize; import com.google.ads.AdView; import android.os.Bundle; import android.app.Activity; import android.gesture.GestureOverlayView; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.FrameLayout; import android.widget.RelativeLayout; public class MainActivity extends Activity implements AdListener{ private BannerAdView av; InterstitialAdView iav; RelativeLayout layout; private int interstitials; Button showButton; private AdView adview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Interstitial showButton = (Button) findViewById(R.id.showbutton); showButton.setClickable(false); showButton.setEnabled(false); iav = new InterstitialAdView(this); iav.setPlacementID("656561"); iav.setAdListener(this); } @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, menu); return true; } public boolean loadAd(MenuItem mi){ av.loadAd(); return true; } public void loadIA(View view){ iav.loadAd(); } public void showIA(View view){ interstitials=iav.show(); if(interstitials<1){ showButton.setClickable(false); showButton.setEnabled(false); } } @Override public void onAdLoaded(InterstitialAdView iAdView) { interstitials++; if(interstitials>0){ showButton.setClickable(true); showButton.setEnabled(true); } } @Override public void onAdRequestFailed(InterstitialAdView iAdView) { Log.e("HelloWorld", "Ad request failed"); } }
package se.sics.contiki.collect.gui; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.util.ArrayList; import java.util.Hashtable; import java.util.Properties; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JSlider; import javax.swing.Timer; import javax.swing.border.LineBorder; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.basic.BasicGraphicsUtils; import se.sics.contiki.collect.CollectServer; import se.sics.contiki.collect.Configurable; import se.sics.contiki.collect.Link; import se.sics.contiki.collect.Node; import se.sics.contiki.collect.SensorData; import se.sics.contiki.collect.Visualizer; public class MapPanel extends JPanel implements Configurable, Visualizer, ActionListener, MouseListener, MouseMotionListener { private static final long serialVersionUID = -8256619482599309425L; private static final Logger log = Logger.getLogger(MapPanel.class.getName()); private static final boolean VISUAL_DRAG = true; private static final Color LINK_COLOR = new Color(0x40, 0x40, 0xf0, 0xff); private static final int delta = 7; private final CollectServer server; private final String category; private final boolean isMap; private String title; private Timer timer; private JPopupMenu popupMenu; private JCheckBoxMenuItem layoutItem; private JCheckBoxMenuItem lockedItem; private JMenuItem shakeItem; // private JCheckBoxMenuItem dragItem; private JCheckBoxMenuItem backgroundItem; private JCheckBoxMenuItem showNetworkItem; private JCheckBoxMenuItem configItem; private JMenuItem resetNetworkItem; private MapNode popupNode; private Hashtable<String,MapNode> nodeTable = new Hashtable<String,MapNode>(); private MapNode[] nodeList = new MapNode[0]; private boolean updateNodeList; private MapNode selectedNode; private ArrayList<MapNode> selectedMapNodes = new ArrayList<MapNode>(); private Node[] selectedNodes; private MapNode draggedNode; private long draggedTime; private ImageIcon mapImage; private String mapName; private boolean showBackground; private int layoutRepel = 100; private int layoutAttract = 50; private int layoutGravity = 1; private boolean isLayoutActive = true; private boolean hideNetwork = false; protected JPanel configPanel; public MapPanel(CollectServer server, String title, String category, boolean isMap) { super(null); this.server = server; this.title = title; this.category = category; this.isMap = isMap; setPreferredSize(new Dimension(300, 200)); popupMenu = new JPopupMenu(getTitle()); if (!isMap) { layoutItem = createCheckBoxMenuItem(popupMenu, "Update Layout", isLayoutActive); popupMenu.add(layoutItem); lockedItem = createCheckBoxMenuItem(popupMenu, "Fixed Node Position", false); shakeItem = createMenuItem(popupMenu, "Shake Nodes"); popupMenu.addSeparator(); } showNetworkItem = createCheckBoxMenuItem(popupMenu, "Show Network Info", true); resetNetworkItem = createMenuItem(popupMenu, "Reset Network"); popupMenu.addSeparator(); if (isMap) { backgroundItem = createCheckBoxMenuItem(popupMenu, "Show Background", false); backgroundItem.setEnabled(false); } else { configItem = createCheckBoxMenuItem(popupMenu, "Show Layout Settings", false); } // popupMenu.addSeparator(); // dragItem = new JCheckBoxMenuItem("Visible Drag", true); // popupMenu.add(dragItem); setBackground(Color.white); addMouseListener(this); addMouseMotionListener(this); if (!isMap) { timer = new Timer(100, this); configPanel = new JPanel(new GridLayout(0, 1)); configPanel.setBorder(LineBorder.createBlackLineBorder()); JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 1000, 1000 - layoutAttract); slider.setBorder(new TitledBorder("Attract Factor: " + (1000 - layoutAttract))); slider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { JSlider slider = (JSlider)e.getSource(); layoutAttract = 1000 - slider.getValue(); ((TitledBorder)slider.getBorder()).setTitle("Attract Factor: " + slider.getValue()); } }); configPanel.add(slider); slider = new JSlider(JSlider.HORIZONTAL, 0, 1000, layoutRepel); slider.setBorder(new TitledBorder("Repel Range: " + layoutRepel)); slider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { JSlider slider = (JSlider)e.getSource(); layoutRepel = slider.getValue(); ((TitledBorder)slider.getBorder()).setTitle("Repel Range: " + layoutRepel); } }); configPanel.add(slider); slider = new JSlider(JSlider.HORIZONTAL, 0, 100, layoutGravity); slider.setBorder(new TitledBorder("Gravity: " + layoutGravity)); slider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { JSlider slider = (JSlider)e.getSource(); layoutGravity = slider.getValue(); ((TitledBorder)slider.getBorder()).setTitle("Gravity: " + layoutGravity); } }); configPanel.add(slider); add(configPanel); configPanel.setVisible(false); addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent ev) { if (configPanel.isVisible()) { updateConfigLayout(); } } }); } } public String getMapBackground() { return isMap ? mapName : null; } public boolean setMapBackground(String image) { if (!isMap) { return false; } if (image == null) { mapImage = null; mapName = null; backgroundItem.setEnabled(false); backgroundItem.setSelected(false); showBackground = false; repaint(); return true; } ImageIcon ii = new ImageIcon(image); if (ii.getIconWidth() <= 0 || ii.getIconHeight() <= 0) { log.warning("could not find image '" + image + '\''); return false; } mapImage = ii; mapName = image; setPreferredSize(new Dimension(ii.getIconWidth(), ii.getIconHeight())); showBackground = true; backgroundItem.setEnabled(true); backgroundItem.setSelected(true); repaint(); return true; } private JCheckBoxMenuItem createCheckBoxMenuItem(JPopupMenu menu, String title, boolean isSelected) { JCheckBoxMenuItem item = new JCheckBoxMenuItem(title, isSelected); item.addActionListener(this); menu.add(item); return item; } private JMenuItem createMenuItem(JPopupMenu menu, String title) { JMenuItem item = new JMenuItem(title); item.addActionListener(this); menu.add(item); return item; } public void setVisible(boolean visible) { if (visible) { clear(); if (timer != null) { timer.start(); } } else { if (timer != null) { timer.stop(); } } super.setVisible(visible); } public void clear() { setCursor(Cursor.getDefaultCursor()); draggedNode = null; updateSelected(); } // Node handling public Node getNode(String id) { MapNode node = nodeTable.get(id); return node != null ? node.node : null; } public MapNode getMapNode(String id) { return nodeTable.get(id); } private MapNode addMapNode(Node nd) { String id = nd.getID(); MapNode node = nodeTable.get(id); if (node == null) { node = new MapNode(this, nd); node.y = 10 + (int) (Math.random() * (Math.max(100, getHeight()) - 20)); node.x = 10 + (int) (Math.random() * (Math.max(100, getWidth()) - 30)); String location = server.getConfig(isMap ? id : ("collect.map." + id)); if (location != null) { try { String[] pos = location.split(","); node.x = Integer.parseInt(pos[0].trim()); node.y = Integer.parseInt(pos[1].trim()); node.hasFixedLocation = !isMap; } catch (Exception e) { System.err.println("could not parse node location: " + location); e.printStackTrace(); } } nodeTable.put(id, node); updateNodeList = true; } return node; } private MapNode[] getNodeList() { if (updateNodeList) { synchronized (nodeTable) { updateNodeList = false; nodeList = nodeTable.values().toArray(new MapNode[nodeTable.size()]); } } return nodeList; } // Visualizer @Override public String getCategory() { return category; } @Override public String getTitle() { return title; } @Override public Component getPanel() { return this; } @Override public void nodesSelected(Node[] nodes) { if (selectedNodes != nodes) { selectedNodes = nodes; if (isVisible()) { updateSelected(); } } } private void updateSelected() { if (selectedMapNodes.size() > 0) { for(MapNode node : selectedMapNodes) { node.isSelected = false; } selectedMapNodes.clear(); } if (selectedNodes == null || selectedNodes.length == 0) { selectedNode = null; } else { for (Node node : selectedNodes) { MapNode mapNode = addMapNode(node); selectedMapNodes.add(mapNode); mapNode.isSelected = true; } selectedNode = selectedMapNodes.get(0); } repaint(); } @Override public void nodeAdded(Node nd) { addMapNode(nd); if (isVisible()) { repaint(); } } @Override public void nodeDataReceived(SensorData sensorData) { if (isVisible()) { repaint(); } } @Override public void clearNodeData() { nodeTable.clear(); updateNodeList = true; nodesSelected(null); if (isVisible()) { repaint(); } } // Graphics @Override protected void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; FontMetrics fm = g.getFontMetrics(); int fnHeight = fm.getHeight(); int fnDescent = fm.getDescent(); int width = getWidth(); int height = getHeight(); g.setColor(getBackground()); g.fillRect(0, 0, width, height); if (showBackground && isMap) { mapImage.paintIcon(this, g, 0, 0); } g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // Display legend if (!hideNetwork) { int legendWidth = fm.stringWidth("ETX"); g.setColor(Color.black); g.drawString("ETX", width - legendWidth - 10, 10 + fnHeight - fnDescent); g.drawRect(width - legendWidth - 30, 8, legendWidth + 24, fnHeight + 4); g.setColor(LINK_COLOR); g2d.drawLine(width - legendWidth - 25, 10 + fnHeight / 2, width - legendWidth - 15, 10 + fnHeight / 2); } for (MapNode n : getNodeList()) { if (!isMap || !hideNetwork) { g.setColor(LINK_COLOR); for (int j = 0, mu = n.node.getLinkCount(); j < mu; j++) { Link link = n.node.getLink(j); MapNode linkNode = addMapNode(link.node); int x2 = linkNode.x; int y2 = linkNode.y; g2d.drawLine(n.x, n.y, x2, y2); if (!hideNetwork) { int xn1, xn2, yn1, yn2; if (n.x <= x2) { xn1 = n.x; xn2 = x2; yn1 = n.y; yn2 = y2; } else { xn1 = x2; xn2 = n.x; yn1 = y2; yn2 = n.y; } int dx = xn1 + (xn2 - xn1) / 2 + 4; int dy = yn1 + (yn2 - yn1) / 2 - fnDescent; if (yn2 < yn1) { dy += fnHeight - fnDescent; } g.drawString( Double.toString(((int) (link.getETX() * 100 + 0.5)) / 100.0), dx, dy); } } } n.paint(g, n.x, n.y); g.setColor(Color.black); if (n.isSelected) { BasicGraphicsUtils.drawDashedRect(g, n.x - delta, n.y - delta, 2 * delta, 2 * delta); } if (selectedNode != null && selectedNode.message != null) { g.drawString(selectedNode.message, 10, 10); } } } // ActionListener public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (!isMap && source == timer) { if (isLayoutActive) { updateNodeLayout(); repaint(); } } else if (!isMap && source == lockedItem) { if (popupNode != null) { popupNode.hasFixedLocation = lockedItem.isSelected(); } } else if (!isMap && source == layoutItem) { isLayoutActive = layoutItem.isSelected(); } else if (!isMap && source == shakeItem) { for(MapNode n : getNodeList()) { if (!n.hasFixedLocation) { n.x += Math.random() * 100 - 50; n.y += Math.random() * 100 - 50; } } } else if (!isMap && source == configItem) { if (configItem.isSelected()) { configPanel.setSize(getPreferredSize()); configPanel.validate(); updateConfigLayout(); configPanel.setVisible(true); } else { configPanel.setVisible(false); } repaint(); } else if (source == showNetworkItem) { hideNetwork = !showNetworkItem.isSelected(); repaint(); } else if (source == resetNetworkItem) { for(MapNode n : getNodeList()) { n.node.clearLinks(); } repaint(); } else if (isMap && source == backgroundItem) { showBackground = mapImage != null && backgroundItem.isSelected(); repaint(); } } private void updateNodeLayout() { MapNode[] nodes = getNodeList(); for (MapNode n : nodes) { // Attract connected nodes for(int i = 0, jn = n.node.getLinkCount(); i < jn; i++) { Link link = n.node.getLink(i); MapNode n2 = addMapNode(link.node); double vx = n2.x - n.x; double vy = n2.y - n.y; double dist = Math.sqrt(vx * vx + vy * vy); dist = dist == 0 ? 0.00001 : dist; double etx = link.getETX(); if (etx > 5) etx = 5; double factor = (etx * layoutAttract - dist) / (dist * 3); double dx = factor * vx; double dy = factor * vy; n2.dx += dx; n2.dy += dy; n.dx -= dx; n.dy -= dy; } // Repel nodes that are too close double dx = 0, dy = 0; for (MapNode n2 : nodes) { if (n == n2) { continue; } double vx = n.x - n2.x; double vy = n.y - n2.y; double dist = vx * vx + vy * vy; if (dist == 0) { dx += Math.random() * 5; dy += Math.random() * 5; } else if (dist < layoutRepel * layoutRepel) { dx += vx / dist; dy += vy / dist; } } double dist = dx * dx + dy * dy; if (dist > 0) { dist = Math.sqrt(dist) / 2; n.dx += dx / dist; n.dy += dy / dist; } n.dy += layoutGravity; } // Update the node positions int width = getWidth(); int height = getHeight(); for(MapNode n : nodes) { if (!n.hasFixedLocation && n != draggedNode) { n.x += Math.max(-5, Math.min(5, n.dx)); n.y += Math.max(-5, Math.min(5, n.dy)); if (n.x < 0) { n.x = 0; } else if (n.x > width) { n.x = width; } if (n.y < 0) { n.y = 0; } else if (n.y > height) { n.y = height; } } n.dx /= 2; n.dy /= 2; } } private void updateConfigLayout() { configPanel.setLocation(getWidth() - configPanel.getWidth() - 10, getHeight() - configPanel.getHeight() - 10); } // Mouselistener private MapNode getNodeAt(int mx, int my) { for(MapNode n : getNodeList()) { if (mx >= (n.x - delta) && mx <= (n.x + delta) && my >= (n.y - delta) && my <= (n.y + delta)) { return n; } } return null; } public void mouseClicked(MouseEvent e) { int mx = e.getX(); int my = e.getY(); if (e.getButton() == MouseEvent.BUTTON1) { MapNode node = getNodeAt(mx, my); if (node != selectedNode) { server.selectNodes(node == null ? null : new Node[] { node.node }); } } showPopup(e); } public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { MapNode aNode = getNodeAt(e.getX(), e.getY()); if (aNode != selectedNode) { server.selectNodes(aNode != null ? new Node[] { aNode.node } : null); } draggedNode = aNode; draggedTime = System.currentTimeMillis(); } else if (selectedNode != null) { if (draggedTime < 0) { setCursor(Cursor.getDefaultCursor()); draggedTime = 0; } selectedNode = draggedNode = null; server.selectNodes(null); } showPopup(e); } public void mouseReleased(MouseEvent e) { if (draggedNode != null && e.getButton() == MouseEvent.BUTTON1) { if ((draggedTime > 0) && (System.currentTimeMillis() - draggedTime) < 300) { // Do not drag if mouse is only moved during click } else { draggedNode.x = e.getX(); draggedNode.y = e.getY(); setCursor(Cursor.getDefaultCursor()); draggedTime = 0; draggedNode = null; repaint(); } } showPopup(e); } private void showPopup(MouseEvent e) { if (e.isPopupTrigger() && (e.getModifiers() & (MouseEvent.SHIFT_MASK|MouseEvent.CTRL_MASK)) == 0) { popupNode = getNodeAt(e.getX(), e.getY()); if (!isMap) { lockedItem.setEnabled(popupNode != null); lockedItem.setSelected(popupNode != null ? popupNode.hasFixedLocation : false); } popupMenu.show(this, e.getX(), e.getY()); } } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } // MouseMotion public void mouseDragged(MouseEvent e) { if (draggedNode == null) { // Do nothing } else if (draggedTime > 0) { if ((System.currentTimeMillis() - draggedTime) > 300) { // No mouse click, time to drag the node draggedTime = -1; setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); } } else if (VISUAL_DRAG /* && dragItem.isSelected() */) { draggedNode.x = e.getX(); draggedNode.y = e.getY(); repaint(); } } public void mouseMoved(MouseEvent e) { } // MapNode private static class MapNode { public final Node node; public int x; public int y; public double dx; public double dy; public boolean hasFixedLocation; public boolean isSelected; public String message; MapNode(MapPanel panel, Node node) { this.node = node; } public void paint(Graphics g, int x, int y) { final int od = 3; g.setColor(Color.black); g.drawString(node.getID(), x + od * 2 + 3, y + 4); if (hasFixedLocation) { g.setColor(Color.red); } g.fillOval(x - od, y - od, od * 2 + 1, od * 2 + 1); } } // end of inner class MapNode @Override public void updateConfig(Properties config) { if (isMap) { for (MapNode n : getNodeList()) { config.put(n.node.getID(), "" + n.x + ',' + n.y); } } else { for (MapNode n : getNodeList()) { if (n.hasFixedLocation) { config.put("collect.map." + n.node.getID(), "" + n.x + ',' + n.y); } } } } }
package team046; import battlecode.common.*; public class RobotPlayer { private static RobotController rc; private static int round; private static double power; private static int hoardNukeResearchMin = 29; private static int zergRushChannel = randomWithRange(0, GameConstants.BROADCAST_MAX_CHANNELS); private static int zergRushCode = randomWithRange(2, GameConstants.BROADCAST_MAX_CHANNELS); private static int EncampmentBuilderChannel = randomWithRange(0, GameConstants.BROADCAST_MAX_CHANNELS); private static int EncampmentSearchStartedChannel = randomWithRange(0, GameConstants.BROADCAST_MAX_CHANNELS); private static int SupplierBuilt = randomWithRange(0, GameConstants.BROADCAST_MAX_CHANNELS); private static int researchNukeChannel = randomWithRange(0, GameConstants.BROADCAST_MAX_CHANNELS); public static void run(RobotController MyJohn12LongRC) { rc = MyJohn12LongRC; while (true) { try { round = Clock.getRoundNum(); power = rc.getTeamPower(); if (rc.getType() == RobotType.HQ) { HQ(); } else if (rc.getType() == RobotType.SOLDIER) { Soldier(); } else if (rc.getType() == RobotType.ARTILLERY) { Artillery(); } /*else if (rc.getType() == RobotType.SUPPLIER) { Supplier(); } else if (rc.getType() == RobotType.GENERATOR) { Generator(); }*/ rc.yield(); } catch (Exception e) { e.printStackTrace(); break; } } } private static void HQ() throws GameActionException { if (rc.isActive()) { if (rc.senseEnemyNukeHalfDone()) { if (rc.checkResearchProgress(Upgrade.NUKE) < 175 && power > GameConstants.BROADCAST_READ_COST + GameConstants.BROADCAST_SEND_COST * 2 && rc.readBroadcast(zergRushChannel) != zergRushCode) { rc.broadcast(zergRushChannel, zergRushCode); rc.broadcast(researchNukeChannel, round); } } else if (round > 50 && !rc.hasUpgrade(Upgrade.PICKAXE)) { rc.researchUpgrade(Upgrade.PICKAXE); return; } else if (round > 200 && !rc.hasUpgrade(Upgrade.FUSION)) { rc.researchUpgrade(Upgrade.FUSION); return; } else if (round > 250 && !rc.hasUpgrade(Upgrade.VISION)) { rc.researchUpgrade(Upgrade.VISION); return; } // Check the HQ's own surroundings else if (rc.senseNearbyGameObjects(Robot.class, 33, rc.getTeam()).length > hoardNukeResearchMin) { rc.researchUpgrade(Upgrade.NUKE); return; } // Last check for a nuke research cue if (power > GameConstants.BROADCAST_READ_COST) { int researchNuke = rc.readBroadcast(researchNukeChannel); power -= GameConstants.BROADCAST_READ_COST; if (researchNuke != 0 && round - researchNuke < 11) { rc.researchUpgrade(Upgrade.NUKE); return; } else if (power > GameConstants.BROADCAST_SEND_COST && researchNuke != 0) { rc.broadcast(researchNukeChannel, 0); power -= GameConstants.BROADCAST_SEND_COST; } } // Find an available spawn direction MapLocation hqLocation = rc.senseHQLocation(); MapLocation nextLoc; for (Direction dir : Direction.values()) { if (dir != Direction.NONE && dir != Direction.OMNI && rc.canMove(dir)) { nextLoc = hqLocation.add(dir); Team mine = rc.senseMine(nextLoc); if (mine == null || mine == rc.getTeam()) { // Calls for nuke research for the next few rounds. if (power > GameConstants.BROADCAST_SEND_COST) { rc.broadcast(researchNukeChannel, round); } rc.spawn(dir); break; } } } } } private static void Soldier() throws GameActionException { if (rc.isActive()) { int EncampmentBuilderRobotID; int EncampmentSearchStartedRound; MapLocation rLoc = rc.getLocation(); MapLocation targetLoc = null; // Get the Encampment builder robot ID (or zero) if (power > GameConstants.BROADCAST_READ_COST * 2) { EncampmentBuilderRobotID = rc.readBroadcast(EncampmentBuilderChannel); EncampmentSearchStartedRound = rc.readBroadcast(EncampmentSearchStartedChannel); power -= GameConstants.BROADCAST_READ_COST * 2; } else { EncampmentBuilderRobotID = -1; EncampmentSearchStartedRound = 0; } if (power > GameConstants.BROADCAST_SEND_COST * 2 && (EncampmentBuilderRobotID == 0 || EncampmentSearchStartedRound + GameConstants.CAPTURE_ROUND_DELAY < round)) { rc.broadcast(EncampmentBuilderChannel, rc.getRobot().getID()); rc.broadcast(EncampmentSearchStartedChannel, round); power -= GameConstants.BROADCAST_SEND_COST * 2; EncampmentBuilderRobotID = rc.getRobot().getID(); } // Check for zerg command if (power > GameConstants.BROADCAST_READ_COST && rc.readBroadcast(zergRushChannel) == zergRushCode) { targetLoc = rc.senseEnemyHQLocation(); power -= GameConstants.BROADCAST_READ_COST; } // Handle Encampment builder robot (including movement) else if (EncampmentBuilderRobotID == rc.getRobot().getID()) { BuildEncampment(rLoc); return; } else { RobotInfo roboData; Robot[] assholes = rc.senseNearbyGameObjects(Robot.class, 3, rc.getTeam().opponent()); Robot[] baddies = rc.senseNearbyGameObjects(Robot.class, 33, rc.getTeam().opponent()); Robot[] mypals = rc.senseNearbyGameObjects(Robot.class, 33, rc.getTeam()); if (assholes.length > 0) { // ATTACK! if (assholes.length == 1) { roboData = rc.senseRobotInfo(assholes[0]); targetLoc = roboData.location; } // Ahhhhh!!~!~ else { return; } } // If we have greater numbers, be more aggressive else if (baddies.length > 0 && mypals.length > baddies.length) { roboData = rc.senseRobotInfo(baddies[0]); targetLoc = roboData.location; } // If we are outnumbered, stop circling around like dumbasses else if (mypals.length > 0 && mypals.length <= baddies.length) { roboData = rc.senseRobotInfo(mypals[0]); targetLoc = roboData.location; } // Check for and plant mines else if (baddies.length == 0 && rc.senseMine(rLoc) == null) { rc.layMine(); return; } } // Set rally point if (targetLoc == null) { MapLocation goodHQ = rc.senseHQLocation(); if (goodHQ.x <= 2 || goodHQ.x >= rc.getMapWidth() - 2) { MapLocation rudeHQ = rc.senseEnemyHQLocation(); Direction dir = goodHQ.directionTo(rudeHQ); int xm = 1, ym = 1; switch (dir) { case NORTH: xm = 0; ym = -3; break; case NORTH_EAST: xm = 3; ym = -3; break; case EAST: xm = 3; ym = 0; break; case SOUTH_EAST: xm = 3; ym = 3; break; case SOUTH: xm = 0; ym = 3; break; case SOUTH_WEST: xm = -3; ym = 3; break; case WEST: xm = -3; ym = 0; break; case NORTH_WEST: xm = -3; ym = -3; break; } targetLoc = new MapLocation(goodHQ.x + xm, goodHQ.y + ym); } else { MapLocation rallyPoints[] = { new MapLocation(goodHQ.x + randomWithRange(1,3), goodHQ.y + randomWithRange(1,3)), new MapLocation(goodHQ.x - randomWithRange(1,3), goodHQ.y - randomWithRange(1,3)) }; targetLoc = rallyPoints[randomWithRange(0, rallyPoints.length - 1)]; } } // If already on targetLoc, sense buddies and send nuke research signal if (power > GameConstants.BROADCAST_READ_COST + GameConstants.BROADCAST_SEND_COST) { int currentStatus = rc.readBroadcast(researchNukeChannel); if (rLoc.equals(targetLoc)) { Robot[] myFriends = rc.senseNearbyGameObjects(Robot.class, 33, rc.getTeam()); if (myFriends.length > hoardNukeResearchMin && currentStatus == 0) { rc.broadcast(researchNukeChannel, round); } else if (myFriends.length < hoardNukeResearchMin && currentStatus == 1) { rc.broadcast(researchNukeChannel, 0); } return; } } MoveRobot(rLoc, targetLoc); } } private static void Artillery() throws GameActionException { if (rc.isActive()) { MapLocation target = null; Robot[] baddies = rc.senseNearbyGameObjects(Robot.class, 33, rc.getTeam().opponent()); if (baddies.length > 0) { RobotInfo baddieInfo = rc.senseRobotInfo(baddies[0]); target = baddieInfo.location; } if (target != null && rc.canAttackSquare(target)) { rc.attackSquare(target); } } } private static void MoveRobot(MapLocation rLoc, MapLocation targetLoc) throws GameActionException { Direction dir = rLoc.directionTo(targetLoc); if (dir == Direction.NONE) { return; } else if (dir == Direction.OMNI) { dir = Direction.EAST; } // If the bot can't move in the default direction, test all other directions if (!rc.canMove(dir)) { int shortest = 1000, testDist; Direction bestDir = dir; MapLocation testLoc; for (Direction testDir : Direction.values()) { if (testDir != dir && testDir != Direction.NONE && testDir != Direction.OMNI && rc.canMove(testDir)) { testLoc = rLoc.add(testDir); testDist = testLoc.distanceSquaredTo(targetLoc); if (testDist < shortest) { shortest = testDist; bestDir = testDir; } } } // If the direction hasn't changed, there is just no where to go. if (bestDir == dir) { return; } dir = bestDir; } MapLocation nextLoc = rLoc.add(dir); Team mine = rc.senseMine(nextLoc); if (mine == Team.NEUTRAL || mine == rc.getTeam().opponent()) { rc.defuseMine(nextLoc); } else { rc.move(dir); } } private static void BuildEncampment(MapLocation rLoc) throws GameActionException { if (power > rc.senseCaptureCost()) { if (rc.senseEncampmentSquare(rLoc)) { // Check how close the encampment is to HQ, if close build an artillery MapLocation goodHQ = rc.senseHQLocation(); if (goodHQ.distanceSquaredTo(rLoc) < 60) { rc.captureEncampment(RobotType.ARTILLERY); } // Otherwise, check status of supplier build and do another one or generator else if (power > GameConstants.BROADCAST_READ_COST + GameConstants.BROADCAST_SEND_COST) { if (rc.readBroadcast(SupplierBuilt) == 0) { rc.captureEncampment(RobotType.SUPPLIER); rc.broadcast(SupplierBuilt, 1); power -= GameConstants.BROADCAST_READ_COST + GameConstants.BROADCAST_SEND_COST; } else { rc.captureEncampment(RobotType.GENERATOR); rc.broadcast(SupplierBuilt, 0); power -= GameConstants.BROADCAST_SEND_COST; } } } else { MapLocation encampmentSquares[] = rc.senseAllEncampmentSquares(); MapLocation goodEncampments[] = rc.senseAlliedEncampmentSquares(); MapLocation targetLoc = encampmentSquares[0]; int closest = 1000; checkLocations: for (MapLocation loc : encampmentSquares) { int dist = rLoc.distanceSquaredTo(loc); if (dist < closest) { for (MapLocation goodLoc : goodEncampments) { if (goodLoc.equals(loc)) { continue checkLocations; } } targetLoc = loc; closest = dist; } } MoveRobot(rLoc, targetLoc); } } } private static int randomWithRange(int min, int max) { int range = Math.abs(max - min) + 1; return (int)(Math.random() * range) + (min <= max ? min : max); } }
package solver.variables.view; import choco.kernel.common.util.iterators.DisposableRangeIterator; import choco.kernel.common.util.iterators.DisposableValueIterator; import choco.kernel.common.util.procedure.IntProcedure; import solver.Cause; import solver.ICause; import solver.Solver; import solver.exception.ContradictionException; import solver.explanations.Explanation; import solver.explanations.VariableState; import solver.variables.AbstractVariable; import solver.variables.EventType; import solver.variables.IntVar; import solver.variables.Variable; import solver.variables.delta.monitor.IntDeltaMonitor; import solver.variables.delta.view.ViewDelta; /** * declare an IntVar based on X, such |X| * <p/> * <p/> * "Views and Iterators for Generic Constraint Implementations" <br/> * C. Shulte and G. Tack.<br/> * Eleventh International Conference on Principles and Practice of Constraint Programming * * @author Charles Prud'homme * @since 09/08/11 */ public final class AbsView extends View<IntVar> { protected DisposableValueIterator _viterator; protected DisposableRangeIterator _riterator; public AbsView(final IntVar var, Solver solver) { super("|" + var.getName() + "|", var, solver); } @Override public void analyseAndAdapt(int mask) { super.analyseAndAdapt(mask); if (!reactOnRemoval && ((modificationEvents & EventType.REMOVE.mask) != 0)) { var.analyseAndAdapt(mask); delta = new ViewDelta(new IntDeltaMonitor(var.getDelta()) { @Override public void forEach(IntProcedure proc, EventType eventType) throws ContradictionException { if (EventType.isRemove(eventType.mask)) { for (int i = frozenFirst; i < frozenLast; i++) { proc.execute(Math.abs(delta.get(i))); } } } }); reactOnRemoval = true; } } @Override public boolean instantiated() { if (var.instantiated()) { return true; } else { if (var.getDomainSize() == 2 && Math.abs(var.getLB()) == var.getUB()) { return true; } } return false; } @Override public boolean removeValue(int value, ICause cause) throws ContradictionException { records.forEach(beforeModification.set(this, EventType.REMOVE, cause)); if (value < 0) { return false; } int inf = getLB(); int sup = getUB(); EventType evt = EventType.REMOVE; if (value == inf) { evt = EventType.INCLOW; } else if (value == sup) { evt = EventType.DECUPP; } boolean done = var.removeValue(-value, this); done |= var.removeValue(value, this); if (instantiated()) { evt = EventType.INSTANTIATE; if (cause.reactOnPromotion()) { cause = Cause.Null; } } if (done) { notifyMonitors(evt, cause); } return done; } @Override public boolean removeInterval(int from, int to, ICause cause) throws ContradictionException { if (from <= getLB()) { return updateLowerBound(to + 1, cause); } else if (getUB() <= to) { return updateUpperBound(from - 1, cause); } else { boolean done = var.removeInterval(-to, -from, this); done |= var.removeInterval(from, to, this); if (done) { notifyMonitors(EventType.REMOVE, cause); } return done; } } @Override public boolean instantiateTo(int value, ICause cause) throws ContradictionException { records.forEach(beforeModification.set(this, EventType.INSTANTIATE, cause)); if (value < 0) { //TODO: explication? this.contradiction(this, EventType.INSTANTIATE, AbstractVariable.MSG_UNKNOWN); } int v = Math.abs(value); boolean done = var.updateLowerBound(-v, this); done |= var.updateUpperBound(v, this); EventType evt = EventType.DECUPP; if (var.hasEnumeratedDomain()) { done |= var.removeInterval(-v + 1, v - 1, this); evt = EventType.INSTANTIATE; if (cause.reactOnPromotion()) { cause = Cause.Null; } } if (done) { notifyMonitors(evt, cause); } return done; } @Override public boolean updateLowerBound(int value, ICause cause) throws ContradictionException { records.forEach(beforeModification.set(this, EventType.INCLOW, cause)); if (value <= 0) { return false; } boolean done = var.removeInterval(-value + 1, value - 1, this); if (done) { EventType evt = EventType.INCLOW; if (instantiated()) { evt = EventType.INSTANTIATE; if (cause.reactOnPromotion()) { cause = Cause.Null; } } notifyMonitors(evt, cause); } return done; } @Override public boolean updateUpperBound(int value, ICause cause) throws ContradictionException { records.forEach(beforeModification.set(this, EventType.DECUPP, cause)); if (value < 0) { //TODO: explication? this.contradiction(this, EventType.DECUPP, AbstractVariable.MSG_UNKNOWN); } boolean done = var.updateLowerBound(-value, this); done |= var.updateUpperBound(value, this); if (done) { EventType evt = EventType.DECUPP; if (instantiated()) { evt = EventType.INSTANTIATE; if (cause.reactOnPromotion()) { cause = Cause.Null; } } notifyMonitors(evt, cause); } return done; } @Override public boolean contains(int value) { return var.contains(value) || var.contains(-value); } @Override public boolean instantiatedTo(int value) { return var.instantiatedTo(value) || var.instantiatedTo(-value) || (var.getDomainSize() == 2 && Math.abs(var.getLB()) == var.getUB()); //<nj> fixed ABS bug } @Override public int getValue() { return getLB(); } @Override public Explanation explain(VariableState what) { return var.explain(VariableState.DOM); } @Override public Explanation explain(VariableState what, int val) { Explanation expl = new Explanation(); expl.add(var.explain(what, val)); expl.add(var.explain(what, -val)); return expl; } @Override public int getLB() { if (var.contains(0)) { return 0; } int elb = var.getLB(); if (elb > 0) { return elb; } int eub = var.getUB(); if (eub < 0) { return -eub; } int l = var.previousValue(0); int u = var.nextValue(0); return Math.min(-l, u); } @Override public int getUB() { int elb = var.getLB(); int eub = var.getUB(); int mm = -elb; if (elb < 0) { if (eub > 0 && eub > mm) { mm = eub; } } else { mm = eub; } return mm; } @Override public int nextValue(int v) { if (v < 0 && var.contains(0)) { return 0; } int l = var.previousValue(-v); if (l == Integer.MIN_VALUE) { l = Integer.MAX_VALUE; } else { l = Math.abs(l); } int u = var.nextValue(v); return Math.min(l, Math.abs(u)); } @Override public int previousValue(int v) { if (v < 0) { return Integer.MIN_VALUE; } int l = var.nextValue(-v); if (l == Integer.MIN_VALUE) { l = Integer.MAX_VALUE; } else { l = Math.abs(l); } int u = var.previousValue(v); return Math.max(l, Math.abs(u)); } @Override public String toString() { return "|" + this.var.toString() + "| = [" + getLB() + "," + getUB() + "]"; } @Override public int getType() { return Variable.INTEGER; } @Override public int getDomainSize() { int d = 0; int ub = getUB(); for (int val = getLB(); val <= ub; val = nextValue(val)) { d++; } return d; } @Override public DisposableValueIterator getValueIterator(boolean bottomUp) { if (_viterator == null || !_viterator.isReusable()) { _viterator = new DisposableValueIterator() { DisposableValueIterator u2l; DisposableValueIterator l2u; int vl2u; int vu2l; @Override public void bottomUpInit() { l2u = var.getValueIterator(true); u2l = var.getValueIterator(false); super.bottomUpInit(); while (l2u.hasNext()) { this.vl2u = l2u.next(); if (this.vl2u >= 0) break; } while (u2l.hasPrevious()) { this.vu2l = u2l.previous(); if (this.vu2l <= 0) break; } } @Override public void topDownInit() { l2u = var.getValueIterator(true); u2l = var.getValueIterator(false); super.topDownInit(); if (l2u.hasNext()) { this.vl2u = l2u.next(); } if (u2l.hasPrevious()) { this.vu2l = u2l.previous(); } } @Override public boolean hasNext() { return this.vl2u < Integer.MAX_VALUE || this.vu2l > -Integer.MAX_VALUE; } @Override public boolean hasPrevious() { return this.vl2u <= 0 || this.vu2l >= 0; } @Override public int next() { int min = this.vl2u < -this.vu2l ? this.vl2u : -this.vu2l; if (this.vl2u == min) { if (this.l2u.hasNext()) { this.vl2u = l2u.next(); } else { this.vl2u = Integer.MAX_VALUE; } } if (-this.vu2l == min) { if (this.u2l.hasPrevious()) { this.vu2l = u2l.previous(); } else { this.vu2l = -Integer.MAX_VALUE; } } return min; } @Override public int previous() { int max = -this.vl2u > this.vu2l ? -this.vl2u : this.vu2l; if (-this.vl2u == max && this.l2u.hasNext()) { this.vl2u = this.l2u.next(); } if (this.vu2l == max && this.u2l.hasPrevious()) { this.vu2l = u2l.previous(); } return max; } @Override public void dispose() { super.dispose(); l2u.dispose(); u2l.dispose(); } }; } if (bottomUp) { _viterator.bottomUpInit(); } else { _viterator.topDownInit(); } return _viterator; } @Override public DisposableRangeIterator getRangeIterator(boolean bottomUp) { if (_riterator == null || !_riterator.isReusable()) { _riterator = new DisposableRangeIterator() { DisposableRangeIterator u2l; DisposableRangeIterator l2u; int ml2u; int Ml2u; int mu2l; int Mu2l; int min; int max; @Override public void bottomUpInit() { l2u = var.getRangeIterator(true); u2l = var.getRangeIterator(false); super.bottomUpInit(); ml2u = Ml2u = mu2l = Mu2l = Integer.MAX_VALUE; while (l2u.hasNext()) { if (l2u.min() >= 0) { ml2u = l2u.min(); Ml2u = l2u.max(); l2u.next(); break; } if (l2u.max() >= 0) { ml2u = 0; Ml2u = l2u.max(); l2u.next(); break; } l2u.next(); } while (u2l.hasPrevious()) { if (u2l.max() <= 0) { Mu2l = -u2l.min(); mu2l = -u2l.max(); u2l.previous(); break; } if (u2l.min() <= 0) { mu2l = 0; Mu2l = -u2l.min(); u2l.previous(); break; } u2l.previous(); } next(); } @Override public void topDownInit() { l2u = var.getRangeIterator(true); u2l = var.getRangeIterator(false); super.topDownInit(); ml2u = Ml2u = mu2l = Mu2l = Integer.MAX_VALUE; if (l2u.hasNext()) { if (l2u.max() <= 0) { this.ml2u = -l2u.max(); this.Ml2u = -l2u.min(); } else if (l2u.min() <= 0) { this.ml2u = 0; this.Ml2u = -l2u.min(); } l2u.next(); } if (u2l.hasPrevious()) { if (u2l.min() >= 0) { this.mu2l = u2l.min(); this.Mu2l = u2l.max(); } else if (u2l.max() >= 0) { this.mu2l = 0; this.Mu2l = u2l.max(); } u2l.previous(); } previous(); } @Override public boolean hasNext() { return min < Integer.MAX_VALUE; } @Override public boolean hasPrevious() { return min < Integer.MAX_VALUE; } @Override public void next() { min = max = Integer.MAX_VALUE; // disjoint ranges if (Ml2u < mu2l - 1) { min = ml2u; max = Ml2u; if (l2u.hasNext()) { ml2u = l2u.min(); Ml2u = l2u.max(); l2u.next(); } else { ml2u = Integer.MAX_VALUE; Ml2u = Integer.MAX_VALUE; } } else if (Mu2l < ml2u - 1) { min = mu2l; max = Mu2l; if (u2l.hasPrevious()) { Mu2l = -u2l.min(); mu2l = -u2l.max(); u2l.previous(); } else { mu2l = Integer.MAX_VALUE; Mu2l = Integer.MAX_VALUE; } } else { // we build the current range if (Ml2u + 1 == mu2l) { min = ml2u; max = Mu2l; } else if (Mu2l + 1 == ml2u) { min = mu2l; max = Ml2u; } else { min = ml2u < mu2l ? ml2u : mu2l; max = Ml2u < Mu2l ? Ml2u : Mu2l; } boolean change; do { change = false; if (min <= ml2u && ml2u <= max) { max = max > Ml2u ? max : Ml2u; if (l2u.hasNext()) { ml2u = l2u.min(); Ml2u = l2u.max(); l2u.next(); change = true; } else { ml2u = Integer.MAX_VALUE; Ml2u = Integer.MAX_VALUE; } } if (min <= mu2l && mu2l <= max) { max = max > Mu2l ? max : Mu2l; if (u2l.hasPrevious()) { Mu2l = -u2l.min(); mu2l = -u2l.max(); u2l.previous(); change = true; } else { mu2l = Integer.MAX_VALUE; Mu2l = Integer.MAX_VALUE; } } } while (change); } } @Override public void previous() { min = max = Integer.MAX_VALUE; // disjoint ranges if (ml2u > Mu2l + 1) { min = ml2u; max = Ml2u; ml2u = Integer.MAX_VALUE; Ml2u = Integer.MAX_VALUE; if (l2u.hasNext()) { //la: grer le 0 et les autres cas if (l2u.max() <= 0) { this.ml2u = -l2u.max(); this.Ml2u = -l2u.min(); } else if (l2u.min() <= 0) { this.ml2u = 0; this.Ml2u = -l2u.min(); } l2u.next(); } } else if (Mu2l < ml2u - 1) { min = mu2l; max = Mu2l; mu2l = Integer.MAX_VALUE; Mu2l = Integer.MAX_VALUE; if (u2l.min() >= 0) { this.mu2l = u2l.min(); this.Mu2l = u2l.max(); } else if (u2l.max() >= 0) { this.mu2l = 0; this.Mu2l = u2l.max(); } } else { // we build the current range if (Ml2u + 1 == mu2l) { min = ml2u; max = Mu2l; } else if (Mu2l + 1 == ml2u) { min = mu2l; max = Ml2u; } else { min = ml2u > mu2l ? ml2u : mu2l; max = Ml2u > Mu2l ? Ml2u : Mu2l; } boolean change; do { change = false; if (min <= Ml2u && Ml2u <= max) { min = min < ml2u ? min : ml2u; ml2u = Integer.MAX_VALUE; Ml2u = Integer.MAX_VALUE; if (l2u.hasNext()) { if (l2u.max() <= 0) { this.ml2u = -l2u.max(); this.Ml2u = -l2u.min(); } else if (l2u.min() <= 0) { this.ml2u = 0; this.Ml2u = -l2u.min(); } l2u.next(); change = true; } } if (min <= mu2l && mu2l <= max) { min = min < mu2l ? min : mu2l; mu2l = Integer.MAX_VALUE; Mu2l = Integer.MAX_VALUE; if (u2l.hasPrevious()) { if (u2l.min() >= 0) { this.mu2l = u2l.min(); this.Mu2l = u2l.max(); } else if (u2l.max() >= 0) { this.mu2l = 0; this.Mu2l = u2l.max(); } u2l.previous(); change = true; } } } while (change); } } @Override public int min() { return min; } @Override public int max() { return max; } @Override public void dispose() { super.dispose(); l2u.dispose(); u2l.dispose(); } }; } if (bottomUp) { _riterator.bottomUpInit(); } else { _riterator.topDownInit(); } return _riterator; } @Override public void transformEvent(EventType evt, ICause cause) throws ContradictionException { if ((evt.mask & EventType.BOUND.mask) != 0) { if (instantiated()) { // specific case where DOM_SIZE = 2 and LB = -UB notifyMonitors(EventType.INSTANTIATE, cause); } else { // otherwise, we do not know the previous values, so its hard to tell wether it is LB or UB mod notifyMonitors(EventType.BOUND, cause); } } else { notifyMonitors(evt, cause); } } }
package org.sikuli.ide; import java.io.*; import java.awt.*; import java.awt.datatransfer.*; import java.awt.image.*; import java.awt.event.*; import java.util.regex.Pattern; import java.util.regex.Matcher; import javax.swing.*; import javax.swing.text.*; import javax.swing.filechooser.FileFilter; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; //import javax.swing.undo.*; import javax.imageio.*; import org.python.util.PythonInterpreter; import org.python.core.*; import org.sikuli.ide.indentation.PythonIndentation; import org.sikuli.script.ImageLocator; import org.sikuli.script.ScriptRunner; import org.sikuli.script.Debug; import org.sikuli.script.Location; public class SikuliPane extends JTextPane implements KeyListener, CaretListener{ private String _editingFilename; private String _srcBundlePath = null; private boolean _dirty = false; private Class _historyBtnClass; private CurrentLineHighlighter _highlighter; private ImageLocator _imgLocator; private String _tabString = " "; private Pattern _lastSearchPattern = null; private String _lastSearchString = null; private Matcher _lastSearchMatcher; private UndoManager _undo = new UndoManager(); // TODO: move to SikuliDocument private PythonIndentation _indentationLogic; public SikuliPane(){ UserPreferences pref = UserPreferences.getInstance(); setEditorKitForContentType("text/python", new SikuliEditorKit()); setContentType("text/python"); initKeyMap(); addKeyListener(this); setTransferHandler(new MyTransferHandler()); _highlighter = new CurrentLineHighlighter(this); addCaretListener(_highlighter); addCaretListener(this); setFont(new Font(pref.getFontName(), Font.PLAIN, pref.getFontSize())); setMargin( new Insets( 3, 3, 3, 3 ) ); //setTabSize(4); setBackground(Color.WHITE); if(!Utils.isMacOSX()) setSelectionColor(new Color(170, 200, 255)); updateDocumentListeners(); _indentationLogic = new PythonIndentation(); } private void updateDocumentListeners(){ getDocument().addDocumentListener(new DirtyHandler()); getDocument().addUndoableEditListener(_undo); } public UndoManager getUndoManager(){ return _undo; } public PythonIndentation getIndentationLogic(){ return _indentationLogic; } private void initKeyMap(){ InputMap map = this.getInputMap(); int shift = InputEvent.SHIFT_MASK; map.put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, shift), SikuliEditorKit.sklDeindentAction); } public void setTabSize(int charactersPerTab) { FontMetrics fm = this.getFontMetrics( this.getFont() ); int charWidth = fm.charWidth( 'w' ); int tabWidth = charWidth * charactersPerTab; TabStop[] tabs = new TabStop[10]; for (int j = 0; j < tabs.length; j++) { int tab = j + 1; tabs[j] = new TabStop( tab * tabWidth ); } TabSet tabSet = new TabSet(tabs); SimpleAttributeSet attributes = new SimpleAttributeSet(); StyleConstants.setFontSize(attributes, 18); StyleConstants.setFontFamily(attributes, "Osaka-Mono"); StyleConstants.setTabSet(attributes, tabSet); int length = getDocument().getLength(); getStyledDocument().setParagraphAttributes(0, length, attributes, true); } public void setTabs(int spaceForTab) { String t = ""; for(int i=0;i<spaceForTab;i++) t += " "; _tabString = t; } public boolean isDirty(){ return _dirty; } public void setDirty(boolean flag){ if(_dirty == flag) return; _dirty = flag; if(flag) getRootPane().putClientProperty("Window.documentModified", true); else SikuliIDE.getInstance().checkDirtyPanes(); } public int getLineAtCaret(int caretPosition) { Element root = getDocument().getDefaultRootElement(); return root.getElementIndex( caretPosition ) + 1; } public int getLineAtCaret() { int caretPosition = getCaretPosition(); Element root = getDocument().getDefaultRootElement(); return root.getElementIndex( caretPosition ) + 1; } public int getColumnAtCaret() { int offset = getCaretPosition(); int column; try { column = offset - Utilities.getRowStart(this, offset); } catch (BadLocationException e) { column = -1; } return column+1; } void setSrcBundle(String newBundlePath){ _srcBundlePath = newBundlePath; _imgLocator = new ImageLocator(_srcBundlePath); } public String getSrcBundle(){ if( _srcBundlePath == null ){ File tmp = Utils.createTempDir(); setSrcBundle(Utils.slashify(tmp.getAbsolutePath(),true)); } return _srcBundlePath; } public void setErrorHighlight(int lineNo){ _highlighter.setErrorLine(lineNo); try{ if(lineNo>0) jumpTo(lineNo); } catch(Exception e){ e.printStackTrace(); } repaint(); } public void setHistoryCaptureButton(CaptureButton btn){ _historyBtnClass = btn.getClass(); } public boolean close() throws IOException{ if( isDirty() ){ Object[] options = {I18N._I("yes"), I18N._I("no"), I18N._I("cancel")}; int ans = JOptionPane.showOptionDialog(this, I18N._I("msgAskSaveChanges", getCurrentShortFilename()), I18N._I("dlgAskCloseTab"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); if( ans == JOptionPane.CANCEL_OPTION || ans == JOptionPane.CLOSED_OPTION ) return false; else if( ans == JOptionPane.YES_OPTION ) saveFile(); setDirty(false); } return true; } public String getCurrentShortFilename(){ if(_srcBundlePath != null){ File f = new File(_srcBundlePath); return f.getName(); } return "Untitled"; } public String getCurrentFilename(){ if(_editingFilename==null){ try{ saveAsFile(); return _editingFilename; } catch(IOException e){ e.printStackTrace(); } } return _editingFilename; } static InputStream SikuliToHtmlConverter = SikuliIDE.class.getResourceAsStream("/scripts/sikuli2html.py"); static String pyConverter = Utils.convertStreamToString(SikuliToHtmlConverter); static InputStream SikuliBundleCleaner= SikuliIDE.class.getResourceAsStream("/scripts/clean-dot-sikuli.py"); static String pyBundleCleaner = Utils.convertStreamToString(SikuliBundleCleaner); private void convertSrcToHtml(String bundle){ PythonInterpreter py = ScriptRunner.getInstance(null).getPythonInterpreter(); Debug.log(2, "Convert Sikuli source code " + bundle + " to HTML"); py.set("local_convert", true); py.set("sikuli_src", bundle); py.exec(pyConverter); } private void writeFile(String filename) throws IOException{ this.write( new BufferedWriter(new OutputStreamWriter( new FileOutputStream(filename), "UTF8"))); } private void cleanBundle(String bundle){ PythonInterpreter py = ScriptRunner.getInstance(null).getPythonInterpreter(); Debug.log(2, "Clear source bundle " + bundle); py.set("bundle_path", bundle); py.exec(pyBundleCleaner); } private void writeSrcFile(boolean writeHTML) throws IOException{ this.write( new BufferedWriter(new OutputStreamWriter( new FileOutputStream(_editingFilename), "UTF8"))); if(writeHTML) convertSrcToHtml(getSrcBundle()); cleanBundle(getSrcBundle()); setDirty(false); } public String saveFile() throws IOException{ if(_editingFilename==null) return saveAsFile(); else{ writeSrcFile(true); return getCurrentShortFilename(); } } public String saveAsFile() throws IOException{ File file = new FileChooser(SikuliIDE.getInstance()).save(); if(file == null) return null; String bundlePath = file.getAbsolutePath(); if( !file.getAbsolutePath().endsWith(".sikuli") ) bundlePath += ".sikuli"; if(Utils.exists(bundlePath)){ int res = JOptionPane.showConfirmDialog( null, I18N._I("msgFileExists", bundlePath), I18N._I("dlgFileExists"), JOptionPane.YES_NO_OPTION); if(res != JOptionPane.YES_OPTION) return null; } saveAsBundle(bundlePath); return getCurrentShortFilename(); } public String exportAsZip() throws IOException, FileNotFoundException{ File file = new FileChooser(SikuliIDE.getInstance()).export(); if(file == null) return null; String zipPath = file.getAbsolutePath(); String srcName = file.getName(); if( !file.getAbsolutePath().endsWith(".skl") ){ zipPath += ".skl"; } else{ srcName = srcName.substring(0, srcName.lastIndexOf('.')); } writeFile(getSrcBundle() + srcName + ".py"); Utils.zip(getSrcBundle(), zipPath); Debug.log(1, "export to executable file: " + zipPath); return zipPath; } private void saveAsBundle(String bundlePath) throws IOException{ bundlePath = Utils.slashify(bundlePath, true); if(_srcBundlePath != null) Utils.xcopy( _srcBundlePath, bundlePath ); else Utils.mkdir(bundlePath); setSrcBundle(bundlePath); _editingFilename = getSourceFilename(bundlePath); Debug.log(1, "save to bundle: " + getSrcBundle()); writeSrcFile(true); //TODO: update all bundle references in ImageButtons //BUG: if save and rename images, the images will be gone.. } private String getSourceFilename(String filename){ if( filename.endsWith(".sikuli") || filename.endsWith(".sikuli" + "/") ){ File f = new File(filename); String dest = f.getName(); dest = dest.replace(".sikuli", ".py"); return getSrcBundle() + dest; } return filename; } public void loadFile(String filename) throws IOException{ if( filename.endsWith("/") ) filename = filename.substring(0, filename.length()-1); setSrcBundle(filename+"/"); _editingFilename = getSourceFilename(filename); this.read( new BufferedReader(new InputStreamReader( new FileInputStream(_editingFilename), "UTF8")), null); updateDocumentListeners(); setDirty(false); } public String loadFile() throws IOException{ File file = new FileChooser(SikuliIDE.getInstance()).load(); if(file == null) return null; String fname = Utils.slashify(file.getAbsolutePath(),false); loadFile(fname); return fname; } int _caret_last_x = -1; boolean _can_update_caret_last_x = true; public void caretUpdate(CaretEvent evt){ if(_can_update_caret_last_x) _caret_last_x = -1; else _can_update_caret_last_x = true; } public void keyPressed(java.awt.event.KeyEvent ke) { } public void keyReleased(java.awt.event.KeyEvent ke) { } private void expandTab() throws BadLocationException{ int pos = getCaretPosition(); Document doc = getDocument(); doc.remove(pos-1, 1); doc.insertString(pos-1, _tabString, null); } public void keyTyped(java.awt.event.KeyEvent ke) { /* try{ //if(ke.getKeyChar() == '\t') expandTab(); checkCompletion(ke); } catch(BadLocationException e){ e.printStackTrace(); } */ } @Override public void read(Reader in, Object desc) throws IOException{ super.read(in, desc); Document doc = getDocument(); Element root = doc.getDefaultRootElement(); parse(root); setCaretPosition(0); } public void jumpTo(int lineNo, int column) throws BadLocationException{ Debug.log(6, "jumpTo: " + lineNo+","+column); int off = getLineStartOffset(lineNo-1)+column-1; int lineCount= getDocument().getDefaultRootElement().getElementCount(); if( lineNo < lineCount ){ int nextLine = getLineStartOffset(lineNo); if( off >= nextLine ) off = nextLine-1; } if(off < 0) off = 0; setCaretPosition( off ); } public void jumpTo(int lineNo) throws BadLocationException{ Debug.log(6,"jumpTo: " + lineNo); setCaretPosition( getLineStartOffset(lineNo-1) ); } public void jumpTo(String funcName) throws BadLocationException{ Debug.log(6, "jumpTo: " + funcName); Element root = getDocument().getDefaultRootElement(); int pos = getFunctionStartOffset(funcName, root); if(pos>=0) setCaretPosition(pos); else throw new BadLocationException("Can't find function " + funcName,-1); } private int getFunctionStartOffset(String func, Element node) throws BadLocationException{ Document doc = getDocument(); int count = node.getElementCount(); Pattern patDef = Pattern.compile("def\\s+"+func+"\\s*\\("); for(int i=0;i<count;i++){ Element elm = node.getElement(i); if( elm.isLeaf() ){ int start = elm.getStartOffset(), end = elm.getEndOffset(); String line = doc.getText(start, end-start); Matcher matcher = patDef.matcher(line); if(matcher.find()) return start; } else{ int p = getFunctionStartOffset(func, elm); if(p>=0) return p; } } return -1; } public int getNumLines(){ Document doc = getDocument(); Element root = doc.getDefaultRootElement(); int lineIdx = root.getElementIndex(doc.getLength()-1); return lineIdx+1; } public void indent(int startLine, int endLine, int level){ Document doc = getDocument(); String strIndent = ""; if(level>0){ for(int i=0;i<level;i++) strIndent += " "; } else{ Debug.error("negative indentation not supported yet!!"); } for(int i=startLine;i<endLine;i++){ try{ int off = getLineStartOffset(i); if(level>0) doc.insertString(off, strIndent, null); } catch(Exception e){ e.printStackTrace(); } } } // line starting from 0 int getLineStartOffset(int line) throws BadLocationException { Element map = getDocument().getDefaultRootElement(); if (line < 0) { throw new BadLocationException("Negative line", -1); } else if (line >= map.getElementCount()) { throw new BadLocationException("No such line", getDocument().getLength()+1); } else { Element lineElem = map.getElement(line); return lineElem.getStartOffset(); } } int parseRange(int start, int end){ try{ end = parseLine(start, end, patPatternStr); end = parseLine(start, end, patSubregionStr); end = parseLine(start, end, patPngStr); } catch(BadLocationException e){ e.printStackTrace(); } return end; } void parse(Element node){ int count = node.getElementCount(); for(int i=0;i<count;i++){ Element elm = node.getElement(i); Debug.log(8, elm.toString() ); if( elm.isLeaf() ){ int start = elm.getStartOffset(), end = elm.getEndOffset(); parseRange(start, end); } else parse(elm); } } static Pattern patPngStr = Pattern.compile("(\"[^\"]+?\\.(?i)png\")"); static Pattern patHistoryBtnStr = Pattern.compile("(\"\\[SIKULI-(CAPTURE|DIFF)\\]\")"); static Pattern patPatternStr = Pattern.compile( "\\b(Pattern\\s*\\(\".*?\"\\)(\\.\\w+\\([^)]*\\))*)"); static Pattern patSubregionStr = Pattern.compile( "\\b(Region\\s*\\([\\d\\s,]+\\))"); int parseLine(int startOff, int endOff, Pattern ptn) throws BadLocationException{ //System.out.println(startOff + " " + endOff); if(endOff <= startOff) return endOff; Document doc = getDocument(); while(true){ String line = doc.getText(startOff, endOff-startOff); Matcher m = ptn.matcher(line); //System.out.println("["+line+"]"); if( m.find() ){ int len = m.end() - m.start(); if(replaceWithImage(startOff+m.start(), startOff+m.end())){ startOff += m.start()+1; endOff -= len-1; } else startOff += m.end()+1; } else break; } return endOff; } public File copyFileToBundle(String filename){ File f = new File(filename); String bundlePath = getSrcBundle(); if(f.exists()){ try{ Utils.xcopy(filename, bundlePath); filename = f.getName(); } catch(IOException e){ e.printStackTrace(); return f; } } filename = bundlePath + "/" + filename; f = new File(filename); if(f.exists()) return f; return null; } public File getFileInBundle(String filename){ if(_imgLocator == null) return null; try{ String fullpath = _imgLocator.locate(filename); return new File(fullpath); } catch(IOException e){ return null; } } boolean replaceWithImage(int startOff, int endOff) throws BadLocationException{ Document doc = getDocument(); String imgStr = doc.getText(startOff, endOff - startOff); String filename = imgStr.substring(1,endOff-startOff-1);; boolean useParameters = false; boolean exact = false; int numMatches = -1; float similarity = -1f; Location offset = null; //Debug.log("imgStr: " + imgStr); //Debug.log("filename " + filename); if( imgStr.startsWith("Pattern") ){ useParameters = true; String[] tokens = imgStr.split("\\)\\s*\\.?"); for(String str : tokens){ //System.out.println("token: " + str); if( str.startsWith("exact") ) exact = true; if( str.startsWith("Pattern") ) filename = str.substring( str.indexOf("\"")+1,str.lastIndexOf("\"")); if( str.startsWith("similar") ){ String strArg = str.substring(str.lastIndexOf("(")+1); try{ similarity = Float.valueOf(strArg); } catch(NumberFormatException e){ return false; } } if( str.startsWith("firstN") ){ // FIXME: replace with limit/max String strArg = str.substring(str.lastIndexOf("(")+1); numMatches = Integer.valueOf(strArg); } if( str.startsWith("targetOffset") ){ String strArg = str.substring(str.lastIndexOf("(")+1); String[] args = strArg.split(","); try{ offset = new Location(0,0); offset.x = Integer.valueOf(args[0]); offset.y = Integer.valueOf(args[1]); } catch(NumberFormatException e){ return false; } } } } else if( imgStr.startsWith("Region") ){ String[] tokens = imgStr.split("[(),]"); try{ int x = Integer.valueOf(tokens[1]), y = Integer.valueOf(tokens[2]), w = Integer.valueOf(tokens[3]), h = Integer.valueOf(tokens[4]); this.select(startOff, endOff); RegionButton icon = new RegionButton(this, x, y, w, h); this.insertComponent(icon); return true; } catch(NumberFormatException e){ return false; } catch(Exception e){ e.printStackTrace(); return false; } } else if( patHistoryBtnStr.matcher(imgStr).matches() ){ Element root = doc.getDefaultRootElement(); int lineIdx = root.getElementIndex(startOff); Element line = root.getElement(lineIdx); try{ CaptureButton btnCapture = (CaptureButton)_historyBtnClass.newInstance(); if( imgStr.indexOf("DIFF") >= 0 ) btnCapture.setDiffMode(true); btnCapture.setSrcElement(line); btnCapture.setParentPane(this); //System.out.println("new btn: " + btnCapture.getSrcElement()); this.select(startOff, endOff); if( btnCapture.hasNext() ){ int pos = startOff; doc.insertString(pos++, "[", null); this.insertComponent(btnCapture); pos++; while(btnCapture.hasNext()){ CaptureButton btn = btnCapture.getNextDiffButton(); doc.insertString(pos++, ",", null); this.insertComponent(btn); pos++; } doc.insertString(pos, "]", null); } else this.insertComponent(btnCapture); } catch(Exception e){ e.printStackTrace(); } return true; } File f = getFileInBundle(filename); Debug.log(7,"replaceWithImage: " + filename); if( f != null && f.exists() ){ this.select(startOff, endOff); ImageButton icon = new ImageButton(this, f.getAbsolutePath()); if(useParameters){ icon.setParameters(exact, similarity, numMatches); if(offset != null) icon.setTargetOffset(offset); } this.insertComponent(icon); return true; } return false; } void checkCompletion(java.awt.event.KeyEvent ke) throws BadLocationException{ Document doc = getDocument(); Element root = doc.getDefaultRootElement(); int pos = getCaretPosition(); int lineIdx = root.getElementIndex(pos); Element line = root.getElement(lineIdx); int start = line.getStartOffset(), len = line.getEndOffset() - start; String strLine = doc.getText(start, len-1); Debug.log(9,"["+strLine+"]"); if( strLine.endsWith("find") && ke.getKeyChar()=='(' ){ ke.consume(); doc.insertString( pos, "(", null); CaptureButton btnCapture = new CaptureButton(this, line); insertComponent(btnCapture); doc.insertString( pos+2, ")", null); } } void insertString(String str){ int sel_start = getSelectionStart(); int sel_end = getSelectionEnd(); if(sel_end != sel_start){ try{ getDocument().remove(sel_start, sel_end-sel_start); } catch(BadLocationException e){ e.printStackTrace(); } } int pos = getCaretPosition(); insertString(pos, str); int new_pos = getCaretPosition(); int end = parseRange(pos, new_pos); setCaretPosition(end); } void insertString(int pos, String str){ Document doc = getDocument(); try{ doc.insertString( pos, str, null ); } catch(Exception e){ e.printStackTrace(); } } void appendString(String str){ Document doc = getDocument(); try{ int start = doc.getLength(); doc.insertString( doc.getLength(), str, null ); int end = doc.getLength(); end = parseLine(start, end, patHistoryBtnStr); } catch(Exception e){ e.printStackTrace(); } } // search forward /* public int search(Pattern pattern){ return search(pattern, true); } public int search(Pattern pattern, boolean forward){ if(!pattern.equals(_lastSearchPattern)){ _lastSearchPattern = pattern; Document doc = getDocument(); int pos = getCaretPosition(); Debug.log("caret: " + pos); try{ String body = doc.getText(pos, doc.getLength()-pos); _lastSearchMatcher = pattern.matcher(body); } catch(BadLocationException e){ e.printStackTrace(); } } return continueSearch(forward); } */ /* public int search(String str){ return search(str, true); } */ public int search(String str, int pos, boolean forward){ int ret = -1; Document doc = getDocument(); Debug.log(9, "search caret: " + pos + ", " + doc.getLength()); try{ String body; int begin; if(forward){ int len = doc.getLength()-pos; body = doc.getText(pos, len>0?len:0); begin = pos; } else{ body = doc.getText(0, pos); begin = 0; } Pattern pattern = Pattern.compile(str); Matcher matcher = pattern.matcher(body); ret = continueSearch(matcher, begin, forward); if(ret < 0){ if(forward && pos != 0) // search from beginning return search(str, 0, forward); if(!forward && pos != doc.getLength()) // search from end return search(str, doc.getLength(), forward); } } catch(BadLocationException e){ Debug.log(7, "search caret: " + pos + ", " + doc.getLength() + e.getStackTrace()); } return ret; } protected int continueSearch(Matcher matcher, int pos, boolean forward){ boolean hasNext = false; int start=0, end=0; if(!forward){ while(matcher.find()){ hasNext = true; start = matcher.start(); end = matcher.end(); } } else{ hasNext = matcher.find(); if(!hasNext) return -1; start = matcher.start(); end = matcher.end(); } if(hasNext){ Document doc = getDocument(); getCaret().setDot(pos+end); getCaret().moveDot(pos+start); getCaret().setSelectionVisible(true); return pos+start; } return -1; } private class DirtyHandler implements DocumentListener { public void changedUpdate(DocumentEvent ev) { Debug.log(9, "change update"); //setDirty(true); } public void insertUpdate(DocumentEvent ev) { Debug.log(9, "insert update"); setDirty(true); } public void removeUpdate(DocumentEvent ev) { Debug.log(9, "remove update"); setDirty(true); } } } class MyTransferHandler extends TransferHandler{ public MyTransferHandler(){ } public void exportToClipboard(JComponent comp, Clipboard clip, int action) { super.exportToClipboard(comp, clip, action); } public int getSourceActions(JComponent c) { return COPY_OR_MOVE; } protected Transferable createTransferable(JComponent c){ JTextPane aTextPane = (JTextPane)c; SikuliEditorKit kit = ((SikuliEditorKit)aTextPane.getEditorKit()); Document doc = aTextPane.getDocument(); int sel_start = aTextPane.getSelectionStart(); int sel_end = aTextPane.getSelectionEnd(); StringWriter writer = new StringWriter(); try{ kit.write(writer, doc, sel_start, sel_end - sel_start ); return new StringSelection(writer.toString()); } catch(Exception e){ e.printStackTrace(); } return null; } public boolean canImport(JComponent comp, DataFlavor[] transferFlavors){ for(int i=0; i<transferFlavors.length; i++){ //System.out.println(transferFlavors[i]); if(transferFlavors[i].equals(DataFlavor.stringFlavor)) return true; } return false; } public boolean importData(JComponent comp, Transferable t){ DataFlavor htmlFlavor = DataFlavor.stringFlavor; if(canImport(comp, t.getTransferDataFlavors())){ try{ String transferString = (String)t.getTransferData(htmlFlavor); SikuliPane targetTextPane = (SikuliPane)comp; targetTextPane.insertString(transferString); }catch (Exception e){ Debug.error("Can't transfer: " + t.toString()); } return true; } return false; } }
package org.exist.xquery.modules; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Properties; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.log4j.Logger; import org.exist.memtree.DocumentBuilderReceiver; import org.exist.memtree.DocumentImpl; import org.exist.memtree.MemTreeBuilder; import org.exist.memtree.SAXAdapter; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.NodeValue; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; /** * Utility Functions for XQuery Extension Modules * * @author Adam Retter <adam@exist-db.org> * @serial 200805202059 * @version 1.1 */ public class ModuleUtils { protected final static Logger LOG = Logger.getLogger(ModuleUtils.class); /** * Takes a String of XML and Creates an XML Node from it using SAX in the * context of the query * * @param context * The Context of the calling XQuery * @param xml * The String of XML * * @return The NodeValue of XML */ public static NodeValue stringToXML(XQueryContext context, String xml) throws XPathException, SAXException { context.pushDocumentContext(); try { // try and construct xml document from input stream, we use eXist's // in-memory DOM implementation XMLReader reader= context.getBroker().getBrokerPool().getParserPool().borrowXMLReader(); LOG.debug("Parsing XML response ..."); // TODO : we should be able to cope with context.getBaseURI() InputSource src = new InputSource(new ByteArrayInputStream(xml.getBytes())); MemTreeBuilder builder = context.getDocumentBuilder(); DocumentBuilderReceiver receiver = new DocumentBuilderReceiver( builder); reader.setContentHandler(receiver); reader.parse(src); Document doc = receiver.getDocument(); // return (NodeValue)doc.getDocumentElement(); return (NodeValue) doc; } catch (IOException e) { throw new XPathException(e.getMessage()); } finally { context.popDocumentContext(); } } /** * Takes a HTML InputSource and creates an XML representation of the HTML by * tidying it (uses NekoHTML) * * @param context * The Context of the calling XQuery * @param srcHtml * The InputSource for the HTML * * @return An in-memory Document representing the XML'ised HTML */ public static DocumentImpl htmlToXHtml(XQueryContext context, String url, InputSource srcHtml) throws XPathException, SAXException { // we use eXist's in-memory DOM implementation org.exist.memtree.DocumentImpl memtreeDoc = null; // use Neko to parse the HTML content to XML XMLReader reader = null; try { LOG.debug("Converting HTML to XML using NekoHTML parser for: " + url); reader = (XMLReader) Class.forName( "org.cyberneko.html.parsers.SAXParser").newInstance(); // do not modify the case of elements and attributes reader .setProperty( "http://cyberneko.org/html/properties/names/elems", "match"); reader.setProperty( "http://cyberneko.org/html/properties/names/attrs", "no-change"); } catch (Exception e) { String errorMsg = "Error while involing NekoHTML parser. (" + e.getMessage() + "). If you want to parse non-wellformed HTML files, put " + "nekohtml.jar into directory 'lib/user'."; LOG.error(errorMsg, e); throw new XPathException(errorMsg, e); } SAXAdapter adapter = new SAXAdapter(); reader.setContentHandler(adapter); try { reader.parse(srcHtml); } catch (IOException e) { throw new XPathException(e.getMessage(), e); } Document doc = adapter.getDocument(); memtreeDoc = (DocumentImpl) doc; memtreeDoc.setContext(context); return memtreeDoc; } /** * Parses a structure like <parameters><param name="a" value="1"/><param * name="b" value="2"/></parameters> into a set of Properties * * @param parameters * The parameters Node * @return a set of name value properties for representing the XML * parameters */ public static Properties parseParameters(Node nParameters) throws XPathException { return parseProperties(nParameters, "param"); } /** * Parses a structure like <properties><property name="a" value="1"/><property * name="b" value="2"/></properties> into a set of Properties * * @param nProperties * The properties Node * @return a set of name value properties for representing the XML * properties */ public static Properties parseProperties(Node nProperties) throws XPathException { return parseProperties(nProperties, "property"); } /** * Parses a structure like <properties><property name="a" value="1"/><property * name="b" value="2"/></properties> into a set of Properties * * @param container * The container of the properties * @param elementName * The name of the property element * @return a set of name value properties for representing the XML * properties */ private final static Properties parseProperties(Node container, String elementName) throws XPathException { Properties properties = new Properties(); if (container != null && container.getNodeType() == Node.ELEMENT_NODE) { NodeList params = ((Element) container) .getElementsByTagName(elementName); for (int i = 0; i < params.getLength(); i++) { Element param = ((Element) params.item(i)); String name = param.getAttribute("name"); String value = param.getAttribute("value"); if (name != null && value != null) { properties.setProperty(name, value); } else { LOG.warn("Name or value attribute missing for " + elementName); } } } return properties; } }
package kg.apc.jmeter.vizualizers; import java.text.DecimalFormatSymbols; import kg.apc.charting.AbstractGraphRow; import kg.apc.charting.rows.GraphRowAverages; import kg.apc.charting.rows.GraphRowOverallAverages; import kg.apc.jmeter.JMeterPluginsUtils; import kg.apc.jmeter.graphs.AbstractVsThreadVisualizer; import org.apache.jmeter.samplers.SampleResult; import org.apache.jorphan.gui.RateRenderer; /** * * @author apc */ public class ThroughputVsThreadsGui extends AbstractVsThreadVisualizer { public ThroughputVsThreadsGui() { super(); graphPanel.getGraphObject().setyAxisLabelRenderer(new CustomRateRenderer(" graphPanel.getGraphObject().setYAxisLabel("Number of estimated transactions /sec"); } @Override public String getLabelResource() { return this.getClass().getSimpleName(); } @Override public String getStaticLabel() { return JMeterPluginsUtils.prefixLabel("Transaction Throughput vs Threads"); } @Override public void add(SampleResult res) { if (!isSampleIncluded(res)) { return; } long time = res.getTime(); if (time < 1) { return; } super.add(res); String label = res.getSampleLabel(); String averageLabel = "Average " + res.getSampleLabel(); GraphRowAverages row = (GraphRowAverages) model.get(label); GraphRowOverallAverages avgRow = (GraphRowOverallAverages) model.get(averageLabel); if(row == null || avgRow == null) { row = (GraphRowAverages) getNewRow(model, AbstractGraphRow.ROW_AVERAGES, label, AbstractGraphRow.MARKER_SIZE_SMALL , false, false, false, true, false); avgRow = (GraphRowOverallAverages) getNewRow(model, AbstractGraphRow.ROW_OVERALL_AVERAGES, averageLabel, AbstractGraphRow.MARKER_SIZE_BIG , false, true, false, false, row.getColor(), false); } int allThreads = getCurrentThreadCount(res); double throughput = (double) allThreads * 1000.0d / time; row.add(allThreads, throughput); avgRow.add(allThreads, throughput); graphPanel.getGraphObject().setCurrentX(allThreads); updateGui(null); } @Override protected JSettingsPanel createSettingsPanel() { return new JSettingsPanel(this, JSettingsPanel.GRADIENT_OPTION | JSettingsPanel.CURRENTX_OPTION | JSettingsPanel.MAXY_OPTION | JSettingsPanel.HIDE_NON_REP_VALUES_OPTION); } @Override public String getWikiPage() { return "TransactionThroughputVsThreads"; } private static class CustomRateRenderer extends RateRenderer { private String zeroLabel; public CustomRateRenderer(String format) { super(format); zeroLabel = "0" + new DecimalFormatSymbols().getDecimalSeparator() + "0/sec"; } @Override public void setValue(Object value) { if (value != null && (value instanceof Double) && ((Double)value).doubleValue() == 0) { setText(zeroLabel); } else { super.setValue(value); } } } }
package edu.umd.cs.findbugs.detect; import java.util.ArrayList; import java.util.BitSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.apache.bcel.Constants; import org.apache.bcel.classfile.Constant; import org.apache.bcel.classfile.ConstantInterfaceMethodref; import org.apache.bcel.classfile.ConstantMethodref; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.MethodGen; import org.apache.bcel.generic.ObjectType; import org.apache.bcel.generic.Type; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.ResourceCollection; import edu.umd.cs.findbugs.ResourceTrackingDetector; import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.StatelessDetector; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.TypeAnnotation; import edu.umd.cs.findbugs.ba.CFG; import edu.umd.cs.findbugs.ba.CFGBuilderException; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.ba.Dataflow; import edu.umd.cs.findbugs.ba.DataflowAnalysisException; import edu.umd.cs.findbugs.ba.Hierarchy; import edu.umd.cs.findbugs.ba.Location; import edu.umd.cs.findbugs.ba.ObjectTypeFactory; import edu.umd.cs.findbugs.ba.ResourceValueAnalysis; import edu.umd.cs.findbugs.ba.ResourceValueFrame; /** * A Detector to look for streams that are opened in a method, do not escape the * method, and are not closed on all paths out of the method. Note that "stream" * is a bit misleading, since we also use the detector to look for database * resources that aren't closed. * * @author David Hovemeyer */ public final class FindOpenStream extends ResourceTrackingDetector<Stream, StreamResourceTracker> implements StatelessDetector { static final boolean DEBUG = SystemProperties.getBoolean("fos.debug"); static final boolean IGNORE_WRAPPED_UNINTERESTING_STREAMS = !SystemProperties.getBoolean("fos.allowWUS"); /** * List of base classes of tracked resources. */ static final ObjectType[] streamBaseList = { ObjectTypeFactory.getInstance("java.io.InputStream"), ObjectTypeFactory.getInstance("java.io.OutputStream"), ObjectTypeFactory.getInstance("java.util.zip.ZipFile"), ObjectTypeFactory.getInstance("java.io.Reader"), ObjectTypeFactory.getInstance("java.io.Writer"), ObjectTypeFactory.getInstance("java.sql.Connection"), ObjectTypeFactory.getInstance("java.sql.Statement"), ObjectTypeFactory.getInstance("java.sql.ResultSet") }; /** * StreamFactory objects used to detect resources created within analyzed * methods. */ static final StreamFactory[] streamFactoryList; static { ArrayList<StreamFactory> streamFactoryCollection = new ArrayList<StreamFactory>(); // Examine InputStreams, OutputStreams, Readers, and Writers, // ignoring byte array, char array, and String variants. streamFactoryCollection.add(new IOStreamFactory("java.io.InputStream", new String[] { "java.io.ByteArrayInputStream", "java.io.StringBufferInputStream", "java.io.PipedInputStream" }, "OS_OPEN_STREAM")); streamFactoryCollection.add(new IOStreamFactory("java.io.OutputStream", new String[] { "java.io.ByteArrayOutputStream", "java.io.PipedOutputStream" }, "OS_OPEN_STREAM")); streamFactoryCollection.add(new IOStreamFactory("java.io.Reader", new String[] { "java.io.StringReader", "java.io.CharArrayReader", "java.io.PipedReader" }, "OS_OPEN_STREAM")); streamFactoryCollection.add(new IOStreamFactory("java.io.Writer", new String[] { "java.io.StringWriter", "java.io.CharArrayWriter", "java.io.PipedWriter" }, "OS_OPEN_STREAM")); streamFactoryCollection.add(new IOStreamFactory("java.util.zip.ZipFile", new String[0], "OS_OPEN_STREAM")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.lang.Class", "getResourceAsStream", "(Ljava/lang/String;)Ljava/io/InputStream;", "OS_OPEN_STREAM")); // Ignore socket input and output streams streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.net.Socket", "getInputStream", "()Ljava/io/InputStream;")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.net.Socket", "getOutputStream", "()Ljava/io/OutputStream;")); // Ignore servlet streams streamFactoryCollection.add(new MethodReturnValueStreamFactory("javax.servlet.ServletRequest", "getInputStream", "()Ljavax/servlet/ServletInputStream;")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("javax.servlet.ServletRequest", "getReader", "()Ljava/io/BufferedReader;")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("javax.servlet.ServletResponse", "getOutputStream", "()Ljavax/servlet/ServletOutputStream;")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("javax.servlet.ServletResponse", "getWriter", "()Ljava/io/PrintWriter;")); // Ignore System.{in,out,err} streamFactoryCollection.add(new StaticFieldLoadStreamFactory("java.io.InputStream", "java.lang.System", "in", "Ljava/io/InputStream;")); streamFactoryCollection.add(new StaticFieldLoadStreamFactory("java.io.OutputStream", "java.lang.System", "out", "Ljava/io/PrintStream;")); streamFactoryCollection.add(new StaticFieldLoadStreamFactory("java.io.OutputStream", "java.lang.System", "err", "Ljava/io/PrintStream;")); // Ignore input streams loaded from instance fields streamFactoryCollection.add(new InstanceFieldLoadStreamFactory("java.io.InputStream")); streamFactoryCollection.add(new InstanceFieldLoadStreamFactory("java.io.Reader")); // Ignore output streams loaded from instance fields. // FIXME: what we really should do here is ignore the stream // loaded from the field, but report any streams that wrap // it. This is an important and useful distinction that the // detector currently doesn't handle. Should be fairly // easy to add. streamFactoryCollection.add(new InstanceFieldLoadStreamFactory("java.io.OutputStream")); streamFactoryCollection.add(new InstanceFieldLoadStreamFactory("java.io.Writer")); // JDBC objects streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.Connection", "prepareStatement", "(Ljava/lang/String;)Ljava/sql/PreparedStatement;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.Connection", "prepareStatement", "(Ljava/lang/String;I)Ljava/sql/PreparedStatement;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.Connection", "prepareStatement", "(Ljava/lang/String;[I)Ljava/sql/PreparedStatement;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.Connection", "prepareStatement", "(Ljava/lang/String;II)Ljava/sql/PreparedStatement;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.Connection", "prepareStatement", "(Ljava/lang/String;III)Ljava/sql/PreparedStatement;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.Connection", "prepareStatement", "(Ljava/lang/String;[Ljava/lang/String;)Ljava/sql/PreparedStatement;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.Connection", "prepareCall", "(Ljava/lang/String;)Ljava/sql/CallableStatement;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.Connection", "prepareCall", "(Ljava/lang/String;II)Ljava/sql/CallableStatement;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.Connection", "prepareCall", "(Ljava/lang/String;III)Ljava/sql/CallableStatement;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.DriverManager", "getConnection", "(Ljava/lang/String;)Ljava/sql/Connection;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.DriverManager", "getConnection", "(Ljava/lang/String;Ljava/util/Properties;)Ljava/sql/Connection;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.DriverManager", "getConnection", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/sql/Connection;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("javax.sql.DataSource", "getConnection", "()Ljava/sql/Connection;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("javax.sql.DataSource", "getConnection", "(Ljava/lang/String;Ljava/lang/String;)Ljava/sql/Connection;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.Connection", "createStatement", "()Ljava/sql/Statement;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.Connection", "createStatement", "(II)Ljava/sql/Statement;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.Connection", "createStatement", "(III)Ljava/sql/Statement;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.Connection", "createStatement", "(Ljava/lang/String;)Ljava/sql/PreparedStatement;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.Connection", "createStatement", "(Ljava/lang/String;I)Ljava/sql/PreparedStatement;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.Connection", "createStatement", "(Ljava/lang/String;II)Ljava/sql/PreparedStatement;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.Connection", "createStatement", "(Ljava/lang/String;III)Ljava/sql/PreparedStatement;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.Connection", "createStatement", "(Ljava/lang/String;[I)Ljava/sql/PreparedStatement;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryCollection.add(new MethodReturnValueStreamFactory("java.sql.Connection", "createStatement", "(Ljava/lang/String;[Ljava/lang/String;)Ljava/sql/PreparedStatement;", "ODR_OPEN_DATABASE_RESOURCE")); streamFactoryList = streamFactoryCollection.toArray(new StreamFactory[streamFactoryCollection.size()]); } private static class PotentialOpenStream { public final String bugType; public final int priority; public final Stream stream; @Override public String toString() { return stream.toString(); } public PotentialOpenStream(String bugType, int priority, Stream stream) { this.bugType = bugType; this.priority = priority; this.stream = stream; } } private List<PotentialOpenStream> potentialOpenStreamList; public FindOpenStream(BugReporter bugReporter) { super(bugReporter); this.potentialOpenStreamList = new LinkedList<PotentialOpenStream>(); } @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(e); } } // List of words that must appear in names of classes which // create possible resources to be tracked. If we don't see a // class containing one of these words, then we don't run the // detector on the class. private static final String[] PRESCREEN_CLASS_LIST = { "Stream", "Reader", "Writer", "ZipFile", "JarFile", "DriverManager", "Connection", "Statement" }; /* * (non-Javadoc) * * @see * edu.umd.cs.findbugs.Detector#visitClassContext(edu.umd.cs.findbugs.ba * .ClassContext) */ @Override public void visitClassContext(ClassContext classContext) { JavaClass jclass = classContext.getJavaClass(); // Check to see if the class references any other classes // which could be resources we want to track. // If we don't find any such classes, we skip analyzing // the class. (Note: could do this by method.) boolean sawResourceClass = false; for (int i = 0; i < jclass.getConstantPool().getLength(); ++i) { Constant constant = jclass.getConstantPool().getConstant(i); String className = null; if (constant instanceof ConstantMethodref) { ConstantMethodref cmr = (ConstantMethodref) constant; int classIndex = cmr.getClassIndex(); className = jclass.getConstantPool().getConstantString(classIndex, Constants.CONSTANT_Class); } else if (constant instanceof ConstantInterfaceMethodref) { ConstantInterfaceMethodref cmr = (ConstantInterfaceMethodref) constant; int classIndex = cmr.getClassIndex(); className = jclass.getConstantPool().getConstantString(classIndex, Constants.CONSTANT_Class); } if (className != null) { if (DEBUG) System.out.println("FindOpenStream: saw class " + className); for (String aPRESCREEN_CLASS_LIST : PRESCREEN_CLASS_LIST) { if (className.indexOf(aPRESCREEN_CLASS_LIST) >= 0) { sawResourceClass = true; break; } } } } if (sawResourceClass) { super.visitClassContext(classContext); } } @Override public boolean prescreen(ClassContext classContext, Method method, boolean mightClose) { BitSet bytecodeSet = classContext.getBytecodeSet(method); if (bytecodeSet == null) return false; return bytecodeSet.get(Constants.NEW) || bytecodeSet.get(Constants.INVOKEINTERFACE) || bytecodeSet.get(Constants.INVOKESPECIAL) || bytecodeSet.get(Constants.INVOKESTATIC) || bytecodeSet.get(Constants.INVOKEVIRTUAL); } @Override public StreamResourceTracker getResourceTracker(ClassContext classContext, Method method) { return new StreamResourceTracker(streamFactoryList, bugReporter); } public static boolean isMainMethod(Method method) { return method.isStatic() && method.getName().equals("main") && method.getSignature().equals("([Ljava/lang/String;)V"); } @Override public void analyzeMethod(ClassContext classContext, Method method, StreamResourceTracker resourceTracker, ResourceCollection<Stream> resourceCollection) throws CFGBuilderException, DataflowAnalysisException { potentialOpenStreamList.clear(); JavaClass javaClass = classContext.getJavaClass(); MethodGen methodGen = classContext.getMethodGen(method); if (methodGen == null) return; CFG cfg = classContext.getCFG(method); // Add Streams passed into the method as parameters. // These are uninteresting, and should poison // any streams which wrap them. try { Type[] parameterTypeList = Type.getArgumentTypes(methodGen.getSignature()); Location firstLocation = new Location(cfg.getEntry().getFirstInstruction(), cfg.getEntry()); int local = methodGen.isStatic() ? 0 : 1; for (Type type : parameterTypeList) { if (type instanceof ObjectType) { ObjectType objectType = (ObjectType) type; for (ObjectType streamBase : streamBaseList) { if (Hierarchy.isSubtype(objectType, streamBase)) { // OK, found a parameter that is a resource. // Create a Stream object to represent it. // The Stream will be uninteresting, so it will // inhibit reporting for any stream that wraps it. Stream paramStream = new Stream(firstLocation, objectType.getClassName(), streamBase.getClassName()); paramStream.setIsOpenOnCreation(true); paramStream.setOpenLocation(firstLocation); paramStream.setInstanceParam(local); resourceCollection.addPreexistingResource(paramStream); break; } } } switch (type.getType()) { case Constants.T_LONG: case Constants.T_DOUBLE: local += 2; break; default: local += 1; break; } } } catch (ClassNotFoundException e) { bugReporter.reportMissingClass(e); } // Set precomputed map of Locations to Stream creation points. // That way, the StreamResourceTracker won't have to // repeatedly try to figure out where Streams are created. resourceTracker.setResourceCollection(resourceCollection); super.analyzeMethod(classContext, method, resourceTracker, resourceCollection); // Compute streams that escape into other streams: // this takes wrapper streams into account. // This will also compute equivalence classes of streams, // so that if one stream in a class is closed, // they are all considered closed. // (FIXME: this is too simplistic, especially if buffering // is involved. Sometime we should really think harder // about how this should work.) resourceTracker.markTransitiveUninterestingStreamEscapes(); // For each stream closed on all paths, mark its equivalence // class as being closed. for (Iterator<Stream> i = resourceCollection.resourceIterator(); i.hasNext();) { Stream stream = i.next(); StreamEquivalenceClass equivalenceClass = resourceTracker.getStreamEquivalenceClass(stream); if (stream.isClosed()) equivalenceClass.setClosed(); } // Iterate through potential open streams, reporting warnings // for the "interesting" streams that haven't been closed // (and aren't in an equivalence class with another stream // that was closed). for (PotentialOpenStream pos : potentialOpenStreamList) { Stream stream = pos.stream; if (stream.isClosed()) // Stream was in an equivalence class with another // stream that was properly closed. continue; if (stream.isUninteresting()) continue; Location openLocation = stream.getOpenLocation(); if (openLocation == null) continue; if (IGNORE_WRAPPED_UNINTERESTING_STREAMS && resourceTracker.isUninterestingStreamEscape(stream)) continue; String sourceFile = javaClass.getSourceFileName(); String leakClass = stream.getStreamBase(); if (isMainMethod(method) && (leakClass.contains("InputStream") || leakClass.contains("Reader"))) return; bugAccumulator.accumulateBug(new BugInstance(this, pos.bugType, pos.priority) .addClassAndMethod(methodGen, sourceFile).addTypeOfNamedClass(leakClass) .describe(TypeAnnotation.CLOSEIT_ROLE), SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen, sourceFile, stream.getLocation().getHandle())); } } @Override public void inspectResult(ClassContext classContext, MethodGen methodGen, CFG cfg, Dataflow<ResourceValueFrame, ResourceValueAnalysis<Stream>> dataflow, Stream stream) { if (DEBUG) { System.out.printf("Result for %s in %s%n", stream, methodGen); dataflow.dumpDataflow(dataflow.getAnalysis()); } ResourceValueFrame exitFrame = dataflow.getResultFact(cfg.getExit()); int exitStatus = exitFrame.getStatus(); if (exitStatus == ResourceValueFrame.OPEN || exitStatus == ResourceValueFrame.OPEN_ON_EXCEPTION_PATH) { // FIXME: Stream object should be queried for the // priority. String bugType = stream.getBugType(); int priority = NORMAL_PRIORITY; if (exitStatus == ResourceValueFrame.OPEN_ON_EXCEPTION_PATH) { bugType += "_EXCEPTION_PATH"; priority = LOW_PRIORITY; } potentialOpenStreamList.add(new PotentialOpenStream(bugType, priority, stream)); } else if (exitStatus == ResourceValueFrame.CLOSED) { // Remember that this stream was closed on all paths. // Later, we will mark all of the streams in its equivalence class // as having been closed. stream.setClosed(); } } // public static void main(String[] argv) throws Exception { // if (argv.length != 3) { // System.err.println("Usage: " + FindOpenStream.class.getName() + // " <class file> <method name> <bytecode offset>"); // System.exit(1); // String classFile = argv[0]; // String methodName = argv[1]; // int offset = Integer.parseInt(argv[2]); // ResourceValueAnalysisTestDriver<Stream, StreamResourceTracker> driver = // new ResourceValueAnalysisTestDriver<Stream, StreamResourceTracker>() { // @Override // public StreamResourceTracker createResourceTracker(ClassContext // classContext, Method method) { // return new StreamResourceTracker(streamFactoryList, // classContext.getLookupFailureCallback()); // driver.execute(classFile, methodName, offset); } // vim:ts=3
package edu.umd.cs.findbugs.updates; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.StringWriter; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import java.util.prefs.Preferences; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.WillClose; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import edu.umd.cs.findbugs.DetectorFactoryCollection; import edu.umd.cs.findbugs.FindBugs; import edu.umd.cs.findbugs.Plugin; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.Version; import edu.umd.cs.findbugs.util.MultiMap; import edu.umd.cs.findbugs.util.Util; import edu.umd.cs.findbugs.xml.OutputStreamXMLOutput; import edu.umd.cs.findbugs.xml.XMLUtil; public class UpdateChecker { public static final String PLUGIN_RELEASE_DATE_FMT = "MM/dd/yyyy hh:mm aa z"; private static final Logger LOGGER = Logger.getLogger(UpdateChecker.class.getName()); private static final String KEY_DISABLE_ALL_UPDATE_CHECKS = "noUpdateChecks"; private static final String KEY_REDIRECT_ALL_UPDATE_CHECKS = "redirectUpdateChecks"; private static final boolean ENV_FB_NO_UPDATE_CHECKS = System.getenv("FB_NO_UPDATE_CHECKS") != null; private final UpdateCheckCallback dfc; private final List<PluginUpdate> pluginUpdates = new CopyOnWriteArrayList<PluginUpdate>(); public UpdateChecker(UpdateCheckCallback dfc) { this.dfc = dfc; } public void checkForUpdates(Collection<Plugin> plugins, final boolean force) { if (updateChecksGloballyDisabled()) { dfc.pluginUpdateCheckComplete(pluginUpdates, force); return; } URI redirectUri = getRedirectURL(force); final CountDownLatch latch; if (redirectUri != null) { latch = new CountDownLatch(1); startUpdateCheckThread(redirectUri, plugins, latch); } else { MultiMap<URI,Plugin> pluginsByUrl = new MultiMap<URI, Plugin>(HashSet.class); for (Plugin plugin : plugins) { URI uri = plugin.getUpdateUrl(); if (uri == null) { logError(Level.FINE, "Not checking for updates for " + plugin.getShortDescription() + " - no update-url attribute in plugin XML file"); continue; } pluginsByUrl.add(uri, plugin); } latch = new CountDownLatch(pluginsByUrl.keySet().size()); for (URI uri : pluginsByUrl.keySet()) { startUpdateCheckThread(uri, pluginsByUrl.get(uri), latch); } } waitForCompletion(latch, force); } /** * @param force * @return */ public @CheckForNull URI getRedirectURL(final boolean force) { String redirect = dfc.getGlobalOption(KEY_REDIRECT_ALL_UPDATE_CHECKS); String sysprop = System.getProperty("findbugs.redirectUpdateChecks"); if (sysprop != null) redirect = sysprop; Plugin setter = dfc.getGlobalOptionSetter(KEY_REDIRECT_ALL_UPDATE_CHECKS); URI redirectUri = null; String pluginName = setter == null ? "<unknown plugin>" : setter.getShortDescription(); if (redirect != null && !redirect.trim().equals("")) { try { redirectUri = new URI(redirect); logError(Level.INFO, "Redirecting all plugin update checks to " + redirectUri + " (" + pluginName + ")"); } catch (URISyntaxException e) { String error = "Invalid update check redirect URI in " + pluginName + ": " + redirect; logError(Level.SEVERE, error); dfc.pluginUpdateCheckComplete(pluginUpdates, force); throw new IllegalStateException(error); } } return redirectUri; } private long dontWarnAgainUntil() { Preferences prefs = Preferences.userNodeForPackage(UpdateChecker.class); String oldSeen = prefs.get("last-plugin-update-seen", ""); if (oldSeen == null || oldSeen.equals("")) return 0; try { return Long.parseLong(oldSeen) + DONT_REMIND_WINDOW; } catch (Exception e) { return 0; } } static final long DONT_REMIND_WINDOW = 3L*24*60*60*1000; public boolean updatesHaveBeenSeenBefore(Collection<UpdateChecker.PluginUpdate> updates) { long now = System.currentTimeMillis(); Preferences prefs = Preferences.userNodeForPackage(UpdateChecker.class); String oldHash = prefs.get("last-plugin-update-hash", ""); String newHash = Integer.toString(buildPluginUpdateHash(updates)); if (oldHash.equals(newHash) && dontWarnAgainUntil() > now) { LOGGER.fine("Skipping update dialog because these updates have been seen before"); return true; } prefs.put("last-plugin-update-hash", newHash); prefs.put("last-plugin-update-seen", Long.toString(now)); return false; } private int buildPluginUpdateHash(Collection<UpdateChecker.PluginUpdate> updates) { HashSet<String> builder = new HashSet<String>(); for (UpdateChecker.PluginUpdate update : updates) { builder.add( update.getPlugin().getPluginId() + update.getVersion()); } return builder.hashCode(); } private void waitForCompletion(final CountDownLatch latch, final boolean force) { Util.runInDameonThread(new Runnable() { public void run() { if (DEBUG) System.out.println("Checking for version updates"); try { if (! latch.await(15, TimeUnit.SECONDS)) { logError(Level.INFO, "Update check timed out"); } dfc.pluginUpdateCheckComplete(pluginUpdates, force); } catch (Exception ignored) { assert true; } } }, "Plugin update checker"); } public boolean updateChecksGloballyDisabled() { return ENV_FB_NO_UPDATE_CHECKS || getPluginThatDisabledUpdateChecks() != null; } public String getPluginThatDisabledUpdateChecks() { String disable = dfc.getGlobalOption(KEY_DISABLE_ALL_UPDATE_CHECKS); Plugin setter = dfc.getGlobalOptionSetter(KEY_DISABLE_ALL_UPDATE_CHECKS); String pluginName = setter == null ? "<unknown plugin>" : setter.getShortDescription(); String disablingPlugin = null; if ("true".equalsIgnoreCase(disable)) { logError(Level.INFO, "Skipping update checks due to " + KEY_DISABLE_ALL_UPDATE_CHECKS + "=true set by " + pluginName); disablingPlugin = pluginName; } else if (disable != null && !"false".equalsIgnoreCase(disable)) { String error = "Unknown value '" + disable + "' for " + KEY_DISABLE_ALL_UPDATE_CHECKS + " in " + pluginName; logError(Level.SEVERE, error); throw new IllegalStateException(error); } return disablingPlugin; } private void startUpdateCheckThread(final URI url, final Collection<Plugin> plugins, final CountDownLatch latch) { if (url == null) { logError(Level.INFO, "Not checking for plugin updates w/ blank URL: " + getPluginNames(plugins)); return; } final String entryPoint = getEntryPoint(); if ((entryPoint.contains("edu.umd.cs.findbugs.FindBugsTestCase") || entryPoint.contains("edu.umd.cs.findbugs.cloud.appEngine.AbstractWebCloudTest")) && (url.getScheme().equals("http") || url.getScheme().equals("https"))) { LOGGER.fine("Skipping update check because we're running in FindBugsTestCase and using " + url.getScheme()); return; } Runnable r = new Runnable() { public void run() { try { actuallyCheckforUpdates(url, plugins, entryPoint); } catch (Exception e) { if (e instanceof IllegalStateException && e.getMessage().contains("Shutdown in progress")) return; logError(e, "Error doing update check at " + url); } finally { latch.countDown(); } } }; if (DEBUG) r.run(); else Util.runInDameonThread(r, "Check for updates"); } static final boolean DEBUG = false; /** protected for testing */ protected void actuallyCheckforUpdates(URI url, Collection<Plugin> plugins, String entryPoint) throws IOException { LOGGER.fine("Checking for updates at " + url + " for " + getPluginNames(plugins)); if (DEBUG) System.out.println(url); HttpURLConnection conn = (HttpURLConnection) url.toURL().openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.connect(); OutputStream out = conn.getOutputStream(); writeXml(out, plugins, entryPoint, true); // for debugging: if (DEBUG) { System.out.println("Sending"); writeXml(System.out, plugins, entryPoint, false); } int responseCode = conn.getResponseCode(); if (responseCode != 200) { logError(SystemProperties.ASSERTIONS_ENABLED ? Level.WARNING : Level.FINE, "Error checking for updates at " + url + ": " + responseCode + " - " + conn.getResponseMessage()); } else { parseUpdateXml(url, plugins, conn.getInputStream()); } conn.disconnect(); } /** protected for testing */ protected final void writeXml(OutputStream out, Collection<Plugin> plugins, String entryPoint, boolean finish) throws IOException { OutputStreamXMLOutput xmlOutput = new OutputStreamXMLOutput(out); try { xmlOutput.beginDocument(); xmlOutput.startTag("findbugs-invocation"); xmlOutput.addAttribute("version", Version.RELEASE); String applicationName = Version.getApplicationName(); if (applicationName == null || applicationName.equals("")) { int lastDot = entryPoint.lastIndexOf('.'); if (lastDot == -1) applicationName = entryPoint; else applicationName = entryPoint.substring(lastDot + 1); } xmlOutput.addAttribute("app-name", applicationName); String applicationVersion = Version.getApplicationVersion(); if (applicationVersion == null) applicationVersion = ""; xmlOutput.addAttribute("app-version", applicationVersion); xmlOutput.addAttribute("entry-point", entryPoint); xmlOutput.addAttribute("os", SystemProperties.getProperty("os.name", "")); xmlOutput.addAttribute("java-version", getMajorJavaVersion()); Locale locale = Locale.getDefault(); xmlOutput.addAttribute("language", locale.getLanguage()); xmlOutput.addAttribute("country", locale.getCountry()); xmlOutput.addAttribute("uuid", getUuid()); xmlOutput.stopTag(false); for (Plugin plugin : plugins) { xmlOutput.startTag("plugin"); xmlOutput.addAttribute("id", plugin.getPluginId()); xmlOutput.addAttribute("name", plugin.getShortDescription()); xmlOutput.addAttribute("version", plugin.getVersion()); Date date = plugin.getReleaseDate(); if (date != null) xmlOutput.addAttribute("release-date", Long.toString(date.getTime())); xmlOutput.stopTag(true); } xmlOutput.closeTag("findbugs-invocation"); xmlOutput.flush(); } finally { if (finish) xmlOutput.finish(); } } // package-private for testing @SuppressWarnings({ "unchecked" }) void parseUpdateXml(URI url, Collection<Plugin> plugins, @WillClose InputStream inputStream) { try { Document doc = new SAXReader().read(inputStream); if (DEBUG) { StringWriter stringWriter = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(stringWriter); xmlWriter.write(doc); xmlWriter.close(); System.out.println("UPDATE RESPONSE: " + stringWriter.toString()); } List<Element> pluginEls = XMLUtil.selectNodes(doc, "fb-plugin-updates/plugin"); Map<String, Plugin> map = new HashMap<String, Plugin>(); for (Plugin p : plugins) map.put(p.getPluginId(), p); for (Element pluginEl : pluginEls) { String id = pluginEl.attributeValue("id"); Plugin plugin = map.get(id); if (plugin != null) { checkPlugin(pluginEl, plugin); } } } catch (Exception e) { logError(e, "Could not parse plugin version update for " + url); } finally { Util.closeSilently(inputStream); } } @SuppressWarnings({"unchecked"}) private void checkPlugin(Element pluginEl, Plugin plugin) { for (Element release : (List<Element>) pluginEl.elements("release")) { checkPluginRelease(plugin, release); } } private void checkPluginRelease(Plugin plugin, Element maxEl) { @CheckForNull Date updateDate = parseReleaseDate(maxEl); @CheckForNull Date installedDate = plugin.getReleaseDate(); if (updateDate != null && installedDate != null && updateDate.before(installedDate)) return; String version = maxEl.attributeValue("version"); if (version.equals(plugin.getVersion())) return; String url = maxEl.attributeValue("url"); String message = maxEl.element("message").getTextTrim(); pluginUpdates.add(new PluginUpdate(plugin, version, updateDate, url, message)); } // protected for testing protected void logError(Level level, String msg) { LOGGER.log(level, msg); } // protected for testing protected void logError(Exception e, String msg) { LOGGER.log(Level.INFO, msg, e); } private @CheckForNull Date parseReleaseDate(Element releaseEl) { SimpleDateFormat format = new SimpleDateFormat(PLUGIN_RELEASE_DATE_FMT); String dateStr = releaseEl.attributeValue("date"); if (dateStr == null) return null; try { return format.parse(dateStr); } catch (Exception e) { throw new IllegalArgumentException("Error parsing " + dateStr, e); } } private String getPluginNames(Collection<Plugin> plugins) { String text = ""; boolean first = true; for (Plugin plugin : plugins) { text = (first ? "" : ", ") + plugin.getShortDescription(); first = false; } return text; } private String getEntryPoint() { String lastFbClass = "<UNKNOWN>"; for (StackTraceElement s : Thread.currentThread().getStackTrace()) { String cls = s.getClassName(); if (cls.startsWith("edu.umd.cs.findbugs.")) { lastFbClass = cls; } } return lastFbClass; } /** Should only be used once */ private static Random random = new Random(); private static synchronized String getUuid() { try { Preferences prefs = Preferences.userNodeForPackage(UpdateChecker.class); long uuid = prefs.getLong("uuid", 0); if (uuid == 0) { uuid = random.nextLong(); prefs.putLong("uuid", uuid); } return Long.toString(uuid, 16); } catch (Throwable e) { return Long.toString(42, 16); } } private String getMajorJavaVersion() { String ver = SystemProperties.getProperty("java.version", ""); Matcher m = Pattern.compile("^\\d+\\.\\d+").matcher(ver); if (m.find()) { return m.group(); } return ""; } public static class PluginUpdate { private final Plugin plugin; private final String version; private final @CheckForNull Date date; private final @CheckForNull String url; private final @Nonnull String message; private PluginUpdate(Plugin plugin, String version, @CheckForNull Date date, @CheckForNull String url, @Nonnull String message) { this.plugin = plugin; this.version = version; this.date = date; this.url = url; this.message = message; } public Plugin getPlugin() { return plugin; } public String getVersion() { return version; } public @CheckForNull Date getDate() { return date; } public @CheckForNull String getUrl() { return url; } public @Nonnull String getMessage() { return message; } @Override public String toString() { SimpleDateFormat format = new SimpleDateFormat(PLUGIN_RELEASE_DATE_FMT); StringBuilder buf = new StringBuilder(); String name = getPlugin().isCorePlugin() ? "FindBugs" : "FindBugs plugin " + getPlugin().getShortDescription(); buf.append( name + " " + getVersion() ); if (date == null) buf.append(" has been released"); else buf.append(" was released " + format.format(date)); buf.append( " (you have " + getPlugin().getVersion() + ")"); buf.append("\n"); buf.append(" " + message.replaceAll("\n", "\n ")); if (url != null) buf.append("\nVisit " + url + " for details."); return buf.toString(); } } public static void main(String args[]) throws Exception { FindBugs.setNoAnalysis(); DetectorFactoryCollection dfc = DetectorFactoryCollection.instance(); UpdateChecker checker = dfc.getUpdateChecker(); if (checker.updateChecksGloballyDisabled()) System.out.println("Update checkes are globally disabled"); URI redirect = checker.getRedirectURL(false); if (redirect != null) System.out.println("All update checks redirected to " + redirect); checker.writeXml(System.out, dfc.plugins(), "UpdateChecker", true); } }
package edu.umd.cs.findbugs.visitclass; import java.io.IOException; import java.io.Serializable; import java.util.Comparator; import java.util.Enumeration; import java.util.Iterator; import java.util.TreeSet; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.bcel.classfile.ClassParser; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; /** * @author pugh */ public class PrintClass { /** * @author pugh */ static final class ZipEntryComparator implements Comparator<ZipEntry>, Serializable { private static final long serialVersionUID = 1L; public int compare(ZipEntry o1, ZipEntry o2) { ZipEntry e1 = (ZipEntry) o1; String s1 = e1.getName(); int pos1 = s1.lastIndexOf('/'); String p1 = "-"; if (pos1 >= 0) p1 = s1.substring(0, pos1); ZipEntry e2 = (ZipEntry) o2; String s2 = e2.getName(); int pos2 = s2.lastIndexOf('/'); String p2 = "-"; if (pos2 >= 0) p2 = s2.substring(0, pos2); int r = p1.compareTo(p2); if (r != 0) return r; return s1.compareTo(s2); } } static boolean code = false, constants = false; public static void main(String argv[]) throws IOException { String[] file_name = new String[argv.length]; int files = 0; ClassParser parser = null; String zip_file = null; /* * Parse command line arguments. */ for (int i = 0; i < argv.length; i++) { if (argv[i].charAt(0) == '-') { // command line switch if (argv[i].equals("-constants")) constants = true; else if (argv[i].equals("-code")) code = true; else if (argv[i].equals("-zip")) zip_file = argv[++i]; } else if (argv[i].endsWith(".zip") || argv[i].endsWith(".jar")) zip_file = argv[i]; else { // add file name to list file_name[files++] = argv[i]; } } if (!constants) code = true; if (files == 0 && zip_file == null) { System.err.println("list: No input files specified"); } else { if (files == 0 && zip_file != null) { ZipFile z = new ZipFile(zip_file); TreeSet<ZipEntry> zipEntries = new TreeSet<ZipEntry>( new ZipEntryComparator()); for (Enumeration<? extends ZipEntry> e = z .entries(); e.hasMoreElements();) zipEntries.add(e.nextElement()); for (Iterator i = zipEntries.iterator(); i.hasNext();) { ZipEntry ze = (ZipEntry) i.next(); String name = ze.getName(); if (name.endsWith(".class")) printClass(new ClassParser(z.getInputStream(ze), name)); } } else for (int i = 0; i < files; i++) if (file_name[i].endsWith(".class")) { if (zip_file == null) printClass(new ClassParser(file_name[i])); else printClass(new ClassParser(zip_file, file_name[i])); } } } private static void printClass(ClassParser parser) throws IOException { JavaClass java_class; java_class = parser.parse(); if (constants || code) System.out.println(java_class); // Dump the contents if (constants) // Dump the constant pool ? System.out.println(java_class.getConstantPool()); if (code) // Dump the method code ? printCode(java_class.getMethods()); } /** * Dump the disassembled code of all methods in the class. */ public static void printCode(Method[] methods) { for (Method m : methods) { System.out.println(m); Code code = m.getCode(); if (code != null) System.out.println(code); } } }
package snow.skittles; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.support.v7.widget.LinearLayoutManager; import android.util.AttributeSet; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class SkittleLayout extends CoordinatorLayout { SkittleContainer skittleContainer; public SkittleLayout(Context context) { super(context); } public SkittleLayout(Context context, AttributeSet attrs) { super(context, attrs); TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.SkittleLayout); int color; Drawable drawable; try { color = array.getResourceId(R.styleable.SkittleLayout_mainSkittleColor, fetchAccentColor(getContext())); drawable = array.getDrawable(R.styleable.SkittleLayout_mainSkittleIcon); if (drawable == null) { drawable = ContextCompat.getDrawable(context, R.drawable.ic_add_white_18dp); } } finally { array.recycle(); } skittleContainer = (SkittleContainer) LayoutInflater.from(context) .inflate(R.layout.skittle_container, this, false); SkittleAdapter skittleAdapter = new SkittleAdapter(color, drawable); skittleContainer.setLayoutManager( new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, true)); skittleContainer.setAdapter(skittleAdapter); skittleContainer.setItemAnimator(new ItemAnimator()); skittleContainer.addItemDecoration(new SkittleDecorator()); addView(skittleContainer); } @Override public void addView(View child) { super.addView(child); if (getChildCount() != 1 && !(child instanceof Snackbar.SnackbarLayout)) addSkittleOnTop(); } @Override public void addView(View child, int index) { super.addView(child, index); if (getChildCount() != 1 && !(child instanceof Snackbar.SnackbarLayout)) addSkittleOnTop(); } @Override public void addView(View child, int width, int height) { super.addView(child, width, height); if (getChildCount() != 1) addSkittleOnTop(); } @Override public void addView(View child, ViewGroup.LayoutParams params) { super.addView(child, params); if (getChildCount() != 1) addSkittleOnTop(); } /** * Utility method called after addView to ensure the skittle container is on top */ private void addSkittleOnTop() { detachViewFromParent(skittleContainer); attachViewToParent(skittleContainer, getChildCount(), skittleContainer.getLayoutParams()); } public SkittleAdapter getSkittleAdapter() { return (SkittleAdapter) skittleContainer.getAdapter(); } int fetchAccentColor(Context mContext) { TypedValue typedValue = new TypedValue(); TypedArray a = mContext.obtainStyledAttributes(typedValue.data, new int[] { R.attr.colorAccent }); int color = a.getColor(0, 0); a.recycle(); return color; } }
package com.foc.property.validators; import java.util.ArrayList; import java.util.Iterator; import com.foc.ConfigInfo; import com.foc.Globals; import com.foc.OptionDialog; import com.foc.desc.FocObject; import com.foc.list.FocList; import com.foc.property.FProperty; import com.foc.tree.FNode; import com.foc.util.ASCII; /** * @author 01Barmaja */ public class UniquePropertyValidator implements FPropertyValidator { private ArrayList<Character> specialCharactersArrayList = null; private final char CHAR_SPACE = ASCII.SPACE; private final char CHAR_DASH = ASCII.DASH; private final char CHAR_SLASH_RIGHT_TO_LEFT = ASCII.SLASH_RIGHT_TO_LEFT; private final char CHAR_SLASH_LEFT_TO_RIGHT = ASCII.SLASH_LEFT_TO_RIGHT; private final char CHAR_UNDER_SCORE = ASCII.UNDER_SCORE; private boolean validateOnlyIfDBResident = true; public void dispose() { if (specialCharactersArrayList != null) { for (int i = 0; i < specialCharactersArrayList.size(); i++) { specialCharactersArrayList.clear(); } specialCharactersArrayList = null; } } public boolean validateProperty(FProperty property) { newSpecialCharactersList(); FocObject focObject = (property != null ? property.getFocObject() : null); if (focObject != null) { if (focObject.getFatherSubject() instanceof FocList) { FocList list = (FocList) focObject.getFatherSubject(); if(list.isDbResident() || !isValidateOnlyIfDBResident()){ Iterator iter = list.newSubjectIterator(); int fieldID = property.getFocField().getID(); boolean found = false; boolean modified = false; String focObjectValueString = focObject.getPropertyString(fieldID).toUpperCase(); String focObjectValueStringModified = deleteSpecialCharactersFromString(focObjectValueString); while (iter != null && iter.hasNext() && !found) { FocObject focObjInList = (FocObject) iter.next(); String focObjectInListValueString = focObjInList.getPropertyString(fieldID).toUpperCase(); if (focObject != focObjInList) { if (focObjectValueString.equals(focObjectInListValueString)) { found = true; } else { focObjectInListValueString = deleteSpecialCharactersFromString(focObjectInListValueString); if (focObjectValueStringModified.equals(focObjectInListValueString)) { found = true; modified = true; } } } } if (found) { if (modified) { if (focObject.getPropertyString(fieldID).indexOf(FNode.NEW_ITEM) == -1) { UniqueWarningDialog optionDialog = new UniqueWarningDialog(property); Globals.popupDialog(optionDialog); } } else { if (focObject.getPropertyString(fieldID).indexOf(FNode.NEW_ITEM) == -1) { String title = "Alert"; String message = "Value '"+focObjectValueString+"' already exist."; if (ConfigInfo.isArabic()) { title = "تنبيه"; message = focObjectValueString + " : "+ "موجودة حاليا, يرجى تبديل الاختيار"; } OptionDialog dialog = new OptionDialog(title, message) { @Override public boolean executeOption(String optionName) { return false; } }; dialog.addOption("OK", ConfigInfo.isArabic() ? "نعم" : "Ok"); dialog.popup(); } property.setString(""); } } } } } return true; } public void newSpecialCharactersList() { specialCharactersArrayList = new ArrayList<Character>(); specialCharactersArrayList.add(CHAR_DASH); specialCharactersArrayList.add(CHAR_SPACE); specialCharactersArrayList.add(CHAR_SLASH_LEFT_TO_RIGHT); specialCharactersArrayList.add(CHAR_SLASH_RIGHT_TO_LEFT); specialCharactersArrayList.add(CHAR_UNDER_SCORE); } public ArrayList<Character> getSpecialCharactersArrayList() { return specialCharactersArrayList; } public boolean isSpecialCharacter(char c) { boolean found = false; for (int i = 0; i < getSpecialCharactersArrayList().size(); i++) { char specialChar = specialCharactersArrayList.get(i); if (specialChar == c) { found = true; } } return found; } public String deleteSpecialCharactersFromString(String str) { String newStr = new String(); if (str != null) { for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (!isSpecialCharacter(c)) { newStr += c; } } } return newStr; } public class UniqueWarningDialog extends OptionDialog { private FProperty property = null; public UniqueWarningDialog(FProperty property){ super("Similar value exist", "Value exist in other format.\n Do you want to keep it?"); this.property = property; addOption("YES", "Yes keep new item"); addOption("NO", "No cancel new item"); } @Override public boolean executeOption(String optionName) { if(optionName.equals("NO")){ property.setString(""); } return false; } } public boolean isValidateOnlyIfDBResident() { return validateOnlyIfDBResident; } public void setValidateOnlyIfDBResident(boolean checkOnlyIfDBResident) { this.validateOnlyIfDBResident = checkOnlyIfDBResident; } }
package io.sniffy.sql; import java.sql.*; import java.util.Properties; import java.util.logging.Logger; import static org.mockito.Mockito.spy; public class TestDriver implements Driver { private final static TestDriver INSTANCE = spy(new TestDriver()); static { load(); } private static void load() { try { DriverManager.registerDriver(INSTANCE); } catch (SQLException e) { e.printStackTrace(); } } public static TestDriver getSpy() { return INSTANCE; } @Override public Connection connect(String url, Properties info) throws SQLException { if (null == url || !acceptsURL(url)) return null; return DriverManager.getConnection(getTargetUrl(url), info); } private String getTargetUrl(String url) { return url.replaceAll("jdbc:h2spy:", "jdbc:h2:"); } @Override public boolean acceptsURL(String url) throws SQLException { return url.startsWith("jdbc:h2spy:"); } @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { return DriverManager.getDriver(getTargetUrl(url)).getPropertyInfo(getTargetUrl(url), info); } @Override public int getMajorVersion() { return 0; } @Override public int getMinorVersion() { return 0; } @Override public boolean jdbcCompliant() { return false; } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } }
package net.mueller_martin.turirun; import java.io.IOException; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.maps.MapProperties; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.Vector2; import com.esotericsoftware.kryonet.Client; import com.esotericsoftware.kryonet.Connection; import com.esotericsoftware.kryonet.Listener; import com.esotericsoftware.kryonet.Listener.ThreadedListener; import net.mueller_martin.turirun.gameobjects.*; import net.mueller_martin.turirun.network.TurirunNetwork; import net.mueller_martin.turirun.network.TurirunNetwork.Register; import net.mueller_martin.turirun.network.TurirunNetwork.AddCharacter; import net.mueller_martin.turirun.network.TurirunNetwork.UpdateCharacter; import net.mueller_martin.turirun.network.TurirunNetwork.MoveCharacter; import java.util.ArrayList; import java.util.List; import java.util.Collections; import java.util.Collections.*; public class WorldController { public final static String TAG = WorldController.class.getName(); public int mapPixelWidth = 300; public int mapPixelHeight = 300; Client client; public Turirun game; public ObjectController objs; public Level level; public CharacterController controller; public static List<Object> events; public WorldController(Turirun game) { this.game = game; this.objs = new ObjectController(); this.client = new Client(); // Create Character Input Controller controller = new CharacterController(); // Events WorldController.events = Collections.synchronizedList(new ArrayList<Object>()); this.init(); } // Start Game public void init() { CharacterObject playerObj = new CharacterObject(10, 10, 50, 50); this.objs.addObject(playerObj); controller.setPlayerObj(playerObj); // Spawn Checkpoint CheckpointGameObject checkpoint = new CheckpointGameObject(300, 300, 200, 200); this.objs.addObject(checkpoint); // Spawn Wall WallGameObject wall = new WallGameObject(100, 300, 80, 80); this.objs.addObject(wall); //map level = new Level(); MapProperties prop = level.map.getProperties(); int mapWidth = prop.get("width", Integer.class); int mapHeight = prop.get("height", Integer.class); System.out.println("mapWidth: " + mapWidth + ", " + "mapHeight: " + mapHeight); int tilePixelWidth = prop.get("tilewidth", Integer.class); int tilePixelHeight = prop.get("tileheight", Integer.class); System.out.println("tilePixelWidth: " + tilePixelWidth + ", " + "tilePixelHeight: " + tilePixelHeight); mapPixelWidth = mapWidth * tilePixelWidth; mapPixelHeight = mapHeight * tilePixelHeight; System.out.println("mapPixelWidth: " + mapPixelWidth + ", " + "mapPixelHeight: " + mapPixelHeight); this.client.start(); // For consistency, the classes to be sent over the network are registered by the same method for both the client and server TurirunNetwork.register(client); client.addListener(new ThreadedListener(new Listener() { public void connected(Connection connection) { } public void received(Connection connection, Object object) { WorldController.events.add(object); } public void disconnected(Connection connection) { } })); try { // Block for max. 3000ms client.connect(3000, "127.0.0.1", TurirunNetwork.tcpPort, TurirunNetwork.udpPort); // Server communication after connection can go here, or in Listener#connected() } catch (IOException e) { Gdx.app.error("Could not connect to server", e.getMessage()); } Register register = new Register(); register.nick = "Foo"; register.type = 1; client.sendTCP(register); } public void draw(SpriteBatch batch) { level.render(); for (GameObject obj: objs.getObjects()) { obj.draw(batch); } } public void update(float deltaTime) { // Input Update controller.update(deltaTime); // Netzwerk Update this.updateEvents(); if (client != null) { // FIXME: last and current postition are always equal //if (controller.character.currentPosition.x != controller.character.lastPosition.x || controller.character.currentPosition.y != controller.character.lastPosition.y) { MoveCharacter move = new MoveCharacter(); move.x = controller.character.currentPosition.x; move.y = controller.character.currentPosition.y; client.sendTCP(move); } } Camera cam = CameraHelper.instance.camera; // The camera dimensions, halved float cameraHalfWidth = cam.viewportWidth * .5f; float cameraHalfHeight = cam.viewportHeight * .5f; // Move camera after player as normal CameraHelper.instance.camera.position.set((int)controller.character.currentPosition.x,(int)controller.character.currentPosition.y,0); float cameraLeft = cam.position.x - cameraHalfWidth; float cameraRight = cam.position.x + cameraHalfWidth; float cameraBottom = cam.position.y - cameraHalfHeight; float cameraTop = cam.position.y + cameraHalfHeight; // Horizontal axis if(mapPixelWidth < cam.viewportWidth) { cam.position.x = mapPixelWidth / 2; } else if(cameraLeft <= 0) { cam.position.x = 0 + cameraHalfWidth; } else if(cameraRight >= mapPixelWidth) { cam.position.x = mapPixelWidth - cameraHalfWidth; } // Vertical axis if(mapPixelHeight < cam.viewportHeight) { cam.position.y = mapPixelHeight / 2; } else if(cameraBottom <= 0) { cam.position.y = 0 + cameraHalfHeight; } else if(cameraTop >= mapPixelHeight) { cam.position.y = mapPixelHeight - cameraHalfHeight; } // update objects for (GameObject obj: objs.getObjects()) { obj.update(deltaTime); resetIfOutsideOfMap(obj); } // check for collusion for (GameObject obj: objs.getObjects()) { for (GameObject collusionObj: objs.getObjects()) { if (obj == collusionObj) continue; if (obj.bounds.intersection(collusionObj.bounds)) { obj.isCollusion(collusionObj); } } } } private void resetIfOutsideOfMap(GameObject obj) { if (obj.currentPosition.x < 0) { System.out.println("x: " + obj.currentPosition.x + " " + mapPixelWidth); obj.currentPosition.x = 1; } if (obj.currentPosition.x + obj.size.x > mapPixelWidth) { System.out.println("x: " + obj.currentPosition.x + " " + mapPixelWidth); obj.currentPosition.x = mapPixelWidth - obj.size.x + 1; } if (obj.currentPosition.y < 0) { System.out.println("y: " + obj.currentPosition.y + " " + mapPixelHeight); obj.currentPosition.y = 1; } if (obj.currentPosition.y + obj.size.y> mapPixelHeight) { System.out.println("y: " + obj.currentPosition.y + " " + mapPixelHeight); obj.currentPosition.y = mapPixelHeight - obj.size.y; } } private void updateEvents() { ArrayList<Object> del = new ArrayList<Object>(); synchronized (WorldController.events) { for (Object event : WorldController.events) { // Add Player if (event instanceof AddCharacter) { AddCharacter msg = (AddCharacter)event; CharacterObject newPlayer = new CharacterObject(msg.character.x, msg.character.y, 50, 50); objs.addObject(msg.character.id, newPlayer); del.add(event); continue; } // Update Player if (event instanceof UpdateCharacter) { UpdateCharacter msg = (UpdateCharacter)event; CharacterObject player = (CharacterObject)objs.getObject(msg.id); player.currentPosition = new Vector2(msg.x, msg.y); } } } for (Object event : del) { WorldController.events.remove(event); } } }
package org.jboss.as.console.client.rbac; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import org.jboss.ballroom.client.rbac.SecurityContext; /** * @author Heiko Braun * @date 8/7/13 */ public class RBACUtil { public static SafeHtml dump(SecurityContext sc) { SafeHtmlBuilder html = new SafeHtmlBuilder(); SecurityContextImpl context = (SecurityContextImpl)sc; // required resource html.appendHtmlConstant("<h2>Resources References for: "+context.nameToken+"</h2>"); html.appendHtmlConstant("<h3>Required</h3>"); html.appendHtmlConstant("<ul>"); for(ResourceRef ref : context.requiredResources) { if(ref.optional) continue; html.appendHtmlConstant("<li>").appendEscaped(ref.address).appendHtmlConstant("</li>"); } html.appendHtmlConstant("</ul><p/>"); // optional resource html.appendHtmlConstant("<h3>Optional</h3>"); html.appendHtmlConstant("<ul>"); for(ResourceRef ref : context.requiredResources) { if(!ref.optional) continue; html.appendHtmlConstant("<li>").appendEscaped(ref.address).appendHtmlConstant("</li>"); } html.appendHtmlConstant("</ul><p/>"); html.appendHtmlConstant("<h2>Constraints</h2>"); for(String resource : context.accessConstraints.keySet()) { html.appendHtmlConstant("<h3>").appendEscaped(resource).appendHtmlConstant("</h3>"); Constraints constraints = context.accessConstraints.get(resource); html.appendHtmlConstant("<ul>"); html.appendHtmlConstant("<li>").appendEscaped("read-config:"+constraints.isReadResource()).appendHtmlConstant("</li>"); html.appendHtmlConstant("<li>").appendEscaped("write-config:"+constraints.isWriteResource()).appendHtmlConstant("</li>"); html.appendHtmlConstant("</ul>"); html.appendHtmlConstant("<p/>"); html.appendHtmlConstant("<h4>Attributes</h4>"); html.appendHtmlConstant("<table border='0' cellpadding='5'>"); html.appendHtmlConstant("<tr>"); html.appendHtmlConstant("<th>"); html.appendEscaped("Attribute Name"); html.appendHtmlConstant("</th>"); html.appendHtmlConstant("<th>"); html.appendEscaped("Read"); html.appendHtmlConstant("</th>"); html.appendHtmlConstant("<th>"); html.appendEscaped("Write"); html.appendHtmlConstant("</th>"); html.appendHtmlConstant("</tr>"); for(String att : constraints.attributePermissions.keySet()) { html.appendHtmlConstant("<tr>"); html.appendHtmlConstant("<td>"); html.appendEscaped(att); html.appendHtmlConstant("</td>"); html.appendHtmlConstant("<td>"); Constraints.AttributePerm attributePerm = constraints.attributePermissions.get(att); html.appendEscaped(String.valueOf(attributePerm.isRead())); html.appendHtmlConstant("</td>"); html.appendHtmlConstant("<td>"); html.appendEscaped(String.valueOf(attributePerm.isWrite())); html.appendHtmlConstant("</td>"); html.appendHtmlConstant("</tr>"); } html.appendHtmlConstant("</table>"); html.appendHtmlConstant("<p/>"); html.appendHtmlConstant("<h4>Operations</h4>"); html.appendHtmlConstant("<table border='0' cellpadding='5'>"); html.appendHtmlConstant("<tr>"); html.appendHtmlConstant("<th>"); html.appendEscaped("Operation Name"); html.appendHtmlConstant("</th>"); html.appendHtmlConstant("<th>"); html.appendEscaped("Exec"); html.appendHtmlConstant("</th>"); html.appendHtmlConstant("</tr>"); if(!constraints.execPermission.isEmpty()) { for(String op : constraints.execPermission.get(resource)) { html.appendHtmlConstant("<tr>"); html.appendHtmlConstant("<td>"); html.appendEscaped(op); html.appendHtmlConstant("</td>"); html.appendHtmlConstant("<td>"); html.appendEscaped(String.valueOf(constraints.isOperationExec(resource, op))); html.appendHtmlConstant("</td>"); html.appendHtmlConstant("</tr>"); } } html.appendHtmlConstant("</table>"); } return html.toSafeHtml(); } }
package ai.h2o.automl.transforms; import org.reflections.Reflections; import water.Key; import water.fvec.TransformWrappedVec; import water.fvec.Vec; import water.rapids.AST; import water.rapids.ASTUniOp; import water.rapids.Exec; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; /** * Stupid class just to get the proverbial ball rolling. * Eventually, will want to javassist (i.e. fuse) transforms over multiple vecs * (rather than 1 at a time, which is the current limitation of this class). * * A pile of heuristics (rules) and models drive the choice of transforms by the column to * be transformed. The set of transforms (in the String[] ops) are the names of the AST * operations * * Here are the features that are currently going to be generated: * 1. apply unary op to a single column * 2. multiply/add/subtract/divide two columns * 3. interact two columns (R style interaction) */ public class Transform { public static final String[] uniOps; static { List<String> ops = new ArrayList<>(); Reflections reflections = new Reflections("water.rapids"); Set<Class<? extends ASTUniOp>> uniOpClasses = reflections.getSubTypesOf(water.rapids.ASTUniOp.class); for(Class c: uniOpClasses) ops.add(c.getSimpleName().substring("AST".length())); ops.add("Ignore"); ops.add("Impute"); ops.add("Cut"); // Ignore means do not include.. no transformation necessary! uniOps = ops.toArray(new String[ops.size()]); } public static void printOps() { for(String op: uniOps) System.out.println(op); } // for AutoCollect type scenario: // 1. decide if situation 1, 2, or 3 // 2. "apply" the transformation (push the transformed vec onto the pile) } class Expr implements Cloneable { private ArrayList<Expr> _exprs; // dag private String _op; // opcode string ("+", "log", etc.) static final String ARGPREFIX="x"; // the arg prefix { x1 x2 x3 . static HashMap<Key, String> _argNames = new HashMap<>(); // mapping of Vec keys to arg names static AtomicInteger _argCnter = new AtomicInteger(0); // argument counter, for labeling args nicely protected Vec _anyVec; // any random vec to be used for constructing the TransformWrappedVec static ArrayList<Key<Vec>> _vecs = new ArrayList<>(); // order of vecs, used for TransformWrappedVec making protected Expr() {} private Expr(String op, Expr... exprs) { compose(op, exprs); } public static Expr binOp(String op, Expr l, Expr r) { return new Expr(op,l,r); } public static Expr binOp(String op, Expr l, Vec r) { return new Expr(op,l, new ExprVec(r)); } public static Expr binOp(String op, Expr l, double r) { return new Expr(op,l, new ExprNum(r)); } public static Expr binOp(String op, Vec l, Expr r) { return new Expr(op, new ExprVec(l),r); } public static Expr binOp(String op, Vec l, Vec r) { return new Expr(op, new ExprVec(l), new ExprVec(r)); } public static Expr binOp(String op, Vec l, double r) { return new Expr(op, new ExprVec(l),new ExprNum(r)); } public static Expr binOp(String op, double l, Expr r) { return new Expr(op, new ExprNum(l),r); } public static Expr binOp(String op, double l, Vec r) { return new Expr(op, new ExprNum(l), new ExprVec(r)); } // op(double, double) is not interesting... public static Expr unOp(String op, Expr e) { return new Expr(op, e); } public static Expr unOp(String op, Vec v) { return new Expr(op, new ExprVec(v)); } private void compose(String op, Expr... exprs) { ArrayList<Expr> exprz = new ArrayList<>(); Collections.addAll(exprz, exprs); _op=op; _exprs=exprz; } @Override protected Expr clone() { Expr e = new Expr(); e._op = _op; e._exprs = new ArrayList<>(); for(Expr expr: _exprs) e._exprs.add(expr.clone()); return e; } public void bop(String op, Expr l, Expr r) { boolean left; if( (left=this!=r) && this!=l ) throw new IllegalArgumentException("expected this expr to appear in arguments."); compose(op,left?clone():l,left?r:clone()); } public void bop(String op, Expr l, Vec r) { if( this!=l ) throw new IllegalArgumentException("expected expr to appear in args"); compose(op,clone(),new ExprVec(r)); } public void bop(String op, Expr l, double r) { if( this!=l ) throw new IllegalArgumentException("expected expr to appear in args"); compose(op,clone(),new ExprNum(r)); } public void bop(String op, Vec l, Expr r) { if( this!=r ) throw new IllegalArgumentException("expected expr to appear in args"); compose(op,new ExprVec(l),clone()); } public void bop(String op, double l, Expr r) { if( this!=r ) throw new IllegalArgumentException("expected expr to appear in args"); compose(op,new ExprNum(l),clone()); } // op(double, double) is not interesting... public void uop(String op) { compose(op,clone()); } /** * Construct a Rapids expression! * @return String that is a rapids expression */ public String toRapids() { _argCnter.set(0); _argNames.clear(); _vecs.clear(); assignArgs(); _anyVec = _vecs.get(0).get(); StringBuilder sb = constructArgs(); return sb.append(asRapids()).append("}").toString(); } public TransformWrappedVec toWrappedVec() { AST fun = new Exec(toRapids()).parse(); return new TransformWrappedVec(_anyVec.group().addVec(), _anyVec._rowLayout, fun, _vecs.toArray(new Key[_vecs.size()])); } private StringBuilder constructArgs() { StringBuilder sb = new StringBuilder("{"); for(int i=1;i<=_argCnter.get();++i) sb.append(" ").append(ARGPREFIX).append(i); sb.append(" ").append(".").append(" "); return sb; } protected StringBuilder asRapids() { StringBuilder sb = new StringBuilder("("); sb.append(_op); for(Expr expr: _exprs) sb.append(" ").append(expr.asRapids()); sb.append(")"); return sb; } protected void assignArgs() { for(Expr expr: _exprs) expr.assignArgs(); } } class ExprNum extends Expr { double _d; ExprNum(double d) { _d=d; } @Override protected StringBuilder asRapids() { return new StringBuilder(""+_d); } @Override protected void assignArgs() { } @Override protected ExprNum clone() { return new ExprNum(_d); } } class ExprVec extends Expr { Vec _v; String _argName; ExprVec(Vec v) { _v=v; } @Override protected StringBuilder asRapids() { return new StringBuilder(_argName); } @Override protected void assignArgs() { _argName = _argNames.get(_v._key); if( null==_argName ) { _argNames.put(_v._key, _argName = ARGPREFIX + _argCnter.incrementAndGet()); _vecs.add(_v._key); } } @Override protected ExprVec clone() { return new ExprVec(_v); } }
package hex.genmodel.algos; import deepwater.backends.BackendModel; import deepwater.backends.BackendParams; import deepwater.backends.BackendTrain; import deepwater.backends.RuntimeOptions; import deepwater.datasets.ImageDataSet; import hex.genmodel.GenModel; import hex.genmodel.MojoModel; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Map; import java.util.UUID; public class DeepWaterMojo extends MojoModel { public final int _mini_batch_size; public final int _height; public final int _width; public final int _channels; public final int _nums; public final int _cats; public final int[] _catOffsets; public final double[] _normMul; public final double[] _normSub; public final boolean _useAllFactorLevels; final protected byte[] _network; final protected byte[] _parameters; final BackendTrain _backend; //interface provider final BackendModel _model; //pointer to C++ process final ImageDataSet _imageDataSet; //interface provider final RuntimeOptions _opts; final BackendParams _backendParams; public DeepWaterMojo(MojoReader cr, Map<String, Object> info, String[] columns, String[][] domains) { super(cr, info, columns, domains); try { _network = _reader.getBinaryFile("model.network"); } catch (IOException e) { throw new RuntimeException(e); } try { _parameters = _reader.getBinaryFile("model.params"); } catch (IOException e) { throw new RuntimeException(e); } _backend = createDeepWaterBackend((String)info.get("backend")); // new ImageTrain(_width, _height, _channels, _deviceID, (int)parameters.getOrMakeRealSeed(), _gpu); _mini_batch_size = (int)info.get("mini_batch_size"); _height = (int)info.get("height"); _width = (int)info.get("width"); _channels = (int)info.get("channels"); _nums = (int)info.get("nums"); _cats = (int)info.get("cats"); _catOffsets = (int[])info.get("catOffsets"); _normMul = (double[])info.get("normMul"); _normSub = (double[])info.get("normSub"); _useAllFactorLevels = (boolean)info.get("useAllFactorLevels"); _imageDataSet = new ImageDataSet(_width, _height, _channels); // float[] meanData = _backend.loadMeanImage(_model, (String)info.get("mean_image_file")); // if(meanData.length > 0) { // _imageDataSet.setMeanData(meanData); _opts = new RuntimeOptions(); _opts.setSeed(0); // ignored _opts.setUseGPU(false); // don't use a GPU for inference _opts.setDeviceID(0); // ignored _backendParams = new BackendParams(); _backendParams.set("mini_batch_size", 1); File file = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString() + ".json"); try { FileOutputStream os = new FileOutputStream(file.toString()); os.write(_network); os.close(); } catch (IOException e) { e.printStackTrace(); } _model = _backend.buildNet(_imageDataSet, _opts, _backendParams, _nclasses, file.toString()); file = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); try { FileOutputStream os = new FileOutputStream(file.toString()); os.write(_parameters); os.close(); } catch (IOException e) { e.printStackTrace(); } _backend.loadParam(_model, file.toString()); } /** * Corresponds to `hex.DeepWater.score0()` */ @Override public final double[] score0(double[] doubles, double offset, double[] preds) { assert(doubles != null) : "doubles are null"; float[] floats = null; int cats = _catOffsets == null ? 0 : _catOffsets[_cats]; if (_nums > 0) floats = new float[_nums + cats]; //TODO: use thread-local storage else floats = new float[_width*_height*_channels]; //TODO: use thread-local storage GenModel.setInput(doubles, floats, _nums, _cats, _catOffsets, _normMul, _normSub, _useAllFactorLevels); // System.err.println(Arrays.toString(doubles)); // System.err.println(Arrays.toString(floats)); float[] predFloats = _backend.predict(_model, floats); assert(_nclasses>=2) : "Only classification is supported right now."; assert(_nclasses == predFloats.length) : "nclasses " + _nclasses + " predFloats.length " + predFloats.length; for (int i=0; i<predFloats.length; ++i) preds[1+i] = predFloats[i]; preds[0] = GenModel.getPrediction(preds, _priorClassDistrib, doubles, _defaultThreshold); return preds; } @Override public double[] score0(double[] row, double[] preds) { return score0(row, 0.0, preds); } static public BackendTrain createDeepWaterBackend(String backend) { try { if (backend.equals("mxnet")) backend="deepwater.backends.mxnet.MXNetBackend"; if (backend.equals("tensorflow")) backend="deepwater.backends.tensorflow.TensorFlowBackend"; return (BackendTrain)(Class.forName(backend).newInstance()); } catch (Throwable e) {} return null; } }
package core; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.PreparedStatement; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import connection.DBMSConnection; import core.test.GeneratorTest; import basicDatatypes.*; import org.apache.log4j.Level; import org.apache.log4j.Logger; import utils.Statistics; public class Generator { private DBMSConnection dbmsConn; private RandomDBValuesGenerator random; private Distribution distribution; private static Logger logger = Logger.getLogger(GeneratorTest.class.getCanonicalName()); // Internal state private Map<String, Queue<ResultSet>> chasedValues; // Pointers to ResultSets storing chased values for each column private Map<String, ResultSet> duplicateValues; // Pointers to ResultSets storing duplicate values for each column public Generator(DBMSConnection dbmsConn){ this.dbmsConn = dbmsConn; random = new RandomDBValuesGenerator(); this.distribution = new Distribution(dbmsConn); chasedValues = new HashMap<String, Queue<ResultSet>>(); duplicateValues = new HashMap<String, ResultSet>(); logger.setLevel(Level.INFO); } /** * @author tir * @param tableName * @param domainIndependentCols : May be null, and it specifies what columns HAVE TO be considered as domainIndependent. * @param duplicateRatio : Probability of generating a duplicate value while populating the columns * * Pump the table, column by column. Each element will be randomly chosen * according to the distribution of the database. Primary keys, instead, will * be newly generated * * Domain independent columns will be generated by taking values from the domain * (that is retrieved by a projection on the database column * -- therefore I assume that the db is NON-EMPTY [as in FactPages]) * * Domain independent columns can also be inferred, by looking at the projection and comparing it * against the total number of tuples in the table <b>tableName</b> */ public List<Schema> pumpTable(int nRows, Schema schema){ // INIT chasedValues.clear(); duplicateValues.clear(); Map<String, Integer> mNumChases = new HashMap<String, Integer>(); // It holds the number of chased elements for each column Map<String, Integer> mNumDuplicates = new HashMap<String, Integer>(); // It holds the number of duplicates that have to be inserted Map<String, Integer> mNumDuplicatesFromFresh = new HashMap<String, Integer>(); // It holds the number of duplicates Map<String, Integer> mFreshGenerated = new HashMap<String, Integer>(); // It keeps fresh generated values, column by column Map<String, Queue<String>> mFreshDuplicates = new HashMap<String, Queue<String>>(); // TODO Is this too much memory consuming? // Fill chased for( Column column : schema.getColumns() ){ chasedValues.put(column.getName(), fillChase(column, schema.getTableName(), mNumChases)); column.incrementCurrentChaseCycle(); mFreshGenerated.put(column.getName(), 0); mFreshDuplicates.put(column.getName(), new LinkedList<String>()); } if( nRows == 0 ){ // This is a pure-chase phase. And it is also THE ONLY place where I need to chase // I need to generate (at least) as many rows as the maximum among the chases int max = 0; for( String key: mNumChases.keySet() ){ if( max < mNumChases.get(key) ) max = mNumChases.get(key); } nRows = max; // Set the number of rows that need to be inserted. } // Fill duplicates for( Column column : schema.getColumns() ){ duplicateValues.put(column.getName(), fillDuplicates(column, schema.getTableName(), nRows, mNumDuplicates, mNumDuplicatesFromFresh)); } Map<String, ResultSet> referencedValues = new HashMap<String, ResultSet>(); List<Schema> tablesToChase = new LinkedList<Schema>(); String templateInsert = dbmsConn.createInsertTemplate(schema); PreparedStatement stmt = null; try { stmt = dbmsConn.getPreparedStatement(templateInsert); logger.debug(templateInsert); // Disable auto-commit dbmsConn.setAutoCommit(false); // TODO The max_cycle thing // Idea: I can say that nRows = number of things that need to be chased, when the maximum // cycle is reached. To test this out for( int j = 1; j <= nRows; ++j ){ int columnIndex = 0; for( Column column : schema.getColumns() ){ boolean stopChase = (column.referencesTo().size() > 0) && column.getMaximumChaseCycles() < column.getCurrentChaseCycle(); if( mNumChases.containsKey(column.getName()) && canAdd(nRows, j, mNumChases.get(column.getName())) ) { dbmsConn.setter(stmt, ++columnIndex, column.getType(), pickNextChased(schema, column)); // Ensures to put all chased elements, in a uniform way w.r.t. other columns } else if( canAdd(nRows, j, mNumDuplicates.get(column.getName()) ) ){ Statistics.addInt(schema.getTableName()+"."+column.getName()+" canAdd", 1); String nextDuplicate = pickNextDupFromOldValues(schema, column, (column.getCurrentChaseCycle() > column.getMaximumChaseCycles())); if( nextDuplicate == null ){ // Necessary to start picking duplicates from freshly generated values if( !mFreshDuplicates.containsKey(column.getName()) ) logger.error("No fresh duplicates available for column "+column.getName() ); nextDuplicate = mFreshDuplicates.get(column.getName()).poll(); logger.debug("Polling"); if( nextDuplicate == null ) { logger.error("No good poll action"); } } dbmsConn.setter(stmt, ++columnIndex, column.getType(), nextDuplicate); // Ensures to put all chased elements, in a uniform way w.r.t. other columns } else if( stopChase ){ // We cannot take a chase value, neither we can pick a duplicate. The only way out is // to tale the necessary number of elements (non-duplicate with this column) from the referenced column(s) dbmsConn.setter(stmt, ++columnIndex, column.getType(), pickFromReferenced(schema, column, referencedValues)); } else{ // Add a random value; if I want to duplicate afterwards, keep it in freshDuplicates list String generatedRandom = random.getRandomValue(column, nRows); dbmsConn.setter(stmt, ++columnIndex, column.getType(), generatedRandom); Statistics.addInt(schema.getTableName()+"."+column.getName()+" fresh values", 1); // Add the random value to the "toInsert" duplicates int freshGenerated = mFreshGenerated.get(column.getName()); if( freshGenerated++ < mNumDuplicatesFromFresh.get(column.getName()) ){ logger.debug(mNumDuplicatesFromFresh.get(column.getName())); mFreshGenerated.put(column.getName(), freshGenerated); mFreshDuplicates.get(column.getName()).add(generatedRandom); } // New values inserted imply new column to chase for( QualifiedName qN : column.referencesTo() ){ if( !tablesToChase.contains(dbmsConn.getSchema(qN.getTableName())) ){ tablesToChase.add(dbmsConn.getSchema(qN.getTableName())); } } } } stmt.addBatch(); if( j % 1000000 == 0 ){ // Let's put a limit to the dimension of the stmt stmt.executeBatch(); dbmsConn.commit(); } } stmt.executeBatch(); dbmsConn.commit(); } catch (SQLException e) { logger.error(e.getMessage()); e.printStackTrace(); } dbmsConn.setAutoCommit(true); return tablesToChase; } /** * This method, for the moment, assumes that it is possible * to reference AT MOST 1 TABLE. * NOT VERY EFFICIENT. If slow, then refactor as the others * @param schema * @param column * @return */ private String pickFromReferenced(Schema schema, Column column, Map<String, ResultSet> referencedValues) { String result = null; if( !referencedValues.containsKey(column.getName()) ){ // SELECT referencedColumn FROM referencedTable WHERE referencedColumn NOT IN (select thisColumn from thisTable) Template templ = new Template("SELECT DISTINCT ? FROM ? WHERE ? NOT IN (SELECT ? FROM ?)"); if( !column.referencesTo().isEmpty() ){ QualifiedName refQN = column.referencesTo().get(0); templ.setNthPlaceholder(1, refQN.getColName()); templ.setNthPlaceholder(2, refQN.getTableName()); templ.setNthPlaceholder(3, refQN.getColName()); templ.setNthPlaceholder(4, column.getName()); templ.setNthPlaceholder(5, schema.getTableName()); } else{ logger.error("Cannot access a referenced field"); } PreparedStatement stmt = dbmsConn.getPreparedStatement(templ); try { referencedValues.put(column.getName(), stmt.executeQuery()); } catch (SQLException e) { e.printStackTrace(); } } ResultSet rs = referencedValues.get(column.getName()); try { if( !rs.next() ){ logger.error("Not possible to add a non-duplicate value"); throw new SQLException(); } result = rs.getString(1); } catch (SQLException e) { e.printStackTrace(); } return result; } private ResultSet fillDuplicates(Column column, String tableName, int nRowsToInsert, Map<String, Integer> mNumDuplicates, Map<String, Integer> mNumDuplicatesFromFresh) { ResultSet result = null; float ratio; // Ratio of the duplicates boolean maxChaseReached = false; // If generating fresh values will lead to a chase, and the maximum number of chases is reached if( (column.referencesTo().size() > 0) && column.getMaximumChaseCycles() < column.getCurrentChaseCycle() ){ // It has NOT to produce fresh values // However, if the field is a allDifferent() then I cannot close the chase with a duplicate if( column.isAllDifferent() ){ mNumDuplicates.put(column.getName(), 0); mNumDuplicatesFromFresh.put(column.getName(), 0); return null; // Either no duplicates or no row at all } // Else, it is ok to close the cycle with a duplicate ratio = 1; maxChaseReached = true; } else{ // First of all, I need to understand the distribution of duplicates. Window analysis! ratio = distribution.naiveStrategy(column.getName(), tableName); Statistics.addFloat(tableName+"."+column.getName()+" dups ratio", ratio); } if( (ratio == 0) && !maxChaseReached){ // Is not( maxChaseReached ) necessary here? mNumDuplicates.put(column.getName(), 0); mNumDuplicatesFromFresh.put(column.getName(), 0); return null; // Either no duplicates or no row at all } int curRows = distribution.nRows(column.getName(), tableName); int curDuplicates = (curRows - distribution.sizeProjection(column.getName(), tableName)); // This is the total number of duplicates that have to be in the final table int nDups = maxChaseReached ? nRowsToInsert + curDuplicates : (int)((nRowsToInsert + curRows) * ratio); Statistics.addInt(tableName+"."+column.getName()+"final total dups", nDups); int toAddDups = nDups - curDuplicates; Statistics.addInt(tableName+"."+column.getName()+"to add dups", toAddDups); mNumDuplicates.put(column.getName(), toAddDups); // Now, establish how many rows I want to take from the current content int nDupsFromCurCol = /*Math.round*/(int)((curRows / (curRows + nRowsToInsert)) * ratio); if( maxChaseReached ) nDupsFromCurCol = toAddDups; // And how many rows I want to take from fresh randomly generated values. mNumDuplicatesFromFresh.put(column.getName(), toAddDups - nDupsFromCurCol); // Point to the rows that I want to duplicate if( curRows <= nDupsFromCurCol ){ logger.debug("curRows= "+curRows+", nDupsFromCol= "+nDupsFromCurCol); nDupsFromCurCol = curRows; // Just take all of them. } int indexMin = curRows - nDupsFromCurCol == 0 ? 0 : random.getRandomInt(curRows - nDupsFromCurCol); String queryString = "SELECT "+column.getName()+ " FROM "+tableName+" LIMIT "+indexMin+", "+nDupsFromCurCol; try{ PreparedStatement stmt = dbmsConn.getPreparedStatement(queryString); result = stmt.executeQuery(); } catch (SQLException e) { e.printStackTrace(); } return result; } /** * Side effect on <b>numChased</b> * @param column * @param tableName * @param numChased * @return */ private Queue<ResultSet> fillChase(Column column, String tableName, Map<String, Integer> mNumChases) { Queue<ResultSet> result = new LinkedList<ResultSet>(); // SELECT referredByCol FROM referredByTable WHERE referredByCol NOT IN (SELECT column.name() FROM schema.name()); Template query = new Template("SELECT DISTINCT ? FROM ? WHERE ? NOT IN (SELECT ? FROM ?)"); Template queryCount = new Template("SELECT COUNT(DISTINCT ?) FROM ? WHERE ? NOT IN (SELECT ? FROM ?)"); for( QualifiedName referencedBy : column.referencedBy() ){ // Fill the query query.setNthPlaceholder(1,referencedBy.getColName()); query.setNthPlaceholder(2, referencedBy.getTableName()); query.setNthPlaceholder(3, referencedBy.getColName()); query.setNthPlaceholder(4, column.getName()); query.setNthPlaceholder(5, tableName); queryCount.setNthPlaceholder(1,referencedBy.getColName()); queryCount.setNthPlaceholder(2, referencedBy.getTableName()); queryCount.setNthPlaceholder(3, referencedBy.getColName()); queryCount.setNthPlaceholder(4, column.getName()); queryCount.setNthPlaceholder(5, tableName); try { PreparedStatement stmt = dbmsConn.getPreparedStatement(query); ResultSet rs = stmt.executeQuery(); result.add(rs); PreparedStatement stmt1 = dbmsConn.getPreparedStatement(queryCount); ResultSet rs1 = stmt1.executeQuery(); if(rs1.next()){ if(mNumChases.containsKey(column.getName())){ mNumChases.put(column.getName(), mNumChases.get(column.getName()) + rs.getInt(1)); // Add to the current value } else{ mNumChases.put(column.getName(), rs1.getInt(1)); // Create a new entry for the column } } else{ logger.error("Empty resultset."); } } catch (SQLException e) { e.printStackTrace(); } } return result; } /** * * @param schema * @param column * @param force It forces to pick an element even if the cursor already reached the end * @return */ private String pickNextDupFromOldValues(Schema schema, Column column, boolean force) { ResultSet duplicatesToInsert = duplicateValues.get(column.getName()); if(duplicatesToInsert == null) return null; String result = null; try { boolean hasNext = duplicatesToInsert.next(); if( !hasNext && force ){ duplicatesToInsert.beforeFirst(); if( !duplicatesToInsert.next() ) logger.error("No duplicate element can be forced"); } else if( !hasNext && !force ){ return null; } result = duplicatesToInsert.getString(1); } catch (SQLException e) { e.printStackTrace(); } return result; } private String pickNextChased(Schema schema, Column column) { Queue<ResultSet> chased = chasedValues.get(column.getName()); ResultSet curSet = chased.peek(); if(curSet == null){ // This shall not happen logger.debug("Problem: Picked a null in chased vector"); return null; } try { if(curSet.next()){ return curSet.getString(1); } else{ // Pick next ResultSet chased.poll(); curSet = chased.peek(); if(curSet == null ) return null; if( curSet.next() == false ) logger.debug("Problem: No element in a non-empty ResultSet"); curSet.getString(1); } } catch (SQLException e) { e.printStackTrace(); } return null; } private boolean canAdd(int total, int current, int modulo) { if(modulo == 0) return false; // if(current == total-1 && modulo != 0) return true; float thing = (float)current % ((float)total / (float)modulo); logger.debug(thing); return thing < 1; } };
package org.hudsonci.inject; import com.google.inject.Binder; import com.google.inject.Module; import org.hudsonci.inject.internal.SmoothieContainerBootstrap; import org.junit.After; import org.junit.Before; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Support for inject tests. * * @author <a href="mailto:jason@planet57.com">Jason Dillon</a> */ public abstract class TestSupport implements Module { protected final Logger log = LoggerFactory.getLogger(getClass()); @Before public void setUp() throws Exception { new SmoothieContainerBootstrap().bootstrap(getClass().getClassLoader(), Smoothie.class, getClass()); } public void configure(final Binder binder) { // nop } @After public void tearDown() throws Exception { SmoothieUtil.reset(); } }
package com.ray3k.skincomposer.dialog; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.ui.Button; import com.badlogic.gdx.scenes.scene2d.ui.Dialog; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.ui.TextField; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.scenes.scene2d.utils.FocusListener; import com.badlogic.gdx.utils.Align; import com.ray3k.skincomposer.Main; import com.ray3k.skincomposer.Spinner; import com.ray3k.skincomposer.Spinner.SpinnerStyle; import com.ray3k.skincomposer.data.AtlasData; import com.ray3k.skincomposer.data.ProjectData; import com.ray3k.skincomposer.panel.PanelPreviewProperties; import com.ray3k.skincomposer.panel.PanelStatusBar; import com.ray3k.skincomposer.utils.Utils; public class DialogSettings extends Dialog { private Skin skin; private SpinnerStyle spinnerStyle; private Integer textureWidth; private Integer textureHeight; private Integer maxUndos; public DialogSettings(String title, Skin skin, String windowStyleName) { super(title, skin, windowStyleName); Main.instance.setListeningForKeys(false); this.skin = skin; spinnerStyle = new Spinner.SpinnerStyle(skin.get("spinner-minus", Button.ButtonStyle.class), skin.get("spinner-plus", Button.ButtonStyle.class), skin.get("spinner", TextField.TextFieldStyle.class)); textureWidth = ProjectData.instance().getMaxTextureWidth(); textureHeight = ProjectData.instance().getMaxTextureHeight(); maxUndos = ProjectData.instance().getMaxUndos(); setFillParent(true); populate(); } @Override protected void result(Object object) { super.result(object); if ((boolean) object) { ProjectData.instance().setChangesSaved(false); ProjectData.instance().setMaxTextureDimensions(textureWidth, textureHeight); ProjectData.instance().setMaxUndos(maxUndos); Main.instance.clearUndoables(); } } @Override public boolean remove() { Main.instance.setListeningForKeys(true); PanelStatusBar.instance.message("Settings Updated"); return super.remove(); } public void populate() { Table t = getContentTable(); Label label = new Label("Settings", skin, "title"); label.setAlignment(Align.center); t.add(label).growX().colspan(2); t.row(); TextButton textButton = new TextButton("Open temp/log directory", skin, "orange-small"); textButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { try { Utils.openFileExplorer(Gdx.files.local("temp/")); } catch (Exception e) { Gdx.app.error(getClass().getName(), "Error opening temp folder", e); } } }); t.add(textButton).colspan(2); t.row(); textButton = new TextButton("Open preferences directory", skin, "orange-small"); textButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { try { Utils.openFileExplorer(Gdx.files.external(".prefs/")); } catch (Exception e) { Gdx.app.error(getClass().getName(), "Error opening temp folder", e); } } }); t.add(textButton).colspan(2); if (ProjectData.instance().areChangesSaved() && ProjectData.instance().getSaveFile().exists()) { t.row(); textButton = new TextButton("Open project/import directory", skin, "orange-small"); textButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { try { Utils.openFileExplorer(ProjectData.instance().getSaveFile().sibling(ProjectData.instance().getSaveFile().nameWithoutExtension() + "_data")); } catch (Exception e) { Gdx.app.error(getClass().getName(), "Error opening temp folder", e); } } }); t.add(textButton).colspan(2); } t.row(); textButton = new TextButton("Repack Texture Atlas", skin, "orange-small"); textButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { Main.instance.showDialogLoading(() -> { try { AtlasData.getInstance().writeAtlas(); AtlasData.getInstance().atlasCurrent = true; PanelPreviewProperties.instance.produceAtlas(); PanelPreviewProperties.instance.render(); } catch (Exception e) { Main.instance.showDialogError("Error", "Unable to write texture atlas to temporary storage!", null); Gdx.app.error(getClass().getName(), "Unable to write texture atlas to temporary storage!", e); } }); } }); t.add(textButton).colspan(2); t.row(); label = new Label("Max Texture Width: ", skin); t.add(label).right(); Spinner spinner = new Spinner(ProjectData.instance().getMaxTextureWidth(), 1.0, true, spinnerStyle); spinner.setMinimum(256.0); spinner.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { textureWidth = (int) spinner.getValue(); } }); spinner.addListener(new FocusListener() { @Override public void keyboardFocusChanged(FocusListener.FocusEvent event, Actor actor, boolean focused) { textureWidth = (int) spinner.getValue(); } }); t.add(spinner).minWidth(150.0f).left(); t.row(); label = new Label("Max Texture Height: ", skin); t.add(label).right(); Spinner spinner2 = new Spinner(ProjectData.instance().getMaxTextureHeight(), 1.0, true, spinnerStyle); spinner2.setMinimum(256.0); spinner2.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { textureWidth = (int) spinner2.getValue(); } }); spinner2.addListener(new FocusListener() { @Override public void keyboardFocusChanged(FocusListener.FocusEvent event, Actor actor, boolean focused) { textureWidth = (int) spinner2.getValue(); } }); t.add(spinner2).minWidth(150.0f).left(); t.row(); label = new Label("Max Number of Undos: ", skin); t.add(label).right(); Spinner spinner3 = new Spinner(ProjectData.instance().getMaxUndos(), 1.0, true, spinnerStyle); spinner3.setMinimum(1.0); spinner3.setMaximum(100.0); spinner3.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { maxUndos = (int) spinner3.getValue(); } }); spinner3.addListener(new FocusListener() { @Override public void keyboardFocusChanged(FocusListener.FocusEvent event, Actor actor, boolean focused) { maxUndos = (int) spinner3.getValue(); } }); t.add(spinner3).minWidth(150.0f).left(); button("OK", true); button ("Cancel", false); key(Keys.ESCAPE, false); } }
package com.gaiagps.iburn.adapters; import android.location.Location; import android.text.Spannable; import android.text.SpannableString; import android.text.style.TextAppearanceSpan; import android.view.View; import android.widget.AdapterView; import android.widget.TextView; import android.widget.Toast; import com.gaiagps.iburn.Constants; import com.gaiagps.iburn.Geo; import com.gaiagps.iburn.R; import com.gaiagps.iburn.api.typeadapter.PlayaDateTypeAdapter; import com.gaiagps.iburn.database.DataProvider; import com.gaiagps.iburn.database.PlayaDatabase; import com.gaiagps.iburn.database.PlayaItemTable; import com.squareup.sqlbrite.SqlBrite; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; public class AdapterUtils { public static final ArrayList<String> sEventTypeAbbreviations = new ArrayList<>(); public static final ArrayList<String> sEventTypeNames = new ArrayList<>(); public static final ArrayList<String> sDayAbbreviations = new ArrayList<>(); public static final ArrayList<String> sDayNames = new ArrayList<>(); static { sDayNames.add("All Days"); sDayAbbreviations.add(null); sDayNames.add("Monday 8/25"); sDayAbbreviations.add("8/25"); sDayNames.add("Tuesday 8/26"); sDayAbbreviations.add("8/26"); sDayNames.add("Wednesday 8/27"); sDayAbbreviations.add("8/27"); sDayNames.add("Thursday 8/28"); sDayAbbreviations.add("8/28"); sDayNames.add("Friday 8/29"); sDayAbbreviations.add("8/29"); sDayNames.add("Saturday 8/30"); sDayAbbreviations.add("8/30"); sDayNames.add("Sunday 8/31"); sDayAbbreviations.add("8/31"); sDayNames.add("Monday 9/1"); sDayAbbreviations.add("9/1"); sDayNames.add("Tuesday 9/2"); sDayAbbreviations.add("9/2"); sEventTypeAbbreviations.add("work"); sEventTypeNames.add("Work"); sEventTypeAbbreviations.add("game"); sEventTypeNames.add("Game"); sEventTypeAbbreviations.add("adlt"); sEventTypeNames.add("Adult"); sEventTypeAbbreviations.add("prty"); sEventTypeNames.add("Party"); sEventTypeAbbreviations.add("perf"); sEventTypeNames.add("Performance"); sEventTypeAbbreviations.add("kid"); sEventTypeNames.add("Kid"); sEventTypeAbbreviations.add("food"); sEventTypeNames.add("Food"); sEventTypeAbbreviations.add("cere"); sEventTypeNames.add("Ceremony"); sEventTypeAbbreviations.add("care"); sEventTypeNames.add("Care"); sEventTypeAbbreviations.add("fire"); sEventTypeNames.add("Fire"); } public static String getStringForEventType(String typeAbbreviation) { if (typeAbbreviation == null) return null; if (sEventTypeAbbreviations.contains(typeAbbreviation)) return sEventTypeNames.get(sEventTypeAbbreviations.indexOf(typeAbbreviation)); return null; } public static double setDistanceText(Location deviceLocation, TextView textView, double lat, double lon) { return setDistanceText(deviceLocation, null, null, null, textView, lat, lon); } /** * Get stylized distance text describing the difference between the given * device location and a given Latitude and Longitude. The unique * method signature owes itself to the precise data available to * a {@link com.gaiagps.iburn.adapters.PlayaItemCursorAdapter} * * @return a time estimate in minutes. */ public static double setDistanceText(Location deviceLocation, Date nowDate, String startDateStr, String endDateStr, TextView textView, double lat, double lon) { if (deviceLocation != null && lat != 0) { double metersToTarget = Geo.getDistance(lat, lon, deviceLocation); double minutesToTarget = Geo.getWalkingEstimateMinutes(metersToTarget); String distanceText; try { Spannable spanRange; if (minutesToTarget < 1) { distanceText = "<1 m"; spanRange = new SpannableString(distanceText); } else { distanceText = String.format("%.0f min", minutesToTarget); // int endSpan = distanceText.length(); spanRange = new SpannableString(distanceText); // TextAppearanceSpan tas = new TextAppearanceSpan(textView.getContext(), R.style.Subdued); // spanRange.setSpan(tas, distanceText.indexOf("min") + 3, endSpan, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } if (nowDate != null && startDateStr != null && endDateStr != null) { // If a date is given, attempt to do coloring of the time estimate (e.g: green if arrival estimate before start date) Date startDate = PlayaDateTypeAdapter.iso8601Format.parse(startDateStr); Date endDate = PlayaDateTypeAdapter.iso8601Format.parse(endDateStr); long duration = endDate.getTime() - startDate.getTime() / 1000 / 60; //minutes if (startDate.before(nowDate) && endDate.after(nowDate)) { // Event already started long timeLeftMinutes = ( endDate.getTime() - nowDate.getTime() ) / 1000 / 60; // Log.i(TAG, "ongoing event ends in " + timeLeftMinutes + " minutes ( " + endDateStr + ") eta " + minutesToTarget + " duration " + duration); if ( (timeLeftMinutes - minutesToTarget) > 0) { // If we'll make at least a quarter of the event, Color it yellow int endSpan = distanceText.indexOf("min") + 3; spanRange = new SpannableString(distanceText); TextAppearanceSpan tas = new TextAppearanceSpan(textView.getContext(), R.style.OrangeText); spanRange.setSpan(tas, 0, endSpan, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } else if (startDate.after(nowDate)) { long timeUntilStartMinutes = ( startDate.getTime() - nowDate.getTime() ) / 1000 / 60; // Log.i(TAG, "fugure event starts in " + timeUntilStartMinutes + " minutes ( " + startDateStr + ") eta " + minutesToTarget + " duration " + duration); if ( (timeUntilStartMinutes - minutesToTarget) > 0) { // If we'll make the event start, Color it green int endSpan = distanceText.indexOf("min") + 3; TextAppearanceSpan tas = new TextAppearanceSpan(textView.getContext(), R.style.GreenText); spanRange.setSpan(tas, 0, endSpan, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } } textView.setText(spanRange); } catch (ParseException e) { e.printStackTrace(); } // If minutes < startDate || minutes < (endDate - now) textView.setVisibility(View.VISIBLE); return minutesToTarget; } else { textView.setText(""); textView.setVisibility(View.INVISIBLE); return -1; } } public static AdapterView.OnItemLongClickListener mListItemLongClickListener = (parent, v, position, id) -> { int model_id = (Integer) v.getTag(R.id.list_item_related_model); Constants.PlayaItemType itemType = (Constants.PlayaItemType) v.getTag(R.id.list_item_related_model_type); String tableName; switch (itemType) { case ART: tableName = PlayaDatabase.ART; break; case CAMP: tableName = PlayaDatabase.CAMPS; break; case EVENT: tableName = PlayaDatabase.EVENTS; break; default: throw new IllegalStateException("Unknown PLAYA_ITEM"); } final DataProvider[] storedProvider = new DataProvider[1]; DataProvider.getInstance(v.getContext()) .doOnNext(provider -> storedProvider[0] = provider) .flatMap(dataProvider -> dataProvider.createQuery(tableName, "SELECT " + PlayaItemTable.favorite + " FROM " + tableName + " WHERE " + PlayaItemTable.id + " = ?", String.valueOf(model_id))) .map(SqlBrite.Query::run) .subscribe(cursor -> { boolean isFavorite = cursor.getInt(0) == 1; storedProvider[0].updateFavorite(PlayaItemTable.favorite, model_id, !isFavorite); Toast.makeText(v.getContext(), String.format("%s Favorites", isFavorite ? "Removed from" : "Added to"), Toast.LENGTH_SHORT).show(); }); return true; }; }
package com.ctrip.xpipe.utils; import java.util.Map; import java.util.ServiceLoader; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ctrip.xpipe.api.foundation.FoundationService; /** * @author wenchao.meng * * Jun 13, 2016 */ public class ServicesUtil { private static Logger logger = LoggerFactory.getLogger(ServicesUtil.class); private static Map<Class<?>, Object> allServices = new ConcurrentHashMap<>(); public static FoundationService getFoundationService(){ return load(FoundationService.class); } @SuppressWarnings("unchecked") private static <T> T load(Class<T> clazz) { T result = (T) allServices.get(clazz); if(result == null){ synchronized (clazz) { result = (T) allServices.get(clazz); if(result == null){ ServiceLoader<T> services = ServiceLoader.load(clazz); int i = 0; for(T service : services){ result = service; i++; logger.info("[load]{}, {}", service.getClass(), service); } if(i == 0){ throw new IllegalStateException("service not found:" + clazz.getClass().getSimpleName() + ", " + "if you work in ctrip, add ctrip-service project in your classpath, otherwise implement your own service"); } if(i > 1){ throw new IllegalStateException("service found more than once"); } allServices.put(clazz, result); } } } return result; } }
package hudson.cli.declarative; import hudson.cli.CLICommand; import hudson.model.Hudson; import org.jvnet.hudson.annotation_indexer.Indexed; import org.kohsuke.args4j.CmdLineException; import java.lang.annotation.Documented; import static java.lang.annotation.ElementType.METHOD; import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Target; /** * Annotates a resolver method that binds a portion of the command line arguments and parameters * to an instance whose {@link CLIMethod} is invoked for the final processing. * * <p> * Hudson uses the return type of the resolver method * to pick the resolver method to use, of all the resolver methods it discovers. That is, * if Hudson is looking to find an instance of type <tt>T</tt> for the current command, it first * looks for the resolver method whose return type is <tt>T</tt>, then it checks for the base type of <tt>T</tt>, * and so on. * * <p> * If the chosen resolver method is an instance method on type <tt>S</tt>, the "parent resolver" is then * located to resolve an instance of type 'S'. This process repeats until a static resolver method is discovered * (since most of Hudson's model objects are anchored to the root {@link Hudson} object, normally that would become * the top-most resolver method.) * * <p> * Parameters of the resolver method receives the same parameter/argument injections that {@link CLIMethod}s receive. * Parameters and arguments consumed by the resolver will not be visible to {@link CLIMethod}s. * * <p> * The resolver method shall never return null &mdash; it should instead indicate a failure by throwing * {@link CmdLineException}. * * @author Kohsuke Kawaguchi * @see CLICommand * @since 1.321 */ @Indexed @Retention(RUNTIME) @Target({METHOD}) @Documented public @interface CLIResolver { }
package org.bouncycastle.asn1.x9; import java.util.Enumeration; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.DERTaggedObject; /** * ASN.1 def for Diffie-Hellman key exchange OtherInfo structure. See * RFC 2631, or X9.42, for further details. * <pre> * OtherInfo ::= SEQUENCE { * keyInfo KeySpecificInfo, * partyAInfo [0] OCTET STRING OPTIONAL, * suppPubInfo [2] OCTET STRING * } * </pre> */ public class OtherInfo extends ASN1Object { private KeySpecificInfo keyInfo; private ASN1OctetString partyAInfo; private ASN1OctetString suppPubInfo; public OtherInfo( KeySpecificInfo keyInfo, ASN1OctetString partyAInfo, ASN1OctetString suppPubInfo) { this.keyInfo = keyInfo; this.partyAInfo = partyAInfo; this.suppPubInfo = suppPubInfo; } /** * Return a OtherInfo object from the passed in object. * * @param obj an object for conversion or a byte[]. * @return a OtherInfo */ public static OtherInfo getInstance(Object obj) { if (obj instanceof OtherInfo) { return (OtherInfo)obj; } else if (obj != null) { return new OtherInfo(ASN1Sequence.getInstance(obj)); } return null; } private OtherInfo( ASN1Sequence seq) { Enumeration e = seq.getObjects(); keyInfo = KeySpecificInfo.getInstance(e.nextElement()); while (e.hasMoreElements()) { DERTaggedObject o = (DERTaggedObject)e.nextElement(); if (o.getTagNo() == 0) { partyAInfo = (ASN1OctetString)o.getObject(); } else if (o.getTagNo() == 2) { suppPubInfo = (ASN1OctetString)o.getObject(); } } } /** * Return the key specific info for the KEK/CEK. * * @return the key specific info. */ public KeySpecificInfo getKeyInfo() { return keyInfo; } /** * PartyA info for key deriviation. * * @return PartyA info. */ public ASN1OctetString getPartyAInfo() { return partyAInfo; } /** * The length of the KEK to be generated as a 4 byte big endian. * * @return KEK length as a 4 byte big endian in an octet string. */ public ASN1OctetString getSuppPubInfo() { return suppPubInfo; } /** * Return an ASN.1 primitive representation of this object. * * @return a DERSequence containing the OtherInfo values. */ public ASN1Primitive toASN1Primitive() { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(keyInfo); if (partyAInfo != null) { v.add(new DERTaggedObject(0, partyAInfo)); } v.add(new DERTaggedObject(2, suppPubInfo)); return new DERSequence(v); } }
package org.mskcc.cbio.portal.dao; import org.mskcc.cbio.portal.util.DatabaseProperties; import org.mskcc.cbio.portal.util.GlobalProperties; import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.dbcp.DelegatingPreparedStatement; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.sql.*; import java.util.HashMap; import java.util.Map; import javax.naming.InitialContext; import javax.sql.DataSource; /** * Connection Utility for JDBC. * * @author Ethan Cerami */ public class JdbcUtil { private static DataSource ds; private static final int MAX_JDBC_CONNECTIONS = 100; private static Map<String,Integer> activeConnectionCount; // keep track of the number of active connection per class/requester private static final Log LOG = LogFactory.getLog(JdbcUtil.class); /** * Gets Connection to the Database. * * @param clazz class * @return Live Connection to Database. * @throws java.sql.SQLException Error Connecting to Database. */ public static Connection getDbConnection(Class clazz) throws SQLException { return getDbConnection(clazz.getName()); } /** * Gets Connection to the Database. * * @param requester name * @return Live Connection to Database. * @throws java.sql.SQLException Error Connecting to Database. */ private static Connection getDbConnection(String requester) throws SQLException { if (ds == null) { ds = initDataSource(); } Connection con; try { con = ds.getConnection(); } catch (Exception e) { logMessage(e.getMessage()); throw new SQLException(e); } if (requester!=null) { Integer count = activeConnectionCount.get(requester); activeConnectionCount.put(requester, count==null ? 1 : (count+1)); } return con; } private static DataSource initDataSource() { DataSource ds = initDataSourceTomcat(); try { ds.getConnection(); } catch (Exception e) { ds = null; } if (ds == null) { ds = initDataSourceDirect(); } activeConnectionCount = new HashMap<String,Integer>(); return ds; } private static DataSource initDataSourceTomcat() { DataSource ds = null; activeConnectionCount = new HashMap<String,Integer>(); try { InitialContext cxt = new InitialContext(); if (cxt == null) { throw new Exception("Context for creating data source not found!"); } ds = (DataSource)cxt.lookup( "java:/comp/env/jdbc/" + GlobalProperties.getProperty("db.portal_db_name") ); if (ds == null) { throw new Exception("Data source not found!"); } } catch (Exception e) { logMessage(e.getMessage()); } return ds; } /** * Initializes Data Source. */ private static DataSource initDataSourceDirect() { DatabaseProperties dbProperties = DatabaseProperties.getInstance(); String host = dbProperties.getDbHost(); String userName = dbProperties.getDbUser(); String password = dbProperties.getDbPassword(); String database = dbProperties.getDbName(); String driverClassname = dbProperties.getDbDriverClassName(); String url = "jdbc:mysql://" + host + "/" + database + "?user=" + userName + "&password=" + password + "&zeroDateTimeBehavior=convertToNull"; // Set up poolable data source BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName(driverClassname); ds.setUsername(userName); ds.setPassword(password); ds.setUrl(url); // By pooling/reusing PreparedStatements, we get a major performance gain ds.setPoolPreparedStatements(true); ds.setMaxActive(MAX_JDBC_CONNECTIONS); return ds; } /** * Frees Database Connection. * * @param con Connection Object. */ public static void closeConnection(Class clazz, Connection con) { closeConnection(clazz.getName(), con); } private static void closeConnection(String requester, Connection con) { try { if (con != null && !con.isClosed()) { con.close(); if (requester!=null) { int count = activeConnectionCount.get(requester)-1; if (count==0) { activeConnectionCount.remove(requester); } else { activeConnectionCount.put(requester, count); } } } } catch (SQLException e) { logMessage("Problem Closed a MySQL connection from " + requester + ": " + activeConnectionCount.toString()); e.printStackTrace(); } } /** * Frees PreparedStatement and ResultSet. * * @param rs ResultSet Object. */ public static void closeAll(ResultSet rs) { JdbcUtil.closeAll((String)null, null, rs); } /** * Frees Database Connection. * * @param con Connection Object. * @param ps Prepared Statement Object. * @param rs ResultSet Object. */ public static void closeAll(Class clazz, Connection con, PreparedStatement ps, ResultSet rs) { closeAll(clazz.getName(), con, rs); } /** * Frees Database Connection. * * @param con Connection Object. * @param rs ResultSet Object. */ private static void closeAll(String requester, Connection con, ResultSet rs) { closeConnection(requester, con); if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * Why does closeAll need a PreparedStatement? * This is a copy of closeAll without the PreparedStatement * @param clazz * @param con * @param rs */ public static void closeAll(Class clazz, Connection con, ResultSet rs) { String requester = clazz.getName(); closeConnection(requester, con); if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * Gets the SQL string statement associated with a PreparedStatement. * <p/> * This method compensates for a bug in the DBCP Code. DBCP wraps an * original PreparedStatement object, but when you call toString() on the * wrapper, it returns a generic String representation that does not include * the actual SQL code which gets executed. To get around this bug, this * method checks to see if we have a DBCP wrapper. If we do, we get the * original delegate, and properly call its toString() method. This * results in the actual SQL statement sent to the database. * * @param pstmt PreparedStatement Object. * @return toString value. */ public static String getSqlQuery(PreparedStatement pstmt) { if (pstmt instanceof DelegatingPreparedStatement) { DelegatingPreparedStatement dp = (DelegatingPreparedStatement) pstmt; Statement delegate = dp.getDelegate(); return delegate.toString(); } else { return pstmt.toString(); } } private static void logMessage(String message) { if (LOG.isInfoEnabled()) { LOG.info(message); } System.err.println(message); } }
package org.radargun.config; import java.util.List; import static org.radargun.config.VmArgUtils.ensureArg; import static org.radargun.config.VmArgUtils.replace; public class FlightRecorder implements VmArg { @Property(doc = "Start flight recording for the benchmark.", optional = false) private boolean enabled = false; @Property(doc = "File for the recording.") private String filename; @Property(doc = "Settings file with recording configuration.") private String settings; @Override public void setArgs(List<String> args) { if (!enabled) return; StringBuilder recordingParams = new StringBuilder("=delay=10s,duration=24h"); if (filename != null) recordingParams.append(",filename=").append(filename); if (settings != null) recordingParams.append(",settings=").append(settings); ensureArg(args, "-XX:+UnlockCommercialFeatures"); ensureArg(args, "-XX:+FlightRecorder"); replace(args, "-XX:StartFlightRecording", recordingParams.toString()); } public boolean isEnabled() { return enabled; } public String getFilename() { return filename; } public String getSettings() { return settings; } }
package org.intermine.web.struts; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.intermine.api.InterMineAPI; import org.intermine.api.profile.Profile; import org.intermine.api.search.Scope; import org.intermine.api.search.WebSearchable; import org.intermine.api.tag.TagNames; import org.intermine.api.template.TemplateManager; import org.intermine.api.template.TemplateQuery; import org.intermine.api.tracker.TemplateTracker; import org.intermine.api.tracker.TrackerDelegate; import org.intermine.web.logic.aspects.Aspect; import org.intermine.web.logic.session.SessionMethods; /** * Display the query builder (if there is a curernt query) or redirect to project.sitePrefix. * * @author Tom Riley */ public class BeginAction extends InterMineAction { private static final Logger LOG = Logger.getLogger(TemplateTracker.class); private static final Integer MAX_TEMPLATES = new Integer(8); /** * Either display the query builder or redirect to project.sitePrefix. * * @param mapping * The ActionMapping used to select this instance * @param form * The optional ActionForm bean for this request (if any) * @param request * The HTTP request we are processing * @param response * The HTTP response we are creating * @return an ActionForward object defining where control goes next * @exception Exception * if the application business logic throws an exception */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); ServletContext servletContext = session.getServletContext(); Properties properties = SessionMethods.getWebProperties(servletContext); // If GALAXY_URL is sent from a Galaxy server, then save it in the session; if not, read // the default value from web.properties and save it in the session if (request.getParameter("GALAXY_URL") != null) { request.getSession().setAttribute("GALAXY_URL", request.getParameter("GALAXY_URL")); String msg = properties.getProperty("galaxy.welcomeMessage"); SessionMethods.recordMessage(msg, session); } else { request.getSession().setAttribute( "GALAXY_URL", properties.getProperty("galaxy.baseurl.default") + properties.getProperty("galaxy.url.value")); } /* count number of templates and bags */ request.setAttribute("bagCount", new Integer(im.getBagManager() .getGlobalBags().size())); request.setAttribute("templateCount", new Integer(im .getTemplateManager().getGlobalTemplates().size())); /*most popular template*/ TrackerDelegate trackerDelegate = im.getTrackerDelegate(); if (trackerDelegate != null) { trackerDelegate.setTemplateManager(im.getTemplateManager()); String templateName = trackerDelegate.getMostPopularTemplate(); if (templateName != null) { Profile profile = SessionMethods.getProfile(session); TemplateQuery template = im.getTemplateManager() .getTemplate(profile, templateName, Scope.ALL); if (template != null) { request.setAttribute("mostPopularTemplate", template.getTitle()); } else { LOG.error("The most popular template " + templateName + "is not a public"); } } } List<TemplateQuery> templates = null; TemplateManager templateManager = im.getTemplateManager(); Map<String, Aspect> aspects = SessionMethods.getAspects(servletContext); Map<String, List<TemplateQuery>> aspectQueries = new HashMap<String, List<TemplateQuery>>(); List<String> mostPopulareTemplateNames; for (String aspect : aspects.keySet()) { templates = templateManager.getAspectTemplates(TagNames.IM_ASPECT_PREFIX + aspect, null); if (SessionMethods.getProfile(session).isLoggedIn()) { mostPopulareTemplateNames = trackerDelegate.getMostPopularTemplateOrder( SessionMethods.getProfile(session), session.getId()); } else { mostPopulareTemplateNames = trackerDelegate.getMostPopularTemplateOrder(); } if (mostPopulareTemplateNames != null) { Collections.sort(templates, new MostPopularTemplateComparator(mostPopulareTemplateNames)); } if (templates.size() > MAX_TEMPLATES) { templates = templates.subList(0, MAX_TEMPLATES - 1); } aspectQueries.put(aspect, templates); } request.setAttribute("aspectQueries", aspectQueries); String[] beginQueryClasses = (properties.get("begin.query.classes").toString()) .split("[ ,]+"); request.setAttribute("beginQueryClasses", beginQueryClasses); return mapping.findForward("begin"); } private class MostPopularTemplateComparator implements Comparator<TemplateQuery> { private List<String> mostPopulareTemplateNames; public MostPopularTemplateComparator(List<String> mostPopulareTemplateNames) { this.mostPopulareTemplateNames = mostPopulareTemplateNames; } public int compare(TemplateQuery template1, TemplateQuery template2) { String templateName1 = template1.getName(); String templateName2 = template2.getName(); if (!mostPopulareTemplateNames.contains(templateName1) && !mostPopulareTemplateNames.contains(templateName2)) { if (template1.getTitle().equals(template2.getTitle())) { return template1.getName().compareTo(template2.getName()); } else { return template1.getTitle().compareTo(template2.getTitle()); } } if (!mostPopulareTemplateNames.contains(templateName1)) { return +1; } if (!mostPopulareTemplateNames.contains(templateName2)) { return -1; } return (mostPopulareTemplateNames.indexOf(templateName1) < mostPopulareTemplateNames.indexOf(templateName2)) ? -1 : 1; } } }
package ar.app.components.sequentialComposer; import java.awt.Color; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.File; import java.util.Arrays; import java.util.List; import ar.Glyphset; import ar.glyphsets.MemMapList; import ar.glyphsets.SyntheticGlyphset; import ar.glyphsets.implicitgeometry.Indexed; import ar.glyphsets.implicitgeometry.Shaper; import ar.glyphsets.implicitgeometry.Valuer; import ar.glyphsets.implicitgeometry.Indexed.ToValue; import ar.glyphsets.implicitgeometry.Valuer.Binary; import ar.rules.CategoricalCounts; import ar.util.Util; public final class OptionDataset<G,I> { public final String name; public final Glyphset<G,I> glyphset; public final File sourceFile; public final Shaper<Indexed, G> shaper; public final Valuer<Indexed, I> valuer; public final OptionAggregator<? super I,?> defaultAggregator; public final List<OptionTransfer<?>> defaultTransfers; public OptionDataset( String name, File file, Shaper<Indexed, G> shaper, Valuer<Indexed,I> valuer, OptionAggregator<? super I,?> defAgg, OptionTransfer<?>... defTrans) { this(name, new MemMapList<>(file, shaper, valuer), file, shaper, valuer, defAgg, defTrans); } public OptionDataset( String name, Glyphset<G,I> glyphset, OptionAggregator<? super I,?> defAgg, OptionTransfer<?>... defTrans) { this(name, glyphset, null, null, null, defAgg, defTrans); } private OptionDataset( String name, Glyphset<G,I> glyphset, File file, Shaper<Indexed,G> shaper, Valuer<Indexed,I> valuer, OptionAggregator<? super I,?> defAgg, OptionTransfer<?>... defTrans) { this.name = name; this.sourceFile = file; this.shaper = shaper; this.valuer = valuer; this.glyphset = glyphset; this.defaultAggregator = defAgg; this.defaultTransfers = Arrays.asList(defTrans); } public String toString() {return name;} public OptionAggregator<? super I,?> defaultAggregator() {return defaultAggregator;} public List<OptionTransfer<?>> defaultTransfers() {return defaultTransfers;} // public static final OptionDataset<Point2D, Integer> WIKIPEDIA_TXT; // static { // OptionDataset<Point2D, Integer> temp; // try { // temp = new OptionDataset<>( // "Wikipedia BFS adjacnecy (Commons txt)", // new DelimitedFile<>( // new File("../data/wiki.full.txt"), ',', new Converter.TYPE[]{Converter.TYPE.LONG,Converter.TYPE.LONG, Converter.TYPE.COLOR}, // new Indexed.ToPoint(false, 0,1), new Valuer.Constant<Indexed,Integer>(1)), // OptionAggregator.COUNT, // new OptionTransfer.MathTransfer(), // new OptionTransfer.Interpolate()); // } catch (Exception e) {temp = null;} // WIKIPEDIA_TXT = temp; public static final OptionDataset<Point2D, String> BOOST_MEMORY; static { OptionDataset<Point2D, String> temp; try { temp = new OptionDataset<> ( "BGL Memory", new File("../data/MemVisScaled.hbin"), new Indexed.ToPoint(true, 0, 1), new ToValue<>(2, new Binary<Integer,String>(0, "Hit", "Miss")), OptionAggregator.COC_COMP, new OptionTransfer.ColorKey(), new OptionTransfer.ColorCatInterpolate()); } catch (Exception e) {temp = null;} BOOST_MEMORY = temp; } public static final OptionDataset<Point2D, CategoricalCounts<String>> CENSUS_TRACTS; static { OptionDataset<Point2D, CategoricalCounts<String>> temp; try { temp = new OptionDataset<>( "US Census Tracts", new File("../data/2010Census_RaceTract.hbin"), new Indexed.ToPoint(true, 0, 1), new Valuer.CategoryCount<>(new Util.ComparableComparator<String>(), 3,2), OptionAggregator.MERGE_CATS, new OptionTransfer.Spread(), new OptionTransfer.ToCount(), new OptionTransfer.MathTransfer(), new OptionTransfer.Interpolate()); } catch (Exception e) {temp = null;} CENSUS_TRACTS = temp; } public static final OptionDataset<Point2D, Character> CENSUS_SYN_PEOPLE; static { OptionDataset<Point2D, Character> temp; try { temp = new OptionDataset<>( "US Census Synthetic People", new File("../data/2010Census_RacePersonPoints.hbin"), new Indexed.ToPoint(true, 0, 1), new Indexed.ToValue<Indexed,Character>(2), OptionAggregator.COC_COMP, new OptionTransfer.ColorKey(), new OptionTransfer.ColorCatInterpolate()); } catch (Exception e) {temp = null;} CENSUS_SYN_PEOPLE = temp; } public static final OptionDataset<Point2D, Color> WIKIPEDIA; static { OptionDataset<Point2D, Color> temp; try { temp = new OptionDataset<>( "Wikipedia BFS adjacnecy", new File("../data/wiki-adj.hbin"), new Indexed.ToPoint(false, 0, 1), new Valuer.Constant<Indexed, Color>(Color.RED), OptionAggregator.COUNT, new OptionTransfer.MathTransfer(), new OptionTransfer.Interpolate()); } catch (Exception e) {temp = null;} WIKIPEDIA = temp; } public static final OptionDataset<Point2D, Color> KIVA; static { OptionDataset<Point2D, Color> temp; try { temp = new OptionDataset<>( "Kiva", new File("../data/kiva-adj.hbin"), new Indexed.ToPoint(false, 0, 1), new Valuer.Constant<Indexed, Color>(Color.RED), OptionAggregator.COUNT, new OptionTransfer.MathTransfer(), new OptionTransfer.Interpolate()); } catch (Exception e) {temp = null;} KIVA = temp; } // public static final OptionDataset<Rectangle2D, Color> CIRCLE_SCATTER; // static { // OptionDataset<Rectangle2D, Color> temp; // try { // temp = new OptionDataset<>( // "Circle Scatter", // GlyphsetUtils.autoLoad(new File("../data/circlepoints.csv"), .1, DynamicQuadTree.<Rectangle2D, Color>make()), // OptionAggregator.COUNT, // new OptionTransfer.Interpolate()); // } catch (Exception e) {temp = null;} // CIRCLE_SCATTER = temp; public static final OptionDataset<Rectangle2D, Integer> CIRCLE_SCATTER; static { OptionDataset<Rectangle2D, Integer> temp; try { temp = new OptionDataset<>( "Circle Scatter (HBIN)", new File("../data/circlepoints.hbin"), new Indexed.ToRect(.1,0,1), new Valuer.Constant<Indexed, Integer>(1), OptionAggregator.COUNT, new OptionTransfer.Interpolate()); } catch (Exception e) { e.printStackTrace(); temp = null;} CIRCLE_SCATTER = temp; } private static int SYNTHETIC_POINT_COUNT = 100_000_000; public static OptionDataset<Point2D, Integer> SYNTHETIC = syntheticPoints(SYNTHETIC_POINT_COUNT); public static OptionDataset<Point2D, Integer> syntheticPoints(int size) { return new OptionDataset<>( String.format("Synthetic Points (%,d points)", size), new SyntheticGlyphset<>(size, 0, new SyntheticGlyphset.UniformPoints()), OptionAggregator.COUNT, new OptionTransfer.Interpolate()); } }
package org.jbox2d.collision; /** * Contact ids to facilitate warm starting. Note: the ContactFeatures class is just embedded in here */ public class ContactID implements Comparable<ContactID> { public static enum Type { VERTEX, FACE } public byte indexA; public byte indexB; public byte typeA; public byte typeB; public int getKey() { return ((int) indexA) << 24 | ((int) indexB) << 16 | ((int) typeA) << 8 | ((int) typeB); } public boolean isEqual(final ContactID cid) { return getKey() == cid.getKey(); } public ContactID() {} public ContactID(final ContactID c) { set(c); } public void set(final ContactID c) { indexA = c.indexA; indexB = c.indexB; typeA = c.typeA; typeB = c.typeB; } public void flip() { byte tempA = indexA; indexA = indexB; indexB = tempA; tempA = typeA; typeA = typeB; typeB = tempA; } /** * zeros out the data */ public void zero() { indexA = 0; indexB = 0; typeA = 0; typeB = 0; } @Override public int compareTo(ContactID o) { return getKey() - o.getKey(); } }
package biz.paluch.jee.commons; import java.util.List; import javax.enterprise.inject.spi.BeanManager; /** * Utility to lookup beans. */ public final class BeanLookup { /** * Default JNDI names of the BeanManager. */ public static final String[] BEANMANAGER_JNDI_NAMES = {"java:comp/BeanManager", "java:comp/env/BeanManager"}; /** * Default BeanManager. */ private static BeanManager defaultBeanManager; /** * Default lookup strategy is using the BeanManager directly. */ private static BeanLookupStrategy lookupStrategy = new BeanManagerLookupStrategy(); private BeanLookup() { } /** * Lookup Beans using its class. * * @param beanManager * @param type * @return List of beans (or empty list) */ public static <T> List<T> lookupBeans(BeanManager beanManager, Class<T> type) { return lookupStrategy.lookupBeans(beanManager, type); } public static <T> T lookupBean(BeanManager beanManager, Class<T> type) { List<T> beans = lookupBeans(beanManager, type); return returnOneBean(type, beans); } public static <T> T lookupBean(Class<T> type) { return lookupBean(beanManager(), type); } /** * Lookup Beans using the Bean-Name. * * @param beanManager * @param beanName * @return List of beans (or empty list) */ public static <T> List<T> lookupBeans(BeanManager beanManager, String beanName) { return lookupStrategy.lookupBeans(beanManager, beanName); } public static <T> T lookupBean(BeanManager beanManager, String beanName) { List<T> beans = lookupBeans(beanManager, beanName); return returnOneBean(beanName, beans); } public static <T> T lookupBean(String beanName) { return lookupBean(beanManager(), beanName); } private static <T> T returnOneBean(Object beanIdentifier, List<T> beans) { if (beans.isEmpty()) { throw new IllegalStateException("bean " + beanIdentifier + " not found"); } else if (beans.size() > 1) { throw new IllegalStateException("found multiple beans <" + beanIdentifier + ">"); } return beans.get(0); } /** * * @return the current lookupStrategy. */ public static BeanLookupStrategy getLookupStrategy() { return lookupStrategy; } /** * Set a new lookup strategy. * * @param strategy */ public static void setLookupStrategy(BeanLookupStrategy strategy) { BeanLookup.lookupStrategy = strategy; } /** * Lookup the BeanManager using {@code NamingLookup} * * @return the BeanManager */ public static BeanManager beanManager() { if(defaultBeanManager == null) { defaultBeanManager = beanManagerLookup(); } return defaultBeanManager; } /** * Set a default bean manager manually * * @param beanManager */ public static void setDefaultBeanManager(BeanManager beanManager) { BeanLookup.defaultBeanManager = beanManager; } /** * Reset the lookup strategy to default. */ public static void reset() { lookupStrategy = new BeanManagerLookupStrategy(); } private static BeanManager beanManagerLookup() { for(String jndiName : BEANMANAGER_JNDI_NAMES) { BeanManager beanManager = NamingLookup.doLookup(jndiName); if(beanManager != null) return beanManager; } throw new IllegalStateException("Did not found any BeanManager!"); } }
package cn.jzvd; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.TextureView; import android.view.View; public class JZResizeTextureView extends TextureView { protected static final String TAG = "JZResizeTextureView"; public int currentVideoWidth = 0; public int currentVideoHeight = 0; public JZResizeTextureView(Context context) { super(context); currentVideoWidth = 0; currentVideoHeight = 0; } public JZResizeTextureView(Context context, AttributeSet attrs) { super(context, attrs); currentVideoWidth = 0; currentVideoHeight = 0; } public void setVideoSize(int currentVideoWidth, int currentVideoHeight) { if (this.currentVideoWidth != currentVideoWidth || this.currentVideoHeight != currentVideoHeight) { this.currentVideoWidth = currentVideoWidth; this.currentVideoHeight = currentVideoHeight; requestLayout(); } } @Override public void setRotation(float rotation) { if (rotation != getRotation()) { super.setRotation(rotation); requestLayout(); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { Log.i(TAG, "onMeasure " + " [" + this.hashCode() + "] "); int viewRotation = (int) getRotation(); int videoWidth = currentVideoWidth; int videoHeight = currentVideoHeight; int parentHeight = ((View) getParent()).getMeasuredHeight(); int parentWidth = ((View) getParent()).getMeasuredWidth(); if (parentWidth != 0 && parentHeight != 0 && videoWidth != 0 && videoHeight != 0) { if (JZVideoPlayer.VIDEO_IMAGE_DISPLAY_TYPE == JZVideoPlayer.VIDEO_IMAGE_DISPLAY_TYPE_FILL_PARENT) { if (viewRotation == 90 || viewRotation == 270) { int tempSize = parentWidth; parentWidth = parentHeight; parentHeight = tempSize; } videoHeight = videoWidth * parentHeight / parentWidth; } } // TextureView90 if (viewRotation == 90 || viewRotation == 270) { int tempMeasureSpec = widthMeasureSpec; widthMeasureSpec = heightMeasureSpec; heightMeasureSpec = tempMeasureSpec; } int width = getDefaultSize(videoWidth, widthMeasureSpec); int height = getDefaultSize(videoHeight, heightMeasureSpec); if (videoWidth > 0 && videoHeight > 0) { int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); Log.i(TAG, "widthMeasureSpec [" + MeasureSpec.toString(widthMeasureSpec) + "]"); Log.i(TAG, "heightMeasureSpec [" + MeasureSpec.toString(heightMeasureSpec) + "]"); if (widthSpecMode == MeasureSpec.EXACTLY && heightSpecMode == MeasureSpec.EXACTLY) { // the size is fixed width = widthSpecSize; height = heightSpecSize; // for compatibility, we adjust size based on aspect ratio if (videoWidth * height < width * videoHeight) { width = height * videoWidth / videoHeight; } else if (videoWidth * height > width * videoHeight) { height = width * videoHeight / videoWidth; } } else if (widthSpecMode == MeasureSpec.EXACTLY) { // only the width is fixed, adjust the height to match aspect ratio if possible width = widthSpecSize; height = width * videoHeight / videoWidth; if (heightSpecMode == MeasureSpec.AT_MOST && height > heightSpecSize) { // couldn't match aspect ratio within the constraints height = heightSpecSize; width = height * videoWidth / videoHeight; } } else if (heightSpecMode == MeasureSpec.EXACTLY) { // only the height is fixed, adjust the width to match aspect ratio if possible height = heightSpecSize; width = height * videoWidth / videoHeight; if (widthSpecMode == MeasureSpec.AT_MOST && width > widthSpecSize) { // couldn't match aspect ratio within the constraints width = widthSpecSize; height = width * videoHeight / videoWidth; } } else { // neither the width nor the height are fixed, try to use actual video size width = videoWidth; height = videoHeight; if (heightSpecMode == MeasureSpec.AT_MOST && height > heightSpecSize) { // too tall, decrease both width and height height = heightSpecSize; width = height * videoWidth / videoHeight; } if (widthSpecMode == MeasureSpec.AT_MOST && width > widthSpecSize) { // too wide, decrease both width and height width = widthSpecSize; height = width * videoHeight / videoWidth; } } } else { // no size yet, just adopt the given spec sizes } if (parentWidth != 0 && parentHeight != 0 && videoWidth != 0 && videoHeight != 0) { if (JZVideoPlayer.VIDEO_IMAGE_DISPLAY_TYPE == JZVideoPlayer.VIDEO_IMAGE_DISPLAY_TYPE_ORIGINAL) { height = videoHeight; width = videoWidth; } else if (JZVideoPlayer.VIDEO_IMAGE_DISPLAY_TYPE == JZVideoPlayer.VIDEO_IMAGE_DISPLAY_TYPE_FILL_SCROP) { if (viewRotation == 90 || viewRotation == 270) { int tempSize = parentWidth; parentWidth = parentHeight; parentHeight = tempSize; } if (((double) videoHeight / videoWidth) > ((double) parentHeight / parentWidth)) { height = (int) (((double) parentWidth / (double) width * (double) height)); width = parentWidth; } else if (((double) videoHeight / videoWidth) < ((double) parentHeight / parentWidth)) { width = (int) (((double) parentHeight / (double) height * (double) width)); height = parentHeight; } } } setMeasuredDimension(width, height); } }
package com.jme3.app.state; import com.jme3.app.Application; import com.jme3.renderer.RenderManager; /** * <code>AbstractAppState</code> implements some common methods * that make creation of AppStates easier. * @author Kirill Vainer * @see com.jme3.app.state.BaseAppState */ public class AbstractAppState implements AppState { /** * <code>initialized</code> is set to true when the method * {@link AbstractAppState#initialize(com.jme3.app.state.AppStateManager, com.jme3.app.Application) } * is called. When {@link AbstractAppState#cleanup() } is called, <code>initialized</code> * is set back to false. */ protected boolean initialized = false; private boolean enabled = true; public void initialize(AppStateManager stateManager, Application app) { initialized = true; } public boolean isInitialized() { return initialized; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isEnabled() { return enabled; } public void stateAttached(AppStateManager stateManager) { } public void stateDetached(AppStateManager stateManager) { } public void update(float tpf) { } public void render(RenderManager rm) { } public void postRender(){ } public void cleanup() { initialized = false; } }
package yuku.alkitab.base.storage; import android.content.*; import android.database.*; import android.database.sqlite.*; import android.provider.*; import android.util.*; import java.util.*; import yuku.alkitab.base.*; import yuku.alkitab.base.EdisiActivity.MEdisiYes; import yuku.alkitab.base.model.*; import yuku.alkitab.base.renungan.*; import yuku.andoutil.*; public class InternalDb { public static final String TAG = InternalDb.class.getSimpleName(); private final InternalDbHelper helper; public InternalDb(InternalDbHelper helper) { this.helper = helper; } public Bukmak2 getBukmakByAri(int ari, int jenis) { Cursor cursor = helper.getReadableDatabase().query( Db.TABEL_Bukmak2, new String[] {BaseColumns._ID, Db.Bukmak2.tulisan, Db.Bukmak2.waktuTambah, Db.Bukmak2.waktuUbah}, Db.Bukmak2.ari + "=? and " + Db.Bukmak2.jenis + "=?", //$NON-NLS-1$ //$NON-NLS-2$ new String[] {String.valueOf(ari), String.valueOf(jenis)}, null, null, null ); try { if (!cursor.moveToNext()) return null; Bukmak2 res = Bukmak2.dariCursor(cursor, ari, jenis); res._id = cursor.getInt(cursor.getColumnIndexOrThrow(BaseColumns._ID)); return res; } finally { cursor.close(); } } public Bukmak2 getBukmakById(long id) { Cursor cursor = helper.getReadableDatabase().query( Db.TABEL_Bukmak2, new String[] {Db.Bukmak2.ari, Db.Bukmak2.jenis, Db.Bukmak2.tulisan, Db.Bukmak2.waktuTambah, Db.Bukmak2.waktuUbah}, "_id=?", //$NON-NLS-1$ new String[] {String.valueOf(id)}, null, null, null); try { if (!cursor.moveToNext()) return null; Bukmak2 res = Bukmak2.dariCursor(cursor); res._id = (int) id; return res; } finally { cursor.close(); } } public int updateBukmak(Bukmak2 bukmak) { return helper.getWritableDatabase().update(Db.TABEL_Bukmak2, bukmak.toContentValues(), "_id=?", new String[] {String.valueOf(bukmak._id)}); //$NON-NLS-1$ } public Bukmak2 insertBukmak(int ari, int jenis, String tulisan, Date waktuTambah, Date waktuUbah) { Bukmak2 res = new Bukmak2(ari, jenis, tulisan, waktuTambah, waktuUbah); SQLiteDatabase db = helper.getWritableDatabase(); long _id = db.insert(Db.TABEL_Bukmak2, null, res.toContentValues()); if (_id == -1) { return null; } else { res._id = _id; return res; } } public void hapusBukmakByAri(int ari, int jenis) { SQLiteDatabase db = helper.getWritableDatabase(); db.beginTransaction(); try { String[] params = {String.valueOf(jenis), String.valueOf(ari)}; SQLiteStatement stmt = db.compileStatement("select _id from " + Db.TABEL_Bukmak2 + " where " + Db.Bukmak2.jenis + "=? and " + Db.Bukmak2.ari + "=?"); stmt.bindAllArgsAsStrings(params); long _id = stmt.simpleQueryForLong(); params = new String[] {String.valueOf(_id)}; db.delete(Db.TABEL_Bukmak2_Label, Db.Bukmak2_Label.bukmak2_id + "=?", params); //$NON-NLS-1$ db.delete(Db.TABEL_Bukmak2, "_id=?", params); //$NON-NLS-1$ db.setTransactionSuccessful(); } finally { db.endTransaction(); } } public void hapusBukmakById(long id) { SQLiteDatabase db = helper.getWritableDatabase(); db.beginTransaction(); try { String[] params = new String[] {String.valueOf(id)}; db.delete(Db.TABEL_Bukmak2_Label, Db.Bukmak2_Label.bukmak2_id + "=?", params); //$NON-NLS-1$ db.delete(Db.TABEL_Bukmak2, "_id=?", params); //$NON-NLS-1$ db.setTransactionSuccessful(); } finally { db.endTransaction(); } } public Cursor listBukmak(int jenis, long labelId, String sortColumn, boolean sortAscending) { SQLiteDatabase db = helper.getReadableDatabase(); String sortClause = sortColumn + (Db.Bukmak2.tulisan.equals(sortColumn)? " collate NOCASE ": "") + (sortAscending? " asc": " desc"); if (labelId == 0) { // no restrictions return db.query(Db.TABEL_Bukmak2, null, Db.Bukmak2.jenis + "=?", new String[]{String.valueOf(jenis)}, null, null, sortClause); } else if (labelId == BukmakListActivity.LABELID_noLabel) { // only without label return db.rawQuery("select " + Db.TABEL_Bukmak2 + ".* from " + Db.TABEL_Bukmak2 + " where " + Db.TABEL_Bukmak2 + "." + Db.Bukmak2.jenis + "=? and " + Db.TABEL_Bukmak2 + "." + BaseColumns._ID + " not in (select " + Db.Bukmak2_Label.bukmak2_id + " from " + Db.TABEL_Bukmak2_Label + ") order by " + Db.TABEL_Bukmak2 + "." + sortClause, new String[] {String.valueOf(jenis)}); } else { // filter by labelId return db.rawQuery("select " + Db.TABEL_Bukmak2 + ".* from " + Db.TABEL_Bukmak2 + ", " + Db.TABEL_Bukmak2_Label + " where " + Db.Bukmak2.jenis + "=? and " + Db.TABEL_Bukmak2 + "." + BaseColumns._ID + " = " + Db.TABEL_Bukmak2_Label + "." + Db.Bukmak2_Label.bukmak2_id + " and " + Db.TABEL_Bukmak2_Label + "." + Db.Bukmak2_Label.label_id + "=? order by " + Db.TABEL_Bukmak2 + "." + sortClause, new String[] {String.valueOf(jenis), String.valueOf(labelId)}); } } public void importBukmak(List<Bukmak2> list, boolean tumpuk) { SQLiteDatabase db = helper.getWritableDatabase(); db.beginTransaction(); try { String where = Db.Bukmak2.ari + "=? and " + Db.Bukmak2.jenis + "=?"; //$NON-NLS-1$ //$NON-NLS-2$ String[] plc = new String[2]; for (Bukmak2 bukmak2: list) { plc[0] = String.valueOf(bukmak2.ari); plc[1] = String.valueOf(bukmak2.jenis); boolean ada = false; Cursor cursor = db.query(Db.TABEL_Bukmak2, null, where, plc, null, null, null); if (cursor.moveToNext()) { // ada, maka kita perlu hapus ada = true; } cursor.close(); // ada tumpuk: delete insert // ada !tumpuk: (nop) // !ada tumpuk: insert // !ada !tumpuk: insert if (ada && tumpuk) { db.delete(Db.TABEL_Bukmak2, where, plc); } if ((ada && tumpuk) || (!ada)) { db.insert(Db.TABEL_Bukmak2, null, bukmak2.toContentValues()); } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } public Cursor listSemuaBukmak() { return helper.getReadableDatabase().query(Db.TABEL_Bukmak2, null, null, null, null, null, null); } private SQLiteStatement stmt_countAtribut = null; public int countAtribut(int ari_kitabpasal) { int ariMin = ari_kitabpasal & 0x00ffff00; int ariMax = ari_kitabpasal | 0x000000ff; if (stmt_countAtribut == null) { stmt_countAtribut = helper.getReadableDatabase().compileStatement("select count(*) from " + Db.TABEL_Bukmak2 + " where " + Db.Bukmak2.ari + ">=? and " + Db.Bukmak2.ari + "<?");//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } stmt_countAtribut.clearBindings(); stmt_countAtribut.bindLong(1, ariMin); stmt_countAtribut.bindLong(2, ariMax); return (int) stmt_countAtribut.simpleQueryForLong(); } private String[] sql_getCatatan_params = new String[2]; /** * @param map_0 adalah ayat, basis 0 * @return null kalau ga ada warna stabilo, atau int[] kalau ada, sesuai offset map_0. */ public int[] putAtribut(int ari_kitabpasal, int[] map_0) { int ariMin = ari_kitabpasal & 0x00ffff00; int ariMax = ari_kitabpasal | 0x000000ff; int[] res = null; sql_getCatatan_params[0] = String.valueOf(ariMin); sql_getCatatan_params[1] = String.valueOf(ariMax); Cursor cursor = helper.getReadableDatabase().rawQuery("select * from " + Db.TABEL_Bukmak2 + " where " + Db.Bukmak2.ari + ">=? and " + Db.Bukmak2.ari + "<?", sql_getCatatan_params); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ try { int kolom_jenis = cursor.getColumnIndexOrThrow(Db.Bukmak2.jenis); int kolom_ari = cursor.getColumnIndexOrThrow(Db.Bukmak2.ari); int kolom_tulisan = cursor.getColumnIndexOrThrow(Db.Bukmak2.tulisan); while (cursor.moveToNext()) { int ari = cursor.getInt(kolom_ari); int jenis = cursor.getInt(kolom_jenis); int ofsetMap = Ari.toAyat(ari) - 1; // dari basis1 ke basis 0 if (ofsetMap >= map_0.length) { Log.e(TAG, "ofsetMap kebanyakan " + ofsetMap + " terjadi pada ari 0x" + Integer.toHexString(ari)); //$NON-NLS-1$ //$NON-NLS-2$ } else { if (jenis == Db.Bukmak2.jenis_bukmak) { map_0[ofsetMap] |= 0x1; } else if (jenis == Db.Bukmak2.jenis_catatan) { map_0[ofsetMap] |= 0x2; } else if (jenis == Db.Bukmak2.jenis_stabilo) { map_0[ofsetMap] |= 0x4; String tulisan = cursor.getString(kolom_tulisan); int warnaRgb = U.dekodStabilo(tulisan); if (res == null) res = new int[map_0.length]; res[ofsetMap] = warnaRgb; } } } } finally { cursor.close(); } return res; } public void updateAtauInsertStabilo(int ari, int warnaRgb) { SQLiteDatabase db = helper.getWritableDatabase(); db.beginTransaction(); Cursor c = db.query(Db.TABEL_Bukmak2, null, Db.Bukmak2.ari + "=? and " + Db.Bukmak2.jenis + "=?", new String[] {String.valueOf(ari), String.valueOf(Db.Bukmak2.jenis_stabilo)}, null, null, null); //$NON-NLS-1$ //$NON-NLS-2$ try { // cek dulu ada ato ga if (c.moveToNext()) { // sudah ada! Bukmak2 bukmak = Bukmak2.dariCursor(c); bukmak.waktuUbah = new Date(); long id = c.getLong(c.getColumnIndexOrThrow("_id")); //$NON-NLS-1$ if (warnaRgb != -1) { bukmak.tulisan = U.enkodStabilo(warnaRgb); db.update(Db.TABEL_Bukmak2, bukmak.toContentValues(), "_id=?", new String[] {String.valueOf(id)}); //$NON-NLS-1$ } else { // delete db.delete(Db.TABEL_Bukmak2, "_id=?", new String[] {String.valueOf(id)}); //$NON-NLS-1$ } } else { // belum ada! if (warnaRgb == -1) { // ga usa ngapa2in, dari belum ada jadi tetep ga ada } else { Date kini = new Date(); Bukmak2 bukmak = new Bukmak2(ari, Db.Bukmak2.jenis_stabilo, U.enkodStabilo(warnaRgb), kini, kini); db.insert(Db.TABEL_Bukmak2, null, bukmak.toContentValues()); } } db.setTransactionSuccessful(); } finally { c.close(); db.endTransaction(); } } public int getWarnaRgbStabilo(int ari) { // cek dulu ada ato ga Cursor c = helper.getReadableDatabase().query(Db.TABEL_Bukmak2, null, Db.Bukmak2.ari + "=? and " + Db.Bukmak2.jenis + "=?", new String[] {String.valueOf(ari), String.valueOf(Db.Bukmak2.jenis_stabilo)}, null, null, null); //$NON-NLS-1$ //$NON-NLS-2$ try { if (c.moveToNext()) { // sudah ada! Bukmak2 bukmak = Bukmak2.dariCursor(c); return U.dekodStabilo(bukmak.tulisan); } else { return -1; } } finally { c.close(); } } public boolean simpanArtikelKeRenungan(IArtikel artikel) { boolean res = false; SQLiteDatabase db = helper.getWritableDatabase(); db.beginTransaction(); try { // hapus dulu yang lama. db.delete(Db.TABEL_Renungan, Db.Renungan.nama + "=? and " + Db.Renungan.tgl + "=?", new String[] {artikel.getNama(), artikel.getTgl()}); //$NON-NLS-1$ //$NON-NLS-2$ ContentValues values = new ContentValues(); values.put(Db.Renungan.nama, artikel.getNama()); values.put(Db.Renungan.tgl, artikel.getTgl()); values.put(Db.Renungan.siapPakai, artikel.getSiapPakai()? 1: 0); if (artikel.getSiapPakai()) { values.put(Db.Renungan.judul, artikel.getJudul().toString()); values.put(Db.Renungan.isi, artikel.getIsiHtml()); values.put(Db.Renungan.header, artikel.getHeaderHtml()); } else { values.put(Db.Renungan.judul, (String)null); values.put(Db.Renungan.isi, (String)null); values.put(Db.Renungan.header, (String)null); } values.put(Db.Renungan.waktuSentuh, Sqlitil.nowDateTime()); db.insert(Db.TABEL_Renungan, null, values); db.setTransactionSuccessful(); res = true; Log.d(TAG, "TukangDonlot donlot selesai dengan sukses dan uda masuk ke db"); //$NON-NLS-1$ } finally { db.endTransaction(); } return res; } /** * Coba ambil artikel dari db lokal. Artikel ga siap pakai pun akan direturn. */ public IArtikel cobaAmbilRenungan(String nama, String tgl) { Cursor c = helper.getReadableDatabase().query(Db.TABEL_Renungan, null, Db.Renungan.nama + "=? and " + Db.Renungan.tgl + "=?", new String[] { nama, tgl }, null, null, null); //$NON-NLS-1$ //$NON-NLS-2$ try { if (c.moveToNext()) { IArtikel res = null; if (nama.equals("rh")) { //$NON-NLS-1$ res = new ArtikelRenunganHarian( tgl, c.getString(c.getColumnIndexOrThrow(Db.Renungan.judul)), c.getString(c.getColumnIndexOrThrow(Db.Renungan.header)), c.getString(c.getColumnIndexOrThrow(Db.Renungan.isi)), c.getInt(c.getColumnIndexOrThrow(Db.Renungan.siapPakai)) > 0 ); } else if (nama.equals("sh")) { //$NON-NLS-1$ res = new ArtikelSantapanHarian( tgl, c.getString(c.getColumnIndexOrThrow(Db.Renungan.judul)), c.getString(c.getColumnIndexOrThrow(Db.Renungan.header)), c.getString(c.getColumnIndexOrThrow(Db.Renungan.isi)), c.getInt(c.getColumnIndexOrThrow(Db.Renungan.siapPakai)) > 0 ); } return res; } else { return null; } } finally { c.close(); } } public List<MEdisiYes> listSemuaEdisi() { List<MEdisiYes> res = new ArrayList<MEdisiYes>(); Cursor cursor = helper.getReadableDatabase().query(Db.TABEL_Edisi, null, null, null, null, null, Db.Edisi.urutan + " asc"); //$NON-NLS-1$ try { int col_aktif = cursor.getColumnIndexOrThrow(Db.Edisi.aktif); int col_judul = cursor.getColumnIndexOrThrow(Db.Edisi.judul); int col_keterangan = cursor.getColumnIndexOrThrow(Db.Edisi.keterangan); int col_namafile = cursor.getColumnIndexOrThrow(Db.Edisi.namafile); int col_namafile_pdbasal = cursor.getColumnIndexOrThrow(Db.Edisi.namafile_pdbasal); int col_urutan = cursor.getColumnIndexOrThrow(Db.Edisi.urutan); while (cursor.moveToNext()) { MEdisiYes yes = new MEdisiYes(); yes.cache_aktif = cursor.getInt(col_aktif) != 0; yes.jenis = Db.Edisi.jenis_yes; yes.keterangan = cursor.getString(col_keterangan); yes.judul = cursor.getString(col_judul); yes.namafile = cursor.getString(col_namafile); yes.namafile_pdbasal = cursor.getString(col_namafile_pdbasal); yes.urutan = cursor.getInt(col_urutan); res.add(yes); } } finally { cursor.close(); } return res; } public void setEdisiYesAktif(String namafile, boolean aktif) { SQLiteDatabase db = helper.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(Db.Edisi.aktif, aktif? 1: 0); db.update(Db.TABEL_Edisi, cv, Db.Edisi.jenis + "=? and " + Db.Edisi.namafile + "=?", new String[] {String.valueOf(Db.Edisi.jenis_yes), namafile}); //$NON-NLS-1$ //$NON-NLS-2$ } public int getUrutanTerbesarEdisiYes() { SQLiteDatabase db = helper.getReadableDatabase(); SQLiteStatement stmt = db.compileStatement("select max(" + Db.Edisi.urutan + ") from " + Db.TABEL_Edisi); //$NON-NLS-1$//$NON-NLS-2$ return (int) stmt.simpleQueryForLong(); } public void tambahEdisiYesDenganAktif(MEdisiYes edisi, boolean aktif) { SQLiteDatabase db = helper.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(Db.Edisi.aktif, aktif); cv.put(Db.Edisi.jenis, Db.Edisi.jenis_yes); cv.put(Db.Edisi.judul, edisi.judul); cv.put(Db.Edisi.keterangan, edisi.keterangan); cv.put(Db.Edisi.namafile, edisi.namafile); cv.put(Db.Edisi.namafile_pdbasal, edisi.namafile_pdbasal); cv.put(Db.Edisi.urutan, edisi.urutan); Log.d(TAG, "tambah edisi yes: " + cv.toString()); //$NON-NLS-1$ db.insert(Db.TABEL_Edisi, null, cv); } public boolean adakahEdisiYesDenganNamafile(String namafile) { SQLiteDatabase db = helper.getReadableDatabase(); SQLiteStatement stmt = db.compileStatement("select count(*) from " + Db.TABEL_Edisi + " where " + Db.Edisi.jenis + "=? and " + Db.Edisi.namafile + "=?"); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$ stmt.clearBindings(); stmt.bindLong(1, Db.Edisi.jenis_yes); stmt.bindString(2, namafile); return stmt.simpleQueryForLong() > 0; } public void hapusEdisiYes(MEdisiYes edisi) { SQLiteDatabase db = helper.getWritableDatabase(); db.delete(Db.TABEL_Edisi, Db.Edisi.namafile + "=?", new String[] {edisi.namafile}); //$NON-NLS-1$ } public List<Label> listSemuaLabel() { List<Label> res = new ArrayList<Label>(); Cursor cursor = helper.getReadableDatabase().query(Db.TABEL_Label, null, null, null, null, null, Db.Label.urutan + " asc"); //$NON-NLS-1$ try { while (cursor.moveToNext()) { res.add(Label.fromCursor(cursor)); } } finally { cursor.close(); } return res; } /** * @return null when not found */ public List<Label> listLabels(long bukmak2_id) { List<Label> res = null; Cursor cursor = helper.getReadableDatabase().rawQuery("select " + Db.TABEL_Label + ".* from " + Db.TABEL_Label + ", " + Db.TABEL_Bukmak2_Label + " where " + Db.TABEL_Bukmak2_Label + "." + Db.Bukmak2_Label.label_id + " = " + Db.TABEL_Label + "." + BaseColumns._ID + " and " + Db.TABEL_Bukmak2_Label + "." + Db.Bukmak2_Label.bukmak2_id + " = ? order by " + Db.TABEL_Label + "." + Db.Label.urutan + " asc", new String[] {String.valueOf(bukmak2_id)}); try { while (cursor.moveToNext()) { if (res == null) res = new ArrayList<Label>(); res.add(Label.fromCursor(cursor)); } } finally { cursor.close(); } return res; } public int getUrutanTerbesarLabel() { SQLiteDatabase db = helper.getReadableDatabase(); SQLiteStatement stmt = db.compileStatement("select max(" + Db.Label.urutan + ") from " + Db.TABEL_Label); //$NON-NLS-1$//$NON-NLS-2$ return (int) stmt.simpleQueryForLong(); } public Label tambahLabel(String judul) { Label res = new Label(-1, judul, getUrutanTerbesarLabel() + 1, ""); SQLiteDatabase db = helper.getWritableDatabase(); long _id = db.insert(Db.TABEL_Label, null, res.toContentValues()); if (_id == -1) { return null; } else { res._id = _id; return res; } } public void updateLabels(Bukmak2 bukmak, Set<Label> labels) { SQLiteDatabase db = helper.getWritableDatabase(); db.beginTransaction(); try { // hapus semua db.delete(Db.TABEL_Bukmak2_Label, Db.Bukmak2_Label.bukmak2_id + "= ?", new String[] {String.valueOf(bukmak._id)}); // tambah semua ContentValues cv = new ContentValues(); for (Label label: labels) { cv.put(Db.Bukmak2_Label.bukmak2_id, bukmak._id); cv.put(Db.Bukmak2_Label.label_id, label._id); db.insert(Db.TABEL_Bukmak2_Label, null, cv); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } public Label getLabelById(long labelId) { SQLiteDatabase db = helper.getReadableDatabase(); Cursor cursor = db.query(Db.TABEL_Label, null, BaseColumns._ID + "=?", new String[] {String.valueOf(labelId)}, null, null, null); try { if (cursor.moveToNext()) { return Label.fromCursor(cursor); } else { return null; } } finally { cursor.close(); } } public void hapusLabelById(long id) { SQLiteDatabase db = helper.getWritableDatabase(); db.beginTransaction(); try { String[] params = new String[] {String.valueOf(id)}; db.delete(Db.TABEL_Bukmak2_Label, Db.Bukmak2_Label.label_id + "=?", params); //$NON-NLS-1$ db.delete(Db.TABEL_Label, "_id=?", params); //$NON-NLS-1$ db.setTransactionSuccessful(); } finally { db.endTransaction(); } } public void renameLabel(Label label, String judul) { SQLiteDatabase db = helper.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(Db.Label.judul, judul); db.update(Db.TABEL_Label, cv, "_id=?", new String[] {String.valueOf(label._id)}); } }
package playn.tests.core; import java.util.ArrayList; import java.util.List; import pythagoras.f.FloatMath; import pythagoras.f.Rectangle; import playn.core.ImmediateLayer; import playn.core.AssetWatcher; import playn.core.GroupLayer; import playn.core.Image; import playn.core.Pattern; import playn.core.Surface; import playn.core.SurfaceLayer; import static playn.core.PlayN.*; public class SurfaceTest extends Test { private List<SurfaceLayer> dots = new ArrayList<SurfaceLayer>(); private SurfaceLayer paintUpped; private Rectangle dotBox; private float elapsed; @Override public String getName() { return "SurfaceTest"; } @Override public String getDescription() { return "Tests various Surface rendering features."; } @Override public void init() { final Image tile = assets().getImage("images/tile.png"); final Image orange = assets().getImage("images/orange.png"); AssetWatcher watcher = new AssetWatcher(new AssetWatcher.Listener() { public void done() { addTests(orange, tile); } public void error(Throwable err) { addDescrip("Error: " + err.getMessage(), 10, errY, graphics().width()-20); errY += 30; } private float errY = 10; }); watcher.add(tile); watcher.add(orange); watcher.start(); } protected void addTests (final Image orange, Image tile) { final Pattern pattern = tile.toPattern(); int samples = 128; // big enough to force a buffer size increase final float[] verts = new float[(samples+1)*4]; final int[] indices = new int[samples*6]; tessellateCurve(0, 40*(float)Math.PI, verts, indices, new F() { public float apply (float x) { return (float)Math.sin(x/20)*50; } }); float ygap = 20, ypos = 10; // draw some wide lines ypos = ygap + addTest(10, ypos, new ImmediateLayer.Renderer() { public void render (Surface surf) { drawLine(surf, 0, 0, 50, 50, 15); drawLine(surf, 70, 50, 120, 0, 10); drawLine(surf, 0, 70, 120, 120, 10); } }, 120, 120, "drawLine with width"); ypos = ygap + addTest(20, ypos, new ImmediateLayer.Renderer() { public void render (Surface surf) { surf.setFillColor(0xFF0000FF).fillRect(0, 0, 100, 25); // these two alpha fills should look the same surf.setFillColor(0x80FF0000).fillRect(0, 0, 50, 25); surf.setAlpha(0.5f).setFillColor(0xFFFF0000).fillRect(50, 0, 50, 25).setAlpha(1f); } }, 100, 25, "left and right half both same color"); ypos = ygap + addTest(20, ypos, new ImmediateLayer.Renderer() { public void render (Surface surf) { surf.setFillColor(0xFF0000FF).fillRect(0, 0, 100, 50); surf.setAlpha(0.5f); surf.drawImage(orange, 55, 5); surf.fillRect(0, 50, 50, 50); surf.drawImage(orange, 55, 55); surf.setAlpha(1f); } }, 100, 100, "fillRect and drawImage at 50% alpha"); ypos = 10; ypos = ygap + addTest(160, ypos, new ImmediateLayer.Renderer() { public void render (Surface surf) { // fill some shapes with patterns surf.setFillPattern(pattern).fillRect(10, 0, 100, 100); // use same fill pattern for the triangles surf.translate(0, 160); surf.fillTriangles(verts, indices); } }, 120, 210, "ImmediateLayer patterned fillRect, fillTriangles"); SurfaceLayer slayer = graphics().createSurfaceLayer(100, 100); slayer.surface().setFillPattern(pattern).fillRect(0, 0, 100, 100); ypos = ygap + addTest(170, ypos, slayer, "SurfaceLayer patterned fillRect"); ypos = 10; // fill a patterned quad in a clipped group layer final int twidth = 150, theight = 75; GroupLayer group = graphics().createGroupLayer(); ypos = ygap + addTest(315, 10, group, twidth, theight, "Clipped pattern should not exceed grey rectangle"); group.add(graphics().createImmediateLayer(new ImmediateLayer.Renderer() { public void render (Surface surf) { surf.setFillColor(0xFFCCCCCC).fillRect(0, 0, twidth, theight); } })); group.add(graphics().createImmediateLayer(twidth, theight, new ImmediateLayer.Renderer() { public void render (Surface surf) { surf.setFillPattern(pattern).fillRect(-10, -10, twidth+20, theight+20); } })); // draw some randomly jiggling dots inside a bounded region dotBox = new Rectangle(315, ypos, 200, 100); ypos = ygap + addTest(dotBox.x, dotBox.y, new ImmediateLayer.Renderer() { public void render (Surface surf) { surf.setFillColor(0xFFCCCCCC).fillRect(0, 0, dotBox.width, dotBox.height); } }, dotBox.width, dotBox.height, "Randomly positioned SurfaceLayers"); for (int ii = 0; ii < 10; ii++) { SurfaceLayer dot = graphics().createSurfaceLayer(10, 10); dot.surface().setFillColor(0xFFFF0000); dot.surface().fillRect(0, 0, 5, 5); dot.surface().fillRect(5, 5, 5, 5); dot.surface().setFillColor(0xFF0000FF); dot.surface().fillRect(5, 0, 5, 5); dot.surface().fillRect(0, 5, 5, 5); dot.setTranslation(dotBox.x + random()*(dotBox.width-10), dotBox.y + random()*(dotBox.height-10)); dots.add(dot); // System.err.println("Created dot at " + dot.transform()); graphics().rootLayer().add(dot); } // add a surface layer that is updated on every call to paint (a bad practice, but one that // should actually work) paintUpped = graphics().createSurfaceLayer(100, 100); ypos = ygap + addTest(315, ypos, paintUpped, "SurfaceLayer updated in paint()"); } protected float addTest(float lx, float ly, ImmediateLayer.Renderer renderer, float lwidth, float lheight, String descrip) { return addTest(lx, ly, graphics().createImmediateLayer(renderer), lwidth, lheight, descrip); } @Override public void update(float delta) { super.update(delta); elapsed += delta; } @Override public void paint(float alpha) { super.paint(alpha); for (SurfaceLayer dot : dots) { if (random() > 0.95) { dot.setTranslation(dotBox.x + random()*(dotBox.width-10), dotBox.y + random()*(dotBox.height-10)); } } if (paintUpped != null) { float sin = Math.abs(FloatMath.sin(elapsed)), cos = Math.abs(FloatMath.cos(elapsed)); int sinColor = (int)(sin * 255), cosColor = (int)(cos * 255); int c1 = (0xFF << 24) | (sinColor << 16) | (cosColor << 8); int c2 = (0xFF << 24) | (cosColor << 16) | (sinColor << 8); paintUpped.surface().clear(); paintUpped.surface().setFillColor(c1).fillRect(0, 0, 50, 50); paintUpped.surface().setFillColor(c2).fillRect(50, 50, 50, 50); } } void drawLine(Surface surf, float x1, float y1, float x2, float y2, float width) { float xmin = Math.min(x1, x2), xmax = Math.max(x1, x2); float ymin = Math.min(y1, y2), ymax = Math.max(y1, y2); surf.setFillColor(0xFF0000AA); surf.fillRect(xmin, ymin, xmax-xmin, ymax-ymin); surf.setFillColor(0xFF99FFCC); surf.drawLine(x1, y1, x2, y2, width); surf.setFillColor(0xFFFF0000); surf.fillRect(x1, y1, 1, 1); surf.fillRect(x2, y2, 1, 1); } private interface F { public float apply (float x); } void tessellateCurve (float minx, float maxx, float[] verts, int[] indices, F f) { int slices = (verts.length-1)/4, vv = 0; float dx = (maxx-minx)/slices; for (float x = minx; x < maxx; x += dx) { verts[vv++] = x; verts[vv++] = 0; verts[vv++] = x; verts[vv++] = f.apply(x); } for (int ss = 0, ii = 0; ss < slices; ss++) { int base = ss*2; indices[ii++] = base; indices[ii++] = base+1; indices[ii++] = base+3; indices[ii++] = base; indices[ii++] = base+3; indices[ii++] = base+2; } } }
package som.vmobjects; import java.util.Arrays; import org.graalvm.collections.EconomicMap; import org.graalvm.collections.MapCursor; import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.CompilerDirectives.CompilationFinal; import com.oracle.truffle.api.nodes.ExplodeLoop; import som.compiler.MixinDefinition.SlotDefinition; import som.interpreter.objectstorage.ClassFactory; import som.interpreter.objectstorage.ObjectLayout; import som.interpreter.objectstorage.StorageLocation; import som.interpreter.objectstorage.StorageLocation.DoubleStorageLocation; import som.interpreter.objectstorage.StorageLocation.LongStorageLocation; import som.interpreter.objectstorage.StorageLocation.ObjectStorageLocation; import som.interpreter.objectstorage.StorageLocation.UnwrittenStorageLocation; import som.vm.constants.Nil; public abstract class SObject extends SObjectWithClass { public static final int NUM_PRIMITIVE_FIELDS = 5; public static final int NUM_OBJECT_FIELDS = 5; // TODO: when we got the possibility that we can hint to the compiler that a // read is from a final field, we should remove this public static final class SImmutableObject extends SObject { public SImmutableObject(final SClass instanceClass, final ClassFactory classGroup, final ObjectLayout layout) { super(instanceClass, classGroup, layout); field1 = field2 = field3 = field4 = field5 = Nil.nilObject; isValue = instanceClass.declaredAsValue(); } public SImmutableObject(final boolean incompleteDefinition, final boolean isKernelObj) { super(incompleteDefinition); assert isKernelObj; isValue = true; } /** * Copy constructor. */ private SImmutableObject(final SImmutableObject old) { super(old); this.primField1 = old.primField1; this.primField2 = old.primField2; this.primField3 = old.primField3; this.primField4 = old.primField4; this.primField5 = old.primField5; this.isValue = old.isValue; } @CompilationFinal public long primField1; @CompilationFinal public long primField2; @CompilationFinal public long primField3; @CompilationFinal public long primField4; @CompilationFinal public long primField5; @CompilationFinal public Object field1; @CompilationFinal public Object field2; @CompilationFinal public Object field3; @CompilationFinal public Object field4; @CompilationFinal public Object field5; @CompilationFinal protected boolean isValue; @Override protected void resetFields() { field1 = field2 = field3 = field4 = field5 = null; primField1 = primField2 = primField3 = primField4 = primField5 = Long.MIN_VALUE; } @Override public boolean isValue() { return isValue; } @Override public SObject cloneBasics() { assert !isValue : "There should not be any need to clone a value"; return new SImmutableObject(this); } } public static final class SMutableObject extends SObject { public long primField1; public long primField2; public long primField3; public long primField4; public long primField5; public Object field1; public Object field2; public Object field3; public Object field4; public Object field5; // this field exists because HotSpot reorders fields, and we need to keep // the layouts in sync to avoid having to manage different offsets for // SMutableObject and SImmuableObject @SuppressWarnings("unused") private boolean isValueOfSImmutableObjectSync; public SMutableObject(final SClass instanceClass, final ClassFactory factory, final ObjectLayout layout) { super(instanceClass, factory, layout); field1 = field2 = field3 = field4 = field5 = Nil.nilObject; } public SMutableObject(final boolean incompleteDefinition) { super(incompleteDefinition); } protected SMutableObject(final SMutableObject old) { super(old); this.primField1 = old.primField1; this.primField2 = old.primField2; this.primField3 = old.primField3; this.primField4 = old.primField4; this.primField5 = old.primField5; } @Override protected void resetFields() { field1 = field2 = field3 = field4 = field5 = null; primField1 = primField2 = primField3 = primField4 = primField5 = Long.MIN_VALUE; } @Override public boolean isValue() { return false; } @Override public SObject cloneBasics() { return new SMutableObject(this); } public SMutableObject shallowCopy() { SMutableObject copy = new SMutableObject(true); copy.primField1 = primField1; copy.primField2 = primField2; copy.primField3 = primField3; copy.primField4 = primField4; copy.primField5 = primField5; copy.classGroup = classGroup; copy.clazz = clazz; copy.objectLayout = objectLayout; copy.primitiveUsedMap = primitiveUsedMap; copy.field1 = field1; copy.field2 = field2; copy.field3 = field3; copy.field4 = field4; copy.field5 = field5; if (extensionPrimFields != null) { copy.extensionPrimFields = extensionPrimFields.clone(); } if (extensionObjFields != null) { copy.extensionObjFields = extensionObjFields.clone(); } return copy; } public boolean txEquals(final SMutableObject o) { // TODO: we actually need to take the object layout into account, // iff we want to ignore class slot stuff... // might be easier to just handle those return o.primField1 == primField1 && o.primField2 == primField2 && o.primField3 == primField3 && o.primField4 == primField4 && o.primField5 == primField5 && o.classGroup == classGroup && // TODO: should not be necessary o.clazz == clazz && // TODO: should not be necessary o.primitiveUsedMap == primitiveUsedMap && // TODO: necessary? Arrays.equals(o.extensionPrimFields, extensionPrimFields) && txMutObjLocEquals(o); } private boolean txMutObjLocEquals(final SMutableObject o) { EconomicMap<SlotDefinition, StorageLocation> oLocs = o.objectLayout.getStorageLocations(); EconomicMap<SlotDefinition, StorageLocation> locs = objectLayout.getStorageLocations(); MapCursor<SlotDefinition, StorageLocation> e = locs.getEntries(); while (e.advance()) { // need to ignore mutators and class slots if (e.getKey().getClass() == SlotDefinition.class && e.getValue().read(this) != oLocs.get(e.getKey()).read(o)) { return false; } } return true; } public void txSet(final SMutableObject wc) { primField1 = wc.primField1; primField2 = wc.primField2; primField3 = wc.primField3; primField4 = wc.primField4; primField5 = wc.primField5; classGroup = wc.classGroup; // TODO: should not be necessary clazz = wc.clazz; // TODO: should not be necessary objectLayout = wc.objectLayout; primitiveUsedMap = wc.primitiveUsedMap; extensionPrimFields = wc.extensionPrimFields; txSetMutObjLoc(wc); } /** Only set the mutable slots. */ private void txSetMutObjLoc(final SMutableObject wc) { EconomicMap<SlotDefinition, StorageLocation> oLocs = wc.objectLayout.getStorageLocations(); MapCursor<SlotDefinition, StorageLocation> e = oLocs.getEntries(); while (e.advance()) { // need to ignore mutators and class slots if (e.getKey().getClass() == SlotDefinition.class) { Object val = e.getValue().read(wc); this.writeSlot(e.getKey(), val); } } } } // TODO: if there is the possibility that we can hint that a read is from a // final field, we should reconsider removing these and store them in // normal object fields @CompilationFinal(dimensions = 0) protected long[] extensionPrimFields; @CompilationFinal(dimensions = 0) protected Object[] extensionObjFields; // we manage the layout entirely in the class, but need to keep a copy here // to know in case the layout changed that we can update the instances lazily @CompilationFinal protected ObjectLayout objectLayout; public int primitiveUsedMap; public SObject(final SClass instanceClass, final ClassFactory factory, final ObjectLayout layout) { super(instanceClass, factory); assert factory.getInstanceLayout() == layout || layout.layoutForSameClasses(factory.getInstanceLayout()); setLayoutInitially(layout); } public SObject(final boolean incompleteDefinition) { assert incompleteDefinition; // used during bootstrap } /** Copy Constructor. */ protected SObject(final SObject old) { super(old); this.objectLayout = old.objectLayout; this.primitiveUsedMap = old.primitiveUsedMap; // TODO: these tests should be compilation constant based on the object layout, check // whether this needs to be optimized // we copy the content here, because we know they are all values if (old.extensionPrimFields != null) { this.extensionPrimFields = old.extensionPrimFields.clone(); } // do not want to copy the content for the obj extension array, because // transfer should handle each of them. if (old.extensionObjFields != null) { this.extensionObjFields = new Object[old.extensionObjFields.length]; } } /** * @return new object of the same type, initialized with same primitive * values, object layout etc. Object fields are not cloned. No deep copying * either. This method is used for cloning transfer objects. */ public abstract SObject cloneBasics(); private void setLayoutInitially(final ObjectLayout layout) { CompilerAsserts.partialEvaluationConstant(layout); objectLayout = layout; extensionPrimFields = getExtendedPrimStorage(layout); extensionObjFields = getExtendedObjectStorage(layout); } public final ObjectLayout getObjectLayout() { // TODO: should I really remove it, or should I update the layout? // assert clazz.getLayoutForInstances() == objectLayout; return objectLayout; } public final long[] getExtendedPrimFields() { return extensionPrimFields; } public final Object[] getExtensionObjFields() { return extensionObjFields; } @Override public final void setClass(final SClass value) { CompilerAsserts.neverPartOfCompilation( "Only meant to be used in object system initalization"); super.setClass(value); setLayoutInitially(value.getLayoutForInstancesUnsafe()); } private long[] getExtendedPrimStorage(final ObjectLayout layout) { int numExtFields = layout.getNumberOfUsedExtendedPrimStorageLocations(); CompilerAsserts.partialEvaluationConstant(numExtFields); if (numExtFields == 0) { return null; } else { return new long[numExtFields]; } } private Object[] getExtendedObjectStorage(final ObjectLayout layout) { int numExtFields = layout.getNumberOfUsedExtendedObjectStorageLocations(); CompilerAsserts.partialEvaluationConstant(numExtFields); if (numExtFields == 0) { return null; } Object[] storage = new Object[numExtFields]; Arrays.fill(storage, Nil.nilObject); return storage; } @ExplodeLoop private EconomicMap<SlotDefinition, Object> getAllFields() { assert objectLayout != null; EconomicMap<SlotDefinition, StorageLocation> locations = objectLayout.getStorageLocations(); EconomicMap<SlotDefinition, Object> fieldValues = EconomicMap.create((int) (locations.size() / 0.75f)); MapCursor<SlotDefinition, StorageLocation> loc = locations.getEntries(); while (loc.advance()) { if (loc.getValue().isSet(this)) { fieldValues.put(loc.getKey(), loc.getValue().read(this)); } else { fieldValues.put(loc.getKey(), null); } } return fieldValues; } protected abstract void resetFields(); @ExplodeLoop private void setAllFields(final EconomicMap<SlotDefinition, Object> fieldValues) { resetFields(); primitiveUsedMap = 0; MapCursor<SlotDefinition, Object> entry = fieldValues.getEntries(); while (entry.advance()) { if (entry.getValue() != null) { writeSlot(entry.getKey(), entry.getValue()); } else if (getLocation(entry.getKey()) instanceof ObjectStorageLocation) { writeSlot(entry.getKey(), Nil.nilObject); } } } public final boolean isLayoutCurrent() { return objectLayout == clazz.getLayoutForInstancesUnsafe() && objectLayout.isValid(); } public final synchronized boolean updateLayoutToMatchClass() { ObjectLayout layoutAtClass = clazz.getLayoutForInstancesToUpdateObject(); if (objectLayout != layoutAtClass) { setLayoutAndTransferFields(layoutAtClass); return true; } else { return false; } } private void setLayoutAndTransferFields(final ObjectLayout layoutAtClass) { CompilerDirectives.transferToInterpreterAndInvalidate(); EconomicMap<SlotDefinition, Object> fieldValues = getAllFields(); objectLayout = layoutAtClass; extensionPrimFields = getExtendedPrimStorage(layoutAtClass); extensionObjFields = getExtendedObjectStorage(layoutAtClass); setAllFields(fieldValues); } /** * Since this operation is racy with other initializations of the field, we * first check whether the slot is unwritten. If that is the case, the slot * is initialized. Otherwise, we check whether the field needs to be * generalized. * * <p> * <strong>Note:</strong> This method is expected to be called while * holding a lock on <code>this</code>. */ protected final void updateLayoutWithInitializedField( final SlotDefinition slot, final Class<?> type) { StorageLocation loc = objectLayout.getStorageLocation(slot); if (loc instanceof UnwrittenStorageLocation) { ObjectLayout layout = classGroup.updateInstanceLayoutWithInitializedField(slot, type); assert objectLayout != layout; setLayoutAndTransferFields(layout); } else if ((type == Long.class && !(loc instanceof LongStorageLocation)) || (type == Double.class && !(loc instanceof DoubleStorageLocation))) { updateLayoutWithGeneralizedField(slot); } } /** * Since this operation is racy with other generalizations of the field, we * first check whether the slot is not already using an * {@link ObjectStorageLocation}. If it is using one, another generalization * happened already, and we don't need to do it anymore. * * <p> * <strong>Note:</strong> This method is expected to be called while * holding a lock on <code>this</code>. */ protected final void updateLayoutWithGeneralizedField(final SlotDefinition slot) { StorageLocation loc = objectLayout.getStorageLocation(slot); if (!(loc instanceof ObjectStorageLocation)) { ObjectLayout layout = classGroup.updateInstanceLayoutWithGeneralizedField(slot); assert objectLayout != layout; setLayoutAndTransferFields(layout); } } public static int getPrimitiveFieldMask(final int fieldIndex) { assert 0 <= fieldIndex && fieldIndex < 32; // this limits the number of object fields for // the moment... return 1 << fieldIndex; } private StorageLocation getLocation(final SlotDefinition slot) { StorageLocation location = objectLayout.getStorageLocation(slot); assert location != null; return location; } public final Object readSlot(final SlotDefinition slot) { CompilerAsserts.neverPartOfCompilation("getField"); StorageLocation location = getLocation(slot); return location.read(this); } public final synchronized void writeUninitializedSlot(final SlotDefinition slot, final Object value) { updateLayoutWithInitializedField(slot, value.getClass()); setFieldAfterLayoutChange(slot, value); } public final synchronized void writeAndGeneralizeSlot(final SlotDefinition slot, final Object value) { updateLayoutWithGeneralizedField(slot); setFieldAfterLayoutChange(slot, value); } public final void writeSlot(final SlotDefinition slot, final Object value) { CompilerAsserts.neverPartOfCompilation("setField"); StorageLocation location = getLocation(slot); location.write(this, value); } private void setFieldAfterLayoutChange(final SlotDefinition slot, final Object value) { CompilerAsserts.neverPartOfCompilation("SObject.setFieldAfterLayoutChange(..)"); StorageLocation location = getLocation(slot); location.write(this, value); } }
package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.scenes.scene2d.OnActionCompleted; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.actions.Delay; import com.badlogic.gdx.scenes.scene2d.actions.MoveBy; import com.badlogic.gdx.scenes.scene2d.actions.Repeat; import com.badlogic.gdx.scenes.scene2d.actions.Sequence; import com.badlogic.gdx.scenes.scene2d.actors.Image; import com.badlogic.gdx.tests.utils.GdxTest; public class ActionTest extends GdxTest implements OnActionCompleted { @Override public boolean needsGL20() { return false; } Stage stage; @Override public void create() { stage = new Stage(480, 320, true); Texture texture = new Texture(Gdx.files.internal("data/badlogic.jpg"), false); texture.setFilter(TextureFilter.Linear, TextureFilter.Linear); Image img = new Image("actor", texture); img.width = img.height = 100; img.originX = 50; img.originY = 50; img.x = img.y = 100; // img.action(Forever.$(Sequence.$(ScaleTo.$(1.1f, // 1.1f,0.3f),ScaleTo.$(1f, 1f, 0.3f)))); // img.action(Forever.$(Parallel.$(RotateTo.$(1, 1)))); // img.action(Delay.$(RotateBy.$(45, 2), // 1).setCompletionListener(this)); // Action actionMoveBy = MoveBy.$(30, 0, 0.5f).setCompletionListener( // new OnActionCompleted() { // @Override // public void completed(Action action) { // System.out.println("move by complete"); // Action actionDelay = Delay.$(actionMoveBy, 1).setCompletionListener( // new OnActionCompleted() { // @Override // public void completed(Action action) { // System.out.println("delay complete"); // img.action(actionDelay); img.action(Repeat.$(Sequence.$(MoveBy.$(50, 0, 1), MoveBy.$(0, 50, 1), MoveBy.$(-50, 0, 1), MoveBy.$(0, -50, 1)), 3)); stage.addActor(img); } @Override public void render() { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f)); stage.draw(); } @Override public void completed(Action action) { System.out.println("completed"); } }
package java.lang; import java.lang.annotation.Annotation; import java.net.URL; public class Package implements java.lang.reflect.AnnotatedElement { private final String pkgName; private final String specTitle; private final String specVersion; private final String specVendor; private final String implTitle; private final String implVersion; private final String implVendor; public String getName() { return pkgName; } public String getSpecificationTitle() { return specTitle; } public String getSpecificationVersion() { return specVersion; } public String getSpecificationVendor() { return specVendor; } public String getImplementationTitle() { return implTitle; } public String getImplementationVersion() { return implVersion; } public String getImplementationVendor() { return implVendor; } public static Package getPackage(String name) { return null; } public static void package2Array (Package pkgs, Package[] arrayPkg) { /** * @j2sNative * for(var n in pkgs) { * if(pkgs[n].__PKG_NAME__) { * arrayPkg.push(pkgs[n]); * this.package2Array(pkgs[n], arrayPkg); * } * } **/{} } public static Package[] getPackages() { /** * @j2sNative * var pkgs=[]; * var allPkg = Clazz.allPackage; * this.package2Array(allPkg, pkgs); * return pkgs; **/{} return null; } public int hashCode(){ return pkgName.hashCode(); } public String toString() { return "package " + pkgName; } Package(String name, String spectitle, String specversion, String specvendor, String impltitle, String implversion, String implvendor, URL sealbase, ClassLoader loader) { pkgName = name; implTitle = impltitle; implVersion = implversion; implVendor = implvendor; specTitle = spectitle; specVersion = specversion; specVendor = specvendor; } public boolean isAnnotationPresent(java.lang.Class<? extends Annotation> annotationType) { // TODO Auto-generated method stub return false; } public <T extends Annotation> T getAnnotation(java.lang.Class<T> annotationType) { // TODO Auto-generated method stub return null; } public Annotation[] getAnnotations() { // TODO Auto-generated method stub return null; } public Annotation[] getDeclaredAnnotations() { // TODO Auto-generated method stub return null; } }
package com.echsylon.atlantis; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializer; import java.util.List; import java.util.Map; import static com.echsylon.atlantis.LogUtils.info; import static com.echsylon.atlantis.Utils.isEmpty; import static com.echsylon.atlantis.Utils.notEmpty; /** * This class provides a set of custom JSON deserializers. */ class JsonSerializers { /** * Returns a new JSON deserializer, specialized for {@link SettingsManager} * objects. * * @return The deserializer to parse {@code SettingsManager} JSON with. */ static JsonDeserializer<SettingsManager> newSettingsDeserializer() { return (json, typeOfT, context) -> { if (json == null) return null; SettingsManager settingsManager = new SettingsManager(); if (json.isJsonObject()) { JsonObject jsonObject = json.getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) { JsonElement jsonElement = entry.getValue(); if (jsonElement.isJsonPrimitive()) settingsManager.set(entry.getKey(), jsonElement.getAsString()); } } return settingsManager; }; } /** * Returns a new JSON serializer, specialized for {@link SettingsManager} * objects. * * @return The serializer to serialize {@code SettingsManager} objects with. */ static JsonSerializer<SettingsManager> newSettingsSerializer() { return (settingsManager, typeOfObject, context) -> { if (settingsManager == null) return null; Map<String, String> settings = settingsManager.getAllAsMap(); if (isEmpty(settings)) return null; JsonObject jsonObject = new JsonObject(); for (Map.Entry<String, String> entry : settings.entrySet()) jsonObject.addProperty(entry.getKey(), entry.getValue()); return jsonObject; }; } /** * Returns a new JSON deserializer, specialized for {@link HeaderManager} * objects. * * @return The deserializer to parse {@code HeaderManager} JSON with. */ static JsonDeserializer<HeaderManager> newHeaderDeserializer() { return (json, typeOfT, context) -> { if (json == null) return null; HeaderManager headerManager = new HeaderManager(); if (json.isJsonObject()) { // Recommended dictionary style headers JsonObject jsonObject = json.getAsJsonObject(); for (Map.Entry<String, JsonElement> property : jsonObject.entrySet()) { String key = property.getKey(); JsonElement jsonElement = property.getValue(); if (jsonElement.isJsonPrimitive()) { // Single header value for the key headerManager.add(key, jsonElement.getAsString()); } else if (jsonElement.isJsonArray()) { // Multiple header values for the key JsonArray jsonArray = jsonElement.getAsJsonArray(); for (JsonElement e : jsonArray) if (e.isJsonPrimitive()) headerManager.add(key, e.getAsString()); } } } else if (json.isJsonArray()) { // List of objects with "key" + "value" properties JsonArray jsonArray = json.getAsJsonArray(); for (JsonElement jsonElement : jsonArray) { if (jsonElement.isJsonObject()) { JsonObject jsonObject = jsonElement.getAsJsonObject(); if (jsonObject.has("key") && jsonObject.has("value")) { String key = jsonObject.get("key").getAsString(); String value = jsonObject.get("value").getAsString(); headerManager.add(key, value); } } } } else if (json.isJsonPrimitive()) { // New-Line separated headers (as expressed by Postman v1) String[] strings = json.getAsString().split("\n"); for (String string : strings) { int index = string.indexOf(':'); int maxIndex = string.length() - 1; if (index != -1 && index < maxIndex) { // Everything before the first ':' is seen as a key and // everything after it is considered a value String key = string.substring(0, index).trim(); String value = string.substring(index + 1).trim(); headerManager.add(key, value); } } } return headerManager; }; } /** * Returns a new JSON serializer, specialized for {@link HeaderManager} * objects. * * @return The serializer to serialize {@code HeaderManager} objects with. */ static JsonSerializer<HeaderManager> newHeaderSerializer() { return (headerManager, typeOfObject, context) -> { if (headerManager == null) return null; Map<String, List<String>> headers = headerManager.getAllAsMultiMap(); if (isEmpty(headers)) return null; JsonObject jsonObject = new JsonObject(); for (Map.Entry<String, List<String>> entry : headers.entrySet()) { List<String> values = entry.getValue(); int count = values.size(); if (count == 1) { // Single value; add as string jsonObject.addProperty(entry.getKey(), values.get(0)); } else if (count > 1) { // Multiple values; add as array JsonArray jsonArray = new JsonArray(); for (String value : values) jsonArray.add(value); jsonObject.add(entry.getKey(), jsonArray); } } return jsonObject; }; } /** * Returns a new JSON deserializer, specialized for {@link Configuration} * objects. * * @return The deserializer to parse {@code Configuration} JSON with. */ static JsonDeserializer<Configuration> newConfigurationDeserializer() { return (json, typeOfT, context) -> { if (json == null) return null; JsonObject jsonObject = json.getAsJsonObject(); Configuration.Builder builder = new Configuration.Builder(); if (jsonObject.has("fallbackBaseUrl")) builder.setFallbackBaseUrl(jsonObject.get("fallbackBaseUrl").getAsString()); if (jsonObject.has("requestFilter")) try { String filterClassName = jsonObject.get("requestFilter").getAsString(); MockRequest.Filter filter = (MockRequest.Filter) Class.forName(filterClassName).newInstance(); builder.setRequestFilter(filter); } catch (Exception e) { info(e, "Couldn't deserialize request filter"); } if (jsonObject.has("tokenHelper")) try { String helperClassName = jsonObject.get("tokenHelper").getAsString(); Atlantis.TokenHelper helper = (Atlantis.TokenHelper) Class.forName(helperClassName).newInstance(); builder.setTokenHelper(helper); } catch (Exception e) { info(e, "Couldn't deserialize token helper"); } if (jsonObject.has("transformationHelper")) try { String helperClassName = jsonObject.get("transformationHelper").getAsString(); Atlantis.TransformationHelper helper = (Atlantis.TransformationHelper) Class.forName(helperClassName).newInstance(); builder.setTransformationHelper(helper); } catch (Exception e) { info(e, "Couldn't deserialize transformation helper"); } if (jsonObject.has("defaultResponseHeaders")) try { JsonElement headers = jsonObject.get("defaultResponseHeaders"); HeaderManager headerManager = context.deserialize(headers, HeaderManager.class); builder.setDefaultResponseHeaderManager(headerManager); } catch (Exception e) { info(e, "Couldn't deserialize default response headers"); } if (jsonObject.has("defaultResponseSettings")) try { JsonElement settings = jsonObject.get("defaultResponseSettings"); SettingsManager settingsManager = context.deserialize(settings, SettingsManager.class); builder.setDefaultResponseSettingsManager(settingsManager); } catch (Exception e) { info(e, "Couldn't deserialize default response settings"); } if (jsonObject.has("requests")) try { JsonArray requests = jsonObject.get("requests").getAsJsonArray(); for (int i = 0, c = requests.size(); i < c; i++) builder.addRequest(context.deserialize(requests.get(i), MockRequest.class)); } catch (Exception e) { info(e, "Couldn't deserialize requests"); } return builder.build(); }; } /** * Returns a new JSON serializer, specialized for {@link Configuration} * objects. * * @return The serializer to serialize {@code Configuration} objects with. */ static JsonSerializer<Configuration> newConfigurationSerializer() { return (configuration, typeOfObject, context) -> { if (configuration == null) return null; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("fallbackBaseUrl", configuration.fallbackBaseUrl()); MockRequest.Filter filter = configuration.requestFilter(); if (filter != null) jsonObject.addProperty("requestFilter", filter.getClass().getCanonicalName()); Atlantis.TokenHelper tokenHelper = configuration.tokenHelper(); if (tokenHelper != null) jsonObject.addProperty("tokenHelper", tokenHelper.getClass().getCanonicalName()); Atlantis.TransformationHelper transformationHelper = configuration.transformationHelper(); if (transformationHelper != null) jsonObject.addProperty("transformationHelper", transformationHelper.getClass().getCanonicalName()); HeaderManager defaultResponseHeaderManager = configuration.defaultResponseHeaderManager(); if (defaultResponseHeaderManager.keyCount() > 0) jsonObject.add("defaultResponseHeaders", context.serialize(defaultResponseHeaderManager)); SettingsManager defaultResponseSettingsManager = configuration.defaultResponseSettingsManager(); if (defaultResponseSettingsManager.entryCount() > 0) jsonObject.add("defaultResponseSettings", context.serialize(defaultResponseSettingsManager)); List<MockRequest> requests = configuration.requests(); if (requests.size() > 0) jsonObject.add("requests", context.serialize(requests)); return jsonObject; }; } /** * Returns a new JSON deserializer, specialized for {@link MockRequest} * objects. * * @return The deserializer to parse {@code MockRequest} JSON with. */ static JsonDeserializer<MockRequest> newRequestDeserializer() { return (json, typeOfT, context) -> { if (json == null) return null; JsonObject jsonObject = json.getAsJsonObject(); MockRequest.Builder builder = new MockRequest.Builder(); builder.setMethod(jsonObject.get("method").getAsString()); builder.setUrl(jsonObject.get("url").getAsString()); if (jsonObject.has("responseFilter")) try { String filterClassName = jsonObject.get("responseFilter").getAsString(); MockResponse.Filter filter = (MockResponse.Filter) Class.forName(filterClassName).newInstance(); builder.setResponseFilter(filter); } catch (Exception e) { info(e, "Couldn't deserialize response filter"); } if (jsonObject.has("headers")) try { HeaderManager headerManager = context.deserialize(jsonObject.get("headers"), HeaderManager.class); builder.setHeaderManager(headerManager); } catch (Exception e) { info(e, "Couldn't deserialize headers"); } if (jsonObject.has("responses")) try { JsonArray responses = jsonObject.get("responses").getAsJsonArray(); for (int i = 0, c = responses.size(); i < c; i++) builder.addResponse(context.deserialize(responses.get(i), MockResponse.class)); } catch (Exception e) { info(e, "Couldn't deserialize responses"); } return builder.build(); }; } /** * Returns a new JSON serializer, specialized for {@link MockRequest} * objects. * * @return The serializer to serialize {@code MockRequest} objects with. */ static JsonSerializer<MockRequest> newRequestSerializer() { return (request, typeOfObject, context) -> { if (request == null) return null; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("method", request.method()); jsonObject.addProperty("url", request.url()); MockResponse.Filter filter = request.responseFilter(); if (filter != null) jsonObject.addProperty("responseFilter", filter.getClass().getCanonicalName()); HeaderManager headerManager = request.headerManager(); if (headerManager.keyCount() > 0) jsonObject.add("headers", context.serialize(headerManager)); List<MockResponse> responses = request.responses(); if (notEmpty(responses)) jsonObject.add("responses", context.serialize(responses)); return jsonObject; }; } /** * Returns a new JSON deserializer, specialized for {@link MockResponse} * objects. * * @return The deserializer to parse {@code MockResponse} objects with. */ static JsonDeserializer<MockResponse> newResponseDeserializer() { return (json, typeOfT, context) -> { if (json == null) return null; JsonObject jsonObject = json.getAsJsonObject(); MockResponse.Builder builder = new MockResponse.Builder(); if (jsonObject.has("source")) builder.setBody(jsonObject.get("source").getAsString()); else if (jsonObject.has("text")) builder.setBody(jsonObject.get("text").getAsString()); if (jsonObject.has("responseCode")) { // Assuming Postman v1 response status notation try { JsonObject statusObject = jsonObject.get("responseCode").getAsJsonObject(); builder.setStatus(statusObject.get("code").getAsInt(), statusObject.get("name").getAsString()); } catch (Exception e) { info(e, "Couldn't deserialize response code"); } } else { // Assuming default Atlantis status notation try { builder.setStatus(jsonObject.get("code").getAsInt(), jsonObject.get("phrase").getAsString()); } catch (Exception e) { info(e, "Couldn't deserialize response code and phrase"); } } if (jsonObject.has("headers")) try { JsonElement headers = jsonObject.get("headers"); HeaderManager headerManager = context.deserialize(headers, HeaderManager.class); builder.setHeaderManager(headerManager); } catch (Exception e) { info(e, "Couldn't deserialize headers"); } if (jsonObject.has("settings")) try { JsonElement settings = jsonObject.get("settings"); SettingsManager settingsManager = context.deserialize(settings, SettingsManager.class); builder.setSettingsManager(settingsManager); } catch (Exception e) { info(e, "Couldn't deserialize responses"); } return builder.build(); }; } /** * Returns a new JSON serializer, specialized for {@link MockResponse} * objects. * * @return The serializer to serialize {@code MockResponse} objects with. */ static JsonSerializer<MockResponse> newResponseSerializer() { return (response, typeOfObject, context) -> { if (response == null) return null; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("code", response.code()); jsonObject.addProperty("phrase", response.phrase()); String source = response.source(); if (notEmpty(source)) jsonObject.addProperty("source", source); HeaderManager headerManager = response.headerManager(); if (headerManager.keyCount() > 0) jsonObject.add("headers", context.serialize(headerManager)); SettingsManager settingsManager = response.settingsManager(); if (settingsManager.entryCount() > 0) jsonObject.add("settings", context.serialize(settingsManager)); return jsonObject; }; } }
package io.mangoo.persistence; import java.util.List; import java.util.Objects; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.google.common.base.Preconditions; import com.google.inject.Inject; import com.google.inject.Singleton; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import dev.morphia.DeleteOptions; import dev.morphia.Morphia; import dev.morphia.query.experimental.filters.Filters; import io.mangoo.core.Config; import io.mangoo.enums.Required; @Singleton public class Datastore { private static final Logger LOG = LogManager.getLogger(Datastore.class); private dev.morphia.Datastore datastore; //NOSONAR private MongoClient mongoClient; private Config config; @Inject public Datastore(Config config) { this.config = Objects.requireNonNull(config, Required.CONFIG.toString()); connect(); } public dev.morphia.Datastore getDatastore() { return this.datastore; } public dev.morphia.Datastore query() { return this.datastore; } public MongoClient getMongoClient() { return this.mongoClient; } private void connect() { this.mongoClient = MongoClients.create(getConnectionString()); if (this.config.isMongoAuth()) { this.datastore = Morphia.createDatastore(this.mongoClient, this.config.getMongoDbName()); LOG.info("Successfully created MongoClient @ {}:{} with authentication", this.config.getMongoHost(), this.config.getMongoPort()); } else { this.datastore = Morphia.createDatastore(this.mongoClient, this.config.getMongoDbName()); LOG.info("Successfully created MongoClient @ {}:{} ***without*** authentication", this.config.getMongoHost(), this.config.getMongoPort()); } this.datastore.getMapper().mapPackage(this.config.getMongoPackage()); LOG.info("Mapped Morphia models of package '" + this.config.getMongoPackage() + "' and created Morphia Datastore with database '" + this.config.getMongoDbName() + "'"); } private String getConnectionString() { StringBuilder buffer = new StringBuilder(); buffer.append("mongodb: if (this.config.isMongoAuth()) { buffer .append(this.config.getMongoUsername()) .append(":") .append(this.config.getMongoPassword()).append("@"); } buffer .append(this.config.getMongoHost()) .append(":") .append(this.config.getMongoPort()); if (this.config.isMongoAuth()) { buffer.append("/?authSource=").append(this.config.getMongoAuthDB()); } return buffer.toString(); } /** * Ensures (creating if necessary) the indexes found during class mapping (using @Indexed, @Indexes) */ public void ensureIndexes() { this.datastore.ensureIndexes(); } /** * Ensure capped DBCollections for Entity(s) */ public void ensureCaps() { this.datastore.ensureCaps(); } /** * Retrieves a mapped Morphia object from MongoDB. If the id is not of * type ObjectId, it will be converted to ObjectId * * @param id The id of the object * @param clazz The mapped Morphia class * @param <T> JavaDoc requires this - please ignore * * @return The requested class from MongoDB or null if none found */ public <T extends Object> T findById(Object id, Class<T> clazz) { Preconditions.checkNotNull(clazz, "Tryed to find an object by id, but given class is null"); Preconditions.checkNotNull(id, "Tryed to find an object by id, but given id is null"); return this.datastore.find(clazz).filter(Filters.eq("_id", id)).first(); } /** * Retrieves a list of mapped Morphia objects from MongoDB * * @param clazz The mapped Morphia class * @param <T> JavaDoc requires this - please ignore * * @return A list of mapped Morphia objects or an empty list if none found */ public <T extends Object> List<T> findAll(Class<T> clazz) { Preconditions.checkNotNull(clazz, "Tryed to get all morphia objects of a given object, but given object is null"); return this.datastore.find(clazz).iterator().toList(); } /** * Counts all objected of a mapped Morphia class * * @param clazz The mapped Morphia class * @param <T> JavaDoc requires this - please ignore * * @return The number of objects in MongoDB */ public <T extends Object> long countAll(Class<T> clazz) { Preconditions.checkNotNull(clazz, "Tryed to count all a morphia objects of a given object, but given object is null"); return this.datastore.find(clazz).count(); } /** * Saves a mapped Morphia object to MongoDB * * @param object The object to save */ public void save(Object object) { Preconditions.checkNotNull(object, "Tryed to save a morphia object, but a given object is null"); this.datastore.save(object); } /** * Deletes a mapped Morphia object in MongoDB * * @param object The object to delete */ public void delete(Object object) { Preconditions.checkNotNull(object, "Tryed to delete a morphia object, but given object is null"); this.datastore.delete(object); } /** * Deletes all mapped Morphia objects of a given class * @param <T> JavaDoc requires this - please ignore * @param clazz The mapped Morphia class */ public <T extends Object> void deleteAll(Class<T> clazz) { Preconditions.checkNotNull(clazz, "Tryed to delete list of mapped morphia objects, but given class is null"); this.datastore.find(clazz).delete(new DeleteOptions().multi(true)); } /** * Drops all data in MongoDB on the connected database */ public void dropDatabase() { this.datastore.getDatabase().drop(); } }
package org.ktunaxa.referral.client.gui; import com.smartgwt.client.types.Cursor; import com.smartgwt.client.types.VerticalAlignment; import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.Button; import com.smartgwt.client.widgets.HTMLFlow; import com.smartgwt.client.widgets.IButton; import com.smartgwt.client.widgets.Img; import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.layout.HLayout; import com.smartgwt.client.widgets.layout.LayoutSpacer; import org.geomajas.gwt.client.command.AbstractCommandCallback; import org.geomajas.gwt.client.command.GwtCommand; import org.geomajas.gwt.client.command.GwtCommandDispatcher; import org.geomajas.gwt.client.util.HtmlBuilder; import org.geomajas.layer.feature.Feature; import org.ktunaxa.bpm.KtunaxaBpmConstant; import org.ktunaxa.referral.client.security.UserContext; import org.ktunaxa.referral.client.widget.AbstractCollapsibleListBlock; import org.ktunaxa.referral.server.command.dto.AssignTaskRequest; import org.ktunaxa.referral.server.command.dto.GetReferralResponse; import org.ktunaxa.referral.server.dto.TaskDto; import java.util.Map; /** * Implementation of the CollapsableBlock abstraction that handles {@link TaskDto} type objects. Instances of this * class will form the list of tasks on task tabs. Each block can collapse and expand. When collapsed only the * task title is visible. * * @author Pieter De Graef * @author Joachim Van der Auwera */ public class TaskBlock extends AbstractCollapsibleListBlock<TaskDto> { private static final String BLOCK_STYLE = "taskBlock"; private static final String TITLE_STYLE = "taskBlockTitle"; private static final String BLOCK_STYLE_COLLAPSED = "taskBlockCollapsed"; private static final String TITLE_STYLE_COLLAPSED = "taskBlockTitleCollapsed"; private static final String IMAGE_MINIMIZE = "[ISOMORPHIC]/skins/ActivitiBlue/images/headerIcons/minimize.gif"; private static final String IMAGE_MAXIMIZE = "[ISOMORPHIC]/skins/ActivitiBlue/images/headerIcons/maximize.gif"; private static final String IMAGE_CLAIM = "[ISOMORPHIC]/images/task/claim.png"; private static final String IMAGE_START = "[ISOMORPHIC]/images/task/start.png"; private static final String IMAGE_ASSIGN = "[ISOMORPHIC]/images/task/assign.png"; private HLayout title; private HTMLFlow content; private Img titleImage = new Img(IMAGE_MINIMIZE, 16, 16); private IButton startButton = new IButton(); private IButton claimButton = new IButton(); // Constructors: public TaskBlock(TaskDto task) { super(task); buildGui(task); } // CollapsableBlock implementation: /** Expand the task block, displaying everything. */ public void expand() { setStyleName(BLOCK_STYLE); title.setStyleName(TITLE_STYLE); titleImage.setSrc(IMAGE_MINIMIZE); content.setVisible(true); } /** Collapse the task block, leaving only the title visible. */ public void collapse() { setStyleName(BLOCK_STYLE_COLLAPSED); title.setStyleName(TITLE_STYLE_COLLAPSED); titleImage.setSrc(IMAGE_MAXIMIZE); content.setVisible(false); } /** * Search the task for a given text string. This method will search through the title, content, checkedContent * and name of the user. * * @param text * The text to search for * @return Returns true if the text has been found somewhere. */ public boolean containsText(String text) { if (text != null) { String lcText = text.toLowerCase(); String compare; compare = getObject().getName(); if (compare != null && compare.toLowerCase().contains(lcText)) { return true; } compare = getObject().getDescription(); if (compare != null && compare.toLowerCase().contains(lcText)) { return true; } } return false; } public Button getEditButton() { return null; } // Private methods: private void buildGui(TaskDto task) { Map<String, String> variables = task.getVariables(); setStyleName(BLOCK_STYLE); title = new HLayout(LayoutConstant.MARGIN_LARGE); title.setSize(LayoutConstant.BLOCK_TITLE_WIDTH, LayoutConstant.BLOCK_TITLE_HEIGHT); title.setLayoutLeftMargin(LayoutConstant.MARGIN_LARGE); title.setStyleName(TITLE_STYLE); title.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { if (content.isVisible()) { collapse(); } else { expand(); } } }); title.setCursor(Cursor.HAND); titleImage.setLayoutAlign(VerticalAlignment.CENTER); title.addMember(titleImage); HTMLFlow titleText = new HTMLFlow("<div class='taskBlockTitleText'>" + variables.get(KtunaxaBpmConstant.VAR_REFERRAL_ID) + ": " + HtmlBuilder.htmlEncode(task.getName()) + "</div>"); titleText.setSize(LayoutConstant.BLOCK_TITLE_WIDTH, LayoutConstant.BLOCK_TITLE_HEIGHT); title.addMember(titleText); addMember(title); HLayout infoLayout = new HLayout(LayoutConstant.MARGIN_SMALL); infoLayout.setLayoutRightMargin(LayoutConstant.MARGIN_SMALL); infoLayout.setLayoutTopMargin(LayoutConstant.MARGIN_SMALL); HTMLFlow info = new HTMLFlow("<div class='taskBlockInfo'>" + HtmlBuilder.htmlEncode(task.getDescription()) + "<br />Referral: " + HtmlBuilder.htmlEncode(variables.get(KtunaxaBpmConstant.VAR_REFERRAL_NAME)) + "</div>"); info.setSize(LayoutConstant.BLOCK_INFO_WIDTH, LayoutConstant.BLOCK_INFO_HEIGHT); infoLayout.addMember(info); infoLayout.addMember(new LayoutSpacer()); final String me = UserContext.getInstance().getUser(); startButton.setIcon(IMAGE_START); startButton.setShowDisabledIcon(true); startButton.setIconWidth(LayoutConstant.ICON_BUTTON_LARGE_ICON_WIDTH); startButton.setIconHeight(LayoutConstant.ICON_BUTTON_LARGE_ICON_HEIGHT); startButton.setWidth(LayoutConstant.ICON_BUTTON_LARGE_WIDTH); startButton.setHeight(LayoutConstant.ICON_BUTTON_LARGE_HEIGHT); startButton.setPrompt("Start"); startButton.setHoverWidth(LayoutConstant.ICON_BUTTON_LARGE_HOVER_WIDTH); startButton.setLayoutAlign(VerticalAlignment.CENTER); startButton.setShowRollOver(false); setStartButtonStatus(task); startButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { assign(getObject(), me, true); } }); infoLayout.addMember(startButton); IButton assignButton = new IButton(); assignButton.setIcon(IMAGE_ASSIGN); assignButton.setShowDisabledIcon(true); assignButton.setIconWidth(LayoutConstant.ICON_BUTTON_LARGE_ICON_WIDTH); assignButton.setIconHeight(LayoutConstant.ICON_BUTTON_LARGE_ICON_HEIGHT); assignButton.setWidth(LayoutConstant.ICON_BUTTON_LARGE_WIDTH); assignButton.setHeight(LayoutConstant.ICON_BUTTON_LARGE_HEIGHT); assignButton.setPrompt("Assign"); assignButton.setHoverWidth(LayoutConstant.ICON_BUTTON_LARGE_HOVER_WIDTH); assignButton.setLayoutAlign(VerticalAlignment.CENTER); assignButton.setShowRollOver(false); if (!UserContext.getInstance().isReferralAdmin()) { // disable when already assigned assignButton.setDisabled(true); } assignButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { SC.say("assign task, temp to KtBpmAdmin " + getObject().getId()); // @todo select user assign(getObject(), me, false); // @todo assign selected user } }); infoLayout.addMember(assignButton); claimButton.setIcon(IMAGE_CLAIM); claimButton.setShowDisabledIcon(true); claimButton.setIconWidth(LayoutConstant.ICON_BUTTON_LARGE_ICON_WIDTH); claimButton.setIconHeight(LayoutConstant.ICON_BUTTON_LARGE_ICON_HEIGHT); claimButton.setWidth(LayoutConstant.ICON_BUTTON_LARGE_WIDTH); claimButton.setHeight(LayoutConstant.ICON_BUTTON_LARGE_HEIGHT); claimButton.setPrompt("Claim"); claimButton.setHoverWidth(LayoutConstant.ICON_BUTTON_LARGE_HOVER_WIDTH); claimButton.setLayoutAlign(VerticalAlignment.CENTER); claimButton.setShowRollOver(false); claimButton.setDisabled(task.isHistory() | (null != task.getAssignee())); claimButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { assign(getObject(), me, false); } }); infoLayout.addMember(claimButton); addMember(infoLayout); String[] rows = null; if (task.isHistory()) { rows = new String[4]; rows[0] = HtmlBuilder.trHtmlContent(new String[] { HtmlBuilder.tdStyle("text-align:right", "Assignee: "), HtmlBuilder.tdStyle("text-align:left", task.getAssignee()) }); rows[1] = HtmlBuilder.trHtmlContent(new String[] { HtmlBuilder.tdStyle("text-align:right", "Started: "), HtmlBuilder.tdStyle("text-align:left", task.getStartTime() + "") }); rows[2] = HtmlBuilder.trHtmlContent(new String[] { HtmlBuilder.tdStyle("text-align:right", "Assignee: "), HtmlBuilder.tdStyle("text-align:left", task.getEndTime() + "") }); // htmlContent += openTr // + HtmlBuilder.getTagString(Html.Tag.TD, "", "text-align:right", "Assignee: ") // + HtmlBuilder.getTagString(Html.Tag.TD, "", "text-align:left", task.getAssignee()) // + closeTr // + openTr // + HtmlBuilder.getTagString(Html.Tag.TD, "", "text-align:right", "Started: ") // + HtmlBuilder.getTagString(Html.Tag.TD, "", "text-align:left", task.getStartTime() + "") // + closeTr // + openTr // + HtmlBuilder.getTagString(Html.Tag.TD, "", "text-align:right", "Ended: ") // + HtmlBuilder.getTagString(Html.Tag.TD, "", "text-align:left", task.getEndTime() + "") // + closeTr; } else { rows = new String[5]; rows[0] = HtmlBuilder.trHtmlContent(new String[] { HtmlBuilder.tdStyle("text-align:right", "Assignee: "), HtmlBuilder.tdStyle("text-align:left", task.getAssignee()) }); rows[1] = HtmlBuilder.trHtmlContent(new String[] { HtmlBuilder.tdStyle("text-align:right", "Created: "), HtmlBuilder.tdStyle("text-align:left", task.getCreateTime() + "") }); rows[2] = HtmlBuilder.trHtmlContent(new String[] { HtmlBuilder.tdStyle("text-align:right", "Completion deadline: "), HtmlBuilder.tdStyle("text-align:left", variables.get(KtunaxaBpmConstant.VAR_COMPLETION_DEADLINE)) }); rows[3] = HtmlBuilder.trHtmlContent(new String[] { HtmlBuilder.tdStyle("text-align:right", "E-mail: "), HtmlBuilder.tdStyle("text-align:left", variables.get(KtunaxaBpmConstant.VAR_EMAIL)) }); // htmlContent += openTr // + HtmlBuilder.getTagString(Html.Tag.TD, "", "text-align:right", "Assignee: ") // + HtmlBuilder.getTagString(Html.Tag.TD, "", "text-align:left", task.getAssignee()) // + closeTr // + openTr // + HtmlBuilder.getTagString(Html.Tag.TD, "", "text-align:right", "Created: ") // + HtmlBuilder.getTagString(Html.Tag.TD, "", "text-align:left", task.getCreateTime() + "") // + closeTr // + openTr // + HtmlBuilder.getTagString(Html.Tag.TD, "", "text-align:right", "Completion deadline: ") // + HtmlBuilder.getTagString(Html.Tag.TD, "", "text-align:left", // variables.get(KtunaxaBpmConstant.VAR_COMPLETION_DEADLINE)) // + closeTr // + openTr // + HtmlBuilder.getTagString(Html.Tag.TD, "", "text-align:right", "E-mail: ") // + HtmlBuilder.getTagString(Html.Tag.TD, "", "text-align:left", // variables.get(KtunaxaBpmConstant.VAR_EMAIL)) // + closeTr; } String engagementLevel = variables.get(KtunaxaBpmConstant.VAR_ENGAGEMENT_LEVEL); if (null != engagementLevel) { String engagementContent = engagementLevel + " (prov " + variables.get(KtunaxaBpmConstant.VAR_PROVINCE_ENGAGEMENT_LEVEL) + ")"; rows[rows.length - 1] = HtmlBuilder.trHtmlContent(new String[] { HtmlBuilder.tdStyle("text-align:right", "Engagement level: "), HtmlBuilder.tdStyle("text-align:left", engagementContent) }); // htmlContent += openTr // + HtmlBuilder.getTagString(Html.Tag.TD, "", "text-align:right", "Engagement level: ") // + HtmlBuilder.getTagString(Html.Tag.TD, "", "text-align:left", engagementContent) // + closeTr; } String htmlContent = HtmlBuilder.tableClassHtmlContent("taskBlockContent", rows); content = new HTMLFlow(htmlContent); content.setWidth100(); addMember(content); } private void setClaimButtonStatus(TaskDto task) { // disable when history or already assigned claimButton.setDisabled(task.isHistory() | (null != task.getAssignee())); } private void setStartButtonStatus(TaskDto task) { String me = UserContext.getInstance().getUser(); // disable when history or assigned to someone else startButton.setDisabled(task.isHistory() | (null != task.getAssignee() && !me.equals(task.getAssignee()))); } private void assign(final TaskDto task, final String assignee, final boolean start) { AssignTaskRequest request = new AssignTaskRequest(); request.setTaskId(task.getId()); request.setAssignee(assignee); GwtCommand command = new GwtCommand(AssignTaskRequest.COMMAND); command.setCommandRequest(request); GwtCommandDispatcher.getInstance().execute(command, new AbstractCommandCallback<GetReferralResponse>() { public void execute(GetReferralResponse response) { setStartButtonStatus(task); setClaimButtonStatus(task); // @todo do I need to modify the state of the task in the list, possibly remove, refresh, whatever? if (start) { start(task, response.getReferral()); } } }); } private void start(TaskDto task, Feature referral) { MapLayout mapLayout = MapLayout.getInstance(); mapLayout.setReferralAndTask(referral, task); mapLayout.focusCurrentTask(); } }
import java.awt.Color; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; /** * Java client for Rewind viewer. Put this file to the same default package where Strategy/MyStrategy/Runner and other * files are extracted. * * Sample usage: * <pre> * {@code * * private final RewindClient rewindClient = new RewindClient(); * * @Override * public void move(Wizard self, World world, Game game, Move move) { * initializeTick(self, world, game, move); * for (Wizard w : world.getWizards()) { * RewindClient.Side side = w.getFaction() == self.getFaction() ? RewindClient.Side.OUR : RewindClient.Side.ENEMY; * rewindClient.livingUnit(w.getId(), w.getX(), w.getY(), w.getRadius(), w.getLife(), w.getMaxLife(), side); * } * ... * rewindClient.endFrame(); * } * } * </pre> * */ public class RewindClient { private final Socket socket; private final OutputStream outputStream; public enum Side { OUR(-1), NEUTRAL(0), ENEMY(1); final int side; Side(int side) { this.side = side; } } /** * Should be send on end of move function all turn primitives can be rendered after that point */ void endFrame() { send("{\"type\":\"end\"}"); } void circle(double x, double y, double r, Color color) { send(String.format("{\"type\": \"circle\", \"x\": %f, \"y\": %f, \"r\": %f, \"color\": %d}", x, y, r, color.getRGB())); } void rect(double x1, double y1, double x2, double y2, Color color) { send(String.format("{\"type\": \"rectangle\", \"x1\": %f, \"y1\": %f, \"x2\": %f, \"y2\": %f, \"color\": %d}", x1, y1, x2, y2, color.getRGB())); } void line(double x1, double y1, double x2, double y2, Color color) { send(String.format("{\"type\": \"line\", \"x1\": %f, \"y1\": %f, \"x2\": %f, \"y2\": %f, \"color\": %d}", x1, y1, x2, y2, color.getRGB())); } void livingUnit(long id, double x, double y, double r, int hp, int maxHp, Side side) { livingUnit(id, x, y, r, hp, maxHp, side, 0, 0); } void livingUnit(long id, double x, double y, double r, int hp, int maxHp, Side side, double course, int unitType) { send(String.format( "{\"type\": \"unit\", \"x\": %f, \"y\": %f, \"r\": %f, \"hp\": %d, \"max_hp\": %d, \"enemy\": %d, \"unit_type\":%d, \"course\": %.3f}", x, y, r, hp, maxHp, side.side, unitType, course)); } public RewindClient(String host, int port) { try { socket = new Socket(host, port); socket.setTcpNoDelay(true); outputStream = socket.getOutputStream(); } catch (IOException e) { throw new RuntimeException(); } } public RewindClient() { this("127.0.0.1", 7000); } private void send(String buf) { try { outputStream.write(buf.getBytes()); outputStream.flush(); } catch (IOException e) { throw new RuntimeException(e); } } }
package hudson.maven; import hudson.*; import hudson.FilePath.FileCallable; import hudson.maven.MavenBuild.ProxyImpl2; import hudson.maven.reporters.MavenFingerprinter; import hudson.maven.reporters.MavenMailer; import hudson.model.*; import hudson.model.Cause.UpstreamCause; import hudson.remoting.Channel; import hudson.remoting.VirtualChannel; import hudson.scm.ChangeLogSet; import hudson.tasks.BuildWrapper; import hudson.tasks.MailSender; import hudson.tasks.Maven.MavenInstallation; import hudson.util.ArgumentListBuilder; import hudson.util.IOUtils; import hudson.util.StreamTaskListener; import org.apache.maven.BuildFailureException; import org.apache.maven.embedder.MavenEmbedderException; import org.apache.maven.execution.MavenSession; import org.apache.maven.execution.ReactorManager; import org.apache.maven.lifecycle.LifecycleExecutionException; import org.apache.maven.monitor.event.EventDispatcher; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuildingException; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import java.io.*; import java.util.*; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; import static hudson.model.Result.FAILURE; /** * {@link Build} for {@link MavenModuleSet}. * * <p> * A "build" of {@link MavenModuleSet} consists of: * * <ol> * <li>Update the workspace. * <li>Parse POMs * <li>Trigger module builds. * </ol> * * This object remembers the changelog and what {@link MavenBuild}s are done * on this. * * @author Kohsuke Kawaguchi */ public class MavenModuleSetBuild extends AbstractMavenBuild<MavenModuleSet,MavenModuleSetBuild> { /** * {@link MavenReporter}s that will contribute project actions. * Can be null if there's none. */ /*package*/ List<MavenReporter> projectActionReporters; public MavenModuleSetBuild(MavenModuleSet job) throws IOException { super(job); } public MavenModuleSetBuild(MavenModuleSet project, File buildDir) throws IOException { super(project, buildDir); } /** * Exposes {@code MAVEN_OPTS} to forked processes. * * When we fork Maven, we do so directly by executing Java, thus this environment variable * is pointless (we have to tweak JVM launch option correctly instead, which can be seen in * {@link MavenProcessFactory}), but setting the environment variable explicitly is still * useful in case this Maven forks other Maven processes via normal way. See HUDSON-3644. */ @Override public EnvVars getEnvironment(TaskListener log) throws IOException, InterruptedException { EnvVars envs = super.getEnvironment(log); String opts = project.getMavenOpts(); if(opts!=null) envs.put("MAVEN_OPTS", opts); return envs; } /** * Displays the combined status of all modules. * <p> * More precisely, this picks up the status of this build itself, * plus all the latest builds of the modules that belongs to this build. */ @Override public Result getResult() { Result r = super.getResult(); for (MavenBuild b : getModuleLastBuilds().values()) { Result br = b.getResult(); if(r==null) r = br; else if(br==Result.NOT_BUILT) continue; // UGLY: when computing combined status, ignore the modules that were not built else if(br!=null) r = r.combine(br); } return r; } /** * Returns the filtered changeset entries that match the given module. */ /*package*/ List<ChangeLogSet.Entry> getChangeSetFor(final MavenModule mod) { return new ArrayList<ChangeLogSet.Entry>() { { // modules that are under 'mod'. lazily computed List<MavenModule> subsidiaries = null; for (ChangeLogSet.Entry e : getChangeSet()) { if(isDescendantOf(e, mod)) { if(subsidiaries==null) subsidiaries = mod.getSubsidiaries(); // make sure at least one change belongs to this module proper, // and not its subsidiary module if (notInSubsidiary(subsidiaries, e)) add(e); } } } private boolean notInSubsidiary(List<MavenModule> subsidiaries, ChangeLogSet.Entry e) { for (String path : e.getAffectedPaths()) if(!belongsToSubsidiary(subsidiaries, path)) return true; return false; } private boolean belongsToSubsidiary(List<MavenModule> subsidiaries, String path) { for (MavenModule sub : subsidiaries) if(path.startsWith(sub.getRelativePath())) return true; return false; } /** * Does this change happen somewhere in the given module or its descendants? */ private boolean isDescendantOf(ChangeLogSet.Entry e, MavenModule mod) { for (String path : e.getAffectedPaths()) if(path.startsWith(mod.getRelativePath())) return true; return false; } }; } /** * Computes the module builds that correspond to this build. * <p> * A module may be built multiple times (by the user action), * so the value is a list. */ public Map<MavenModule,List<MavenBuild>> getModuleBuilds() { Collection<MavenModule> mods = getParent().getModules(); // identify the build number range. [start,end) MavenModuleSetBuild nb = getNextBuild(); int end = nb!=null ? nb.getNumber() : Integer.MAX_VALUE; // preserve the order by using LinkedHashMap Map<MavenModule,List<MavenBuild>> r = new LinkedHashMap<MavenModule,List<MavenBuild>>(mods.size()); for (MavenModule m : mods) { List<MavenBuild> builds = new ArrayList<MavenBuild>(); MavenBuild b = m.getNearestBuild(number); while(b!=null && b.getNumber()<end) { builds.add(b); b = b.getNextBuild(); } r.put(m,builds); } return r; } @Override public synchronized void delete() throws IOException { super.delete(); // Delete all contained module builds too for (List<MavenBuild> list : getModuleBuilds().values()) for (MavenBuild build : list) build.delete(); } @Override public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) { // map corresponding module build under this object if(token.indexOf('$')>0) { MavenModule m = getProject().getModule(token); if(m!=null) return m.getBuildByNumber(getNumber()); } return super.getDynamic(token,req,rsp); } /** * Computes the latest module builds that correspond to this build. * (when indivudual modules are built, a new ModuleSetBuild is not created, * but rather the new module build falls under the previous ModuleSetBuild) */ public Map<MavenModule,MavenBuild> getModuleLastBuilds() { Collection<MavenModule> mods = getParent().getModules(); // identify the build number range. [start,end) MavenModuleSetBuild nb = getNextBuild(); int end = nb!=null ? nb.getNumber() : Integer.MAX_VALUE; // preserve the order by using LinkedHashMap Map<MavenModule,MavenBuild> r = new LinkedHashMap<MavenModule,MavenBuild>(mods.size()); for (MavenModule m : mods) { MavenBuild b = m.getNearestOldBuild(end - 1); if(b!=null && b.getNumber()>=getNumber()) r.put(m,b); } return r; } public void registerAsProjectAction(MavenReporter reporter) { if(projectActionReporters==null) projectActionReporters = new ArrayList<MavenReporter>(); projectActionReporters.add(reporter); } /** * Finds {@link Action}s from all the module builds that belong to this * {@link MavenModuleSetBuild}. One action per one {@link MavenModule}, * and newer ones take precedence over older ones. */ public <T extends Action> List<T> findModuleBuildActions(Class<T> action) { Collection<MavenModule> mods = getParent().getModules(); List<T> r = new ArrayList<T>(mods.size()); // identify the build number range. [start,end) MavenModuleSetBuild nb = getNextBuild(); int end = nb!=null ? nb.getNumber()-1 : Integer.MAX_VALUE; for (MavenModule m : mods) { MavenBuild b = m.getNearestOldBuild(end); while(b!=null && b.getNumber()>=number) { T a = b.getAction(action); if(a!=null) { r.add(a); break; } b = b.getPreviousBuild(); } } return r; } public void run() { run(new RunnerImpl()); getProject().updateTransientActions(); } @Override public Fingerprint.RangeSet getDownstreamRelationship(AbstractProject that) { Fingerprint.RangeSet rs = super.getDownstreamRelationship(that); for(List<MavenBuild> builds : getModuleBuilds().values()) for (MavenBuild b : builds) rs.add(b.getDownstreamRelationship(that)); return rs; } /** * Called when a module build that corresponds to this module set build * has completed. */ /*package*/ void notifyModuleBuild(MavenBuild newBuild) { try { // update module set build number getParent().updateNextBuildNumber(); // update actions Map<MavenModule, List<MavenBuild>> moduleBuilds = getModuleBuilds(); // actions need to be replaced atomically especially // given that two builds might complete simultaneously. synchronized(this) { boolean modified = false; List<Action> actions = getActions(); Set<Class<? extends AggregatableAction>> individuals = new HashSet<Class<? extends AggregatableAction>>(); for (Action a : actions) { if(a instanceof MavenAggregatedReport) { MavenAggregatedReport mar = (MavenAggregatedReport) a; mar.update(moduleBuilds,newBuild); individuals.add(mar.getIndividualActionType()); modified = true; } } // see if the new build has any new aggregatable action that we haven't seen. for (AggregatableAction aa : newBuild.getActions(AggregatableAction.class)) { if(individuals.add(aa.getClass())) { // new AggregatableAction MavenAggregatedReport mar = aa.createAggregatedAction(this, moduleBuilds); mar.update(moduleBuilds,newBuild); actions.add(mar); modified = true; } } if(modified) { save(); getProject().updateTransientActions(); } } // symlink to this module build String moduleFsName = newBuild.getProject().getModuleName().toFileSystemName(); Util.createSymlink(getRootDir(), "../../modules/"+ moduleFsName +"/builds/"+newBuild.getId() /*ugly!*/, moduleFsName, StreamTaskListener.NULL); } catch (IOException e) { LOGGER.log(Level.WARNING,"Failed to update "+this,e); } catch (InterruptedException e) { LOGGER.log(Level.WARNING,"Failed to update "+this,e); } } /** * The sole job of the {@link MavenModuleSet} build is to update SCM * and triggers module builds. */ private class RunnerImpl extends AbstractRunner { private Map<ModuleName,MavenBuild.ProxyImpl2> proxies; protected Result doRun(final BuildListener listener) throws Exception { PrintStream logger = listener.getLogger(); try { EnvVars envVars = getEnvironment(listener); MavenInstallation mvn = project.getMaven(); if(mvn==null) throw new AbortException("A Maven installation needs to be available for this project to be built.\n"+ "Either your server has no Maven installations defined, or the requested Maven version does not exist."); mvn = mvn.forEnvironment(envVars).forNode(Computer.currentComputer().getNode(), listener); if(!project.isAggregatorStyleBuild()) { parsePoms(listener, logger, envVars, mvn); // start module builds logger.println("Triggering "+project.getRootModule().getModuleName()); project.getRootModule().scheduleBuild(new UpstreamCause((Run<?,?>)MavenModuleSetBuild.this)); } else { // do builds here try { List<BuildWrapper> wrappers = new ArrayList<BuildWrapper>(); for (BuildWrapper w : project.getBuildWrappersList()) wrappers.add(w); ParametersAction parameters = getAction(ParametersAction.class); if (parameters != null) parameters.createBuildWrappers(MavenModuleSetBuild.this,wrappers); for( BuildWrapper w : wrappers) { Environment e = w.setUp(MavenModuleSetBuild.this, launcher, listener); if(e==null) return Result.FAILURE; buildEnvironments.add(e); e.buildEnvVars(envVars); // #3502: too late for getEnvironment to do this } if(!preBuild(listener, project.getPublishers())) return Result.FAILURE; parsePoms(listener, logger, envVars, mvn); // #5428 : do pre-build *before* parsing pom SplittableBuildListener slistener = new SplittableBuildListener(listener); proxies = new HashMap<ModuleName, ProxyImpl2>(); List<String> changedModules = new ArrayList<String>(); for (MavenModule m : project.sortedActiveModules) { MavenBuild mb = m.newBuild(); // Check if incrementalBuild is selected and that there are changes - // we act as if incrementalBuild is not set if there are no changes. if (!MavenModuleSetBuild.this.getChangeSet().isEmptySet() && project.isIncrementalBuild()) { // If there are changes for this module, add it. // Also add it if we've never seen this module before, // or if the previous build of this module failed or was unstable. if ((mb.getPreviousBuiltBuild() == null) || (!getChangeSetFor(m).isEmpty()) || (mb.getPreviousBuiltBuild().getResult().isWorseThan(Result.SUCCESS))) { changedModules.add(m.getModuleName().toString()); } } mb.setWorkspace(getModuleRoot().child(m.getRelativePath())); proxies.put(m.getModuleName(), mb.new ProxyImpl2(MavenModuleSetBuild.this,slistener)); } // run the complete build here // figure out the root POM location. // choice of module root ('ws' in this method) is somewhat arbitrary // when multiple CVS/SVN modules are checked out, so also check // the path against the workspace root if that seems like what the user meant (see issue #1293) String rootPOM = project.getRootPOM(); FilePath pom = getModuleRoot().child(rootPOM); FilePath parentLoc = getWorkspace().child(rootPOM); if(!pom.exists() && parentLoc.exists()) pom = parentLoc; ProcessCache.MavenProcess process = MavenBuild.mavenProcessCache.get(launcher.getChannel(), slistener, new MavenProcessFactory(project,launcher,envVars,pom.getParent())); ArgumentListBuilder margs = new ArgumentListBuilder().add("-B").add("-f", pom.getRemote()); if(project.usesPrivateRepository()) margs.add("-Dmaven.repo.local="+getWorkspace().child(".repository")); // If incrementalBuild is set, and we're on Maven 2.1 or later, *and* there's at least one module // listed in changedModules, do the Maven incremental build commands - if there are no changed modules, // We're building everything anyway. if (project.isIncrementalBuild() && mvn.isMaven2_1(launcher) && !changedModules.isEmpty()) { margs.add("-amd"); margs.add("-pl", Util.join(changedModules, ",")); } if (project.getAlternateSettings() != null) { margs.add("-s").add(getWorkspace().child(project.getAlternateSettings())); } margs.addTokenized(envVars.expand(project.getGoals())); Builder builder = new Builder(slistener, proxies, project.sortedActiveModules, margs.toList(), envVars); MavenProbeAction mpa=null; try { mpa = new MavenProbeAction(project,process.channel); addAction(mpa); return process.call(builder); } finally { builder.end(launcher); getActions().remove(mpa); process.discard(); } } finally { // tear down in reverse order boolean failed=false; for( int i=buildEnvironments.size()-1; i>=0; i if (!buildEnvironments.get(i).tearDown(MavenModuleSetBuild.this,listener)) { failed=true; } } buildEnvironments = null; // WARNING The return in the finally clause will trump any return before if (failed) return Result.FAILURE; } } return null; } catch (AbortException e) { if(e.getMessage()!=null) listener.error(e.getMessage()); return Result.FAILURE; } catch (InterruptedIOException e) { e.printStackTrace(listener.error("Aborted Maven execution for InterruptedIOException")); return Result.ABORTED; } catch (InterruptedException e) { e.printStackTrace(listener.error("Aborted Maven execution for InterruptedException")); return Result.ABORTED; } catch (IOException e) { e.printStackTrace(listener.error(Messages.MavenModuleSetBuild_FailedToParsePom())); return Result.FAILURE; } catch (RunnerAbortedException e) { return Result.FAILURE; } catch (RuntimeException e) { // bug in the code. e.printStackTrace(listener.error("Processing failed due to a bug in the code. Please report this to users@hudson.dev.java.net")); logger.println("project="+project); logger.println("project.getModules()="+project.getModules()); logger.println("project.getRootModule()="+project.getRootModule()); throw e; } } private void parsePoms(BuildListener listener, PrintStream logger, EnvVars envVars, MavenInstallation mvn) throws IOException, InterruptedException { logger.println("Parsing POMs"); List<PomInfo> poms; try { poms = getModuleRoot().act(new PomParser(listener, mvn, project)); } catch (IOException e) { if (e.getCause() instanceof AbortException) throw (AbortException) e.getCause(); throw e; } catch (MavenExecutionException e) { // Maven failed to parse POM e.getCause().printStackTrace(listener.error(Messages.MavenModuleSetBuild_FailedToParsePom())); throw new AbortException(); } // update the module list Map<ModuleName,MavenModule> modules = project.modules; synchronized(modules) { Map<ModuleName,MavenModule> old = new HashMap<ModuleName, MavenModule>(modules); List<MavenModule> sortedModules = new ArrayList<MavenModule>(); modules.clear(); if(debug) logger.println("Root POM is "+poms.get(0).name); project.reconfigure(poms.get(0)); for (PomInfo pom : poms) { MavenModule mm = old.get(pom.name); if(mm!=null) {// found an existing matching module if(debug) logger.println("Reconfiguring "+mm); mm.reconfigure(pom); modules.put(pom.name,mm); } else {// this looks like a new module logger.println(Messages.MavenModuleSetBuild_DiscoveredModule(pom.name,pom.displayName)); mm = new MavenModule(project,pom,getNumber()); modules.put(mm.getModuleName(),mm); } sortedModules.add(mm); mm.save(); } // at this point the list contains all the live modules project.sortedActiveModules = sortedModules; // remaining modules are no longer active. old.keySet().removeAll(modules.keySet()); for (MavenModule om : old.values()) { if(debug) logger.println("Disabling "+om); om.makeDisabled(true); } modules.putAll(old); } // we might have added new modules Hudson.getInstance().rebuildDependencyGraph(); // module builds must start with this build's number for (MavenModule m : modules.values()) m.updateNextBuildNumber(getNumber()); } protected void post2(BuildListener listener) throws Exception { // asynchronous executions from the build might have left some unsaved state, // so just to be safe, save them all. for (MavenBuild b : getModuleLastBuilds().values()) b.save(); // at this point the result is all set, so ignore the return value if (!performAllBuildSteps(listener, project.getPublishers(), true)) setResult(FAILURE); if (!performAllBuildSteps(listener, project.getProperties(), true)) setResult(FAILURE); // aggregate all module fingerprints to us, // so that dependencies between module builds can be understood as // dependencies between module set builds. // TODO: we really want to implement this as a publisher, // but we don't want to ask for a user configuration, nor should it // show up in the persisted record. MavenFingerprinter.aggregate(MavenModuleSetBuild.this); } @Override public void cleanUp(BuildListener listener) throws Exception { if(project.isAggregatorStyleBuild()) { // schedule downstream builds. for non aggregator style builds, // this is done by each module scheduleDownstreamBuilds(listener); } MavenMailer mailer = project.getReporters().get(MavenMailer.class); if (mailer != null) { new MailSender(mailer.recipients, mailer.dontNotifyEveryUnstableBuild, mailer.sendToIndividuals).execute(MavenModuleSetBuild.this, listener); } // too late to set the build result at this point. so ignore failures. performAllBuildSteps(listener, project.getPublishers(), false); performAllBuildSteps(listener, project.getProperties(), false); } } /** * Runs Maven and builds the project. * * This is only used for * {@link MavenModuleSet#isAggregatorStyleBuild() the aggregator style build}. */ private static final class Builder extends MavenBuilder { private final Map<ModuleName,MavenBuildProxy2> proxies; private final Map<ModuleName,List<MavenReporter>> reporters = new HashMap<ModuleName,List<MavenReporter>>(); private final Map<ModuleName,List<ExecutedMojo>> executedMojos = new HashMap<ModuleName,List<ExecutedMojo>>(); private long mojoStartTime; private MavenBuildProxy2 lastProxy; /** * Kept so that we can finalize them in the end method. */ private final transient Map<ModuleName,ProxyImpl2> sourceProxies; public Builder(BuildListener listener,Map<ModuleName,ProxyImpl2> proxies, Collection<MavenModule> modules, List<String> goals, Map<String,String> systemProps) { super(listener,goals,systemProps); this.sourceProxies = proxies; this.proxies = new HashMap<ModuleName, MavenBuildProxy2>(proxies); for (Entry<ModuleName,MavenBuildProxy2> e : this.proxies.entrySet()) e.setValue(new FilterImpl(e.getValue())); for (MavenModule m : modules) reporters.put(m.getModuleName(),m.createReporters()); } private class FilterImpl extends MavenBuildProxy2.Filter<MavenBuildProxy2> implements Serializable { public FilterImpl(MavenBuildProxy2 core) { super(core); } @Override public void executeAsync(final BuildCallable<?,?> program) throws IOException { futures.add(Channel.current().callAsync(new AsyncInvoker(core,program))); } private static final long serialVersionUID = 1L; } /** * Invoked after the maven has finished running, and in the master, not in the maven process. */ void end(Launcher launcher) throws IOException, InterruptedException { for (Map.Entry<ModuleName,ProxyImpl2> e : sourceProxies.entrySet()) { ProxyImpl2 p = e.getValue(); for (MavenReporter r : reporters.get(e.getKey())) { // we'd love to do this when the module build ends, but doing so requires // we know how many task segments are in the current build. r.end(p.owner(),launcher,listener); p.appendLastLog(); } p.close(); } } @Override public Result call() throws IOException { try { return super.call(); } finally { if(lastProxy!=null) lastProxy.appendLastLog(); } } @Override void preBuild(MavenSession session, ReactorManager rm, EventDispatcher dispatcher) throws BuildFailureException, LifecycleExecutionException, IOException, InterruptedException { // set all modules which are not actually being build (in incremental builds) to NOT_BUILD @SuppressWarnings("unchecked") List<MavenProject> projects = rm.getSortedProjects(); Set<ModuleName> buildingProjects = new HashSet<ModuleName>(); for (MavenProject p : projects) { buildingProjects.add(new ModuleName(p)); } for (Entry<ModuleName,MavenBuildProxy2> e : this.proxies.entrySet()) { if (! buildingProjects.contains(e.getKey())) { MavenBuildProxy2 proxy = e.getValue(); proxy.start(); proxy.setResult(Result.NOT_BUILT); proxy.end(); } } } void postBuild(MavenSession session, ReactorManager rm, EventDispatcher dispatcher) throws BuildFailureException, LifecycleExecutionException, IOException, InterruptedException { // TODO } void preModule(MavenProject project) throws InterruptedException, IOException, hudson.maven.agent.AbortException { ModuleName name = new ModuleName(project); MavenBuildProxy2 proxy = proxies.get(name); listener.getLogger().flush(); // make sure the data until here are all written proxy.start(); for (MavenReporter r : reporters.get(name)) if(!r.preBuild(proxy,project,listener)) throw new hudson.maven.agent.AbortException(r+" failed"); } void postModule(MavenProject project) throws InterruptedException, IOException, hudson.maven.agent.AbortException { ModuleName name = new ModuleName(project); MavenBuildProxy2 proxy = proxies.get(name); List<MavenReporter> rs = reporters.get(name); if(rs==null) { // probe for issue #906 throw new AssertionError("reporters.get("+name+")==null. reporters="+reporters+" proxies="+proxies); } for (MavenReporter r : rs) if(!r.postBuild(proxy,project,listener)) throw new hudson.maven.agent.AbortException(r+" failed"); proxy.setExecutedMojos(executedMojos.get(name)); listener.getLogger().flush(); // make sure the data until here are all written proxy.end(); lastProxy = proxy; } void preExecute(MavenProject project, MojoInfo mojoInfo) throws IOException, InterruptedException, hudson.maven.agent.AbortException { ModuleName name = new ModuleName(project); MavenBuildProxy proxy = proxies.get(name); for (MavenReporter r : reporters.get(name)) if(!r.preExecute(proxy,project,mojoInfo,listener)) throw new hudson.maven.agent.AbortException(r+" failed"); mojoStartTime = System.currentTimeMillis(); } void postExecute(MavenProject project, MojoInfo mojoInfo, Exception exception) throws IOException, InterruptedException, hudson.maven.agent.AbortException { ModuleName name = new ModuleName(project); List<ExecutedMojo> mojoList = executedMojos.get(name); if(mojoList==null) executedMojos.put(name,mojoList=new ArrayList<ExecutedMojo>()); mojoList.add(new ExecutedMojo(mojoInfo,System.currentTimeMillis()-mojoStartTime)); MavenBuildProxy2 proxy = proxies.get(name); for (MavenReporter r : reporters.get(name)) if(!r.postExecute(proxy,project,mojoInfo,listener,exception)) throw new hudson.maven.agent.AbortException(r+" failed"); if(exception!=null) proxy.setResult(Result.FAILURE); } void onReportGenerated(MavenProject project, MavenReportInfo report) throws IOException, InterruptedException, hudson.maven.agent.AbortException { ModuleName name = new ModuleName(project); MavenBuildProxy proxy = proxies.get(name); for (MavenReporter r : reporters.get(name)) if(!r.reportGenerated(proxy,project,report,listener)) throw new hudson.maven.agent.AbortException(r+" failed"); } private static final long serialVersionUID = 1L; } /** * Used to tunnel exception from Maven through remoting. */ private static final class MavenExecutionException extends RuntimeException { private MavenExecutionException(Exception cause) { super(cause); } @Override public Exception getCause() { return (Exception)super.getCause(); } private static final long serialVersionUID = 1L; } /** * Executed on the slave to parse POM and extract information into {@link PomInfo}, * which will be then brought back to the master. */ private static final class PomParser implements FileCallable<List<PomInfo>> { private final BuildListener listener; private final String rootPOM; /** * Capture the value of the static field so that the debug flag * takes an effect even when {@link PomParser} runs in a slave. */ private final boolean verbose = debug; private final MavenInstallation mavenHome; private final String profiles; private final Properties properties; private final String privateRepository; private final String alternateSettings; private final boolean nonRecursive; // We're called against the module root, not the workspace, which can cause a lot of confusion. private final String workspaceProper; public PomParser(BuildListener listener, MavenInstallation mavenHome, MavenModuleSet project) { // project cannot be shipped to the remote JVM, so all the relevant properties need to be captured now. this.listener = listener; this.mavenHome = mavenHome; this.rootPOM = project.getRootPOM(); this.profiles = project.getProfiles(); this.properties = project.getMavenProperties(); this.nonRecursive = project.isNonRecursive(); this.workspaceProper = project.getLastBuild().getWorkspace().getRemote(); if (project.usesPrivateRepository()) { this.privateRepository = project.getLastBuild().getWorkspace().child(".repository").getRemote(); } else { this.privateRepository = null; } this.alternateSettings = project.getAlternateSettings(); } /** * Computes the path of {@link #rootPOM}. * * Returns "abc" if rootPOM="abc/pom.xml" * If rootPOM="pom.xml", this method returns "". */ private String getRootPath() { int idx = Math.max(rootPOM.lastIndexOf('/'), rootPOM.lastIndexOf('\\')); if(idx==-1) return ""; return rootPOM.substring(0,idx); } public List<PomInfo> invoke(File ws, VirtualChannel channel) throws IOException { File pom; PrintStream logger = listener.getLogger(); if (IOUtils.isAbsolute(rootPOM)) { pom = new File(rootPOM); } else { // choice of module root ('ws' in this method) is somewhat arbitrary // when multiple CVS/SVN modules are checked out, so also check // the path against the workspace root if that seems like what the user meant (see issue #1293) pom = new File(ws, rootPOM); File parentLoc = new File(ws.getParentFile(),rootPOM); if(!pom.exists() && parentLoc.exists()) pom = parentLoc; } if(!pom.exists()) throw new AbortException(Messages.MavenModuleSetBuild_NoSuchPOMFile(pom)); if(verbose) logger.println("Parsing " + (nonRecursive ? "non-recursively " : "recursively ") + pom); File settingsLoc = (alternateSettings == null) ? null : new File(workspaceProper, alternateSettings); if ((settingsLoc != null) && (!settingsLoc.exists())) { throw new AbortException(Messages.MavenModuleSetBuild_NoSuchAlternateSettings(settingsLoc.getAbsolutePath())); } try { MavenEmbedder embedder = MavenUtil. createEmbedder(listener, mavenHome.getHomeDir(), profiles, properties, privateRepository, settingsLoc); MavenProject mp = embedder.readProject(pom); Map<MavenProject,String> relPath = new HashMap<MavenProject,String>(); MavenUtil.resolveModules(embedder,mp,getRootPath(),relPath,listener,nonRecursive); if(verbose) { for (Entry<MavenProject, String> e : relPath.entrySet()) logger.printf("Discovered %s at %s\n",e.getKey().getId(),e.getValue()); } List<PomInfo> infos = new ArrayList<PomInfo>(); toPomInfo(mp,null,relPath,infos); for (PomInfo pi : infos) pi.cutCycle(); embedder.stop(); return infos; } catch (MavenEmbedderException e) { throw new MavenExecutionException(e); } catch (ProjectBuildingException e) { throw new MavenExecutionException(e); } } private void toPomInfo(MavenProject mp, PomInfo parent, Map<MavenProject,String> relPath, List<PomInfo> infos) { PomInfo pi = new PomInfo(mp, parent, relPath.get(mp)); infos.add(pi); for (MavenProject child : (List<MavenProject>)mp.getCollectedProjects()) toPomInfo(child,pi,relPath,infos); } private static final long serialVersionUID = 1L; } private static final Logger LOGGER = Logger.getLogger(MavenModuleSetBuild.class.getName()); /** * Extra verbose debug switch. */ public static boolean debug = false; @Override public MavenModuleSet getParent() {// don't know why, but javac wants this return super.getParent(); } }
package org.umlg.sqlg.test; import org.apache.tinkerpop.gremlin.process.traversal.P; import org.apache.tinkerpop.gremlin.process.traversal.Traversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.T; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.util.Arrays; import java.util.List; public class TestHas extends BaseTest { @Test public void g_V_hasXblahX() { loadModern(); final Traversal<Vertex, Vertex> traversal = this.sqlgGraph.traversal().V().has("blah"); printTraversalForm(traversal); Assert.assertFalse(traversal.hasNext()); } @Test public void testHasProperty() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "name", "a"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A", "name", "a"); this.sqlgGraph.addVertex(T.label, "A"); this.sqlgGraph.addVertex(T.label, "A"); this.sqlgGraph.tx().commit(); Assert.assertEquals(2, this.sqlgGraph.traversal().V().has("name").count().next(), 0); Assert.assertTrue(this.sqlgGraph.traversal().V().has("name").toList().containsAll(Arrays.asList(a1, a2))); } @Test public void testHasNotProperty() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "name", "a"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A", "name", "a"); Vertex a3 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a4 = this.sqlgGraph.addVertex(T.label, "A"); this.sqlgGraph.tx().commit(); Assert.assertEquals(2, this.sqlgGraph.traversal().V().hasNot("name").count().next(), 0); Assert.assertTrue(this.sqlgGraph.traversal().V().hasNot("name").toList().containsAll(Arrays.asList(a3, a4))); } @Test public void g_V_in_hasIdXneqX1XX() { loadModern(); Object marko = convertToVertex(this.sqlgGraph, "marko").id(); List<Vertex> vertices = this.sqlgGraph.traversal().V().in().hasId(P.neq(marko)).toList(); int count = 0; for (Vertex vertex : vertices) { Assert.assertTrue(vertex.value("name").equals("josh") || vertex.value("name").equals("peter")); count++; } Assert.assertEquals(3, count); } @Test public void testHasNotId() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); a1.addEdge("ab", b1); this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal().V().in().hasId(P.neq(a1.id())).toList(); Assert.assertEquals(0, vertices.size()); } @Test public void g_V_hasId() throws IOException { loadModern(); assertModernGraph(this.sqlgGraph, true, false); GraphTraversalSource g = this.sqlgGraph.traversal(); Object id = convertToVertexId("marko"); List<Vertex> traversala2 = g.V().has(T.id, id).toList(); Assert.assertEquals(1, traversala2.size()); Assert.assertEquals(convertToVertex(this.sqlgGraph, "marko"), traversala2.get(0)); traversala2 = g.V().hasId(id).toList(); Assert.assertEquals(1, traversala2.size()); Assert.assertEquals(convertToVertex(this.sqlgGraph, "marko"), traversala2.get(0)); } @Test public void testHasId() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); a1.addEdge("ab", b1); this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal().V().hasId(a1.id()).toList(); Assert.assertEquals(1, vertices.size()); Assert.assertEquals(a1, vertices.get(0)); } @Test public void testHasIDDifferentLabels() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C"); Edge e1 = a1.addEdge("ab", b1); List<Object> edges = this.sqlgGraph.traversal().V(a1.id()).outE("ab").as("e").inV().hasId(b1.id()).select("e") .toList(); Assert.assertEquals(1, edges.size()); Assert.assertEquals(e1, edges.get(0)); edges = this.sqlgGraph.traversal().V(a1.id()).outE("ab").as("e").inV().hasId(a1.id(),b1.id()).select("e") .toList(); Assert.assertEquals(1, edges.size()); Assert.assertEquals(e1, edges.get(0)); edges = this.sqlgGraph.traversal().V(a1.id()).outE("ab").as("e").inV().hasId(P.within(b1.id())).select("e") .toList(); Assert.assertEquals(1, edges.size()); Assert.assertEquals(e1, edges.get(0)); edges = this.sqlgGraph.traversal().V(a1.id()).outE("ab").as("e").inV().hasId(c1.id()).select("e") .toList(); Assert.assertEquals(0, edges.size()); edges = this.sqlgGraph.traversal().V(a1.id()).outE("ab").as("e").inV().hasId(P.within(c1.id())).select("e") .toList(); Assert.assertEquals(0, edges.size()); edges = this.sqlgGraph.traversal().V(a1.id()).outE("ab").as("e").inV().hasId(P.within(a1.id(),c1.id())).select("e") .toList(); Assert.assertEquals(0, edges.size()); edges = this.sqlgGraph.traversal().V(a1.id()).outE("ab").as("e").inV().hasId(P.within(a1.id(),b2.id())).select("e") .toList(); Assert.assertEquals(0, edges.size()); } @Test public void testHas() { this.sqlgGraph.addVertex("name", "marko"); this.sqlgGraph.addVertex("name", "peter"); this.sqlgGraph.tx().commit(); Assert.assertEquals(1, this.sqlgGraph.traversal().V().has("name", "marko").count().next(), 0); } @Test public void testQueryTableNotYetExists() { this.sqlgGraph.addVertex(T.label, "Animal"); this.sqlgGraph.tx().commit(); Assert.assertEquals(0, this.sqlgGraph.traversal().V().has(T.label, "Person").count().next(), 0); } @Test public void testQueryPropertyNotYetExists() { this.sqlgGraph.addVertex(T.label, "Person"); this.sqlgGraph.tx().commit(); Assert.assertEquals(0, this.sqlgGraph.traversal().V().has(T.label, "Person").has("name", "john").count().next(), 0); } @Test public void testHasOnEdge() { Vertex v1 = this.sqlgGraph.addVertex("name", "marko"); Vertex v2 = this.sqlgGraph.addVertex("name", "peter"); v1.addEdge("friend", v2, "weight", "5"); this.sqlgGraph.tx().commit(); Assert.assertEquals(1, this.sqlgGraph.traversal().E().has("weight", "5").count().next(), 0); } @Test public void testEdgeQueryTableNotYetExists() { Vertex v1 = this.sqlgGraph.addVertex(T.label, "Animal"); Vertex v2 = this.sqlgGraph.addVertex(T.label, "Animal"); v1.addEdge("friend", v2); this.sqlgGraph.tx().commit(); Assert.assertEquals(0, this.sqlgGraph.traversal().E().has(T.label, "friendXXX").count().next(), 0); } @Test public void testEdgeQueryPropertyNotYetExists() { Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person"); Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person"); v1.addEdge("friend", v2); this.sqlgGraph.tx().commit(); Assert.assertEquals(0, this.sqlgGraph.traversal().V().has(T.label, "friend").has("weight", "5").count().next(), 0); } @Test public void testHasOnTableThatDoesNotExist() { Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person"); Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person"); v1.addEdge("friend", v2); this.sqlgGraph.tx().commit(); Assert.assertEquals(0, this.sqlgGraph.traversal().V().has(T.label, "friend").has("weight", "5").count().next(), 0); Assert.assertFalse(this.sqlgGraph.traversal().V().has(T.label, "xxx").hasNext()); Assert.assertFalse(this.sqlgGraph.traversal().V().has(T.label, "public.xxx").hasNext()); } }
package to.etc.domui.component.tbl; import java.util.*; import javax.annotation.*; import to.etc.domui.component.buttons.*; import to.etc.domui.dom.css.*; import to.etc.domui.dom.html.*; import to.etc.domui.server.*; import to.etc.domui.util.*; import to.etc.webapp.nls.*; public class DataPager extends Div implements IDataTableChangeListener { private SmallImgButton m_firstBtn; private SmallImgButton m_prevBtn; private SmallImgButton m_nextBtn; private SmallImgButton m_lastBtn; private SmallImgButton m_showSelectionBtn; private SmallImgButton m_selectAllBtn, m_selectNoneBtn; private Img m_truncated; TabularComponentBase< ? > m_table; private TextNode m_txt; private Div m_textDiv; // private Div m_buttonDiv; private String m_nextImg, m_nextDisImg; private String m_prevImg, m_prevDisImg; private String m_firstImg, m_firstDisImg; private String m_lastImg, m_lastDisImg; private String m_overflowImg; /** When set (default) this shows selection details when a table has a selectable model. */ private boolean m_showSelection = true; private Div m_buttonDiv; @Nonnull private List<SmallImgButton> m_extraButtonList = new ArrayList<SmallImgButton>(); public DataPager() {} public DataPager(final TabularComponentBase< ? > tbl) { m_table = tbl; tbl.addChangeListener(this); } @Override public void createContent() throws Exception { init(); //-- The text part: message Div d = new Div(); add(d); d.setFloat(FloatType.RIGHT); m_txt = new TextNode(); d.add(m_txt); m_textDiv = d; m_buttonDiv = new Div(); add(m_buttonDiv); m_buttonDiv.setCssClass("ui-szless"); m_firstBtn = new SmallImgButton(); m_buttonDiv.add(m_firstBtn); m_prevBtn = new SmallImgButton(); m_buttonDiv.add(m_prevBtn); m_nextBtn = new SmallImgButton(); m_buttonDiv.add(m_nextBtn); m_lastBtn = new SmallImgButton(); m_buttonDiv.add(m_lastBtn); m_buttonDiv.add("\u00a0\u00a0"); for(@Nonnull SmallImgButton sib : m_extraButtonList) { m_buttonDiv.add(sib); } // if(m_showSelection) { // if(m_table instanceof ISelectableTableComponent< ? >) { // Fixme needs interface // final ISelectableTableComponent< ? > dt = (ISelectableTableComponent< ? >) m_table; // if(dt.getSelectionModel() != null && dt.getSelectionModel().isMultiSelect()) { // if(dt.isMultiSelectionVisible()) { // renderSelectionExtras(); // } else { // m_showSelectionBtn = new SmallImgButton("THEME/dpr-select-on.png"); // m_buttonDiv.add(m_showSelectionBtn); // m_showSelectionBtn.setClicked(new IClicked<NodeBase>() { // @Override // public void clicked(NodeBase clickednode) throws Exception { // dt.setShowSelection(true); // clickednode.remove(); // m_showSelectionBtn = null; // m_showSelectionBtn.setTitle(Msgs.BUNDLE.getString("ui.dpr.selections")); if(isShowSelection()) { redraw(); } //-- Click handlers for paging. m_firstBtn.setClicked(new IClicked<NodeBase>() { @Override public void clicked(final NodeBase b) throws Exception { m_table.setCurrentPage(0); } }); m_lastBtn.setClicked(new IClicked<NodeBase>() { @Override public void clicked(final NodeBase b) throws Exception { int pg = m_table.getPageCount(); if(pg == 0) return; m_table.setCurrentPage(pg - 1); } }); m_prevBtn.setClicked(new IClicked<NodeBase>() { @Override public void clicked(final NodeBase b) throws Exception { int cp = m_table.getCurrentPage(); if(cp <= 0) return; m_table.setCurrentPage(cp - 1); } }); m_nextBtn.setClicked(new IClicked<NodeBase>() { @Override public void clicked(final NodeBase b) throws Exception { int cp = m_table.getCurrentPage(); int mx = m_table.getPageCount(); cp++; if(cp >= mx) return; m_table.setCurrentPage(cp); } }); } @Nullable private ISelectableTableComponent< ? > getSelectableTable() { if(m_table instanceof ISelectableTableComponent< ? >) return (ISelectableTableComponent< ? >) m_table; return null; } @Nullable private ISelectionModel< ? > getSelectionModel() { ISelectableTableComponent< ? > stm = getSelectableTable(); if(null == stm) return null; return stm.getSelectionModel(); } // private void renderSelectionExtras() { // final ISelectableTableComponent sti = getSelectableTable(); // if(null == sti || m_buttonDiv == null || !sti.isMultiSelectionVisible()) // return; // if(null != sti.getSelectionAllHandler()) { // SmallImgButton sb = new SmallImgButton("THEME/dpr-select-all.png"); // m_buttonDiv.add(sb); // sb.setTitle(Msgs.BUNDLE.getString("ui.dpr.all")); // sb.setClicked(new IClicked<SmallImgButton>() { // @Override // public void clicked(SmallImgButton clickednode) throws Exception { // sti.getSelectionAllHandler().selectAll(sti.getModel(), sti.getSelectionModel()); // SmallImgButton sb = new SmallImgButton("THEME/dpr-select-none.png"); // m_buttonDiv.add(sb); // sb.setTitle(Msgs.BUNDLE.getString("ui.dpr.none")); // sb.setClicked(new IClicked<SmallImgButton>() { // @Override // public void clicked(SmallImgButton clickednode) throws Exception { // ISelectionModel<?> sm = getSelectionModel(); // if(null != sm) // sm.clearSelection(); /** * Return T if the "show selection UI" button should be visible. * @return * @throws Exception */ private boolean isNeedSelectionButton() throws Exception { ISelectionModel< ? > sm = getSelectionModel(); if(sm == null || !m_showSelection) return false; if(!sm.isMultiSelect()) return false; ISelectableTableComponent< ? > tc = getSelectableTable(); if(null == tc) throw new IllegalStateException("Null selectable table?"); if(tc.isMultiSelectionVisible()) return false; if(tc.getModel() == null || tc.getModel().getRows() == 0) return false; return true; } /** * Returns T if the "select all/select none" buttons should be visible. * @return */ private boolean isNeedExtraButtons() { ISelectionModel< ? > sm = getSelectionModel(); if(sm == null || !m_showSelection) return false; if(!sm.isMultiSelect()) return false; ISelectableTableComponent< ? > tc = getSelectableTable(); if(null == tc) throw new IllegalStateException("Null selectable table?"); return tc.isMultiSelectionVisible(); } @Override public void selectionUIChanged(@Nonnull TabularComponentBase< ? > tbl) throws Exception { redraw(); // if(tbl instanceof DataTable) { // DataTable< ? > dt = (DataTable< ? >) tbl; // if(dt.isMultiSelectionVisible()) { // if(null != m_showSelectionBtn) { // m_showSelectionBtn.remove(); // m_showSelectionBtn = null; // renderSelectionExtras(); } private void init() throws Exception { if(m_nextImg != null) return; Map<String, Object> map = DomApplication.get().getThemeMap(null); m_nextImg = get(map, "dpr_next", "THEME/nav-next.png"); m_prevImg = get(map, "dpr_prev", "THEME/nav-prev.png"); m_firstImg = get(map, "dpr_first", "THEME/nav-first.png"); m_lastImg = get(map, "dpr_last", "THEME/nav-last.png"); m_nextDisImg = get(map, "dpr_dis_next", "THEME/nav-next-dis.png"); m_prevDisImg = get(map, "dpr_dis_prev", "THEME/nav-prev-dis.png"); m_firstDisImg = get(map, "dpr_dis_first", "THEME/nav-first-dis.png"); m_lastDisImg = get(map, "dpr_dis_last", "THEME/nav-last-dis.png"); m_overflowImg = get(map, "dpr_overflow", "THEME/nav-overflow.png"); } private static String enc(String in) { return in; // return in.replace("&", "&amp;"); } private String get(Map<String, Object> map, String key, String def) { Object v = map.get(key); if(null == v) return enc(def); if(v instanceof String) { return enc((String) v); } throw new IllegalArgumentException("Bad key value for " + key + " in style.properties: expected string, got " + v); } /* CODING: Handle changes to the table. */ private void redraw() throws Exception { if(m_buttonDiv == null) return; int cp = m_table.getCurrentPage(); int np = m_table.getPageCount(); if(np == 0) // mtesic:there is already 'There are no results' message inside DataCellTable // m_txt.setText(NlsContext.getGlobalMessage(Msgs.UI_PAGER_EMPTY)); m_txt.setText(""); else m_txt.setText(Msgs.BUNDLE.formatMessage(Msgs.UI_PAGER_TEXT, Integer.valueOf(cp + 1), Integer.valueOf(np), Integer.valueOf(m_table.getModel().getRows()))); if(cp <= 0) { m_firstBtn.setSrc(m_firstDisImg); m_prevBtn.setSrc(m_prevDisImg); } else { m_firstBtn.setSrc(m_firstImg); m_prevBtn.setSrc(m_prevImg); } if(cp + 1 >= np) { m_lastBtn.setSrc(m_lastDisImg); m_nextBtn.setSrc(m_nextDisImg); } else { m_lastBtn.setSrc(m_lastImg); m_nextBtn.setSrc(m_nextImg); // "THEME/go-next-view.png.svg?w=16&h=16"); } int tc = m_table.getTruncatedCount(); if(tc > 0) { if(m_truncated == null) { m_truncated = new Img(); m_truncated.setSrc(m_overflowImg); m_truncated.setTitle(Msgs.BUNDLE.formatMessage(Msgs.UI_PAGER_OVER, Integer.valueOf(tc))); m_textDiv.add(m_truncated); } } else { if(m_truncated != null) { m_truncated.remove(); m_truncated = null; } } redrawSelectionButtons(); } private void redrawSelectionButtons() throws Exception { //-- Show/hide the "show selection" button final ISelectableTableComponent<Object> dt = (ISelectableTableComponent<Object>) getSelectableTable(); if(null == dt) throw new IllegalStateException("Null selectable table?"); if(isNeedSelectionButton()) { if(m_showSelectionBtn == null) { m_showSelectionBtn = new SmallImgButton("THEME/dpr-select-on.png"); m_buttonDiv.add(4, m_showSelectionBtn); // Always after last navigation button m_showSelectionBtn.setClicked(new IClicked<NodeBase>() { @Override public void clicked(NodeBase clickednode) throws Exception { dt.setShowSelection(true); clickednode.remove(); m_showSelectionBtn = null; } }); m_showSelectionBtn.setTitle(Msgs.BUNDLE.getString("ui.dpr.selections")); } } else { if(m_showSelectionBtn != null) { m_showSelectionBtn.remove(); m_showSelectionBtn = null; } } //-- Show/hide the extras button boolean needselectall = false; boolean needselectnone = false; if(isNeedExtraButtons()) { needselectall = dt.getSelectionAllHandler() != null; needselectnone = true; } if(m_selectAllBtn == null && needselectall) { m_selectAllBtn = new SmallImgButton("THEME/dpr-select-all.png"); m_buttonDiv.add(4, m_selectAllBtn); m_selectAllBtn.setTitle(Msgs.BUNDLE.getString("ui.dpr.all")); m_selectAllBtn.setClicked(new IClicked<SmallImgButton>() { @Override public void clicked(SmallImgButton clickednode) throws Exception { ISelectionAllHandler ah = dt.getSelectionAllHandler(); if(null == ah) throw new IllegalStateException("selectionAllHandler is null"); ah.selectAll(dt.getModel(), dt.getSelectionModel()); } }); } else if(m_selectAllBtn != null && ! needselectall) { m_selectAllBtn.remove(); m_selectAllBtn = null; } if(m_selectNoneBtn == null && needselectnone) { m_selectNoneBtn = new SmallImgButton("THEME/dpr-select-none.png"); m_buttonDiv.add(4, m_selectNoneBtn); m_selectNoneBtn.setTitle(Msgs.BUNDLE.getString("ui.dpr.none")); m_selectNoneBtn.setClicked(new IClicked<SmallImgButton>() { @Override public void clicked(SmallImgButton clickednode) throws Exception { ISelectionModel<?> sm = getSelectionModel(); if(null != sm) sm.clearSelection(); } }); } else if(m_selectNoneBtn != null && !needselectnone) { m_selectNoneBtn.remove(); m_selectNoneBtn = null; } } public Div getButtonDiv() { return m_buttonDiv; } public void addButton(final String image, final IClicked<DataPager> click, final BundleRef bundle, final String ttlkey) { SmallImgButton i = new SmallImgButton(image, new IClicked<SmallImgButton>() { @Override public void clicked(final SmallImgButton b) throws Exception { click.clicked(DataPager.this); } }); if(bundle != null) i.setTitle(bundle.getString(ttlkey)); else if(ttlkey != null) i.setTitle(ttlkey); getButtonDiv().add(i); } /* CODING: DataTableChangeListener implementation. */ @Override public void modelChanged(final @Nonnull TabularComponentBase< ? > tbl, final @Nullable ITableModel< ? > old, final @Nullable ITableModel< ? > nw) throws Exception { redraw(); } @Override public void pageChanged(final @Nonnull TabularComponentBase< ? > tbl) throws Exception { redraw(); } public boolean isShowSelection() { return m_showSelection; } public void setShowSelection(boolean showSelection) { if(m_showSelection == showSelection) return; m_showSelection = showSelection; forceRebuild(); } public void addButton(@Nonnull SmallImgButton sib) { m_extraButtonList.add(sib); forceRebuild(); } public void addButton(@Nonnull String img, @Nonnull IClicked<SmallImgButton> clicked) { m_extraButtonList.add(new SmallImgButton(img, clicked)); } }
package info.tregmine.api.firework; import org.bukkit.Color; import org.bukkit.FireworkEffect; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.FireworkMeta; public class createFirwork { private FireworkEffect.Type type = FireworkEffect.Type.BALL; private Color[] colors = new Color[19]; public int colorCounter = 0; public void addColor(Color _color) { if (colorCounter > 0) { for (Color color : colors) { if (color.equals(_color)) { return; } } } colors[colorCounter] = _color; // colorCounter++; } public String colorToString(Color c) { if (c.equals(Color.WHITE)) { return "white"; } if (c.equals(Color.BLACK)) { return "black"; } if (c.equals(Color.BLUE)) { return "blue"; } if (c.equals(Color.FUCHSIA)) { return "fuchsia"; } if (c.equals(Color.GRAY)) { return "gray"; } if (c.equals(Color.GREEN)) { return "green"; } if (c.equals(Color.LIME)) { return "lime"; } if (c.equals(Color.MAROON)) { return "maroon"; } if (c.equals(Color.NAVY)) { return "navy"; } if (c.equals(Color.OLIVE)) { return "olive"; } if (c.equals(Color.ORANGE)) { return "orange"; } if (c.equals(Color.PURPLE)) { return "purple"; } if (c.equals(Color.AQUA)) { return "aqua"; } if (c.equals(Color.RED)) { return "red"; } if (c.equals(Color.SILVER)) { return "silver"; } if (c.equals(Color.TEAL)) { return "teal"; } if (c.equals(Color.YELLOW)) { return "yellow"; } return c.toString(); } public Color[] haveColors() { Color[] c = new Color[colorCounter]; for (int i = 0; i >= colorCounter; i++) { c[i] = colors[i]; } return c; } public String[] hasColorAsString() { String [] colorNames = new String[colorCounter]; for (int i = 0; i >= colorCounter;i++) { colorNames[i] = this.colorToString(colors[i]); } return colorNames; } public void addType(FireworkEffect.Type _type) { this.type = _type; } public ItemStack getAsStack(int _stackSize){ ItemStack item = new ItemStack(Material.FIREWORK, _stackSize); FireworkEffect.Builder effect = FireworkEffect.builder(); System.console().printf("" + this.haveColors().length); for (Color color : this.haveColors()) { System.console().printf(color.toString()); effect.withColor(color); } // effect.withColor(Color.WHITE); FireworkMeta meta = (FireworkMeta) item.getItemMeta(); meta.setDisplayName("Firework: " + haveColors().toString() ); meta.addEffect(effect.build()); item.setItemMeta(meta); return item; } }
package org.jfree.chart.axis; import java.io.Serializable; import org.jfree.chart.util.ParamChecks; import org.jfree.text.TextBlockAnchor; import org.jfree.ui.RectangleAnchor; import org.jfree.ui.RectangleEdge; import org.jfree.ui.TextAnchor; /** * Records the label positions for a category axis. Instances of this class * are immutable. */ public class CategoryLabelPositions implements Serializable { /** For serialization. */ private static final long serialVersionUID = -8999557901920364580L; /** STANDARD category label positions. */ public static final CategoryLabelPositions STANDARD = new CategoryLabelPositions( new CategoryLabelPosition( RectangleAnchor.BOTTOM, TextBlockAnchor.BOTTOM_CENTER), // TOP new CategoryLabelPosition( RectangleAnchor.TOP, TextBlockAnchor.TOP_CENTER), // BOTTOM new CategoryLabelPosition( RectangleAnchor.RIGHT, TextBlockAnchor.CENTER_RIGHT, CategoryLabelWidthType.RANGE, 0.30f), // LEFT new CategoryLabelPosition( RectangleAnchor.LEFT, TextBlockAnchor.CENTER_LEFT, CategoryLabelWidthType.RANGE, 0.30f) // RIGHT ); /** UP_90 category label positions. */ public static final CategoryLabelPositions UP_90 = new CategoryLabelPositions( new CategoryLabelPosition( RectangleAnchor.BOTTOM, TextBlockAnchor.CENTER_LEFT, TextAnchor.CENTER_LEFT, -Math.PI / 2.0, CategoryLabelWidthType.RANGE, 0.30f), // TOP new CategoryLabelPosition( RectangleAnchor.TOP, TextBlockAnchor.CENTER_RIGHT, TextAnchor.CENTER_RIGHT, -Math.PI / 2.0, CategoryLabelWidthType.RANGE, 0.30f), // BOTTOM new CategoryLabelPosition( RectangleAnchor.RIGHT, TextBlockAnchor.BOTTOM_CENTER, TextAnchor.BOTTOM_CENTER, -Math.PI / 2.0, CategoryLabelWidthType.CATEGORY, 0.9f), // LEFT new CategoryLabelPosition( RectangleAnchor.LEFT, TextBlockAnchor.TOP_CENTER, TextAnchor.TOP_CENTER, -Math.PI / 2.0, CategoryLabelWidthType.CATEGORY, 0.90f) // RIGHT ); /** DOWN_90 category label positions. */ public static final CategoryLabelPositions DOWN_90 = new CategoryLabelPositions( new CategoryLabelPosition( RectangleAnchor.BOTTOM, TextBlockAnchor.CENTER_RIGHT, TextAnchor.CENTER_RIGHT, Math.PI / 2.0, CategoryLabelWidthType.RANGE, 0.30f), // TOP new CategoryLabelPosition( RectangleAnchor.TOP, TextBlockAnchor.CENTER_LEFT, TextAnchor.CENTER_LEFT, Math.PI / 2.0, CategoryLabelWidthType.RANGE, 0.30f), // BOTTOM new CategoryLabelPosition( RectangleAnchor.RIGHT, TextBlockAnchor.TOP_CENTER, TextAnchor.TOP_CENTER, Math.PI / 2.0, CategoryLabelWidthType.CATEGORY, 0.90f), // LEFT new CategoryLabelPosition( RectangleAnchor.LEFT, TextBlockAnchor.BOTTOM_CENTER, TextAnchor.BOTTOM_CENTER, Math.PI / 2.0, CategoryLabelWidthType.CATEGORY, 0.90f) // RIGHT ); /** UP_45 category label positions. */ public static final CategoryLabelPositions UP_45 = createUpRotationLabelPositions(Math.PI / 4.0); /** DOWN_45 category label positions. */ public static final CategoryLabelPositions DOWN_45 = createDownRotationLabelPositions(Math.PI / 4.0); /** * Creates a new instance where the category labels angled upwards by the * specified amount. * * @param angle the rotation angle (should be &lt; Math.PI / 2.0). * * @return A category label position specification. */ public static CategoryLabelPositions createUpRotationLabelPositions( double angle) { return new CategoryLabelPositions( new CategoryLabelPosition( RectangleAnchor.BOTTOM, TextBlockAnchor.BOTTOM_LEFT, TextAnchor.BOTTOM_LEFT, -angle, CategoryLabelWidthType.RANGE, 0.50f), // TOP new CategoryLabelPosition( RectangleAnchor.TOP, TextBlockAnchor.TOP_RIGHT, TextAnchor.TOP_RIGHT, -angle, CategoryLabelWidthType.RANGE, 0.50f), // BOTTOM new CategoryLabelPosition( RectangleAnchor.RIGHT, TextBlockAnchor.BOTTOM_RIGHT, TextAnchor.BOTTOM_RIGHT, -angle, CategoryLabelWidthType.RANGE, 0.50f), // LEFT new CategoryLabelPosition( RectangleAnchor.LEFT, TextBlockAnchor.TOP_LEFT, TextAnchor.TOP_LEFT, -angle, CategoryLabelWidthType.RANGE, 0.50f) // RIGHT ); } /** * Creates a new instance where the category labels angled downwards by the * specified amount. * * @param angle the rotation angle (should be &lt; Math.PI / 2.0). * * @return A category label position specification. */ public static CategoryLabelPositions createDownRotationLabelPositions( double angle) { return new CategoryLabelPositions( new CategoryLabelPosition( RectangleAnchor.BOTTOM, TextBlockAnchor.BOTTOM_RIGHT, TextAnchor.BOTTOM_RIGHT, angle, CategoryLabelWidthType.RANGE, 0.50f), // TOP new CategoryLabelPosition( RectangleAnchor.TOP, TextBlockAnchor.TOP_LEFT, TextAnchor.TOP_LEFT, angle, CategoryLabelWidthType.RANGE, 0.50f), // BOTTOM new CategoryLabelPosition( RectangleAnchor.RIGHT, TextBlockAnchor.TOP_RIGHT, TextAnchor.TOP_RIGHT, angle, CategoryLabelWidthType.RANGE, 0.50f), // LEFT new CategoryLabelPosition( RectangleAnchor.LEFT, TextBlockAnchor.BOTTOM_LEFT, TextAnchor.BOTTOM_LEFT, angle, CategoryLabelWidthType.RANGE, 0.50f) // RIGHT ); } /** * The label positioning details used when an axis is at the top of a * chart. */ private CategoryLabelPosition positionForAxisAtTop; /** * The label positioning details used when an axis is at the bottom of a * chart. */ private CategoryLabelPosition positionForAxisAtBottom; /** * The label positioning details used when an axis is at the left of a * chart. */ private CategoryLabelPosition positionForAxisAtLeft; /** * The label positioning details used when an axis is at the right of a * chart. */ private CategoryLabelPosition positionForAxisAtRight; /** * Default constructor. */ public CategoryLabelPositions() { this.positionForAxisAtTop = new CategoryLabelPosition(); this.positionForAxisAtBottom = new CategoryLabelPosition(); this.positionForAxisAtLeft = new CategoryLabelPosition(); this.positionForAxisAtRight = new CategoryLabelPosition(); } /** * Creates a new position specification. * * @param top the label position info used when an axis is at the top * (<code>null</code> not permitted). * @param bottom the label position info used when an axis is at the * bottom (<code>null</code> not permitted). * @param left the label position info used when an axis is at the left * (<code>null</code> not permitted). * @param right the label position info used when an axis is at the right * (<code>null</code> not permitted). */ public CategoryLabelPositions(CategoryLabelPosition top, CategoryLabelPosition bottom, CategoryLabelPosition left, CategoryLabelPosition right) { ParamChecks.nullNotPermitted(top, "top"); ParamChecks.nullNotPermitted(bottom, "bottom"); ParamChecks.nullNotPermitted(left, "left"); ParamChecks.nullNotPermitted(right, "right"); this.positionForAxisAtTop = top; this.positionForAxisAtBottom = bottom; this.positionForAxisAtLeft = left; this.positionForAxisAtRight = right; } /** * Returns the category label position specification for an axis at the * given location. * * @param edge the axis location. * * @return The category label position specification. */ public CategoryLabelPosition getLabelPosition(RectangleEdge edge) { CategoryLabelPosition result = null; if (edge == RectangleEdge.TOP) { result = this.positionForAxisAtTop; } else if (edge == RectangleEdge.BOTTOM) { result = this.positionForAxisAtBottom; } else if (edge == RectangleEdge.LEFT) { result = this.positionForAxisAtLeft; } else if (edge == RectangleEdge.RIGHT) { result = this.positionForAxisAtRight; } return result; } /** * Returns a new instance based on an existing instance but with the top * position changed. * * @param base the base (<code>null</code> not permitted). * @param top the top position (<code>null</code> not permitted). * * @return A new instance (never <code>null</code>). */ public static CategoryLabelPositions replaceTopPosition( CategoryLabelPositions base, CategoryLabelPosition top) { ParamChecks.nullNotPermitted(base, "base"); ParamChecks.nullNotPermitted(top, "top"); return new CategoryLabelPositions(top, base.getLabelPosition(RectangleEdge.BOTTOM), base.getLabelPosition(RectangleEdge.LEFT), base.getLabelPosition(RectangleEdge.RIGHT)); } /** * Returns a new instance based on an existing instance but with the bottom * position changed. * * @param base the base (<code>null</code> not permitted). * @param bottom the bottom position (<code>null</code> not permitted). * * @return A new instance (never <code>null</code>). */ public static CategoryLabelPositions replaceBottomPosition( CategoryLabelPositions base, CategoryLabelPosition bottom) { ParamChecks.nullNotPermitted(base, "base"); ParamChecks.nullNotPermitted(bottom, "bottom"); return new CategoryLabelPositions( base.getLabelPosition(RectangleEdge.TOP), bottom, base.getLabelPosition(RectangleEdge.LEFT), base.getLabelPosition(RectangleEdge.RIGHT)); } /** * Returns a new instance based on an existing instance but with the left * position changed. * * @param base the base (<code>null</code> not permitted). * @param left the left position (<code>null</code> not permitted). * * @return A new instance (never <code>null</code>). */ public static CategoryLabelPositions replaceLeftPosition( CategoryLabelPositions base, CategoryLabelPosition left) { ParamChecks.nullNotPermitted(base, "base"); ParamChecks.nullNotPermitted(left, "left"); return new CategoryLabelPositions( base.getLabelPosition(RectangleEdge.TOP), base.getLabelPosition(RectangleEdge.BOTTOM), left, base.getLabelPosition(RectangleEdge.RIGHT)); } /** * Returns a new instance based on an existing instance but with the right * position changed. * * @param base the base (<code>null</code> not permitted). * @param right the right position (<code>null</code> not permitted). * * @return A new instance (never <code>null</code>). */ public static CategoryLabelPositions replaceRightPosition( CategoryLabelPositions base, CategoryLabelPosition right) { ParamChecks.nullNotPermitted(base, "base"); ParamChecks.nullNotPermitted(right, "right"); return new CategoryLabelPositions( base.getLabelPosition(RectangleEdge.TOP), base.getLabelPosition(RectangleEdge.BOTTOM), base.getLabelPosition(RectangleEdge.LEFT), right); } /** * Returns <code>true</code> if this object is equal to the specified * object, and <code>false</code> otherwise. * * @param obj the other object. * * @return A boolean. */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof CategoryLabelPositions)) { return false; } CategoryLabelPositions that = (CategoryLabelPositions) obj; if (!this.positionForAxisAtTop.equals(that.positionForAxisAtTop)) { return false; } if (!this.positionForAxisAtBottom.equals( that.positionForAxisAtBottom)) { return false; } if (!this.positionForAxisAtLeft.equals(that.positionForAxisAtLeft)) { return false; } if (!this.positionForAxisAtRight.equals(that.positionForAxisAtRight)) { return false; } return true; } /** * Returns a hash code for this object. * * @return A hash code. */ @Override public int hashCode() { int result = 19; result = 37 * result + this.positionForAxisAtTop.hashCode(); result = 37 * result + this.positionForAxisAtBottom.hashCode(); result = 37 * result + this.positionForAxisAtLeft.hashCode(); result = 37 * result + this.positionForAxisAtRight.hashCode(); return result; } }
package com.felhr.deviceids; public class XdcVcpIds { /* * Werner Wolfrum (w.wolfrum@wolfrum-elektronik.de) */ /* Different products and vendors of XdcVcp family */ private static final ConcreteDevice[] xdcvcpDevices = new ConcreteDevice[] { new ConcreteDevice(0x264D, 0x0232), // VCP (Virtual Com Port) new ConcreteDevice(0x264D, 0x0120) // USI (Universal Sensor Interface) new ConcreteDevice(0x0483, 0x5740), //CC3D (STM) }; public static boolean isDeviceSupported(int vendorId, int productId) { for(int i=0;i<=xdcvcpDevices.length-1;i++) { if(xdcvcpDevices[i].vendorId == vendorId && xdcvcpDevices[i].productId == productId ) { return true; } } return false; } private static class ConcreteDevice { public int vendorId; public int productId; public ConcreteDevice(int vendorId, int productId) { this.vendorId = vendorId; this.productId = productId; } } }
package VASSAL.launch; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.apache.commons.lang3.SystemUtils; import VASSAL.tools.version.GitProperties; public class StandardConfig implements Config { private final Path baseDir; private final Path docDir; private final Path confDir; private final Path tmpDir; private final Path prefsDir; private final Path errorLogPath; private final Path javaBinPath; private final int instanceID; private final String version; private final String reportableVersion; public StandardConfig() throws IOException { // Set the instance id from the system properties. final String idstr = System.getProperty("VASSAL.id"); if (idstr == null) { instanceID = 0; } else { int id; try { id = Integer.parseInt(idstr); } catch (NumberFormatException e) { id = -1; } instanceID = id; } // Set the version, reportable version final GitProperties gitProperties = new GitProperties(); version = gitProperties.getVersion(); reportableVersion = version.contains("-") ? version.substring(0, version.indexOf('-')) : version; baseDir = Path.of(System.getProperty("user.dir")); docDir = baseDir.resolve( SystemUtils.IS_OS_MAC_OSX ? "Contents/Resources/doc" : "doc" ); // Set up the config dir and ensure it exists if (SystemUtils.IS_OS_MAC_OSX) { confDir = Path.of(System.getProperty("user.home"), "Library/Application Support/VASSAL"); } else if (SystemUtils.IS_OS_WINDOWS) { confDir = Path.of(System.getenv("APPDATA"), "VASSAL"); } else { confDir = Path.of(System.getProperty("user.home"), ".VASSAL"); } Files.createDirectories(confDir); prefsDir = confDir.resolve("prefs"); errorLogPath = confDir.resolve("errorLog-" + getVersion()); javaBinPath = Path.of(System.getProperty("java.home"), "bin", "java"); // Set up the temp dir and ensure it exists tmpDir = Files.createTempDirectory("vassal_"); tmpDir.toFile().deleteOnExit(); } @Override public String getVersion() { return version; } @Override public String getReportableVersion() { return reportableVersion; } @Override public int getInstanceID() { return instanceID; } @Override public Path getBaseDir() { return baseDir; } @Override public Path getDocDir() { return docDir; } @Override public Path getConfDir() { return confDir; } @Override public Path getTempDir() { return tmpDir; } @Override public Path getPrefsDir() { return prefsDir; } @Override public Path getErrorLogPath() { return errorLogPath; } @Override public Path getJavaBinPath() { return javaBinPath; } }
package theschoolproject; //THis will be the dungeon room, 16x11 = 176 tiles import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import resources.SettingsProperties; public class Room { int width = 17; int height = 13; int[] tiles = new int[width * height]; FloorTile[] tileArry = new FloorTile[width * height]; GamePanel mainPanel; SettingsProperties props = new SettingsProperties(); BufferedImage lvl; int drawCycle = 0; public Room(GamePanel gp, String LevelImage) { mainPanel = gp; for (int i = 0; i < tileArry.length; i++) { tileArry[i] = new FloorTile(1); } lvl = UsefulSnippets.loadImage(LevelImage); loadLevel(); } public final void loadLevel() { lvl.getRGB(0, 0, width, height, tiles, 0, width); for (int i = 0; i < lvl.getWidth(); i++) { for (int j = 0; j < lvl.getHeight(); j++) { if (tiles[i + j * width] == 0xFFFFFFFF) { tileArry[i + j * width].setTile(1); //Wall } if (tiles[i + j * width] == 0xFF000000) { tileArry[i + j * width].setTile(2); //Floor } if (tiles[i + j * width] == 0xFF532F00) { tileArry[i + j * width].setTile(3); //Door } if (tiles[i + j * width] == 0xFF0000ff) { tileArry[i + j * width].setTile(9); //Water } if (tiles[i + j * width] == 0xFF03a5ff) { tileArry[i + j * width].setTile(5); //Ice } if (tiles[i + j * width] == 0xFFfc1604) { tileArry[i + j * width].setTile(6); //Lava } if (tiles[i + j * width] == 0xFF073a08) { tileArry[i + j * width].setTile(7); //Moss } if (tiles[i + j * width] == 0xFF007f00) { tileArry[i + j * width].setTile(8); //Grass } if (tiles[i + j * width] == 0xFF6b3d00) { tileArry[i + j * width].setTile(9); //Rock } } } System.out.println(tileArry[5 + 5 * width].TILE_ID); for (int i = 1; i < lvl.getWidth() - 1; i++) { for (int j = 1; j < lvl.getHeight() - 1; j++) { if (tileArry[i + j * width].TILE_ID == 1) { if (tileArry[i + (j + 1) * width].TILE_ID == 4) { tileArry[i + j * width].setMetadata(1); tileArry[i + j * width].metaDir = 0; } if (tileArry[i + (j - 1) * width].TILE_ID == 4) { tileArry[i + j * width].setMetadata(1); tileArry[i + j * width].metaDir = 2; } if (tileArry[(i + 1) + j * width].TILE_ID == 4) { tileArry[i + j * width].setMetadata(1); tileArry[i + j * width].metaDir = 1; } if (tileArry[(i - 1) + j * width].TILE_ID == 4) { tileArry[i + j * width].setMetadata(1); tileArry[i + j * width].metaDir = 3; } } } } } public void draw(Graphics g) { for (int i = 0; i < lvl.getWidth(); i++) { for (int j = 0; j < lvl.getHeight(); j++) { g.setColor(tileArry[i + j * width].getColor()); g.fill3DRect(i * 50, j * 50, 50, 50, true); switch (tileArry[i + j * width].TILE_ID) { case 0: break; case 1: g.drawImage(mainPanel.spritesTex[tileArry[i + j * width].metaData][1], i * 50, j * 50, null); break; case 2: g.drawImage(mainPanel.spritesTex[tileArry[i + j * width].metaData][0], i * 50, j * 50, null); break; case 3: g.drawImage(mainPanel.spritesTex[tileArry[i + j * width].metaData][5], i * 50, j * 50, null); break; case 4: drawCycle++; if (drawCycle > 10) { tileArry[i + j * width].metaData = UsefulSnippets.generateRandomNumber(3); drawCycle = 0; g.drawImage(mainPanel.spritesTex[tileArry[i + j * width].metaData][2], i * 50, j * 50, null); } else { g.drawImage(mainPanel.spritesTex[tileArry[i + j * width].metaData][2], i * 50, j * 50, null); } break; case 5: g.drawImage(mainPanel.spritesTex[tileArry[i + j * width].metaData][3], i * 50, j * 50, null); break; case 6: g.drawImage(mainPanel.spritesTex[tileArry[i + j * width].metaData][6], i * 50, j * 50, null); break; case 7: g.drawImage(mainPanel.spritesTex[tileArry[i + j * width].metaData][6], i * 50, j * 50, null); break; case 8: g.drawImage(mainPanel.spritesTex[tileArry[i + j * width].metaData][6], i * 50, j * 50, null); break; case 9: g.drawImage(mainPanel.spritesTex[tileArry[i + (j-1) * width].metaData][2], i * 50, j * 50, null); g.drawImage(mainPanel.spritesTex[1][5], i * 50, j * 50, null); break; } // if (SettingsProperties.debugModeG == true) { // g.setColor(Color.yellow); // g.fill3DRect((mainPanel.pl.tileLocX) * 50, (mainPanel.pl.tileLocY) * 50, 50, 50, true); // g.setColor(new Color(0, 255, 0, 7)); // g.fill3DRect((mainPanel.pl.tileLocX + 1) * 50, (mainPanel.pl.tileLocY) * 50, 50, 50, true); // g.fill3DRect((mainPanel.pl.tileLocX) * 50, (mainPanel.pl.tileLocY + 1) * 50, 50, 50, true); // g.fill3DRect((mainPanel.pl.tileLocX - 1) * 50, (mainPanel.pl.tileLocY) * 50, 50, 50, true); // g.fill3DRect((mainPanel.pl.tileLocX) * 50, (mainPanel.pl.tileLocY - 1) * 50, 50, 50, true); // g.setColor(new Color(255, 0, 0, 7)); // if (tileArry[(mainPanel.pl.tileLocX + 1) + (mainPanel.pl.tileLocY) * width].isSolid()) { // g.fill3DRect((mainPanel.pl.tileLocX + 1) * 50, (mainPanel.pl.tileLocY) * 50, 50, 50, true); // if (tileArry[(mainPanel.pl.tileLocX) + (mainPanel.pl.tileLocY + 1) * width].isSolid()) { // g.fill3DRect((mainPanel.pl.tileLocX) * 50, (mainPanel.pl.tileLocY + 1) * 50, 50, 50, true); // if (tileArry[(mainPanel.pl.tileLocX - 1) + (mainPanel.pl.tileLocY) * width].isSolid()) { // g.fill3DRect((mainPanel.pl.tileLocX - 1) * 50, (mainPanel.pl.tileLocY) * 50, 50, 50, true); // if (tileArry[(mainPanel.pl.tileLocX) + (mainPanel.pl.tileLocY - 1) * width].isSolid()) { // g.fill3DRect((mainPanel.pl.tileLocX) * 50, (mainPanel.pl.tileLocY - 1) * 50, 50, 50, true); // g.setColor(Color.white); } } } }
// This file is part of OpenTSDB. // This program is free software: you can redistribute it and/or modify it // option) any later version. This program is distributed in the hope that it // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser package net.opentsdb.tsd; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.google.common.base.Objects; import com.stumbleupon.async.Deferred; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.handler.codec.http.DefaultHttpResponse; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.jboss.netty.handler.codec.http.HttpMethod; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpResponseStatus; import org.jboss.netty.handler.codec.http.HttpVersion; import org.jboss.netty.handler.codec.http.QueryStringDecoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.opentsdb.core.TSDB; import net.opentsdb.stats.QueryStats; /** * Abstract base class for HTTP queries. * * @since 2.2 */ public abstract class AbstractHttpQuery { private static final Logger LOG = LoggerFactory.getLogger(AbstractHttpQuery.class); /** When the query was started (useful for timing). */ private final long start_time = System.nanoTime(); /** The request in this HTTP query. */ private final HttpRequest request; /** The channel on which the request was received. */ private final Channel chan; /** Shortcut to the request method */ private final HttpMethod method; /** Parsed query string (lazily built on first access). */ private Map<String, List<String>> querystring; /** Deferred result of this query, to allow asynchronous processing. * (Optional.) */ protected final Deferred<Object> deferred = new Deferred<Object>(); /** The response object we'll fill with data */ private final DefaultHttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); /** The {@code TSDB} instance we belong to */ protected final TSDB tsdb; /** Used for recording query statistics */ protected QueryStats stats; /** * Set up required internal state. For subclasses. * * @param request the incoming HTTP request * @param chan the {@link Channel} the request was received on */ protected AbstractHttpQuery(final TSDB tsdb, final HttpRequest request, final Channel chan) { this.tsdb = tsdb; this.request = request; this.chan = chan; this.method = request.getMethod(); } /** * Returns the underlying Netty {@link HttpRequest} of this query. */ public HttpRequest request() { return request; } /** Returns the HTTP method/verb for the request */ public HttpMethod method() { return this.method; } /** Returns the response object, allowing serializers to set headers */ public DefaultHttpResponse response() { return this.response; } /** * Returns the underlying Netty {@link Channel} of this query. */ public Channel channel() { return chan; } /** @return The remote address and port in the format <ip>:<port> */ public String getRemoteAddress() { return chan.getRemoteAddress().toString(); } /** * Copies the header list and obfuscates the "cookie" header in case it * contains auth tokens, etc. Note that it flattens duplicate headers keys * as comma separated lists per the RFC * @return The full set of headers for this query with the cookie obfuscated */ public Map<String, String> getPrintableHeaders() { final Map<String, String> headers = new HashMap<String, String>( request.getHeaders().size()); for (final Entry<String, String> header : request.getHeaders()) { if (header.getKey().toLowerCase().equals("cookie")) { // null out the cookies headers.put(header.getKey(), "*******"); } else { // http://tools.ietf.org/html/rfc2616#section-4.2 if (headers.containsKey(header.getKey())) { headers.put(header.getKey(), headers.get(header.getKey()) + "," + header.getValue()); } else { headers.put(header.getKey(), header.getValue()); } } } return headers; } /** * Copies the header list so modifications won't affect the original set. * Note that it flattens duplicate headers keys as comma separated lists * per the RFC * @return The full set of headers for this query */ public Map<String, String> getHeaders() { final Map<String, String> headers = new HashMap<String, String>( request.getHeaders().size()); for (final Entry<String, String> header : request.getHeaders()) { // http://tools.ietf.org/html/rfc2616#section-4.2 if (headers.containsKey(header.getKey())) { headers.put(header.getKey(), headers.get(header.getKey()) + "," + header.getValue()); } else { headers.put(header.getKey(), header.getValue()); } } return headers; } /** @param stats The stats object to mark after writing is complete */ public void setStats(final QueryStats stats) { this.stats = stats; } /** Return the time in nanoseconds that this query object was * created. */ public long startTimeNanos() { return start_time; } /** Returns how many ms have elapsed since this query was created. */ public int processingTimeMillis() { return (int) ((System.nanoTime() - start_time) / 1000000); } /** * Returns the query string parameters passed in the URI. */ public Map<String, List<String>> getQueryString() { if (querystring == null) { try { querystring = new QueryStringDecoder(request.getUri()).getParameters(); } catch (IllegalArgumentException e) { throw new BadRequestException("Bad query string: " + e.getMessage()); } } return querystring; } /** * Returns the value of the given query string parameter. * <p> * If this parameter occurs multiple times in the URL, only the last value * is returned and others are silently ignored. * @param paramname Name of the query string parameter to get. * @return The value of the parameter or {@code null} if this parameter * wasn't passed in the URI. */ public String getQueryStringParam(final String paramname) { final List<String> params = getQueryString().get(paramname); return params == null ? null : params.get(params.size() - 1); } /** * Returns the non-empty value of the given required query string parameter. * <p> * If this parameter occurs multiple times in the URL, only the last value * is returned and others are silently ignored. * @param paramname Name of the query string parameter to get. * @return The value of the parameter. * @throws BadRequestException if this query string parameter wasn't passed * or if its last occurrence had an empty value ({@code &amp;a=}). */ public String getRequiredQueryStringParam(final String paramname) throws BadRequestException { final String value = getQueryStringParam(paramname); if (value == null || value.isEmpty()) { throw BadRequestException.missingParameter(paramname); } return value; } /** * Returns whether or not the given query string parameter was passed. * @param paramname Name of the query string parameter to get. * @return {@code true} if the parameter */ public boolean hasQueryStringParam(final String paramname) { return getQueryString().get(paramname) != null; } /** * Returns all the values of the given query string parameter. * <p> * In case this parameter occurs multiple times in the URL, this method is * useful to get all the values. * @param paramname Name of the query string parameter to get. * @return The values of the parameter or {@code null} if this parameter * wasn't passed in the URI. */ public List<String> getQueryStringParams(final String paramname) { return getQueryString().get(paramname); } /** * Returns only the path component of the URI as a string * This call strips the protocol, host, port and query string parameters * leaving only the path e.g. "/path/starts/here" * <p> * Note that for slightly quicker performance you can call request().getUri() * to get the full path as a string but you'll have to strip query string * parameters manually. * @return The path component of the URI * @throws NullPointerException if the URI is null */ public String getQueryPath() { return new QueryStringDecoder(request.getUri()).getPath(); } /** * Returns the path component of the URI as an array of strings, split on the * forward slash * Similar to the {@link #getQueryPath} call, this returns only the path * without the protocol, host, port or query string params. E.g. * "/path/starts/here" will return an array of {"path", "starts", "here"} * <p> * Note that for maximum speed you may want to parse the query path manually. * @return An array with 1 or more components, note the first item may be * an empty string. * @throws BadRequestException if the URI is empty or does not start with a * slash * @throws NullPointerException if the URI is null */ public String[] explodePath() { final String path = getQueryPath(); if (path.isEmpty()) { throw new BadRequestException("Query path is empty"); } if (path.charAt(0) != '/') { throw new BadRequestException("Query path doesn't start with a slash"); } // split may be a tad slower than other methods, but since the URIs are // usually pretty short and not every request will make this call, we // probably don't need any premature optimization return path.substring(1).split("/"); } /** * Parses the query string to determine the base route for handing a query * off to an RPC handler. * @return the base route * @throws BadRequestException if some necessary part of the query cannot * be parsed. */ public abstract String getQueryBaseRoute(); /** * Attempts to parse the character set from the request header. If not set * defaults to UTF-8 * @return A Charset object * @throws UnsupportedCharsetException if the parsed character set is invalid */ public Charset getCharset() { // RFC2616 3.7 for (String type : this.request.headers().getAll("Content-Type")) { int idx = type.toUpperCase().indexOf("CHARSET="); if (idx > 1) { String charset = type.substring(idx+8); return Charset.forName(charset); } } return Charset.forName("UTF-8"); } /** @return True if the request has content, false if not. */ public boolean hasContent() { return this.request.getContent() != null && this.request.getContent().readable(); } /** * Decodes the request content to a string using the appropriate character set * @return Decoded content or an empty string if the request did not include * content * @throws UnsupportedCharsetException if the parsed character set is invalid */ public String getContent() { return this.request.getContent().toString(this.getCharset()); } /** * Method to call after writing the HTTP response to the wire. The default * is to simply log the request info. Can be overridden by subclasses. */ public void done() { final int processing_time = processingTimeMillis(); final String url = request.getUri(); final String msg = String.format("HTTP %s done in %d ms", url, processing_time); if (url.startsWith("/api/put") && LOG.isDebugEnabled()) { // NOTE: Suppresses too many log lines from /api/put. LOG.debug(msg); } else { logInfo(msg); } logInfo("HTTP " + request.getUri() + " done in " + processing_time + "ms"); } /** * Sends <code>500/Internal Server Error</code> to the client. * @param cause The unexpected exception that caused this error. */ public void internalError(final Exception cause) { logError("Internal Server Error on " + request().getUri(), cause); sendStatusOnly(HttpResponseStatus.INTERNAL_SERVER_ERROR); } /** * Sends <code>400/Bad Request</code> status to the client. * @param exception The exception that was thrown */ public void badRequest(final BadRequestException exception) { logWarn("Bad Request on " + request().getUri() + ": " + exception.getMessage()); sendStatusOnly(HttpResponseStatus.BAD_REQUEST); } /** * Sends <code>404/Not Found</code> to the client. */ public void notFound() { logWarn("Not Found: " + request().getUri()); sendStatusOnly(HttpResponseStatus.NOT_FOUND); } /** * Send just the status code without a body, used for 204 or 304 * @param status The response code to reply with */ public void sendStatusOnly(final HttpResponseStatus status) { if (!chan.isConnected()) { if(stats != null) { stats.markSendFailed(); } done(); return; } response.setStatus(status); final boolean keepalive = HttpHeaders.isKeepAlive(request); if (keepalive) { HttpHeaders.setContentLength(response, 0); } final ChannelFuture future = chan.write(response); if (stats != null) { future.addListener(new SendSuccess()); } if (!keepalive) { future.addListener(ChannelFutureListener.CLOSE); } done(); } /** * Sends an HTTP reply to the client. * @param status The status of the request (e.g. 200 OK or 404 Not Found). * @param buf The content of the reply to send. */ public void sendBuffer(final HttpResponseStatus status, final ChannelBuffer buf, final String contentType) { if (!chan.isConnected()) { if(stats != null) { stats.markSendFailed(); } done(); return; } response.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType); // TODO(tsuna): Server, X-Backend, etc. headers. // only reset the status if we have the default status, otherwise the user // already set it response.setStatus(status); response.setContent(buf); final boolean keepalive = HttpHeaders.isKeepAlive(request); if (keepalive) { HttpHeaders.setContentLength(response, buf.readableBytes()); } final ChannelFuture future = chan.write(response); if (stats != null) { future.addListener(new SendSuccess()); } if (!keepalive) { future.addListener(ChannelFutureListener.CLOSE); } done(); } /** A simple class that marks a query as complete when the stats are set */ private class SendSuccess implements ChannelFutureListener { @Override public void operationComplete(final ChannelFuture future) throws Exception { if(future.isSuccess()) { stats.markSent();} else stats.markSendFailed(); } } /** @return Information about the query */ public String toString() { return Objects.toStringHelper(this) .add("start_time", start_time) .add("request", request) .add("chan", chan) .add("querystring", querystring) .toString(); } // Logging helpers. // /** * Logger for the query instance. */ protected Logger logger() { return LOG; } protected final String logChannel() { if (request.containsHeader("X-Forwarded-For")) { String inetAddress; String proxyChain = request.getHeader("X-Forwarded-For"); int firstComma = proxyChain.indexOf(','); if (firstComma != -1) { inetAddress = proxyChain.substring(0, proxyChain.indexOf(',')); } else { inetAddress = proxyChain; } return "[id: 0x" + Integer.toHexString(chan.hashCode()) + ", /" + inetAddress + " => " + chan.getLocalAddress() + ']'; } else { return chan.toString(); } } protected final void logInfo(final String msg) { if (logger().isInfoEnabled()) { logger().info(logChannel() + ' ' + msg); } } protected final void logWarn(final String msg) { if (logger().isWarnEnabled()) { logger().warn(logChannel() + ' ' + msg); } } protected final void logError(final String msg, final Exception e) { if (logger().isErrorEnabled()) { logger().error(logChannel() + ' ' + msg, e); } } }
package ui; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import javafx.beans.value.ChangeListener; import javafx.beans.value.WeakChangeListener; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Parent; import javafx.scene.control.Button; import javafx.scene.control.TextArea; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.Stage; import model.Model; import model.TurboIssue; import model.TurboLabel; import model.TurboMilestone; import model.TurboUser; import util.Browse; public class IssueEditComponent extends VBox { private final TurboIssue issue; private final Model model; private final Stage parentStage; private ColumnControl columns; private final CompletableFuture<String> response; public IssueEditComponent(TurboIssue displayedIssue, Stage parentStage, Model model, ColumnControl columns) { this.issue = displayedIssue; this.model = model; this.parentStage = parentStage; this.response = new CompletableFuture<>(); this.columns = columns; setup(); } public CompletableFuture<String> getResponse() { return response; } private static final int TITLE_SPACING = 5; private static final int ELEMENT_SPACING = 10; private static final int MIDDLE_SPACING = 5; private ArrayList<ChangeListener<?>> changeListeners = new ArrayList<ChangeListener<?>>(); private void setup() { setPadding(new Insets(15)); setSpacing(MIDDLE_SPACING); getChildren().addAll(top(), bottom()); } private ChangeListener<String> createIssueTitleChangeListener(){ WeakReference<TurboIssue> issueRef = new WeakReference<TurboIssue>(issue); ChangeListener<String> listener = (observable, oldValue, newValue) -> { TurboIssue issue = issueRef.get(); if(issue != null){ issueRef.get().setTitle(newValue); } }; changeListeners.add(listener); return listener; } private ChangeListener<String> createIssueDescriptionChangeListener(){ WeakReference<TurboIssue> issueRef = new WeakReference<TurboIssue>(issue); ChangeListener<String> listener = (observable, oldValue, newValue) -> { TurboIssue issue = issueRef.get(); if(issue != null){ issue.setDescription(newValue); } }; changeListeners.add(listener); return listener; } private Parent top() { HBox title = new HBox(); title.setAlignment(Pos.BASELINE_LEFT); title.setSpacing(TITLE_SPACING); // TODO ALIGNMENT Text issueId = new Text("#" + issue.getId()); issueId.setStyle("-fx-font-size: 16pt;"); issueId.setOnMouseClicked(e -> { Browse.browse(issue.getHtmlUrl()); }); TextArea issueTitle = new TextArea(issue.getTitle()); issueTitle.setPromptText("Title"); issueTitle.setPrefRowCount(3); issueTitle.setPrefColumnCount(42); issueTitle.setWrapText(true); issueTitle.textProperty().addListener(new WeakChangeListener<String>(createIssueTitleChangeListener())); Parent statusBox = createStatusBox(parentStage); VBox topLeft = new VBox(); topLeft.setSpacing(5); topLeft.setAlignment(Pos.CENTER); topLeft.getChildren().addAll(issueId, statusBox); title.getChildren().addAll(topLeft, issueTitle); TextArea issueDesc = new TextArea(issue.getDescription()); issueDesc.setPrefRowCount(8); issueDesc.setPrefColumnCount(42); issueDesc.setWrapText(true); issueDesc.setPromptText("Description"); issueDesc.textProperty().addListener(new WeakChangeListener<String>(createIssueDescriptionChangeListener())); VBox top = new VBox(); top.setSpacing(ELEMENT_SPACING); top.getChildren().addAll(title, issueDesc); return top; } private LabelDisplayBox createStatusBox(Stage stage) { ObservableList<TurboLabel> statusLabel = FXCollections.observableArrayList(); for (TurboLabel label : issue.getLabels()) { if (label.getGroup() != null && label.getGroup().equals("status")) { statusLabel.add(label); break; } } final LabelDisplayBox statusBox = new LabelDisplayBox(statusLabel, true, "Status"); ObservableList<TurboLabel> allStatuses = FXCollections.observableArrayList(); for (TurboLabel label : model.getLabels()) { if (label.getGroup() != null && label.getGroup().equals("status")) { allStatuses.add(label); } } statusBox.setOnMouseClicked((e) -> { (new LabelCheckboxListDialog(stage, allStatuses)) .setInitialChecked(issue.getLabels()) .show().thenApply( (List<TurboLabel> response) -> { ObservableList<TurboLabel> issueLabels = issue.getLabels(); issueLabels.removeIf(label -> label.getGroup() != null && label.getGroup().equals("status")); issueLabels.addAll(FXCollections.observableArrayList(response)); issue.setLabels(issueLabels); statusLabel.setAll(FXCollections.observableArrayList(response)); return true; }).exceptionally(ex -> { ex.printStackTrace(); return false; }); }); statusBox.setMaxWidth(0); return statusBox; } private Parent bottom() { Parent parents = createParentsBox(parentStage); Parent milestone = createMilestoneBox(parentStage); Parent labels = createLabelBox(parentStage); Parent assignee = createAssigneeBox(parentStage); HBox buttons = createButtons(parentStage); VBox bottom = new VBox(); bottom.setSpacing(ELEMENT_SPACING); bottom.getChildren().addAll(parents, milestone, labels, assignee, buttons); return bottom; } private HBox createButtons(Stage stage) { HBox buttons = new HBox(); buttons.setAlignment(Pos.BASELINE_RIGHT); buttons.setSpacing(8); Button cancel = new Button(); cancel.setText("Cancel"); cancel.setOnMouseClicked(e -> { response.complete("cancel"); columns.deselect(); }); Button done = new Button(); done.setText("Done"); done.setOnMouseClicked(e -> { response.complete("done"); }); buttons.getChildren().addAll(done, cancel); return buttons; } private Parent createParentsBox(Stage stage) { final ParentIssuesDisplayBox parentsBox = new ParentIssuesDisplayBox(issue); List<TurboIssue> allIssues = model.getIssues(); parentsBox.setOnMouseClicked((e) -> { Integer originalParent = issue.getParentIssue(); Integer indexForExistingParent = model.getIndexOfIssue(originalParent); ArrayList<Integer> existingIndices = new ArrayList<Integer>(); if(indexForExistingParent > 0){ existingIndices.add(indexForExistingParent); } (new CheckboxListDialog(stage, FXCollections .observableArrayList(allIssues))) .setWindowTitle("Choose Parents") .setMultipleSelection(false) .setInitialCheckedState(existingIndices) .show() .thenApply((List<Integer> response) -> { boolean wasAnythingSelected = response.size() > 0; if (wasAnythingSelected) { Integer parent = response.size() > 0 ? allIssues.get(response.get(0)).getId() : null; issue.setParentIssue(parent); //TODO: // model.processInheritedLabels(issue, originalParent); } else { issue.setParentIssue(-1); } return true; }) .exceptionally(ex -> { ex.printStackTrace(); return false; }); }); return parentsBox; } private LabelDisplayBox createLabelBox(Stage stage) { ObservableList<TurboLabel> nonStatusLabels = FXCollections.observableArrayList(); for (TurboLabel label : issue.getLabels()) { if (label.getGroup() == null || !label.getGroup().equals("status")) { nonStatusLabels.add(label); } } final LabelDisplayBox labelBox = new LabelDisplayBox(nonStatusLabels, true, "Labels"); ObservableList<TurboLabel> allLabels = FXCollections.observableArrayList(); for (TurboLabel label : model.getLabels()) { if (label.getGroup() == null || !label.getGroup().equals("status")) { allLabels.add(label); } } labelBox.setOnMouseClicked((e) -> { (new LabelCheckboxListDialog(stage, allLabels)) .setInitialChecked(issue.getLabels()) .show().thenApply( (List<TurboLabel> response) -> { ObservableList<TurboLabel> issueLabels = issue.getLabels(); issueLabels.removeIf(label -> label.getGroup() == null || !label.getGroup().equals("status")); issueLabels.addAll(FXCollections.observableArrayList(response)); issue.setLabels(issueLabels); nonStatusLabels.setAll(FXCollections.observableArrayList(response)); return true; }) .exceptionally(ex -> { ex.printStackTrace(); return false; }); }); return labelBox; } private Parent createAssigneeBox(Stage stage) { final ListableDisplayBox assigneeBox = new ListableDisplayBox("Assignee", issue.getAssignee()); List<TurboUser> allAssignees = model.getCollaborators(); assigneeBox.setOnMouseClicked((e) -> { ArrayList<Integer> existingIndices = new ArrayList<Integer>(); if (issue.getAssignee() != null) { int existingIndex = -1; for (int i=0; i<allAssignees.size(); i++) { if (allAssignees.get(i).equals(issue.getAssignee())) { existingIndex = i; } } if(existingIndex != -1){ existingIndices.add(existingIndex); } } (new CheckboxListDialog(stage, FXCollections .observableArrayList(allAssignees))) .setWindowTitle("Choose Assignee") .setMultipleSelection(false) .setInitialCheckedState(existingIndices) .show() .thenApply((response) -> { TurboUser assignee = response.size() > 0 ? allAssignees.get(response.get(0)) : null; assigneeBox.setListableItem(assignee); issue.setAssignee(assignee); return true; }) .exceptionally(ex -> { ex.printStackTrace(); return false; }); }); return assigneeBox; } private Parent createMilestoneBox(Stage stage) { final ListableDisplayBox milestoneBox = new ListableDisplayBox("Milestone", issue.getMilestone()); List<TurboMilestone> allMilestones = model.getMilestones(); milestoneBox.setOnMouseClicked((e) -> { ArrayList<Integer> existingIndices = new ArrayList<Integer>(); if (issue.getMilestone() != null) { int existingIndex = -1; for (int i=0; i<allMilestones.size(); i++) { if (allMilestones.get(i).equals(issue.getMilestone())) { existingIndex = i; } } if(existingIndex != -1){ existingIndices.add(existingIndex); } } (new CheckboxListDialog(stage, FXCollections .observableArrayList(allMilestones))) .setWindowTitle("Choose Milestone") .setMultipleSelection(false) .setInitialCheckedState(existingIndices) .show() .thenApply((response) -> { TurboMilestone milestone = response.size() > 0 ? allMilestones.get(response.get(0)) : null; milestoneBox.setListableItem(milestone); issue.setMilestone(milestone); return true; }) .exceptionally(ex -> { ex.printStackTrace(); return false; }); }); return milestoneBox; } }
package com.gallatinsystems.device.dao; import java.util.Date; import java.util.logging.Logger; import com.gallatinsystems.device.domain.Device; import com.gallatinsystems.device.domain.Device.DeviceType; import com.gallatinsystems.framework.dao.BaseDAO; /** * data access object for devices. * * @author Christopher Fagiani * */ public class DeviceDAO extends BaseDAO<Device> { public static final String NO_IMEI = "NO_IMEI"; @SuppressWarnings("unused") private static final Logger log = Logger.getLogger(DeviceDAO.class .getName()); public DeviceDAO() { super(Device.class); } /** * gets a single device by phoneNumber. If phone number is not unique (this * shouldn't happen), it returns the first instance found. * * @param phoneNumber * @return */ public Device get(String phoneNumber) { return super.findByProperty("phoneNumber", phoneNumber, STRING_TYPE); } /** * gets a single device by imei/esn. If phone number is not unique (this * shouldn't happen), it returns the first instance found. * * @param imei * @return */ public Device getByImei(String imei) { if (NO_IMEI.equals(imei)) { // WiFi only devices could have "NO_IMEI" as value // We want to fall back to search by `phoneNumber` (MAC address) return null; } return super.findByProperty("esn", imei, STRING_TYPE); } /** * updates the device's last known position * * @param phoneNumber * @param lat * @param lon * @param accuracy * @param version * @param deviceIdentifier * @param imei */ public void updateDeviceLocation(String phoneNumber, Double lat, Double lon, Double accuracy, String version, String deviceIdentifier, String imei, String osVersion) { Device d = null; if (imei != null) { // New Apps from 1.10.0 and on provide IMEI/ESN d = getByImei(imei); } if (d == null) { d = get(phoneNumber); // Fall back to less-stable ID } if (d == null) { // if device is null, we have to create it d = new Device(); d.setCreatedDateTime(new Date()); d.setDeviceType(DeviceType.CELL_PHONE_ANDROID); d.setPhoneNumber(phoneNumber); } if (lat != null && lon != null) { d.setLastKnownLat(lat); d.setLastKnownLon(lon); d.setLastKnownAccuracy(accuracy); } if (deviceIdentifier != null) { d.setDeviceIdentifier(deviceIdentifier); } if (imei != null && !NO_IMEI.equals(imei)) { d.setEsn(imei); } if (osVersion != null) { d.setOsVersion(osVersion); } d.setLastLocationBeaconTime(new Date()); d.setGallatinSoftwareManifest(version); save(d); } }
/* * The Command to make objects out of a buffer */ package htmleditor.commands; import htmleditor.HTMLEditor; import javafx.event.Event; /** * * @author jlt8213 */ public class ObjectCommand implements Command { HTMLEditor editor ; public ObjectCommand(HTMLEditor editor){ this.editor = editor; } public void execute(Event t){ System.out.println("Objectify stub"); } }
package integracionis2; import java.util.Scanner; /** * * @author Usuario */ public class IntegracionIS2 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here System.out.println("hola mundo"); Scanner ingreso=new Scanner(System.in); int galones, opciones; String tipo = null; double diesel=2.00, gasolina=3.00,precio=0; double iva=12,calculoiva = 0; double total = 0,subtotal = 0; System.out.println("Gasolinera"); System.out.println("Bienvenidos a PetroEcuador"); System.out.println("1)Gasolina $3.00 \n2)Diesel $2.00"); opciones=ingreso.nextInt(); System.out.println("ingrese la cantidad en Galones"); galones=ingreso.nextInt(); if (opciones==1) { tipo="Gasolina"; precio=gasolina; subtotal=galones*gasolina; calculoiva=subtotal*iva/100; total=subtotal+calculoiva; } if (opciones==2) { tipo="Diesel"; precio=diesel; subtotal=galones*diesel; calculoiva=subtotal*iva/100; total=subtotal+calculoiva; } System.out.println("*******Factura*******"); System.out.println("Combustible :"+tipo); System.out.println("Cantidad :"+galones); System.out.println("Precio :"+precio); System.out.println("Subtotal :"+subtotal); System.out.println("Iva :"+calculoiva); System.out.println("Total :"+total); } }
package org.bdgp.MMSlide; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.logging.Handler; import java.util.logging.Level; import org.bdgp.MMSlide.DB.Config; import org.bdgp.MMSlide.DB.ModuleConfig; import org.bdgp.MMSlide.DB.Task; import org.bdgp.MMSlide.DB.TaskConfig; import org.bdgp.MMSlide.DB.TaskDispatch; import org.bdgp.MMSlide.DB.WorkflowInstance; import org.bdgp.MMSlide.DB.WorkflowModule; import org.bdgp.MMSlide.DB.Task.Status; import org.bdgp.MMSlide.Modules.Interfaces.Module; import org.bdgp.MMSlide.Modules.Interfaces.TaskListener; import com.github.mdr.ascii.java.GraphBuilder; import com.github.mdr.ascii.java.GraphLayouter; import com.j256.ormlite.field.FieldType; import com.j256.ormlite.field.SqlType; import com.j256.ormlite.stmt.StatementBuilder.StatementType; import com.j256.ormlite.support.CompiledStatement; import static org.bdgp.MMSlide.Util.where; public class WorkflowRunner { /** * Default file names for the metadata files. */ public static final String WORKFLOW_DB = "workflow.db"; public static final String LOG_FILE = "log.txt"; private Connection workflowDb; private Connection instanceDb; private File workflowDirectory; private WorkflowInstance instance; private Dao<WorkflowModule> workflow; private Dao<ModuleConfig> moduleConfig; private Dao<WorkflowInstance> workflowInstance; private Dao<TaskDispatch> taskDispatch; private Dao<TaskConfig> taskConfig; private Dao<Task> taskStatus; private Map<String,Module> moduleInstances; private List<Handler> logHandlers; private Level logLevel; private ExecutorService pool; private int maxThreads; private List<TaskListener> taskListeners; private MMSlide mmslide; private boolean isStopped; private Logger logger; private String instancePath; private String instanceDbName; /** * Constructor for WorkflowRunner. This loads the workflow.txt file * in the workflow directory and performs some consistency checks * on the workflow described in the file. * @param workflowDirectory */ public WorkflowRunner( File workflowDirectory, Integer instanceId, Level loglevel, MMSlide mmslide) { // Load the workflow database and workflow table if (workflowDirectory == null || !workflowDirectory.exists() || !workflowDirectory.isDirectory()) { throw new RuntimeException("Directory "+workflowDirectory+" is not a valid directory."); } this.workflowDb = Connection.get(new File(workflowDirectory, WORKFLOW_DB).getPath()); Dao<WorkflowModule> workflow = this.workflowDb.table(WorkflowModule.class); // set the workflow directory this.workflowInstance = this.workflowDb.table(WorkflowInstance.class); this.workflowDirectory = workflowDirectory; this.workflow = workflow; // set the instance DB this.instance = instanceId == null? newWorkflowInstance() : workflowInstance.selectOneOrDie(where("id",instanceId)); this.instancePath = new File(this.workflowDirectory, this.instance.getStorageLocation()).getPath(); this.instanceDbName = String.format("%s.db", this.instance.getName()); this.instanceDb = Connection.get(new File(instancePath, instanceDbName).getPath()); // set the number of cores to use in the thread pool this.maxThreads = Runtime.getRuntime().availableProcessors(); this.pool = Executors.newFixedThreadPool(this.maxThreads); // initialize various Dao's for convenience this.moduleConfig = this.instanceDb.table(ModuleConfig.class); this.taskConfig = this.instanceDb.table(TaskConfig.class); this.taskStatus = this.instanceDb.table(Task.class); this.taskDispatch = this.instanceDb.table(TaskDispatch.class); this.taskListeners = new ArrayList<TaskListener>(); this.mmslide = mmslide; this.moduleInstances = new HashMap<String,Module>(); this.isStopped = true; // instantiate the workflow module object instances for (WorkflowModule w : workflow.select()) { // Make sure parent IDs are defined if (w.getParentId() != null) { List<WorkflowModule> parent = workflow.select(where("id", w.getParentId())); if (parent.size() == 0) { throw new RuntimeException("Workflow references unknown parent ID "+w.getParentId()); } } // Make sure all modules implement Module if (!Module.class.isAssignableFrom(w.getModule())) { throw new RuntimeException("First module "+w.getModuleName() +" in Workflow does not inherit the Module interface."); } // Instantiate the module instances and put them in a hash try { Module m = w.getModule().newInstance(); m.initialize(this, w.getId()); moduleInstances.put(w.getId(), m); } catch (InstantiationException e) {throw new RuntimeException(e);} catch (IllegalAccessException e) {throw new RuntimeException(e);} } // init the logger this.initLogger(); } /** * Initialize the workflow instance's subdirectories and tasks.txt files. * @return the assigned instance_id for the new workflow instance. */ private WorkflowInstance newWorkflowInstance() { WorkflowInstance instance = new WorkflowInstance(); workflowInstance.insert(instance); // Create a new directory for the workflow instance. instance.createStorageLocation(this.workflowDirectory.getPath()); workflowInstance.update(instance,"id"); this.logger.info(String.format("Created new workflow instance: %s", workflowInstance)); return instance; } public void deleteTaskRecords() { List<WorkflowModule> modules = workflow.select(where("parentId",null)); for (WorkflowModule module : modules) { deleteTaskRecords(module); } this.logger.info(String.format("Removed old task, taskdispatch and taskconfig records")); } public void deleteTaskRecords(WorkflowModule module) { // Delete any child task/dispatch records List<WorkflowModule> childModules = workflow.select(where("parentId",module.getId())); for (WorkflowModule child : childModules) { deleteTaskRecords(child); } // Delete task dispatch and config records List<Task> tasks = taskStatus.select(where("moduleId",module.getId())); for (Task task : tasks) { taskConfig.delete(where("id",new Integer(task.getId()).toString())); taskDispatch.delete(where("taskId",task.getId())); } // Then delete task records taskStatus.delete(where("moduleId",module.getId())); } public void createTaskRecords() { this.logger.info("Creating new task records"); List<WorkflowModule> modules = workflow.select(where("parentId",null)); while (modules.size() > 0) { List<WorkflowModule> childModules = new ArrayList<WorkflowModule>(); for (WorkflowModule module : modules) { Module m = moduleInstances.get(module.getId()); if (m == null) { throw new RuntimeException("No instantiated module found with ID: "+module.getId()); } m.createTaskRecords(); childModules.addAll(workflow.select(where("parentId",module.getId()))); } modules = childModules; } } public void initLogger() { // initialize the workflow logger this.logger = Logger.create(null, "WorkflowRunner", logLevel); // Write to a log file in the instance dir this.logHandlers = new ArrayList<Handler>(); try { this.logHandlers.add(new Logger.LogFileHandler( new File(workflowDirectory, new File(instance.getStorageLocation(), LOG_FILE).getPath()).getPath())); } catch (SecurityException e) {throw new RuntimeException(e);} catch (IOException e) {throw new RuntimeException(e);} for (Handler handler : this.logHandlers) { this.logger.addHandler(handler); } } public void logWorkflowInfo() { // log some info on this workflow this.logger.info( String.format("Running workflow instance: %s", WorkflowRunner.this.instance.getName())); this.logger.info(String.format("Using workflow DB directory: %s", this.workflowDirectory)); this.logger.info(String.format("Using workflow DB: %s", WORKFLOW_DB)); this.logger.info(String.format("Using instance directory: %s", this.instancePath)); this.logger.info(String.format("Using instance DB: %s", this.instanceDbName)); this.logger.info(String.format("Using thread pool with %d max threads", this.maxThreads)); // Log the workflow module info this.logger.info("Workflow Modules:"); List<WorkflowModule> modules = this.workflow.select(where("parentId",null)); Collections.sort(modules, new Comparator<WorkflowModule>() { @Override public int compare(WorkflowModule a, WorkflowModule b) { return a.getModuleName().compareTo(b.getModuleName()); }}); GraphBuilder<String> graph = new GraphBuilder<String>(); Map<String,String> labels = new HashMap<String,String>(); while (modules.size() > 0) { List<WorkflowModule> childModules = new ArrayList<WorkflowModule>(); for (WorkflowModule module : modules) { Module m = moduleInstances.get(module.getId()); if (m == null) { throw new RuntimeException("No instantiated module found with ID: "+module.getId()); } // print workflow module info this.logger.info(String.format(" %s", module.toString(true))); this.logger.info(String.format( " %s(title=%s, description=%s, type=%s)", m.getClass().getSimpleName(), Util.escape(m.getTitle()), Util.escape(m.getDescription()), m.getTaskType())); // print workflow module config List<ModuleConfig> configs = this.moduleConfig.select(where("id", module.getId())); Collections.sort(configs, new Comparator<ModuleConfig>() { @Override public int compare(ModuleConfig a, ModuleConfig b) { return a.getId().compareTo(b.getId()); }}); for (ModuleConfig config : configs) { this.logger.info(String.format(" %s", config)); } // Print the tasks associated with this module List<Task> tasks = this.taskStatus.select(where("moduleId",module.getId())); Collections.sort(tasks, new Comparator<Task>() { @Override public int compare(Task a, Task b) { return a.getId()-b.getId(); }}); for (Task task : tasks) { this.logger.info(String.format(" %s", task)); // Print the task configs for the task List<TaskConfig> taskConfigs = this.taskConfig.select(where("id", new Integer(task.getId()).toString())); Collections.sort(taskConfigs, new Comparator<TaskConfig>() { @Override public int compare(TaskConfig a, TaskConfig b) { return new Integer(a.getId()).intValue()-new Integer(b.getId()).intValue(); }}); for (TaskConfig taskConfig : taskConfigs) { this.logger.info(String.format(" %s", taskConfig)); } } // build a workflow graph String label = String.format("%s:%s", module.getId(), m.getTaskType()); labels.put(module.getId(), label); graph.addVertex(label); if (module.getParentId() != null) { graph.addEdge(labels.get(module.getParentId()), label); } // now evaluate any child nodes childModules.addAll(this.workflow.select(where("parentId",module.getId()))); } modules = childModules; } // draw the workflow module graph GraphLayouter<String> layout = new GraphLayouter<String>(); this.logger.info(String.format("Workflow Graph:%n%s", layout.layout(graph.build()))); // Draw the task dispatch graph GraphBuilder<String> taskGraph = new GraphBuilder<String>(); Map<Integer,String> taskLabels = new HashMap<Integer,String>(); List<Task> tasks = this.taskStatus.select(); Collections.sort(tasks, new Comparator<Task>() { @Override public int compare(Task a, Task b) { return a.getId()-b.getId(); }}); for (int t=0; t<tasks.size(); ++t) { Task task = tasks.get(t); Module module = this.moduleInstances.get(task.getModuleId()); String label = String.format("%s:%s:%s", task.getName(), task.getStatus(), module.getTaskType()); taskLabels.put(task.getId(), label); taskGraph.addVertex(label); } List<TaskDispatch> dispatches = this.taskDispatch.select(); for (TaskDispatch dispatch : dispatches) { String parent = taskLabels.get(dispatch.getParentTaskId()); String child = taskLabels.get(dispatch.getTaskId()); taskGraph.addEdge(parent, child); } GraphLayouter<String> taskLayout = new GraphLayouter<String>(); this.logger.info(String.format("Task Dispatch Graph:%n%s", taskLayout.layout(taskGraph.build()))); } public Future<Status> run(final String startModuleId, final Map<String,Config> inheritedTaskConfig) { int cores = Runtime.getRuntime().availableProcessors(); this.pool = Executors.newFixedThreadPool(cores); Future<Status> future = pool.submit(new Callable<Status>() { @Override public Status call() { try { WorkflowRunner.this.isStopped = false; // Log some information on this workflow WorkflowRunner.this.logWorkflowInfo(); // start the first task(s) List<Task> start = taskStatus.select(where("moduleId",startModuleId)); List<Future<Status>> futures = new ArrayList<Future<Status>>(); for (Task t : start) { Future<Status> future = run(t, inheritedTaskConfig); futures.add(future); // If this is a serial task and it failed, don't run the successive sibling tasks if (WorkflowRunner.this.moduleInstances.get(t.getModuleId()).getTaskType() == Module.TaskType.SERIAL) { Status status; try { status = future.get(); } catch (InterruptedException e) {throw new RuntimeException(e);} catch (ExecutionException e) {throw new RuntimeException(e);} if (status != Status.SUCCESS) { WorkflowRunner.this.logger.severe(String.format( "Top-level task %s returned status %s, not running successive sibling tasks", t.getName(), status)); break; } } } List<Status> statuses = new ArrayList<Status>(); for (Future<Status> future : futures) { try { statuses.add(future.get()); } catch (InterruptedException e) {throw new RuntimeException(e);} catch (ExecutionException e) {throw new RuntimeException(e);} } return coalesceStatuses(statuses); } catch (Throwable e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); WorkflowRunner.this.logger.severe(String.format("Caught exception while running workflow: %s", sw.toString())); throw new RuntimeException(e); } } }); return future; } /** * Given a task, call all of its successors. * @param task * @param resume */ public Future<Status> run( final Task task, final Map<String,Config> inheritedTaskConfig) { this.logger.info(String.format("%s: running task %s", task.getName(), task)); final WorkflowModule module = this.workflow.selectOneOrDie( where("id",task.getModuleId())); // get an instance of the module final Module taskModule = moduleInstances.get(module.getId()); if (taskModule == null) { throw new RuntimeException("No instantiated module found with ID: "+module.getId()); } // merge the task and module configuration List<Config> configs = new ArrayList<Config>(); List<ModuleConfig> moduleConfigs = moduleConfig.select(where("id",task.getModuleId())); for (ModuleConfig moduleConfig : moduleConfigs) { configs.add(moduleConfig); this.logger.info(String.format("%s: using module config: %s", task.getName(), moduleConfig)); } if (inheritedTaskConfig != null) { for (Map.Entry<String,Config> entry : inheritedTaskConfig.entrySet()) { configs.add(entry.getValue()); this.logger.info(String.format("%s: using inherited task config: %s", task.getName(), entry.getValue())); } } List<TaskConfig> taskConfigs = taskConfig.select(where("id",task.getId())); for (TaskConfig tc : taskConfigs) { configs.add(tc); this.logger.info(String.format("%s: using task config: %s", task.getName(), tc)); } final Map<String,Config> config = Config.merge(configs); Callable<Status> callable = new Callable<Status>() { @Override public Status call() { Status status = task.getStatus(); WorkflowRunner.this.logger.info(String.format("%s: Previous status was: %s", task.getName(), status)); if (WorkflowRunner.this.isStopped == true) return status; // instantiate a logger for the task Logger taskLogger = Logger.create( new File(WorkflowRunner.this.getWorkflowDir(), new File(WorkflowRunner.this.getInstance().getStorageLocation(), new File(task.getStorageLocation(), LOG_FILE).getPath()).getPath()).getPath(), String.format("%s", task.getName()), logLevel); for (Handler handler : WorkflowRunner.this.logHandlers) { taskLogger.addHandler(handler); } // run the task WorkflowRunner.this.logger.info(String.format("%s: Running task", task.getName())); try { status = taskModule.run(task, config, taskLogger); } // Uncaught exceptions set the status to ERROR catch (Throwable e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); WorkflowRunner.this.logger.severe(String.format("%s: Error reported during task:%n%s", task.getName(), sw.toString())); status = Status.ERROR; } finally { WorkflowRunner.this.logger.info(String.format("%s: Calling cleanup", task.getName())); taskModule.cleanup(task); } WorkflowRunner.this.logger.info(String.format("%s: Finished running task", task.getName())); // notify any task listeners for (TaskListener listener : taskListeners) { listener.notifyTask(task); } WorkflowRunner.this.logger.info(String.format("%s: Setting task status to %s", task.getName(), status)); task.setStatus(status); if (status == Status.SUCCESS) { try { // We need to update the status of this task AND flag the unprocessed child tasks that // will be ready to run. Both of these actions must be done in a single atomic DB // operation to avoid race conditions. As far as I can tell, the HSQLDB merge statement // is atomic, so hopefully this works. CompiledStatement compiledStatement = taskStatus.getConnectionSource().getReadWriteConnection().compileStatement( "merge into TASK using (\n"+ " select c.\"id\", p.\"id\", cast('IN_PROGRESS' as longvarchar)\n"+ " from TASK p\n"+ " join TASKDISPATCH td\n"+ " on p.\"id\"=td.\"parentTaskId\"\n"+ " join TASK c\n"+ " on c.\"id\"=td.\"taskId\"\n"+ " left join (TASKDISPATCH td2\n"+ " join TASK p2\n"+ " on p2.\"id\"=td2.\"parentTaskId\")\n"+ " on c.\"id\"=td2.\"taskId\"\n"+ " and p2.\"id\"<>?\n"+ " and p2.\"status\"<>'SUCCESS'\n"+ " where c.\"status\" in ('NEW','DEFER')\n"+ " and c.\"parentTaskId\" is null\n"+ " and p2.\"id\" is null\n"+ " and p.\"id\"=?\n"+ " union all\n"+ " select p.\"id\", p.\"parentTaskId\", cast('SUCCESS' as longvarchar)\n"+ " from TASK p\n"+ " where p.\"id\"=?) \n"+ " as t(taskId, parentTaskId, status) on TASK.\"id\"=t.taskId\n"+ " when matched then update set TASK.\"parentTaskId\"=t.parentTaskId, TASK.\"status\"=t.status", StatementType.UPDATE, new FieldType[0]); compiledStatement.setObject(0, task.getId(), SqlType.INTEGER); compiledStatement.setObject(1, task.getId(), SqlType.INTEGER); compiledStatement.setObject(2, task.getId(), SqlType.INTEGER); compiledStatement.runUpdate(); } catch (SecurityException e) {throw new RuntimeException(e);} catch (SQLException e) {throw new RuntimeException(e);} } else { // update the task status in the DB taskStatus.update(task, "id"); } // enqueue the child tasks if all parent tasks completed successfully List<TaskDispatch> childTaskIds = taskDispatch.select( where("parentTaskId",task.getId())); List<Future<Status>> childFutures = new ArrayList<Future<Status>>(); if (status == Status.SUCCESS) { // Sort task dispatches by task ID Collections.sort(childTaskIds, new Comparator<TaskDispatch>() { @Override public int compare(TaskDispatch a, TaskDispatch b) { return a.getTaskId()-b.getTaskId(); }}); for (TaskDispatch childTaskId : childTaskIds) { Task childTask = taskStatus.selectOneOrDie( where("id",childTaskId.getTaskId())); if (childTask.getStatus() == Status.IN_PROGRESS && childTask.getParentTaskId() != null && childTask.getParentTaskId().equals(task.getId())) { WorkflowRunner.this.logger.info(String.format("%s: Dispatching child task: %s", task.getName(), childTask)); Future<Status> future = run(childTask, config); // If a serial task fails, don't run the successive sibling tasks Module.TaskType childTaskType = WorkflowRunner.this.moduleInstances.get(childTask.getModuleId()).getTaskType(); if (childTaskType == Module.TaskType.SERIAL && future.isCancelled()) { WorkflowRunner.this.logger.severe(String.format( "Child task %s was cancelled, not running successive sibling tasks", childTask.getName())); break; } if (childTaskType == Module.TaskType.SERIAL && future.isDone()) { Status s; try { s = future.get(); } catch (InterruptedException e) {throw new RuntimeException(e);} catch (ExecutionException e) {throw new RuntimeException(e);} if (s != Task.Status.SUCCESS) { WorkflowRunner.this.logger.severe(String.format( "Child task %s returned status %s, not running successive sibling tasks", childTask.getName(), s)); break; } } // Otherwise, add the task to childFutures.add(future); } } } // resolve all the futures into statuses List<Status> statuses = new ArrayList<Status>(); statuses.add(status); for (Future<Status> f : childFutures) { try { Status s = f.get(); statuses.add(s); } catch (ExecutionException e) {throw new RuntimeException(e);} catch (InterruptedException e) {throw new RuntimeException(e);} } // return the coalesced status Status returnStatus = coalesceStatuses(statuses); WorkflowRunner.this.logger.info(String.format("%s: Returning coalesced status: %s", task.getName(), returnStatus)); return returnStatus; } }; Future<Status> future; // Serial tasks get run immediately if (taskModule.getTaskType() == Module.TaskType.SERIAL) { FutureTask<Status> futureTask = new FutureTask<Status>(callable); this.logger.info(String.format("%s: Starting serial task", task.getName())); futureTask.run(); future = futureTask; } // Parallel tasks get put in the task pool else if (taskModule.getTaskType() == Module.TaskType.PARALLEL) { this.logger.info(String.format("%s: Submitting parallel task", task.getName())); future = pool.submit(callable); } else { throw new RuntimeException("Unknown task type: "+taskModule.getTaskType()); } return future; } /** * Sort the child statuses and set this status to * the highest priority status. */ private static Status coalesceStatuses(List<Status> statuses) { if (statuses.size() > 0) { Collections.sort(statuses); return statuses.get(0); } return Status.SUCCESS; } /** * Stop any new tasks from getting queued up. */ public void stop() { logger.warning("Stopping all jobs"); isStopped = true; // notify any task listeners for (TaskListener listener : taskListeners) { listener.stopped(); } pool.shutdown(); } /** * Stop all actively executing tasks and stop processing any waiting tasks. */ public List<Runnable> kill() { logger.warning("Killing all jobs"); isStopped = true; // notify any task listeners for (TaskListener listener : taskListeners) { listener.killed(); } List<Runnable> runnables = pool.shutdownNow(); return runnables; } /** * Get a list of the instance ids from the workflow instance file inside * a workflow directory. * @param workflowDirectory * @return */ public static List<Integer> getInstanceIds(String workflowDirectory) { List<Integer> instanceIds = new ArrayList<Integer>(); Connection workflowDb = Connection.get(new File(workflowDirectory, WORKFLOW_DB).getPath()); if (workflowDb != null) { Dao<WorkflowInstance> workflowInstance = workflowDb.table(WorkflowInstance.class); for (WorkflowInstance instance : workflowInstance.select()) { instanceIds.add(instance.getId()); } Collections.sort(instanceIds); } return instanceIds; } // Various getters/setters public Dao<WorkflowModule> getWorkflow() { return workflow; } public Dao<ModuleConfig> getModuleConfig() { return moduleConfig; } public Dao<WorkflowInstance> getWorkflowInstance() { return workflowInstance; } public Level getLogLevel() { return logLevel; } public void setLogLevel(Level logLevel) { this.logLevel = logLevel; } public int getMaxThreads() { return maxThreads; } public WorkflowInstance getInstance() { return instance; } public Dao<Task> getTaskStatus() { return taskStatus; } public Dao<TaskDispatch> getTaskDispatch() { return taskDispatch; } public Dao<TaskConfig> getTaskConfig() { return taskConfig; } public Connection getWorkflowDb() { return workflowDb; } public File getWorkflowDir() { return workflowDirectory; } public Connection getInstanceDb() { return instanceDb; } public MMSlide getMMSlide() { return mmslide; } public void addTaskListener(TaskListener listener) { taskListeners.add(listener); } public void removeTaskListener(TaskListener listener) { taskListeners.remove(listener); } public void addLogHandler(Handler handler) { logHandlers.add(handler); this.logger.addHandler(handler); } public boolean removeLogHandler(Handler handler) { this.logger.removeHandler(handler); return logHandlers.remove(handler); } public Logger getLogger() { return this.logger; } }
package com.gmail.emerssso.srbase; import com.gmail.emerssso.srbase.database.SRContentProvider; import com.gmail.emerssso.srbase.database.SRTable; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; //TODO: Add methods for calling EditPart and EditDaily //and make sure to pass SR ID in Intent extras // TODO: Auto-generated Javadoc //TODO: Write Some more in the Javadoc header /** * This activity manages the creation and modification * of SR elements in the database. * * @author Conner Kasten */ public class EditSRActivity extends Activity { /** The SR number. */ private EditText mSRNumber; /** The customer. */ private EditText mCustomer; /** The model number. */ private EditText mModelNumber; /** The serial number. */ private EditText mSerialNumber; /** The description. */ private EditText mDescription; /** The Daily Button. */ private Button mDaily; /** The Part Button. */ private Button mPart; /** The Confirm Button. */ private Button mEnter; /** The saved URI. */ private Uri savedUri; /* (non-Javadoc) * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { mSRNumber = (EditText) findViewById(R.id.SRNumber); mCustomer = (EditText) findViewById(R.id.customerName); mModelNumber = (EditText) findViewById(R.id.modelNumber); mSerialNumber = (EditText) findViewById(R.id.serialNumber); mDescription = (EditText) findViewById(R.id.description); mDaily = (Button) findViewById(R.id.add_daily); mPart = (Button) findViewById(R.id.add_part); mEnter = (Button) findViewById(R.id.confirm); Bundle extras = getIntent().getExtras(); savedUri = (savedInstanceState == null) ? null : (Uri) savedInstanceState .getParcelable(SRContentProvider.CONTENT_ITEM_TYPE); if (extras != null) { savedUri = extras .getParcelable(SRContentProvider.CONTENT_ITEM_TYPE); fillData(savedUri); } mEnter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResult(RESULT_OK); finish(); } }); } /** * Fill data. * * @param uri the uri */ private void fillData(Uri uri) { String[] projection = { SRTable.COLUMN_CUSTOMER_NAME, SRTable.COLUMN_DESCRIPTION, SRTable.COLUMN_MODEL_NUMBER, SRTable.COLUMN_SERIAL_NUMBER, SRTable.COLUMN_SR_NUMBER}; Cursor cursor = getContentResolver() .query(uri, projection, null, null,null); if (cursor != null) { cursor.moveToFirst(); mSRNumber.setText(cursor.getString(cursor .getColumnIndexOrThrow(SRTable.COLUMN_SR_NUMBER))); mCustomer.setText(cursor.getString(cursor .getColumnIndexOrThrow(SRTable.COLUMN_CUSTOMER_NAME))); mModelNumber.setText(cursor.getString(cursor .getColumnIndexOrThrow(SRTable.COLUMN_MODEL_NUMBER))); mSerialNumber.setText(cursor.getString(cursor .getColumnIndexOrThrow(SRTable.COLUMN_SERIAL_NUMBER))); mDescription.setText(cursor.getString(cursor .getColumnIndexOrThrow(SRTable.COLUMN_DESCRIPTION))); cursor.close(); } } /* (non-Javadoc) * @see android.app.Activity#onSaveInstanceState(android.os.Bundle) */ protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); saveState(); outState.putParcelable(SRContentProvider.CONTENT_ITEM_TYPE, savedUri); } /* (non-Javadoc) * @see android.app.Activity#onPause() */ @Override protected void onPause() { super.onPause(); saveState(); } /** * Save state. */ private void saveState() { String srNumber = mSRNumber.getText().toString(); String customer = mCustomer.getText().toString(); String modelNumber = mModelNumber.getText().toString(); String serialNumber = mSerialNumber.getText().toString(); String description = mDescription.getText().toString(); if (srNumber.length() == 0) { Toast.makeText(EditSRActivity.this, "SR Number missing", Toast.LENGTH_LONG).show(); return; } ContentValues values = new ContentValues(); values.put(SRTable.COLUMN_SR_NUMBER, srNumber); values.put(SRTable.COLUMN_CUSTOMER_NAME, customer); values.put(SRTable.COLUMN_MODEL_NUMBER, modelNumber); values.put(SRTable.COLUMN_SERIAL_NUMBER, serialNumber); values.put(SRTable.COLUMN_DESCRIPTION, description); if (savedUri == null) { // New SR savedUri = getContentResolver() .insert(SRContentProvider.CONTENT_URI, values); } else { // Update SR getContentResolver().update(savedUri, values, null, null); } } }
package algorithms.imageProcessing.matching; import algorithms.QuickSort; import algorithms.compGeometry.FurthestPair; import algorithms.compGeometry.PerimeterFinder2; import algorithms.imageProcessing.ColorHistogram; import algorithms.imageProcessing.FixedSizeSortedVector; import algorithms.imageProcessing.Image; import algorithms.imageProcessing.ImageIOHelper; import algorithms.imageProcessing.ImageProcessor; import algorithms.imageProcessing.MiscellaneousCurveHelper; import algorithms.imageProcessing.SIGMA; import algorithms.imageProcessing.VanishingPoints; import algorithms.imageProcessing.features.CorrespondenceList; import algorithms.imageProcessing.features.ORB; import algorithms.imageProcessing.features.ORB.Descriptors; import static algorithms.imageProcessing.features.ORB.convertToImage; import algorithms.imageProcessing.matching.PartialShapeMatcher.Result; import algorithms.imageProcessing.matching.ShapeFinder.ShapeFinderResult; import algorithms.imageProcessing.transform.EpipolarTransformer; import algorithms.imageProcessing.transform.MatchedPointsTransformationCalculator; import algorithms.imageProcessing.transform.TransformationParameters; import algorithms.imageProcessing.transform.Transformer; import algorithms.misc.Misc; import algorithms.misc.MiscDebug; import algorithms.misc.MiscMath; import algorithms.search.NearestNeighbor2D; import algorithms.util.CorrespondencePlotter; import algorithms.util.OneDIntArray; import algorithms.util.PairFloatArray; import algorithms.util.PairInt; import algorithms.util.PairIntArray; import algorithms.util.QuadInt; import algorithms.util.TrioInt; import algorithms.util.TwoDFloatArray; import algorithms.util.TwoDIntArray; import algorithms.util.VeryLongBitString; import gnu.trove.iterator.TIntIterator; import gnu.trove.iterator.TIntObjectIterator; import gnu.trove.iterator.TObjectIntIterator; import gnu.trove.list.TDoubleList; import gnu.trove.list.TFloatList; import gnu.trove.list.TIntList; import gnu.trove.list.array.TDoubleArrayList; import gnu.trove.list.array.TFloatArrayList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.TIntIntMap; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.TObjectIntMap; import gnu.trove.map.hash.TIntIntHashMap; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.map.hash.TObjectIntHashMap; import gnu.trove.set.TIntSet; import gnu.trove.set.hash.TIntHashSet; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Stack; import org.ejml.simple.SimpleMatrix; /** * a class to hold various methods related to matching * the descriptors of ORB. * See also ObjectMatcher. * * @see ORB * @see ObjectMatcher * * @author nichole */ public class ORBMatcher { // vahnishing points for dataset2 private VanishingPoints vp2 = null; public void setVanishingPointsForSet2(VanishingPoints vp) { vp2 = vp; } // method in progress to replace match0 public List<CorrespondenceList> match0(ORB orb1, ORB orb2, Set<PairInt> labeledPoints1, List<Set<PairInt>> labeledPoints2) { /* NOTE: bounds are not smoothed within this method, so if a partial shape matching is ever appended to it, one will need to make separate smoothed bounds for it. */ if (!orb1.getDescrChoice().equals(orb2.getDescrChoice())) { throw new IllegalStateException("orbs must contain same kind of descirptors"); } int distTol = 10;//20;//15;//5 PairIntArray bounds1 = createOrderedBoundsSansSmoothing( labeledPoints1); if (bounds1.getN() < 7) { throw new IllegalStateException("the boundary of object 1 " + " must have at least 7 points"); } //TODO: this needs a setting that allows a filter to be made to // prefer keypoints furthest from the outer bounds (==inner points). // This is helpful for matching objects which have different // backgrounds or foregrounds because they have changed location // or pose. // -- all keypoints can be used for the geometric model, // but for costs in the last results, might need to restrict // the costs to inner descriptors. int[] minMaxXYB1 = MiscMath.findMinMaxXY(bounds1); NearestNeighbor2D nnb1 = new NearestNeighbor2D(Misc.convert(bounds1), minMaxXYB1[1] + distTol + 1, minMaxXYB1[3] + distTol + 1); TObjectIntMap<PairInt> bounds1IndexMap = new TObjectIntHashMap<PairInt>(); for (int i = 0; i < bounds1.getN(); ++i) { bounds1IndexMap.put(new PairInt(bounds1.getX(i), bounds1.getY(i)), i); } int nBands = 3; if (orb1.getDescrChoice().equals(ORB.DescriptorChoice.HSV)) { if (orb1.getDescriptorsH() == null || orb2.getDescriptorsH() == null) { throw new IllegalStateException("hsv descriptors must be created first"); } } else if (orb1.getDescrChoice().equals(ORB.DescriptorChoice.ALT)) { if (orb1.getDescriptorsListAlt() == null || orb2.getDescriptorsListAlt() == null) { throw new IllegalStateException("alt descriptors must be created first"); } nBands = 1; } else if (orb1.getDescrChoice().equals(ORB.DescriptorChoice.GREYSCALE)) { if (orb1.getDescriptorsList() == null || orb2.getDescriptorsList() == null) { throw new IllegalStateException("descriptors must be created first"); } nBands = 1; } // NOTE: keeping coords in full size reference frames TFloatList scales1 = extractScales(orb1.getScalesList()); TFloatList scales2 = extractScales(orb2.getScalesList()); if (Math.abs(scales1.get(0) - 1) > 0.01) { throw new IllegalArgumentException("logic depends upon first scale" + " level being '1'"); } if (Math.abs(scales2.get(0) - 1) > 0.01) { throw new IllegalArgumentException("logic depends upon first scale" + " level being '1'"); } TIntIntMap sizes2Maps = new TIntIntHashMap(); for (int i = 0; i < labeledPoints2.size(); ++i) { Set<PairInt> set2 = labeledPoints2.get(i); if (set2.size() < 7) { continue; } int sz = calculateObjectSize(set2); { MiscellaneousCurveHelper curveHelper = new MiscellaneousCurveHelper(); double[] xyCen = curveHelper.calculateXYCentroids(set2); System.out.println("set " + i + " center=" + (int) xyCen[0] + "," + (int) xyCen[1] + " size_full=" + sz); } sizes2Maps.put(i, sz); } List<TObjectIntMap<PairInt>> kp1IdxMapList = new ArrayList<TObjectIntMap<PairInt>>(); for (int octave = 0; octave < scales1.size(); ++octave) { TObjectIntMap<PairInt> keypoints1IndexMap = new TObjectIntHashMap<PairInt>(); for (int i = 0; i < orb1.getKeyPoint1List().get(octave).size(); ++i) { int x = orb1.getKeyPoint1List().get(octave).get(i); int y = orb1.getKeyPoint0List().get(octave).get(i); keypoints1IndexMap.put(new PairInt(x, y), i); } kp1IdxMapList.add(keypoints1IndexMap); } List<TObjectIntMap<PairInt>> kp2IdxMapList = new ArrayList<TObjectIntMap<PairInt>>(); for (int octave = 0; octave < scales2.size(); ++octave) { TObjectIntMap<PairInt> keypoints2IndexMap = new TObjectIntHashMap<PairInt>(); for (int i = 0; i < orb2.getKeyPoint1List().get(octave).size(); ++i) { int x = orb2.getKeyPoint1List().get(octave).get(i); int y = orb2.getKeyPoint0List().get(octave).get(i); keypoints2IndexMap.put(new PairInt(x, y), i); } kp2IdxMapList.add(keypoints2IndexMap); } // NOTE: some points are on the boundaries of a labeled region // and may actually belong to another or both regions. // In the search by labeled region below, the transformation is // found using only the labeled region keypoints, but then is // applied to all keypoints, so the boundary keypoints are still // findable at a later stage. // -- for some cases, it might be necessary to consider changing // the keypoint2 maps to hold more than one labeled region for them, // increasing the keypoints2 in the adjacent regions when they // have too few (<3) to be found. // making a lookup map for keypoint indexes in points2 labeled sets List<TIntObjectMap<TIntSet>> labels2KPIdxsList = new ArrayList<TIntObjectMap<TIntSet>>(); for (int octave = 0; octave < scales2.size(); ++octave) { TIntObjectMap<TIntSet> labels2KPIdxs = new TIntObjectHashMap<TIntSet>(); labels2KPIdxsList.add(labels2KPIdxs); TObjectIntMap<PairInt> keypoints2IndexMap = kp2IdxMapList.get(octave); for (int segIdx = 0; segIdx < labeledPoints2.size(); ++segIdx) { for (PairInt p : labeledPoints2.get(segIdx)) { if (keypoints2IndexMap.containsKey(p)) { int kp2Idx = keypoints2IndexMap.get(p); TIntSet kpIdxs = labels2KPIdxs.get(segIdx); if (kpIdxs == null) { kpIdxs = new TIntHashSet(); labels2KPIdxs.put(segIdx, kpIdxs); } kpIdxs.add(kp2Idx); } } } } // -- initialize bounds2MapsList and populte on demand Map<OneDIntArray, PairIntArray> keyBounds2Map = new HashMap<OneDIntArray, PairIntArray>(); // index = index of labeledPoints, item = bitstring with neighbors set TIntObjectMap<VeryLongBitString> label2AdjacencyMap = createAdjacencyMap(labeledPoints2); //key = ordered pair of adjacent label2s, value=size of combined regions TObjectIntMap<PairInt> label2PairSizes = new TObjectIntHashMap<PairInt>(); // keys for these data are dataCount int dataCount = 0; TIntObjectMap<List<QuadInt>> correspondences = new TIntObjectHashMap<List<QuadInt>>(); TIntObjectMap<TransformationParameters> transformations = new TIntObjectHashMap<TransformationParameters>(); TIntObjectMap<Double> descCosts = new TIntObjectHashMap<Double>(); TIntIntMap nDesc = new TIntIntHashMap(); TIntObjectMap<Double> distCosts = new TIntObjectHashMap<Double>(); TIntIntMap nBounds = new TIntIntHashMap(); TIntObjectMap<Double> boundsDistCosts = new TIntObjectHashMap<Double>(); TIntIntMap octs1 = new TIntIntHashMap(); TIntIntMap octs2 = new TIntIntHashMap(); TIntIntMap segIdxs = new TIntIntHashMap(); for (int octave1 = 0; octave1 < scales1.size(); ++octave1) { //for (int octave1 = 0; octave1 < 1; ++octave1) { float scale1 = scales1.get(octave1); float sz1 = calculateObjectSize(labeledPoints1)/scale1; int nkp1 = orb1.getKeyPoint0List().get(octave1).size(); TObjectIntMap<PairInt> leftIdxMap = new TObjectIntHashMap<PairInt>(); PairIntArray left = new PairIntArray(nkp1); for (int i = 0; i < nkp1; ++i) { int x = orb1.getKeyPoint1List().get(octave1).get(i); int y = orb1.getKeyPoint0List().get(octave1).get(i); left.add(x, y); leftIdxMap.put(new PairInt(x, y), i); } assert(left.getN() == leftIdxMap.size()); int[] minMaxXY1 = MiscMath.findMinMaxXY(left); NearestNeighbor2D nn1 = new NearestNeighbor2D(Misc.convert(left), minMaxXY1[1] + distTol + 1, minMaxXY1[3] + distTol + 1); for (int octave2 = 0; octave2 < scales2.size(); ++octave2) { //for (int octave2 = 2; octave2 < 3; ++octave2) { float scale2 = scales2.get(octave2); // key = keypoint coords, value = index of keypoint within // the orb keypoint list for this octave2 TObjectIntMap<PairInt> keypoints2IndexMap = kp2IdxMapList.get(octave2); TIntObjectMap<TIntSet> labels2KPIdxs = labels2KPIdxsList.get(octave2); //key = keypoint coords, value = label that keypoint is within TObjectIntMap<PairInt> keypoints2LabelMap = new TObjectIntHashMap<PairInt>(); { TIntObjectIterator<TIntSet> iter = labels2KPIdxs.iterator(); for (int ii = 0; ii < labels2KPIdxs.size(); ++ii) { iter.advance(); int label = iter.key(); TIntSet kp2Idxs = iter.value(); TIntIterator iter2 = kp2Idxs.iterator(); while (iter2.hasNext()) { int kp2Idx = iter2.next(); PairInt p = new PairInt( orb2.getKeyPoint1List().get(octave2).get(kp2Idx), orb2.getKeyPoint0List().get(octave2).get(kp2Idx) ); keypoints2LabelMap.put(p, label); } } } TwoDFloatArray img2 = orb2.getPyramidImages().get(octave2); TIntObjectIterator<TIntSet> iter2 = labels2KPIdxs.iterator(); for (int i2 = 0; i2 < labels2KPIdxs.size(); ++i2) { iter2.advance(); int segIdx = iter2.key(); TIntSet kp2Idxs = iter2.value(); float sz2 = sizes2Maps.get(segIdx)/scale2; if (sz2 == 0 || kp2Idxs.size() < 2) { continue; } //NOTE: not removing small sz2 if ((sz2 > sz1 && Math.abs(sz2 / sz1) > 1.2)) { continue; } System.out.println("octave1=" + octave1 + " octave2=" + octave2 + " sz1=" + sz1 + " sz2=" + sz2 + " segIdx=" + segIdx + " nKP2=" + kp2Idxs.size()); TObjectIntMap<PairInt> rightIdxMap = new TObjectIntHashMap<PairInt>(kp2Idxs.size()); TIntIterator iter = kp2Idxs.iterator(); PairIntArray right = new PairIntArray(kp2Idxs.size()); while (iter.hasNext()) { int kpIdx2 = iter.next(); int x = orb2.getKeyPoint1List().get(octave2).get(kpIdx2); int y = orb2.getKeyPoint0List().get(octave2).get(kpIdx2); rightIdxMap.put(new PairInt(x, y), right.getN()); right.add(x, y); } MiscellaneousCurveHelper curveHelper = new MiscellaneousCurveHelper(); double[] xyCen2 = curveHelper.calculateXYCentroids( labeledPoints2.get(segIdx)); ORB.Descriptors[] desc1 = getDescriptors(orb1, octave1); ORB.Descriptors[] desc2 = getDescriptors(orb2, octave2); int[][] costD = ORB.calcDescriptorCostMatrix(desc1, desc2); // sorted greedy ordered by incr descr cost PairIntArray m1 = new PairIntArray(); PairIntArray m2 = new PairIntArray(); // using only the keypoints contained within the current // labeled region, combinations of point pairs are used to // find the best euclidean transformation. // the transformation is applied to the bounds to pick // up other points used later in the total cost. // 0 = the salukwzde distance, that is the normalized tot cost // 1 = sum of normalized keypoint descriptors // 2 = sum of normalized keypoint distances from transformations // 3 = number of keypoint matches (not incl boundary that aren't // 4 = sum of normalized bounds distances from transformations // 5 = number of normalized bounds matches double[] normalizedCost = new double[6]; TransformationParameters params = matchGreedy(segIdx, left, right, nBands, costD, nn1, leftIdxMap, keypoints2IndexMap, extractKeypoints(orb2, octave2), m1, m2, orb1.getPyramidImages().get(0).a[0].length, orb1.getPyramidImages().get(0).a.length, distTol, bounds1, keypoints2LabelMap, scale1, scale2, xyCen2, label2PairSizes, labeledPoints2, normalizedCost); //assert(normalizedCost[3] <= nkp1); //NOTE: below here, have decided not to use epipolar // fit and projections to find the missed high // projection points, // because the distances from epipolar lines are not // precise enough in some projections to distinguish // nearest neighbors...there are work arounds, but // one can see from the epipolar line distance // tests for android 04 to android 02 that offsets // of more than 10 pixels are within tolerance, so // it is not easy to distinguish between true and // false matches. System.out.println("octave1=" + octave1 + " octave2=" + octave2 + " euclid m1.n=" + m1.getN() + " segIdx=" + segIdx + " c=" + normalizedCost[0]); if (params == null || m1.getN() < 7) { continue; } int nTot = m1.getN() ;//+ addedKPIdxs.size(); List<QuadInt> corres = new ArrayList<QuadInt>(nTot); // for any point in result that is a keypoint, // add the descriptor cost to totalDescrSum for (int j = 0; j < m1.getN(); ++j) { int x1 = m1.getX(j); int y1 = m1.getY(j); PairInt p1 = new PairInt(x1, y1); int x2 = m2.getX(j); int y2 = m2.getY(j); PairInt p2 = new PairInt(x2, y2); corres.add(new QuadInt(p1, p2)); } assert(corres.size() == nTot); //normalizedCost: // 0 = the salukwzde distance, that is the normalized tot cost // 1 = sum of normalized keypoint descriptors // 2 = sum of normalized keypoint distances from transformations // 3 = number of keypoint matches (not incl boundary that aren't // 4 = sum of normalized bounds distances from transformations // 5 = number of normalized bounds matches correspondences.put(dataCount, corres); transformations.put(dataCount, params); descCosts.put(dataCount, normalizedCost[1]); nDesc.put(dataCount, (int)normalizedCost[3]); distCosts.put(dataCount, normalizedCost[2]); boundsDistCosts.put(dataCount, normalizedCost[4]); nBounds.put(dataCount, (int)normalizedCost[5]); octs1.put(dataCount, octave1); octs2.put(dataCount, octave2); segIdxs.put(dataCount, segIdx); dataCount++; }// end loop over octave2's segIdx }// end loop over octave2 } // end loop over octave1 assert(correspondences.size() == dataCount); //calculate "salukvazde distances" as costs to rank results /* looking at which cost components can be compared across octaves: -- the fraction of whole for the boundaries of shape do not need to be re-normalized for scale. the parameter is the adjustment for that. -- the descriptor costs do not need to be "re-normalized" for scale. -- the distances of points from transformed location does depend upon scale, but that is scaled and normalized before distSum -- * the number of descriptors does depend upon scale and this is normalized. the number of descriptors is small in number and geometric compression to fewer numbers can have a large effect. ideally the descriptor cost shows that, but this may need to be looked at more carefully... */ int img1Width = orb1.getPyramidImages().get(0).a[0].length; int img1Height = orb1.getPyramidImages().get(0).a.length; float sz1_0 = calculateObjectSize(bounds1); Transformer transformer = new Transformer(); // key = octave1, octave2, label2, value = OneDIntArray sortedkeys2 Map<TrioInt, OneDIntArray> sortedKeysMap = new HashMap<TrioInt, OneDIntArray>(); TIntIntMap nBounds1 = new TIntIntHashMap(); TIntObjectMap<PairIntArray> bounds2s = new TIntObjectHashMap<PairIntArray>(); TIntObjectMap<PairIntArray> boundsMatched = new TIntObjectHashMap<PairIntArray>(); TIntObjectMap<Double> bDistCost = new TIntObjectHashMap<Double>(); for (int i = 0; i < dataCount; ++i) { int octave1 = octs1.get(i); int octave2 = octs2.get(i); int segIdx = segIdxs.get(i); float scale1 = scales1.get(octave1); // NOTE: all coordinates are in reference frame of the full // size octave images, that is octave1=0 and octave2=0 // key = keypoint coords, value = index of keypoint within // the orb keypoint list for this octave2 TObjectIntMap<PairInt> keypoints2IndexMap = kp2IdxMapList.get(octave2); TIntObjectMap<TIntSet> labels2KPIdxs = labels2KPIdxsList.get(octave2); //key = keypoint coords, value = label that keypoint is within TObjectIntMap<PairInt> keypoints2LabelMap = new TObjectIntHashMap<PairInt>(); { TIntObjectIterator<TIntSet> iter = labels2KPIdxs.iterator(); for (int ii = 0; ii < labels2KPIdxs.size(); ++ii) { iter.advance(); int label = iter.key(); TIntSet kp2Idxs = iter.value(); TIntIterator iter2 = kp2Idxs.iterator(); while (iter2.hasNext()) { int kp2Idx = iter2.next(); PairInt p = new PairInt( orb2.getKeyPoint1List().get(octave2).get(kp2Idx), orb2.getKeyPoint0List().get(octave2).get(kp2Idx) ); keypoints2LabelMap.put(p, label); } } } // trimmed or expanded to combine to a contiguous region OneDIntArray sortedKeys2 = new OneDIntArray( extractAndSortLabels(segIdx, correspondences.get(i), keypoints2LabelMap, label2AdjacencyMap)); sortedKeysMap.put(new TrioInt(octave1, octave2, segIdx), sortedKeys2); PairIntArray bounds2; if (keyBounds2Map.containsKey(sortedKeys2)) { bounds2 = keyBounds2Map.get(sortedKeys2); } else { Set<PairInt> combSet = new HashSet<PairInt>(); for (int label2 : sortedKeys2.a) { combSet.addAll(labeledPoints2.get(label2)); } bounds2 = createOrderedBoundsSansSmoothing(combSet); keyBounds2Map.put(sortedKeys2, bounds2); } TObjectIntMap<PairInt> bounds2IndexMap = new TObjectIntHashMap<PairInt>(); for (int ii = 0; ii < bounds2.getN(); ++ii) { PairInt p = new PairInt(bounds2.getX(ii), bounds2.getY(ii)); bounds2IndexMap.put(p, ii); } int ne1 = bounds1.getN(); int ne2 = bounds2.getN(); PairIntArray bounds2Tr = transformer.applyTransformation( transformations.get(i), bounds2); /* MatchedPointsTransformationCalculator tc = new MatchedPointsTransformationCalculator(); TransformationParameters revParams = tc.swapReferenceFrames(transformations.get(i)); PairIntArray bounds1RevTr = transformer.applyTransformation( revParams, bounds1); Set<PairInt> unique = new HashSet<PairInt>(); for (int k = 0; k < bounds1RevTr.getN(); ++k) { unique.add(new PairInt(bounds1RevTr.getX(k), bounds1RevTr.getY(k))); } ne1 = unique.size(); */ nBounds1.put(i, ne1); float sz2Tr = calculateObjectSize(bounds2Tr); if ((sz1_0 > sz2Tr && ((sz1_0/sz2Tr) > 1.5)) || (sz2Tr > sz1_0 && ((sz2Tr/sz1_0) > 1.5))) { System.out.print("ERROR: scale difference too large:" + " oct1=" + octave1 + " oct2=" + octave2 + " segIdx=" + segIdx); if (sz1_0 > sz2Tr) { System.out.println(" ratio=" + (sz1_0/sz2Tr)); } else { System.out.println(" ratio=" + (sz2Tr/sz1_0)); } {// DEBUG: temporarily writing out error images float scale2 = scales2.get(octave2); Image img2 = ORB.convertToImage( orb2.getPyramidImages().get(octave2)); for (int ii = 0; ii < bounds2.getN(); ++ii) { int x = Math.round((float)bounds2.getX(ii)/scale2); int y = Math.round((float)bounds2.getY(ii)/scale2); ImageIOHelper.addPointToImage(x, y, img2, 1, 0, 255, 0); } MiscDebug.writeImage(img2, "_ERR_" + octave1 + "_" + octave2 + "_" + segIdx + "_" + MiscDebug.getCurrentTimeFormatted()); } correspondences.get(i).clear(); bounds2s.put(i, bounds2); boundsMatched.put(i, new PairIntArray()); bDistCost.put(i, Double.MAX_VALUE); continue; } int distTol2 = Math.round((float)distTol/scale1); if (distTol2 < 1) { distTol2 = 1; } PairIntArray boundsMatchingIndexes = new PairIntArray(); //sumsExtr = []{sumDist, count} double[] sumsExtr = sumKeypointDescAndDist2To1( bounds2, bounds2Tr, nnb1, bounds1IndexMap, bounds2IndexMap, img1Width, img1Height, distTol2, boundsMatchingIndexes); int nBMatched = (int)sumsExtr[1]; bounds2s.put(i, bounds2); boundsMatched.put(i, boundsMatchingIndexes); bDistCost.put(i, sumsExtr[0]); for (int ii = 0; ii < boundsMatchingIndexes.getN(); ++ii) { int idx1 = boundsMatchingIndexes.getX(ii); int idx2 = boundsMatchingIndexes.getY(ii); int x1 = bounds1.getX(idx1); int y1 = bounds1.getY(idx1); int x2 = bounds2.getX(idx2); int y2 = bounds2.getY(idx2); QuadInt q = new QuadInt(x1, y1, x2, y2); correspondences.get(i).add(q); } } assert(dataCount == nBounds1.size()); assert(dataCount == bounds2s.size()); assert(dataCount == boundsMatched.size()); assert(dataCount == bDistCost.size()); assert(dataCount == transformations.size()); float maxDesc = nBands * 256.0f; TIntList indexes = new TIntArrayList(dataCount); TFloatList costs = new TFloatArrayList(dataCount); for (int i = 0; i < dataCount; ++i) { int octave1 = octs1.get(i); int octave2 = octs2.get(i); float nKP1 = orb1.getKeyPoint0List().get(octave1).size(); float nb1 = (float)bounds1.getN(); float nd = nDesc.get(i); float descCost = descCosts.get(i).floatValue()/nd; float distCost = distCosts.get(i).floatValue()/nd; // calculate "fraction of whole" for keypoint descriptors final float f1 = 1.f - (nd/nKP1); float d1 = descCost; float d2 = distCost; float nBMatched = boundsMatched.get(i).getN(); float boundaryDistCost = bDistCost.get(i).floatValue()/nBMatched; // -- fraction of whole for boundary matching float f3 = 1.f - (nBMatched / (float)nBounds1.get(i)); float d3 = boundaryDistCost; float tot = 2.f*f1 * f1 + d1 * d1 + d2 * d2 + d3 * d3 + f3 * f3; tot = f1 * f1 + d1 * d1 + d3 * d3 + f3 * f3; //tot = f1 * f1 + d1 * d1; indexes.add(i); costs.add(tot); String str1 = String.format( "octave1=%d octave2=%d segIdx=%d (rot=%d, s=%.2f) nCor=%d nDesc=%d", octave1, octave2, segIdxs.get(i), Math.round(transformations.get(i).getRotationInDegrees()), transformations.get(i).getScale(), correspondences.get(i).size(), (int)nd); String str2 = String.format( "i=%d descCost=%.2f f1=%.2f distCost=%.2f boundDistcost=%.2f f3=%.2f tot=%f", i, d1, f1, d2, d3, f3, tot); System.out.println(str1 + " " + str2); if (!Float.isInfinite(tot)) { {// DEBUG, print matched in green List<QuadInt> qs = correspondences.get(i); String str3 = Integer.toString(segIdxs.get(i)); while (str3.length() < 3) { str3 = "0" + str3; } float scale1 = scales1.get(octave1); Image img1 = ORB.convertToImage( orb1.getPyramidImages().get(octave1)); for (int ii = 0; ii < qs.size(); ++ii) { int x = Math.round((float)qs.get(ii).getA()/scale1); int y = Math.round((float)qs.get(ii).getB()/scale1); ImageIOHelper.addPointToImage(x, y, img1, 1, 0, 255, 0); } MiscDebug.writeImage(img1, "_TMP1_" + octave1 + "_" + octave2 + "_" + str3 + "_" + MiscDebug.getCurrentTimeFormatted()); float scale2 = scales2.get(octave2); img1 = ORB.convertToImage( orb2.getPyramidImages().get(octave2)); for (int ii = 0; ii < qs.size(); ++ii) { int x = Math.round((float)qs.get(ii).getC()/scale2); int y = Math.round((float)qs.get(ii).getD()/scale2); ImageIOHelper.addPointToImage(x, y, img1, 1, 0, 255, 0); } MiscDebug.writeImage(img1, "_TMP2_" + octave1 + "_" + octave2 + "_" + str3 + "_" + MiscDebug.getCurrentTimeFormatted()); } } } assert(dataCount == nBounds1.size()); assert(dataCount == bounds2s.size()); assert(dataCount == boundsMatched.size()); assert(dataCount == bDistCost.size()); assert(dataCount == indexes.size()); assert(dataCount == costs.size()); QuickSort.sortBy1stArg(costs, indexes); //System.out.println("costs: " + Arrays.toString(costs)); //System.out.println("indexes: " + Arrays.toString(costs)); // trim to the top results within 1.12 * best int lastIdx = -1; float limit = 1.12f * costs.get(0); for (int j = 0; j < costs.size(); ++j) { if (costs.get(j) > limit) { break; } lastIdx = j; System.out.format( "final results==%d %d segIdx=%d cost=%.2f (rot=%.2f)\n", costs.size(), j, segIdxs.get(indexes.get(j)), costs.get(j), transformations.get(indexes.get(j)).getRotationInDegrees()); } // remove keys beyond lastIdx for (int i = (lastIdx + 1); i < dataCount; ++i) { int key = indexes.get(i); correspondences.remove(key); transformations.remove(key); descCosts.remove(key); nDesc.remove(key); distCosts.remove(key); boundsDistCosts.remove(key); nBounds.remove(key); octs1.remove(key); octs2.remove(key); segIdxs.remove(key); nBounds1.remove(key); bounds2s.remove(key); boundsMatched.remove(key); bDistCost.remove(key); } indexes = indexes.subList(0, lastIdx + 1); costs = costs.subList(0, lastIdx + 1); dataCount = lastIdx; assert(indexes.size() == correspondences.size()); // a look at the chord differences double maxChordAvg = Double.MIN_VALUE; TIntObjectMap<Double> chordDiffAvgs = new TIntObjectHashMap<Double>(); // could rewrite indexes here or just increase the new list // to same size as others and use "idx" to set a field for (int i = 0; i < indexes.size(); ++i) { int key = indexes.get(i); chordDiffAvgs.put(key, Double.MAX_VALUE); } TIntIntMap nb1s = new TIntIntHashMap(); TIntIntMap nb2s = new TIntIntHashMap(); TIntObjectMap<CorrespondenceList> results = new TIntObjectHashMap<CorrespondenceList>(); for (int i = 0; i < indexes.size(); ++i) { if (Float.isInfinite(costs.get(i))) { break; } int idx = indexes.get(i); int segIdx = segIdxs.get(idx); int octave1 = octs1.get(idx); int octave2 = octs2.get(idx); float scale1 = orb1.getScalesList().get(octave1).get(0); float scale2 = orb2.getScalesList().get(octave2).get(0); List<QuadInt> qs = correspondences.get(idx); // the curves have to be nearly the same scale PairIntArray p = reduceBounds(bounds1, scale1); PairIntArray q = reduceBounds(bounds2s.get(idx), scale2); PairIntArray matchedIndexes = boundsMatched.get(idx); PairIntArray mIdxs = new PairIntArray(matchedIndexes.getN()); for (int j = 0; j < matchedIndexes.getN(); ++j) { int idx1 = Math.round((float)matchedIndexes.getX(j)/scale1); int idx2 = Math.round((float)matchedIndexes.getY(j)/scale2); mIdxs.add(idx1, idx2); } //large voundaries needs larger dp for better runtime int dp = 1; if (p.getN() > 500 || q.getN() > 500) { int dn = Math.max(p.getN(), q.getN()); dp += Math.ceil((float)dn/500.f); } PartialShapeMatcher matcher = new PartialShapeMatcher(); matcher.overrideSamplingDistance(dp); TDoubleList chordDiffs = matcher.calculateChordDiffs(p, q, mIdxs); /* { if (segIdx == 0 || segIdx == 2) { double[] diffs = chordDiffs.toArray(new double[chordDiffs.size()]); System.out.println("segIdx=" + segIdx + " cds=" + Arrays.toString(diffs)); } }*/ TIntList rm = new TIntArrayList(); double thresh = .3; double chordDiffSum = 0; for (int j = 0; j < chordDiffs.size(); ++j) { // filter out points > thresh double d = chordDiffs.get(j); if (d > thresh) { rm.add(j); } else { chordDiffSum += d; } } for (int j = (rm.size() - 1); j > -1; --j) { int rmIdx = rm.get(j); int idx1 = mIdxs.getX(rmIdx); int idx2 = mIdxs.getY(rmIdx); PairInt p1 = new PairInt(p.getX(idx1), p.getY(idx1)); PairInt p2 = new PairInt(q.getX(idx2), q.getY(idx2)); //TODO: improve this w/ index map when have finished changes for (int k = 0; k < qs.size(); ++k) { QuadInt q0 = qs.get(k); PairInt p1c = new PairInt(q0.getA(), q0.getB()); PairInt p2c = new PairInt(q0.getC(), q0.getD()); if (p1.equals(p1c) && p2.equals(p2c)) { qs.remove(k); break; } } matchedIndexes.removeRange(rmIdx, rmIdx); chordDiffs.removeAt(rmIdx); } // should correct the correpondence distances too double chordAvg = chordDiffSum/(double)matchedIndexes.getN(); if (chordAvg > maxChordAvg) { maxChordAvg = chordAvg; } if (matchedIndexes.getN() > 0) { chordDiffAvgs.put(idx, chordAvg); } // points are in full reference frame results.put(idx, new CorrespondenceList(qs)); nb1s.put(idx, p.getN()); nb2s.put(idx, q.getN()); } // re-calculate the costs to include the shape component TFloatList resultCosts = new TFloatArrayList(); TIntList dataIndexes = new TIntArrayList(); for (int i = 0; i < indexes.size(); ++i) { if (Float.isInfinite(costs.get(i))) { break; } int idx = indexes.get(i); int octave1 = octs1.get(idx); int octave2 = octs2.get(idx); PairIntArray matchedIndexes = boundsMatched.get(idx); int nBMatched = matchedIndexes.getN(); float nb1 = nb1s.get(idx); float d5 = (float)(chordDiffAvgs.get(idx)/maxChordAvg); float f5 = 1.f - ((float)nBMatched/nb1); float nKP1 = orb1.getKeyPoint0List().get(octave1).size(); float nd = nDesc.get(idx); float descCost = descCosts.get(idx).floatValue()/nd; float distCost = distCosts.get(idx).floatValue()/nd; // calculate "fraction of whole" for keypoint descriptors final float f1 = 1.f - (nd/nKP1); float d1 = descCost; float d2 = distCost; float boundaryDistCost = bDistCost.get(idx).floatValue()/nBMatched; // -- fraction of whole for boundary matching float f3 = 1.f - (nBMatched / (float)nBounds1.get(idx)); float d3 = boundaryDistCost; float tot = 2.f * f1 * f1 + d1 * d1 + d2 * d2 + d3 * d3 + f3 * f3; tot = f1 * f1 + d1 * d1 + d2 * d2 + d3 * d3 + f3 * f3 + d5 * d5 + f5 * f5; //tot = f1 * f1 + d1 * d1; if (!Float.isFinite(tot)) { continue; } resultCosts.add(tot); dataIndexes.add(idx); String str1 = String.format( "** oct1=%d oct2=%d segIdx=%d (rot=%d, s=%.2f) nCor=%d nDesc=%d nB=%d", octave1, octave2, segIdxs.get(idx), Math.round(transformations.get(idx).getRotationInDegrees()), transformations.get(idx).getScale(), correspondences.get(idx).size(), (int)nd, (int)nb1); String str2 = String.format( "\n i=%d d1(desc)=%.2f f1=%.2f d2(dist)=%.2f d3(bDist)=%.2f f3=%.2f d5=%.2f f5=%.2f tot=%f", i, d1, f1, d2, d3, f3, d5, f5, tot); System.out.println(str1 + " " + str2); } assert(resultCosts.size() == dataIndexes.size()); QuickSort.sortBy1stArg(resultCosts, dataIndexes); {// DEBUG a look at the bounds and keypoints tested by octave for (int i = 0; i < scales2.size(); ++i) { float scale2 = scales2.get(i); Image img1 = ORB.convertToImage(orb2.getPyramidImages().get(i)); // plot keypoints TIntObjectMap<TIntSet> labelKP2IndexMap = labels2KPIdxsList.get(i); TIntObjectIterator<TIntSet> iter1 = labelKP2IndexMap.iterator(); for (int ii = 0; ii < labelKP2IndexMap.size(); ++ii) { iter1.advance(); int[] clr = ImageIOHelper.getNextRGB(ii); int segIdx = iter1.key(); TIntSet kpIdxs = iter1.value(); TIntIterator iter2 = kpIdxs.iterator(); while (iter2.hasNext()) { int kpIdx = iter2.next(); int x = Math.round((float) orb2.getKeyPoint1List().get(i).get(kpIdx)/ scale2); int y = Math.round((float) orb2.getKeyPoint0List().get(i).get(kpIdx)/ scale2); ImageIOHelper.addPointToImage(x, y, img1, 1, clr[0], clr[1], clr[2]); } } MiscDebug.writeImage(img1, "_TMP3__" + i + "_" + MiscDebug.getCurrentTimeFormatted()); // plot bounds img1 = ORB.convertToImage(orb2.getPyramidImages().get(i)); int count = 0; for (Entry<OneDIntArray, PairIntArray> entry : keyBounds2Map.entrySet()) { int[] clr = ImageIOHelper.getNextRGB(count); PairIntArray bounds2 = entry.getValue(); for (int idx = 0; idx < bounds2.getN(); ++idx) { int x = Math.round((float) bounds2.getX(idx)/ scale2); int y = Math.round((float) bounds2.getY(idx)/ scale2); ImageIOHelper.addPointToImage(x, y, img1, 0, clr[0], clr[1], clr[2]); } } MiscDebug.writeImage(img1, "_TMP4_" +count + "_" + MiscDebug.getCurrentTimeFormatted()); count++; } } if (results.size() < 2) { List<CorrespondenceList> out = new ArrayList<CorrespondenceList>( results.size()); for (int i = 0; i < dataIndexes.size(); ++i) { out.add(results.get(dataIndexes.get(i))); } return out; } float c0 = resultCosts.get(0); float c1 = resultCosts.get(1); float f = (c1 - c0)/c0; System.out.println("best cost=" + c0 + " nCorr=" + results.get(dataIndexes.get(0)).getPoints1().size()); System.out.println("2nd best cost=" + resultCosts.get(1) + " nCorr=" + results.get(dataIndexes.get(1)).getPoints1().size() + " (diff is " + f + " frac of best)"); float limitFactor = 0.2f; if (f < limitFactor) { List<CorrespondenceList> output = refineCostsWithColor( results, resultCosts, dataIndexes, orb1, orb2, octs1, octs2, segIdxs, labeledPoints1, labeledPoints2, bounds1, nb1s, bounds2s, sortedKeysMap, transformations, limitFactor); return output; } /* if (followWithShapeSearch) { results = aggregatedShapeMatch(orb1, orb2, nBands, labeledPoints1, labeledPoints2, octs1, octs2, segIdxs, scales1, scales2); System.out.println("nShapes=" + results.size()); }*/ List<CorrespondenceList> output = new ArrayList<CorrespondenceList>( results.size()); for (int i = 0; i < dataIndexes.size(); ++i) { output.add(results.get(dataIndexes.get(i))); } return output; } /** * * NOT READY FOR USE yet. * * needs the orbs to contain the theta pyramidal images. * add usage here. * * @param orb1 * @param orb2 * @param labeledPoints1 * @param labeledPoints2 * @return */ public List<CorrespondenceList> matchSmall(ORB orb1, ORB orb2, Set<PairInt> labeledPoints1, List<Set<PairInt>> labeledPoints2) { TFloatList scales1 = extractScales(orb1.getScalesList()); TFloatList scales2 = extractScales(orb2.getScalesList()); SIGMA sigma = SIGMA.ZEROPOINTFIVE; ImageProcessor imageProcessor = new ImageProcessor(); ColorHistogram cHist = new ColorHistogram(); int templateSize = calculateObjectSize(labeledPoints1); TIntObjectMap<Set<PairInt>> labeledPoints1Lists = new TIntObjectHashMap<Set<PairInt>>(); // key = octave number, value = histograms of cie luv TIntObjectMap<TwoDIntArray> ch1s = new TIntObjectHashMap<TwoDIntArray>(); // key = octave number, value = ordered boundaries of sets TIntObjectMap<PairIntArray> labeledBoundaries1 = new TIntObjectHashMap<PairIntArray>(); for (int octave1 = 0; octave1 < scales1.size(); ++octave1) { float scale1 = scales1.get(octave1); Set<PairInt> set1 = new HashSet<PairInt>(); for (PairInt p : labeledPoints1) { PairInt p1 = new PairInt(Math.round((float) p.getX() / scale1), Math.round((float) p.getY() / scale1)); set1.add(p1); } labeledPoints1Lists.put(octave1, set1); Image img = ORB.convertToImage(orb1.getPyramidImages().get(octave1)); int[][] ch = cHist.histogramCIELUV(img, set1); ch1s.put(octave1, new TwoDIntArray(ch)); PairIntArray bounds = imageProcessor.extractSmoothedOrderedBoundary( new HashSet(set1), sigma, img.getWidth(), img.getHeight()); labeledBoundaries1.put(octave1, bounds); } int dp = 1; float intersectionLimit = 0.5F; // key = octave number, value = list of labeled sets TIntObjectMap<List<Set<PairInt>>> labeledPoints2Lists = new TIntObjectHashMap<List<Set<PairInt>>>(); // key = octave number, value = list of histograms of cie lab theta TIntObjectMap<List<TwoDIntArray>> ch2Lists = new TIntObjectHashMap<List<TwoDIntArray>>(); // key = octave number, value = list of ordered points in labeled set TIntObjectMap<List<PairIntArray>> labeledBoundaries2Lists = new TIntObjectHashMap<List<PairIntArray>>(); for (int k = 0; k < labeledPoints2.size(); ++k) { Set<PairInt> set = labeledPoints2.get(k); if (set.size() < 7) { // NOTE: this means that subsequent datasets2 will not be // lists having same indexes as labeledPoints2 continue; } assert(Math.abs(scales2.get(0) - 1) < 0.02); PairIntArray bounds = imageProcessor.extractSmoothedOrderedBoundary( new HashSet(set), sigma, orb2.getPyramidImages().get(0).a[0].length, orb2.getPyramidImages().get(0).a.length); for (int octave2 = 0; octave2 < scales2.size(); ++octave2) { float scale2 = scales2.get(octave2); Image img = ORB.convertToImage( orb2.getPyramidImages().get(octave2)); int w2 = img.getWidth(); int h2 = img.getHeight(); Set<PairInt> set2 = new HashSet<PairInt>(); for (PairInt p : set) { int x = Math.round((float) p.getX() / scale2); int y = Math.round((float) p.getY() / scale2); if (x == w2) { x = w2 - 1; } if (y == h2) { y = h2 - 1; } PairInt p2 = new PairInt(x, y); set2.add(p2); } List<Set<PairInt>> list2 = labeledPoints2Lists.get(octave2); if (list2 == null) { list2 = new ArrayList<Set<PairInt>>(); labeledPoints2Lists.put(octave2, list2); } list2.add(set2); // create histograms for later comparison w/ template at // different scales int[][] ch = cHist.histogramCIELUV(img, set2); List<TwoDIntArray> ch2List = ch2Lists.get(octave2); if (ch2List == null) { ch2List = new ArrayList<TwoDIntArray>(); ch2Lists.put(octave2, ch2List); } ch2List.add(new TwoDIntArray(ch)); List<PairIntArray> list3 = labeledBoundaries2Lists.get(octave2); if (list3 == null) { list3 = new ArrayList<PairIntArray>(); labeledBoundaries2Lists.put(octave2, list3); } PairIntArray bounds2 = reduceBounds(bounds, scale2); list3.add(bounds2); assert(labeledBoundaries2Lists.get(octave2).size() == labeledPoints2Lists.get(octave2).size()); assert(labeledBoundaries2Lists.get(octave2).size() == ch2Lists.get(octave2).size()); } } // populated on demand, key=octave, key=segmented cell, value=size TObjectIntMap<PairInt> size2Map = new TObjectIntHashMap<PairInt>(); // -- compare sets over octaves, first by color histogram intersection, // then by partial shape matcher // delaying evaluation of results until end in order to get the // maximum chord differerence sum, needed for Salukwzde distance. // for each i, list of Results, chordDiffSums, bounds1, bounds2 // bundling Results and bounds into an object TIntObjectMap<List<PObject>> resultsMap = new TIntObjectHashMap<List<PObject>>(); TIntObjectMap<TDoubleList> chordDiffSumsMap = new TIntObjectHashMap<TDoubleList>(); TIntObjectMap<TFloatList> intersectionsMap = new TIntObjectHashMap<TFloatList>(); double maxDiffChordSum = Double.MIN_VALUE; double maxAvgDiffChord = Double.MIN_VALUE; double maxAvgDist = Double.MIN_VALUE; for (int i = 0; i < scales1.size(); ++i) { //for (int i = 2; i < 3; ++i) { float scale1 = scales1.get(i); int[][] ch1 = ch1s.get(i).a; //Set<PairInt> templateSet = labeledPoints1Lists.get(i); PairIntArray bounds1 = labeledBoundaries1.get(i); float sz1 = calculateObjectSize(bounds1); List<PObject> results = new ArrayList<PObject>(); TDoubleList chordDiffSums = new TDoubleArrayList(); TFloatList intersections = new TFloatArrayList(); for (int j = 0; j < scales2.size(); ++j) { //for (int j = 0; j < 1; ++j) { float scale2 = scales2.get(j); List<TwoDIntArray> listOfCH2s = ch2Lists.get(j); if (listOfCH2s == null) { continue; } List<Set<PairInt>> listOfSets2 = labeledPoints2Lists.get(j); List<PairIntArray> listOfBounds2 = labeledBoundaries2Lists.get(j); for (int k = 0; k < listOfCH2s.size(); ++k) { PairIntArray bounds2 = listOfBounds2.get(k); PairInt octLabelKey = new PairInt(j, k); float sz2; if (size2Map.containsKey(octLabelKey)) { sz2 = size2Map.get(octLabelKey); } else { sz2 = calculateObjectSize(bounds2); } if (sz2 == 0) { continue; } if ((sz1 > sz2 && Math.abs((float)sz1 / (float)sz2) > 1.15) || (sz2 > sz1 && Math.abs((float)sz2 / (float)sz1) > 1.15)) { continue; } int[][] ch2 = listOfCH2s.get(k).a; float intersection = cHist.intersection(ch1, ch2); if (intersection < intersectionLimit) { continue; } System.out.println("p2=" + listOfSets2.get(k).iterator().next() + " sz1=" + sz1 + " sz2=" + sz2 + " nSet=" + listOfSets2.get(k).size()); PartialShapeMatcher matcher = new PartialShapeMatcher(); matcher.overrideSamplingDistance(dp); //matcher.setToDebug(); matcher._overrideToThreshhold(0.2f); matcher.setToRemoveOutliers(); PartialShapeMatcher.Result r = matcher.match(bounds1, bounds2); if (r == null) { continue; } //NOTE: to increase the abilit to find projected objects // that have euclidean poses and skew, might consider // fast ways to approximate an affine and evaluate it // after the euclidean solution here. // affine transformations leave parallel lines in the // transformed space so could look for that in the // unmatched portion: // for example, if half of the object is matched, // could determine the distance of the matched to the // unmatched and use that with knowledge of the // euclidean expected distance to approximate a shear. // for the evaluations to remain easy to compare results // with other results, would not want to allow too much // shear... // in order to add the chord differences, this additional // calculation needs to be handled in the // partial shape matcher (but can be left until the end) double c = r.getChordDiffSum(); results.add(new PObject(r, bounds1, bounds2, scale1, scale2)); chordDiffSums.add(r.getChordDiffSum()); intersections.add(intersection); if (r.getChordDiffSum() > maxDiffChordSum) { maxDiffChordSum = r.getChordDiffSum(); } double avgCD = r.getChordDiffSum() / (double) r.getNumberOfMatches(); if (avgCD > maxAvgDiffChord) { maxAvgDiffChord = avgCD; } double avgDist = r.getDistSum() / (double) r.getNumberOfMatches(); if (avgDist > maxAvgDist) { maxAvgDist = avgDist; } System.out.println(String.format( "%d %d p in set=%s shape matcher c=%.2f np=%d inter=%.2f dist=%.2f avgDist=%.2f", i, j, listOfSets2.get(k).iterator().next().toString(), (float) c, r.getNumberOfMatches(), (float) intersection, (float) r.getDistSum(), (float) avgDist)); try { CorrespondencePlotter plotter = new CorrespondencePlotter(bounds1, bounds2); for (int ii = 0; ii < r.getNumberOfMatches(); ++ii) { int idx1 = r.getIdx1(ii); int idx2 = r.getIdx2(ii); int x1 = bounds1.getX(idx1); int y1 = bounds1.getY(idx1); int x2 = bounds2.getX(idx2); int y2 = bounds2.getY(idx2); if ((ii % 4) == 0) { plotter.drawLineInAlternatingColors(x1, y1, x2, y2, 0); } } String strI = Integer.toString(i); while (strI.length() < 2) { strI = "0" + strI; } String strJ = Integer.toString(j); while (strJ.length() < 2) { strJ = "0" + strJ; } String strK = Integer.toString(k); while (strK.length() < 2) { strK = "0" + strK; } String str = strI + strJ + strK; String filePath = plotter.writeImage("_andr_" + str); } catch (Throwable t) { } } //end loop over k labeled sets of dataset 2 } // end loop over j datasets 2 if (!results.isEmpty()) { resultsMap.put(i, results); chordDiffSumsMap.put(i, chordDiffSums); intersectionsMap.put(i, intersections); } } // end loop over i dataset 1 // calculate the Salukwdze distances /* for each i, need the max chord diff sum, nPoints in bound1, and best Results */ double minSD = Double.MAX_VALUE; int minSDI = -1; TIntObjectIterator<List<PObject>> iter = resultsMap.iterator(); for (int i = 0; i < resultsMap.size(); ++i) { iter.advance(); int idx = iter.key(); //double maxDiffChordSum = chordDiffSumsMap.get(idx).max(); double minCost = Double.MAX_VALUE; int minCostIdx = -1; List<PObject> resultsList = resultsMap.get(idx); for (int j = 0; j < resultsList.size(); ++j) { PObject obj = resultsList.get(j); float costIntersection = 1.0F - intersectionsMap.get(idx).get(j); PartialShapeMatcher.Result r = obj.r; int nb1 = Math.round((float) obj.bounds1.getN() / (float) dp); float np = r.getNumberOfMatches(); float countComp = 1.0F - (np / (float) nb1); float countCompSq = countComp * countComp; double chordComp = ((float) r.getChordDiffSum() / np) / maxAvgDiffChord; double chordCompSq = chordComp * chordComp; double avgDist = r.getDistSum() / np; double distComp = avgDist / maxAvgDist; double distCompSq = distComp * distComp; // Salukwzde uses square sums //double sd = r.calculateSalukwdzeDistanceSquared( // maxDiffChordSum, nb1); // TODO: consider formal analysis of dependencies and hence // error terms: //double sd = chordCompSq*countCompSq // + distCompSq*countCompSq; //NOTE: The coverage of the matches is currently // approximated as simply numberMatched/maxNumberMatchable, // but a term representing the spatial distribution appears // to be necessary also. // will try largestNumberGap/maxNumberMatchable. // TODO: need to improve this in detail later int lGap = maxNumberOfGaps(obj.bounds1, r)/dp; float gCountComp = (float)lGap/(float)nb1; //double sd = chordCompSq + countCompSq + distCompSq; double sd = chordComp + countComp + gCountComp + distComp + costIntersection; if (sd < minCost) { minCost = sd; minCostIdx = j; } if (sd < minSD) { minSD = sd; minSDI = idx; } System.out.println("sd=" + sd + " n1=" + obj.bounds1.getN() + " n2=" + obj.bounds2.getN() + " origN1=" + r.getOriginalN1() + " nMatches=" + r.getNumberOfMatches() + String.format( " chord=%.2f count=%.2f spatial=%.2f dist=%.2f inter=%.2f", (float)chordComp, (float)countComp, (float)gCountComp, (float)distComp, (float)costIntersection) ); } assert (minCostIdx > -1); TDoubleList cList = chordDiffSumsMap.get(idx); TFloatList iList = intersectionsMap.get(idx); for (int j = resultsList.size() - 1; j > -1; --j) { if (j != minCostIdx) { resultsList.remove(j); cList.removeAt(j); iList.removeAt(j); } } } if (resultsMap.size() > 1) { // TODO: build a test for this. // possibly need to transform results to same reference // frame to compare. // using best SD for now TIntSet rm = new TIntHashSet(); iter = resultsMap.iterator(); for (int i = 0; i < resultsMap.size(); ++i) { iter.advance(); int idx = iter.key(); if (idx != minSDI) { rm.add(idx); } } TIntIterator iter2 = rm.iterator(); while (iter2.hasNext()) { int idx = iter2.next(); resultsMap.remove(idx); } } List<CorrespondenceList> topResults = new ArrayList<CorrespondenceList>(); iter = resultsMap.iterator(); for (int i = 0; i < resultsMap.size(); ++i) { iter.advance(); int idx = iter.key(); List<PObject> resultsList = resultsMap.get(idx); assert (resultsList.size() == 1); PObject obj = resultsList.get(0); int n = obj.r.getNumberOfMatches(); if (obj.r.getTransformationParameters() == null) { continue; } PairInt[] m1 = new PairInt[n]; PairInt[] m2 = new PairInt[n]; float scale1 = obj.scale1; float scale2 = obj.scale2; for (int ii = 0; ii < n; ++ii) { int idx1 = obj.r.getIdx1(ii); int idx2 = obj.r.getIdx2(ii); int x1 = Math.round(obj.bounds1.getX(idx1) * scale1); int y1 = Math.round(obj.bounds1.getY(idx1) * scale1); int x2 = Math.round(obj.bounds2.getX(idx2) * scale2); int y2 = Math.round(obj.bounds2.getY(idx2) * scale2); m1[ii] = new PairInt(x1, y1); m2[ii] = new PairInt(x2, y2); } CorrespondenceList cor = new CorrespondenceList(obj.r.getTransformationParameters(), m1, m2); topResults.add(cor); } return topResults; } /** * * NOT READY FOR USE yet. * * searchs among aggregated adjacent labeled points to find best * fitting shape and color object where template is * dataset 1 and the searchable is dataset 2. * * * @param orb1 * @param orb2 * @param labeledPoints1 * @param labeledPoints2 * @return */ public List<CorrespondenceList> matchAggregatedShape( ORB orb1, ORB orb2, Set<PairInt> labeledPoints1, List<Set<PairInt>> labeledPoints2) { //TODO: revisit and edit for changes present in match0 TFloatList scales1 = extractScales(orb1.getScalesList()); TFloatList scales2 = extractScales(orb2.getScalesList()); if (Math.abs(scales1.get(0) - 1) > 0.01) { throw new IllegalArgumentException("logic depends upon first scale" + " level being '1'"); } if (Math.abs(scales2.get(0) - 1) > 0.01) { throw new IllegalArgumentException("logic depends upon first scale" + " level being '1'"); } SIGMA sigma = SIGMA.ZEROPOINTFIVE; ImageProcessor imageProcessor = new ImageProcessor(); ColorHistogram cHist = new ColorHistogram(); int templateSize = calculateObjectSize(labeledPoints1); TIntObjectMap<Set<PairInt>> labeledPoints1Lists = new TIntObjectHashMap<Set<PairInt>>(); // key = octave number, value = histograms of cie cie luv TIntObjectMap<TwoDIntArray> ch1s = new TIntObjectHashMap<TwoDIntArray>(); // key = octave number, value = ordered boundaries of sets TIntObjectMap<PairIntArray> labeledBoundaries1 = new TIntObjectHashMap<PairIntArray>(); for (int octave1 = 0; octave1 < scales1.size(); ++octave1) { float scale1 = scales1.get(octave1); Set<PairInt> set1 = new HashSet<PairInt>(); for (PairInt p : labeledPoints1) { PairInt p1 = new PairInt(Math.round((float) p.getX() / scale1), Math.round((float) p.getY() / scale1)); set1.add(p1); } labeledPoints1Lists.put(octave1, set1); Image img = ORB.convertToImage(orb1.getPyramidImages().get(octave1)); int[][] ch = cHist.histogramCIELUV(img, set1); ch1s.put(octave1, new TwoDIntArray(ch)); PairIntArray bounds = imageProcessor.extractSmoothedOrderedBoundary( new HashSet(set1), sigma, img.getWidth(), img.getHeight()); labeledBoundaries1.put(octave1, bounds); } int dp = 1; float intersectionLimit = 0.5F; // key = octave number, value = list of labeled sets TIntObjectMap<List<Set<PairInt>>> labeledPoints2Lists = new TIntObjectHashMap<List<Set<PairInt>>>(); // key = octave number, value = list of histograms of cie lab theta TIntObjectMap<List<TwoDIntArray>> ch2Lists = new TIntObjectHashMap<List<TwoDIntArray>>(); for (int k = 0; k < labeledPoints2.size(); ++k) { Set<PairInt> set = labeledPoints2.get(k); if (set.size() < 7) { // NOTE: this means that subsequent datasets2 will not be // lists having same indexes as labeledPoints2 continue; } assert(Math.abs(scales2.get(0) - 1) < 0.02); PairIntArray bounds = imageProcessor.extractSmoothedOrderedBoundary( new HashSet(set), sigma, orb2.getPyramidImages().get(0).a[0].length, orb2.getPyramidImages().get(0).a.length); for (int octave2 = 0; octave2 < scales2.size(); ++octave2) { float scale2 = scales2.get(octave2); Image img = ORB.convertToImage( orb2.getPyramidImages().get(octave2)); int w2 = img.getWidth(); int h2 = img.getHeight(); Set<PairInt> set2 = new HashSet<PairInt>(); for (PairInt p : set) { int x = Math.round((float) p.getX() / scale2); int y = Math.round((float) p.getY() / scale2); if (x == w2) { x = w2 - 1; } if (y == h2) { y = h2 - 1; } PairInt p2 = new PairInt(x, y); set2.add(p2); } List<Set<PairInt>> list2 = labeledPoints2Lists.get(octave2); if (list2 == null) { list2 = new ArrayList<Set<PairInt>>(); labeledPoints2Lists.put(octave2, list2); } list2.add(set2); // create histograms for later comparison w/ template at // different scales int[][] ch = cHist.histogramCIELUV(img, set2); List<TwoDIntArray> ch2List = ch2Lists.get(octave2); if (ch2List == null) { ch2List = new ArrayList<TwoDIntArray>(); ch2Lists.put(octave2, ch2List); } ch2List.add(new TwoDIntArray(ch)); assert(labeledPoints2Lists.get(octave2).size() == ch2Lists.get(octave2).size()); } } // populated on demand, key=octave, key=segmented cell, value=size TObjectIntMap<PairInt> size2Map = new TObjectIntHashMap<PairInt>(); // -- compare sets over octaves: // aggregated search of adjacent labeled cells to compare their combined // properties of color histogram and shape to the template. // the differences in chords for true match shapes should not change // with scale (excepting due to resolution affecting the shapes), // so the maximum difference in the avg chord can be // used on all of the results when re-normalizing and re-calculating dist. // The number of matches possible for each scale does change with scale // and that is handled in the "fraction of whole term" already. // so a "re-normalization" to calculate new salukvazde costs just needs // to use the maximum avg chord sum diff for all. // delaying evaluation of results until end in order to get the // maximum chord differerence sum, needed for Salukwzde distance. // for each i, list of Results, chordDiffSums, bounds1, bounds2 // bundling Results and bounds into an object TIntObjectMap<List<PObject>> resultsMap = new TIntObjectHashMap<List<PObject>>(); TIntObjectMap<TDoubleList> chordDiffSumsMap = new TIntObjectHashMap<TDoubleList>(); TIntObjectMap<TFloatList> intersectionsMap = new TIntObjectHashMap<TFloatList>(); double maxDiffChordSum = Double.MIN_VALUE; double maxAvgDiffChord = Double.MIN_VALUE; double maxAvgDist = Double.MIN_VALUE; // maps to reuse the aggregated boundaries // list is octave2 items // each map key=segmented cell label indexes, // value = index to map in octave2IndexBoundsMaps List<Map<OneDIntArray, PairIntArray>> octave2KeyIndexMaps = new ArrayList<Map<OneDIntArray, PairIntArray>>(); for (int j = 0; j < scales2.size(); ++j) { octave2KeyIndexMaps.add(new HashMap<OneDIntArray, PairIntArray>()); } for (int i = 0; i < scales1.size(); ++i) { //for (int i = 0; i < 1; ++i) { float scale1 = scales1.get(i); int[][] ch1 = ch1s.get(i).a; //Set<PairInt> templateSet = labeledPoints1Lists.get(i); PairIntArray bounds1 = labeledBoundaries1.get(i); float sz1 = calculateObjectSize(bounds1); List<PObject> results = new ArrayList<PObject>(); TDoubleList chordDiffSums = new TDoubleArrayList(); TFloatList intersections = new TFloatArrayList(); for (int j = 0; j < scales2.size(); ++j) { //for (int j = 0; j < 1; ++j) { float scale2 = scales2.get(j); List<TwoDIntArray> listOfCH2s = ch2Lists.get(j); if (listOfCH2s == null) { continue; } List<Set<PairInt>> listOfSets2 = labeledPoints2Lists.get(j); Map<OneDIntArray, PairIntArray> keyBoundsMap = octave2KeyIndexMaps.get(j); ShapeFinder shapeFinder = new ShapeFinder( bounds1, ch1, scale1, sz1, orb1.getPyramidImages().get(i).a[0].length -1, orb1.getPyramidImages().get(i).a.length - 1, listOfSets2, listOfCH2s, scale2, keyBoundsMap, orb2.getPyramidImages().get(j).a[0].length -1, orb2.getPyramidImages().get(j).a.length - 1, intersectionLimit ); shapeFinder.pyr1 = orb1.getPyramidImages().get(i); shapeFinder.pyr2 = orb2.getPyramidImages().get(j); shapeFinder.lbl = Integer.toString(i) + ":" + Integer.toString(j) + "_"; shapeFinder.oct1 = i; shapeFinder.oct2 = j; { //if (i==2&&j==0) { Image img1 = ORB.convertToImage(orb1.getPyramidImages().get(i)); Image img2 = ORB.convertToImage(orb2.getPyramidImages().get(j)); MiscDebug.writeImage(img2, "AAA_2_" + j); MiscDebug.writeImage(img1, "AAA_1_" + i); for (int i2 = 0; i2 < listOfSets2.size(); ++i2) { int clr = ImageIOHelper.getNextColorRGB(i2); Set<PairInt> set = listOfSets2.get(i2); for (PairInt p : set) { ImageIOHelper.addPointToImage(p.getX(), p.getY(), img2, 1, clr); } } MiscDebug.writeImage(img2, "_AAA_2_s_" + j); } ShapeFinderResult r = shapeFinder.findAggregated(); if (r == null) { continue; } double c = r.getChordDiffSum(); results.add(new PObject(r, r.bounds1, r.bounds2, scale1, scale2)); chordDiffSums.add(r.getChordDiffSum()); intersections.add(r.intersection); if (r.getChordDiffSum() > maxDiffChordSum) { maxDiffChordSum = r.getChordDiffSum(); } double avgCD = r.getChordDiffSum() / (double) r.getNumberOfMatches(); if (avgCD > maxAvgDiffChord) { maxAvgDiffChord = avgCD; } double avgDist = r.getDistSum() / (double) r.getNumberOfMatches(); if (avgDist > maxAvgDist) { maxAvgDist = avgDist; } System.out.println(String.format( "%d %d p in set=(%d,%d) shape matcher c=%.2f np=%d inter=%.2f dist=%.2f avgDist=%.2f", i, j, r.bounds2.getX(0), r.bounds2.getY(0), (float) c, r.getNumberOfMatches(), (float) r.intersection, (float) r.getDistSum(), (float) avgDist)); } // end loop over j datasets 2 if (!results.isEmpty()) { resultsMap.put(i, results); chordDiffSumsMap.put(i, chordDiffSums); intersectionsMap.put(i, intersections); } } // end loop over i dataset 1 // calculate the Salukwdze distances /* for each i, need the max chord diff sum, nPoints in bound1, and best Results */ double minSD = Double.MAX_VALUE; int minSDI = -1; TIntObjectIterator<List<PObject>> iter = resultsMap.iterator(); for (int i = 0; i < resultsMap.size(); ++i) { iter.advance(); int idx = iter.key(); //double maxDiffChordSum = chordDiffSumsMap.get(idx).max(); double minCost = Double.MAX_VALUE; int minCostIdx = -1; List<PObject> resultsList = resultsMap.get(idx); for (int j = 0; j < resultsList.size(); ++j) { PObject obj = resultsList.get(j); float costIntersection = 1.0F - intersectionsMap.get(idx).get(j); PartialShapeMatcher.Result r = obj.r; int nb1 = Math.round((float) obj.bounds1.getN() / (float) dp); float np = r.getNumberOfMatches(); float countComp = 1.0F - (np / (float) nb1); float countCompSq = countComp * countComp; double chordComp = ((float) r.getChordDiffSum() / np) / maxAvgDiffChord; double chordCompSq = chordComp * chordComp; double avgDist = r.getDistSum() / np; double distComp = avgDist / maxAvgDist; double distCompSq = distComp * distComp; // Salukwzde uses square sums //double sd = r.calculateSalukwdzeDistanceSquared( // maxDiffChordSum, nb1); // TODO: consider formal analysis of dependencies and hence // error terms: //double sd = chordCompSq*countCompSq // + distCompSq*countCompSq; //NOTE: The coverage of the matches is currently // approximated as simply numberMatched/maxNumberMatchable, // but a term representing the spatial distribution appears // to be necessary also. // will try largestNumberGap/maxNumberMatchable. // TODO: need to improve this in detail later int lGap = maxNumberOfGaps(obj.bounds1, r)/dp; float gCountComp = (float)lGap/(float)nb1; //double sd = chordCompSq + countCompSq + distCompSq; double sd = chordComp + countComp + gCountComp + distComp + costIntersection; if (sd < minCost) { minCost = sd; minCostIdx = j; } if (sd < minSD) { minSD = sd; minSDI = idx; } System.out.println("sd=" + sd + " n1=" + obj.bounds1.getN() + " n2=" + obj.bounds2.getN() + " origN1=" + r.getOriginalN1() + " nMatches=" + r.getNumberOfMatches() + String.format( " chord=%.2f count=%.2f spatial=%.2f dist=%.2f inter=%.2f", (float)chordComp, (float)countComp, (float)gCountComp, (float)distComp, (float)costIntersection) ); } assert (minCostIdx > -1); TDoubleList cList = chordDiffSumsMap.get(idx); TFloatList iList = intersectionsMap.get(idx); for (int j = resultsList.size() - 1; j > -1; --j) { if (j != minCostIdx) { resultsList.remove(j); cList.removeAt(j); iList.removeAt(j); } } } if (resultsMap.size() > 1) { // TODO: build a test for this. // possibly need to transform results to same reference // frame to compare. // using best SD for now TIntSet rm = new TIntHashSet(); iter = resultsMap.iterator(); for (int i = 0; i < resultsMap.size(); ++i) { iter.advance(); int idx = iter.key(); if (idx != minSDI) { rm.add(idx); } } TIntIterator iter2 = rm.iterator(); while (iter2.hasNext()) { int idx = iter2.next(); resultsMap.remove(idx); } } List<CorrespondenceList> topResults = new ArrayList<CorrespondenceList>(); iter = resultsMap.iterator(); for (int i = 0; i < resultsMap.size(); ++i) { iter.advance(); int idx = iter.key(); List<PObject> resultsList = resultsMap.get(idx); assert (resultsList.size() == 1); PObject obj = resultsList.get(0); int n = obj.r.getNumberOfMatches(); PairInt[] m1 = new PairInt[n]; PairInt[] m2 = new PairInt[n]; float scale1 = obj.scale1; float scale2 = obj.scale2; for (int ii = 0; ii < n; ++ii) { int idx1 = obj.r.getIdx1(ii); int idx2 = obj.r.getIdx2(ii); int x1 = Math.round(obj.bounds1.getX(idx1) * scale1); int y1 = Math.round(obj.bounds1.getY(idx1) * scale1); int x2 = Math.round(obj.bounds2.getX(idx2) * scale2); int y2 = Math.round(obj.bounds2.getY(idx2) * scale2); m1[ii] = new PairInt(x1, y1); m2[ii] = new PairInt(x2, y2); } CorrespondenceList cor = new CorrespondenceList(obj.r.getTransformationParameters(), m1, m2); topResults.add(cor); } return topResults; } private TFloatList extractScales(List<TFloatList> scalesList) { TFloatList scales = new TFloatArrayList(); for (int i = 0; i < scalesList.size(); ++i) { scales.add(scalesList.get(i).get(0)); } return scales; } private int calculateNMaxMatchable(List<TIntList> keypointsX1, List<TIntList> keypointsX2) { int nMaxM = Integer.MIN_VALUE; for (int i = 0; i < keypointsX1.size(); ++i) { int n1 = keypointsX1.get(i).size(); for (int j = 0; j < keypointsX2.size(); ++j) { int n2 = keypointsX2.get(j).size(); int min = Math.min(n1, n2); if (min > nMaxM) { nMaxM = min; } } } return nMaxM; } private int maxSize(List<TIntList> a) { int maxSz = Integer.MIN_VALUE; for (TIntList b : a) { int sz = b.size(); if (sz > maxSz) { maxSz = sz; } } return maxSz; } public static double distance(int x, int y, PairInt b) { int diffX = x - b.getX(); int diffY = y - b.getY(); double dist = Math.sqrt(diffX * diffX + diffY * diffY); return dist; } public static int distance(PairInt p1, PairInt p2) { int diffX = p1.getX() - p2.getX(); int diffY = p1.getY() - p2.getY(); return (int) Math.sqrt(diffX * diffX + diffY * diffY); } /** * greedy matching of d1 to d2 by min cost, with unique mappings for * all indexes. * * @param d1 * @param d2 * @return matches - two dimensional int array of indexes in d1 and * d2 which are matched. */ public static int[][] matchDescriptors(VeryLongBitString[] d1, VeryLongBitString[] d2, List<PairInt> keypoints1, List<PairInt> keypoints2) { int n1 = d1.length; int n2 = d2.length; //[n1][n2] int[][] cost = ORB.calcDescriptorCostMatrix(d1, d2); int[][] matches = greedyMatch(keypoints1, keypoints2, cost); // greedy or optimal match can be performed here. // NOTE: some matching problems might benefit from using the spatial // information at the same time. for those, will consider adding // an evaluation term for these descriptors to a specialization of // PartialShapeMatcher.java return matches; } /** * greedy matching of d1 to d2 by min difference, with unique mappings for * all indexes. * NOTE that if 2 descriptors match equally well, either one * might get the assignment. * Consider using instead, matchDescriptors2 which matches * by descriptor and relative spatial location. * * @param d1 * @param d2 * @param keypoints2 * @param keypoints1 * @return matches - two dimensional int array of indexes in d1 and * d2 which are matched. */ public static int[][] matchDescriptors(ORB.Descriptors[] d1, ORB.Descriptors[] d2, List<PairInt> keypoints1, List<PairInt> keypoints2) { if (d1.length != d2.length) { throw new IllegalArgumentException("d1 and d2 must" + " be same length"); } int n1 = d1[0].descriptors.length; int n2 = d2[0].descriptors.length; if (n1 != keypoints1.size()) { throw new IllegalArgumentException("number of descriptors in " + " d1 bitstrings must be same as keypoints1 length"); } if (n2 != keypoints2.size()) { throw new IllegalArgumentException("number of descriptors in " + " d2 bitstrings must be same as keypoints2 length"); } //[n1][n2] int[][] cost = ORB.calcDescriptorCostMatrix(d1, d2); int[][] matches = greedyMatch(keypoints1, keypoints2, cost); // greedy or optimal match can be performed here. // NOTE: some matching problems might benefit from using the spatial // information at the same time. for those, will consider adding // an evaluation term for these descriptors to a specialization of // PartialShapeMatcher.java return matches; } private static void debugPrint(List<QuadInt> pairs, int i, int j, TwoDFloatArray pyr1, TwoDFloatArray pyr2, float s1, float s2) { Image img1 = ORB.convertToImage(pyr1); Image img2 = ORB.convertToImage(pyr2); try { for (int ii = 0; ii < pairs.size(); ++ii) { QuadInt q = pairs.get(ii); int x1 = Math.round(q.getA() / s1); int y1 = Math.round(q.getB() / s1); int x2 = Math.round(q.getC() / s2); int y2 = Math.round(q.getD() / s2); ImageIOHelper.addPointToImage(x1, y1, img1, 1, 255, 0, 0); ImageIOHelper.addPointToImage(x2, y2, img2, 1, 255, 0, 0); } String strI = Integer.toString(i); while (strI.length() < 3) { strI = "0" + strI; } String strJ = Integer.toString(j); while (strJ.length() < 3) { strJ = "0" + strJ; } String str = "_pairs_" + strI + "_" + strJ + "_"; MiscDebug.writeImage(img1, str + "_" + strI); MiscDebug.writeImage(img2, str + "_" + strJ); } catch (Exception e) { } } private static void debugPrint(TwoDFloatArray pyr1, TwoDFloatArray pyr2, TIntList kpX1, TIntList kpY1, TIntList kpX2, TIntList kpY2, float scale1, float scale2, int img1Idx, int img2Idx) { Image img1 = ORB.convertToImage(pyr1); Image img2 = ORB.convertToImage(pyr2); try { for (int i = 0; i < kpX1.size(); ++i) { int x1 = (int) (kpX1.get(i) / scale1); int y1 = (int) (kpY1.get(i) / scale1); ImageIOHelper.addPointToImage(x1, y1, img1, 1, 255, 0, 0); } for (int i = 0; i < kpX2.size(); ++i) { int x2 = (int) (kpX2.get(i) / scale2); int y2 = (int) (kpY2.get(i) / scale2); ImageIOHelper.addPointToImage(x2, y2, img2, 1, 255, 0, 0); } String strI = Integer.toString(img1Idx); while (strI.length() < 3) { strI = "0" + strI; } String strJ = Integer.toString(img2Idx); while (strJ.length() < 3) { strJ = "0" + strJ; } String str = "_kp_" + strI + "_" + strJ + "_"; MiscDebug.writeImage(img1, str + "_i"); MiscDebug.writeImage(img2, str + "_j"); } catch (Exception e) { } } private static void debugPrint(TwoDFloatArray pyr1, TwoDFloatArray pyr2, TIntList kpX1, TIntList kpY1, TIntList kpX2, TIntList kpY2, int img1Idx, int img2Idx) { Image img1 = ORB.convertToImage(pyr1); Image img2 = ORB.convertToImage(pyr2); try { for (int i = 0; i < kpX1.size(); ++i) { int x1 = kpX1.get(i); int y1 = kpY1.get(i); ImageIOHelper.addPointToImage(x1, y1, img1, 1, 255, 0, 0); } for (int i = 0; i < kpX2.size(); ++i) { int x2 = kpX2.get(i); int y2 = kpY2.get(i); ImageIOHelper.addPointToImage(x2, y2, img2, 1, 255, 0, 0); } String strI = Integer.toString(img1Idx); while (strI.length() < 3) { strI = "0" + strI; } String strJ = Integer.toString(img2Idx); while (strJ.length() < 3) { strJ = "0" + strJ; } String str = "_kp_" + strI + "_" + strJ + "_"; MiscDebug.writeImage(img1, str + "_i"); MiscDebug.writeImage(img2, str + "_j"); } catch (Exception e) { } } private static Set<PairInt> makeSet(TIntList kpX1, TIntList kpY1) { Set<PairInt> set = new HashSet<PairInt>(); for (int i = 0; i < kpX1.size(); ++i) { PairInt p = new PairInt(kpX1.get(i), kpY1.get(i)); set.add(p); } return set; } private static Descriptors[] getDescriptors(ORB orb, int i) { ORB.Descriptors[] d = null; if (orb.getDescrChoice().equals(ORB.DescriptorChoice.ALT)) { d = new ORB.Descriptors[]{orb.getDescriptorsListAlt().get(i)}; } else if (orb.getDescrChoice().equals(ORB.DescriptorChoice.HSV)) { d = new ORB.Descriptors[]{orb.getDescriptorsH().get(i), orb.getDescriptorsS().get(i), orb.getDescriptorsV().get(i)}; } else if (orb.getDescrChoice().equals(ORB.DescriptorChoice.GREYSCALE)) { d = new ORB.Descriptors[]{orb.getDescriptorsList().get(i)}; } return d; } private static List<QuadInt> createPairLabelIndexes(int[][] cost, int nBands, List<TIntList> pointIndexLists1, TIntList kpX1, TIntList kpY1, List<TIntList> pointIndexLists2, TIntList kpX2, TIntList kpY2) { int costLimit = Math.round((float) (nBands * 256) * 0.65F); int minP1Diff = 3; Set<QuadInt> exists = new HashSet<QuadInt>(); // pairs of idx from set1 and idx from set 2 Set<PairInt> skip = new HashSet<PairInt>(); List<QuadInt> pairIndexes = new ArrayList<QuadInt>(); List<PairInt> pair2Indexes = calculatePairIndexes(pointIndexLists2, kpX2, kpY2, minP1Diff); for (int ii = 0; ii < pointIndexLists1.size(); ++ii) { TIntList kpIndexes1 = pointIndexLists1.get(ii); if (kpIndexes1.size() < 2) { continue; } // draw 2 from kpIndexes1 for (int ii1 = 0; ii1 < kpIndexes1.size(); ++ii1) { int idx1 = kpIndexes1.get(ii1); int t1X = kpX1.get(idx1); int t1Y = kpY1.get(idx1); boolean skipIdx1 = false; for (int ii2 = 0; ii2 < kpIndexes1.size(); ++ii2) { if (ii1 == ii2) { continue; } int idx2 = kpIndexes1.get(ii2); int t2X = kpX1.get(idx2); int t2Y = kpY1.get(idx2); if (t1X == t2X && t1Y == t2Y) { continue; } int diffX = t1X - t2X; int diffY = t1Y - t2Y; int distSq = diffX * diffX + diffY * diffY; //if (distSq > limitSq) { // continue; if (distSq < minP1Diff * minP1Diff) { continue; } for (PairInt p2Index : pair2Indexes) { int idx3 = p2Index.getX(); int idx4 = p2Index.getY(); PairInt p13 = new PairInt(idx1, idx3); if (skip.contains(p13)) { skipIdx1 = true; break; } PairInt p24 = new PairInt(idx2, idx4); if (skip.contains(p24)) { continue; } int c13 = cost[idx1][idx3]; // if idx1 and idx3 cost is above limit, skip if (c13 > costLimit) { skip.add(p13); skipIdx1 = true; break; } int c24 = cost[idx2][idx4]; if (c24 > costLimit) { skip.add(p24); continue; } QuadInt q = new QuadInt(idx1, idx2, idx3, idx4); QuadInt qChk = new QuadInt(idx2, idx1, idx4, idx3); if (exists.contains(q) || exists.contains(qChk)) { continue; } /* int s1X = kpX2.get(idx3); int s1Y = kpY2.get(idx3); int s2X = kpX2.get(idx4); int s2Y = kpY2.get(idx4); int diffX2 = s1X - s2X; int diffY2 = s1Y - s2Y; int distSq2 = diffX2 * diffX2 + diffY2 * diffY2; //if (distSq2 > limitSq) { // continue; //} if ((distSq2 < minP1Diff * minP1Diff)) { continue; } */ pairIndexes.add(q); exists.add(q); } if (skipIdx1) { break; } } } } return pairIndexes; } public static int calculateObjectSize(Set<PairInt> points) { // O(N*lg_2(N)) FurthestPair furthestPair = new FurthestPair(); PairInt[] fp = furthestPair.find(points); if (fp == null || fp.length < 2) { throw new IllegalArgumentException("did not find a furthest pair" + " in points"); } double dist = ORBMatcher.distance(fp[0], fp[1]); return (int) Math.round(dist); } public static int calculateObjectSize(PairIntArray points) { return calculateObjectSize(Misc.convert(points)); } private static float calculateDiagonal(List<TIntList> keypointsX1, List<TIntList> keypointsY1, int idx) { TIntList x1 = keypointsX1.get(idx); TIntList y1 = keypointsY1.get(idx); int maxX = x1.max(); int maxY = y1.max(); return (float) Math.sqrt(maxX * maxX + maxY * maxY); } /** * NOTE: preliminary results show that this matches the right pattern as * a subset of the object, but needs to be followed by a slightly larger * aggregated search by segmentation cells using partial shape matcher * for example. This was started in ShapeFinder, but needs to be * adjusted for a search given seed cells and possibly improved for the * other TODO items). * @param keypoints1 * @param keypoints2 * @param mT * @param mS * @param nn * @param minMaxXY2 * @param limit * @param tIndexes * @param idx1P2CostMap * @param indexes * @param costs * @return */ private static List<CorrespondenceList> completeUsingCombinations(List<PairInt> keypoints1, List<PairInt> keypoints2, PairIntArray mT, PairIntArray mS, NearestNeighbor2D nn, int[] minMaxXY2, int limit, TIntList tIndexes, TIntObjectMap<TObjectIntMap<PairInt>> idx1P2CostMap, PairInt[] indexes, int[] costs, int bitTolerance, int nBands) { int nTop = mT.getN(); System.out.println("have " + nTop + " sets of points for " + " n of k=2 combinations"); // need to make pairs of combinations from mT,mS // to calcuate euclidean transformations and evaluate them. // -- can reduce the number of combinations by imposing a // distance limit on separation of feasible pairs int limitSq = limit * limit; MatchedPointsTransformationCalculator tc = new MatchedPointsTransformationCalculator(); Transformer transformer = new Transformer(); // this fixed size sorted vector is faster for shorter arrays. // TODO: consider ways to robustly set the size from the cost // statistics to ensure the vector will always contain the // correct solution even if not in top position. int nt = mT.getN(); FixedSizeSortedVector<CObject> vec = new FixedSizeSortedVector<CObject>(nt, CObject.class); double minCost = Double.MAX_VALUE; //CorrespondenceList minCostCor = null; //PairIntArray minCostTrT = null; double[] minCostI = new double[nTop]; double[] minDistI = new double[nTop]; // temporary storage of corresp coords until object construction int[] m1x = new int[nTop]; int[] m1y = new int[nTop]; int[] m2x = new int[nTop]; int[] m2y = new int[nTop]; int mCount = 0; for (int i = 0; i < nTop; ++i) { int t1X = mT.getX(i); int t1Y = mT.getY(i); int s1X = mS.getX(i); int s1Y = mS.getY(i); // choose all combinations of 2nd point within distance // limit of point s1. for (int j = i + 1; j < mS.getN(); ++j) { int t2X = mT.getX(j); int t2Y = mT.getY(j); int s2X = mS.getX(j); int s2Y = mS.getY(j); if ((t1X == t2X && t1Y == t2Y) || (s1X == s2X && s1Y == s2Y)) { continue; } int diffX = s1X - s2X; int diffY = s1Y - s2Y; int distSq = diffX * diffX + diffY * diffY; if (distSq > limitSq) { continue; } // -- calculate euclid transformation // -- evaluate the fit TransformationParameters params = tc.calulateEuclidean(t1X, t1Y, t2X, t2Y, s1X, s1Y, s2X, s2Y, 0, 0); float scale = params.getScale(); mCount = 0; // template object transformed PairIntArray trT = transformer.applyTransformation(params, mT); /* two components to the evaluation and both need normalizations so that their contributions to total result are equally weighted. (1) descriptors: -- score is sum of each matched (3*256 - cost) -- the normalization is the maximum possible score, so will use the number of template points. --> norm = nTemplate * 3 * 256 -- normalized score = (3*256 - cost)/norm ==> normalized cost = 1 - ((3*256 - cost)/norm) (2) spatial distances from transformed points: -- sum of distances within limit and replacement of distance by limit if no matching nearest neighbor is found. -- divide each distance by the transformation scale to compare same values -- divide the total sum by the total max possible --> norm = nTemplate * limit / scale Then the total cost is (1) + (2) and the min cost among all of these combinations is the resulting correspondence list */ double maxCost = nBands * 256; double maxDist = limit / scale; double sum1 = 0; double sum2 = 0; double sum = 0; for (int k = 0; k < trT.getN(); ++k) { int xTr = trT.getX(k); int yTr = trT.getY(k); int idx1 = tIndexes.get(k); Set<PairInt> nearest = null; if ((xTr >= 0) && (yTr >= 0) && (xTr <= (minMaxXY2[1] + limit)) && (yTr <= (minMaxXY2[3] + limit))) { nearest = nn.findClosest(xTr, yTr, limit); } int minC = Integer.MAX_VALUE; PairInt minCP2 = null; if (nearest != null && !nearest.isEmpty()) { TObjectIntMap<PairInt> cMap = idx1P2CostMap.get(idx1); for (PairInt p2 : nearest) { if (!cMap.containsKey(p2)) { continue; } int c = cMap.get(p2); if (c < minC) { minC = c; minCP2 = p2; } } } if (minCP2 != null) { double costNorm = minC / maxCost; sum1 += costNorm; double dist = ORBMatcher.distance(xTr, yTr, minCP2); double distNorm = dist / maxDist; sum2 += distNorm; m1x[mCount] = keypoints1.get(idx1).getX(); m1y[mCount] = keypoints1.get(idx1).getY(); m2x[mCount] = minCP2.getX(); m2y[mCount] = minCP2.getY(); minCostI[mCount] = costNorm; minDistI[mCount] = distNorm; mCount++; } else { sum1 += 1; sum2 += 1; } } sum = sum1 + sum2; if ((minCost == Double.MAX_VALUE) || (sum < (minCost + bitTolerance))) { if (sum < minCost) { minCost = sum; } List<PairInt> m1 = new ArrayList<PairInt>(); List<PairInt> m2 = new ArrayList<PairInt>(); CorrespondenceList corr = new CorrespondenceList(params.getScale(), Math.round(params.getRotationInDegrees()), Math.round(params.getTranslationX()), Math.round(params.getTranslationY()), 0, 0, 0, m1, m2); for (int mi = 0; mi < mCount; ++mi) { m1.add(new PairInt(m1x[mi], m1y[mi])); m2.add(new PairInt(m2x[mi], m2y[mi])); } CObject cObj = new CObject(sum, corr, trT); vec.add(cObj); } } } if (vec.getNumberOfItems() == 0) { return null; } List<CorrespondenceList> topResults = new ArrayList<CorrespondenceList>(); for (int i = 0; i < vec.getNumberOfItems(); ++i) { CObject a = vec.getArray()[i]; if (a.cost > (minCost + bitTolerance)) { break; } topResults.add(a.cCor); } return topResults; } private static List<PairInt> calculatePairIndexes(List<TIntList> pointIndexLists2, TIntList kpX2, TIntList kpY2, int minPDiff) { List<PairInt> pairIndexes = new ArrayList<PairInt>(); Set<PairInt> exists = new HashSet<PairInt>(); // draw 2 pairs from other dataset for (int jj = 0; jj < pointIndexLists2.size(); ++jj) { TIntList kpIndexes2 = pointIndexLists2.get(jj); if (kpIndexes2.size() < 2) { continue; } // draw 2 from kpIndexes2 for (int jj1 = 0; jj1 < kpIndexes2.size(); ++jj1) { int idx3 = kpIndexes2.get(jj1); int s1X = kpX2.get(idx3); int s1Y = kpY2.get(idx3); for (int jj2 = 0; jj2 < kpIndexes2.size(); ++jj2) { if (jj1 == jj2) { continue; } int idx4 = kpIndexes2.get(jj2); int s2X = kpX2.get(idx4); int s2Y = kpY2.get(idx4); if (s1X == s2X && s1Y == s2Y) { continue; } PairInt q = new PairInt(idx3, idx4); if (exists.contains(q)) { continue; } int diffX2 = s1X - s2X; int diffY2 = s1Y - s2Y; int distSq2 = diffX2 * diffX2 + diffY2 * diffY2; //if (distSq2 > limitSq) { // continue; if (distSq2 < minPDiff * minPDiff) { continue; } pairIndexes.add(q); exists.add(q); } } } return pairIndexes; } private static float calculateDiagonal2(List<TwoDFloatArray> pyramidImages, int idx) { int w = pyramidImages.get(idx).a.length; int h = pyramidImages.get(idx).a[0].length; double diag = Math.sqrt(w * w + h * h); return (float) diag; } private static int[][] greedyMatch(List<PairInt> keypoints1, List<PairInt> keypoints2, int[][] cost) { int n1 = keypoints1.size(); int n2 = keypoints2.size(); // for the greedy match, separating the index information from the cost // and then sorting by cost int nTot = n1 * n2; PairInt[] indexes = new PairInt[nTot]; int[] costs = new int[nTot]; int count = 0; for (int i = 0; i < n1; ++i) { for (int j = 0; j < n2; ++j) { indexes[count] = new PairInt(i, j); costs[count] = cost[i][j]; count++; } } assert (count == nTot); QuickSort.sortBy1stArg(costs, indexes); Set<PairInt> set1 = new HashSet<PairInt>(); Set<PairInt> set2 = new HashSet<PairInt>(); List<PairInt> matches = new ArrayList<PairInt>(); // visit lowest costs (== differences) first for (int i = 0; i < nTot; ++i) { PairInt index12 = indexes[i]; int idx1 = index12.getX(); int idx2 = index12.getY(); PairInt p1 = keypoints1.get(idx1); PairInt p2 = keypoints2.get(idx2); if (set1.contains(p1) || set2.contains(p2)) { continue; } //System.out.println("p1=" + p1 + " " + " p2=" + p2 + " cost=" + costs[i]); matches.add(index12); set1.add(p1); set2.add(p2); } int[][] results = new int[matches.size()][2]; for (int i = 0; i < matches.size(); ++i) { results[i][0] = matches.get(i).getX(); results[i][1] = matches.get(i).getY(); } return results; } private static double[] sumKeypointDistanceDifference(TIntList a2Indexes, PairIntArray tr2, TIntList kpX2, TIntList kpY2, NearestNeighbor2D nn, TransformationParameters params, int maxX, int maxY, int pixTolerance, double maxDist, int[] m1x, int[] m1y, int[] m2x, int[] m2y) { double sum2 = 0; int mCount = 0; for (int k = 0; k < tr2.getN(); ++k) { int x2Tr = tr2.getX(k); int y2Tr = tr2.getY(k); int idx2 = a2Indexes.get(k); Set<PairInt> nearest = null; if ((x2Tr >= 0) && (y2Tr >= 0) && (x2Tr <= (maxX + pixTolerance)) && (y2Tr <= (maxY + pixTolerance))) { nearest = nn.findClosest(x2Tr, y2Tr, pixTolerance); } double minDist = Double.MAX_VALUE; PairInt minDistP1 = null; if (nearest != null && !nearest.isEmpty()) { for (PairInt p11 : nearest) { double dist = ORBMatcher.distance(x2Tr, y2Tr, p11); if (dist < minDist) { minDist = dist; minDistP1 = p11; } } } if (minDistP1 != null) { double dist = minDist; double distNorm = dist / maxDist; sum2 += distNorm; m2x[mCount] = kpX2.get(idx2); m2y[mCount] = kpY2.get(idx2); m1x[mCount] = minDistP1.getX(); m1y[mCount] = minDistP1.getY(); mCount++; } else { sum2 += 1; } } // end loop over trnsformed set 2 return new double[]{sum2, mCount}; } private static double[] sumKeypointDescAndDist(int[][] cost, int nBands, TIntList a1Indexes, PairIntArray tr1, TIntList kpX1, TIntList kpY1, NearestNeighbor2D nn2, TObjectIntMap<PairInt> p2KPIndexMap, TransformationParameters params, int maxX2, int maxY2, int pixTolerance, double maxDist, PairInt[] m1, PairInt[] m2) { double sumDesc = 0; double sumDist = 0; int count = 0; double maxDesc = nBands * 256.0; for (int k = 0; k < tr1.getN(); ++k) { int x1Tr = tr1.getX(k); int y1Tr = tr1.getY(k); int idx1 = a1Indexes.get(k); Set<PairInt> nearest = null; if ((x1Tr >= 0) && (y1Tr >= 0) && (x1Tr <= (maxX2 + pixTolerance)) && (y1Tr <= (maxY2 + pixTolerance))) { nearest = nn2.findClosest(x1Tr, y1Tr, pixTolerance); } int minC = Integer.MAX_VALUE; PairInt minCP2 = null; int minIdx2 = 0; if (nearest != null && !nearest.isEmpty()) { for (PairInt p2 : nearest) { int idx2 = p2KPIndexMap.get(p2); int c = cost[idx1][idx2]; if (c < minC) { minC = c; minCP2 = p2; minIdx2 = idx2; } } } if (minCP2 != null) { double costNorm = minC / maxDesc; sumDesc += costNorm; double dist = ORBMatcher.distance(x1Tr, y1Tr, minCP2); double distNorm = dist / maxDist; sumDist += distNorm; m1[count] = new PairInt(kpX1.get(idx1), kpY1.get(idx1)); m2[count] = minCP2; count++; } else { sumDesc += 1; sumDist += 1; } } return new double[]{sumDesc, sumDist, count}; } private static double[] sumKeypointDescAndDist(int[][] cost, int nBands, TIntList a1Indexes, PairIntArray tr1, TIntList kpX1, TIntList kpY1, NearestNeighbor2D nn2, TObjectIntMap<PairInt> p2KPIndexMap, int maxX2, int maxY2, int pixTolerance, double maxDist, int[] m1, int[] m2) { double sumDesc = 0; double sumDist = 0; int count = 0; double maxDesc = nBands * 256.0; //best first match, after nearest neighbors // TODO: consider optimal bipartite matching when have an // implementation of multi-level-buckets float[] costA = new float[tr1.getN()]; float[] costDesc = new float[tr1.getN()]; float[] costDist = new float[tr1.getN()]; int[] indexes = new int[tr1.getN()]; for (int k = 0; k < tr1.getN(); ++k) { int x1Tr = tr1.getX(k); int y1Tr = tr1.getY(k); int idx1 = a1Indexes.get(k); Set<PairInt> nearest = null; if ((x1Tr >= 0) && (y1Tr >= 0) && (x1Tr <= (maxX2 + pixTolerance)) && (y1Tr <= (maxY2 + pixTolerance))) { nearest = nn2.findClosest(x1Tr, y1Tr, pixTolerance); } int minC = Integer.MAX_VALUE; PairInt minCP2 = null; int minIdx2 = 0; if (nearest != null && !nearest.isEmpty()) { for (PairInt p2 : nearest) { int idx2 = p2KPIndexMap.get(p2); int c = cost[idx1][idx2]; if (c < minC) { minC = c; minCP2 = p2; minIdx2 = idx2; } } } if (minCP2 != null) { double costNorm = minC / maxDesc; sumDesc += costNorm; double dist = ORBMatcher.distance(x1Tr, y1Tr, minCP2); double distNorm = dist / maxDist; sumDist += distNorm; m1[count] = idx1; m2[count] = minIdx2; costA[count] = (float) (costNorm + distNorm); costDesc[count] = (float) costNorm; costDist[count] = (float) distNorm; indexes[count] = count; count++; } else { sumDesc += 1; sumDist += 1; } } if (count > 1) { costA = Arrays.copyOf(costA, count); indexes = Arrays.copyOf(indexes, count); QuickSort.sortBy1stArg(costA, indexes); TIntSet set1 = new TIntHashSet(); TIntSet set2 = new TIntHashSet(); List<PairInt> matched = new ArrayList<PairInt>(); TIntList idxs = new TIntArrayList(); for (int i = 0; i < count; ++i) { int idx = indexes[i]; int idx1 = m1[idx]; int idx2 = m2[idx]; if (set1.contains(idx1) || set2.contains(idx2)) { continue; } idxs.add(idx); matched.add(new PairInt(idx1, idx2)); set1.add(idx1); set2.add(idx2); } int nRedundant = count - matched.size(); if (nRedundant > 0) { sumDesc = 0; sumDist = 0; for (int i = 0; i < matched.size(); ++i) { m1[i] = matched.get(i).getX(); m2[i] = matched.get(i).getY(); int idx = idxs.get(i); sumDesc += costDesc[idx]; sumDist += costDist[idx]; } sumDesc += (tr1.getN() - matched.size()); sumDist += (tr1.getN() - matched.size()); count = matched.size(); } } return new double[]{sumDesc, sumDist, count}; } /** * match left and right using the right transformed to left and nn1 * and return the sum of the descriptor costs, distance differences * and number matched. * NOTE that the each item in a sum has been normalized before adding, * so for example, one item contributes between 0 and 1 to the total sum. * a "+1" or +maxValue was not added for points not matched. * @param cost * @param nBands * @param a2 * @param a2TrTo1 * @param nn1 * @param p1KPIndexMap point indexes lookup w.r.t. entire keypoints1 list * which has same indexes as costD first dimension. note that the * template object dataset, a.k.a. left or a1 includes all points of * keypoints1...no segmentation dividing the points into more than one * array list. nn1 contains all keypoints1 points. * @param p2KPIndexMap point indexes lookup w.r.t. entire keypoints2 list * which has same indexes as costD second dimension. these indexes are not the same * indexes as a2 indexes. * @param img1Width * @param img1Height * @param pixTolerance * @param maxDist * @param m1 * @param m2 * @return */ private static double[] sumKeypointDescAndDist2To1( int[][] cost, int nBands, PairIntArray a2, PairIntArray a2TrTo1, NearestNeighbor2D nn1, TObjectIntMap<PairInt> p1KPIndexMap, TObjectIntMap<PairInt> p2KPIndexMap, TIntSet skip2, int distTol, int[] m1, int[] m2) { int n2 = a2TrTo1.getN(); float distMax = (float)Math.sqrt(2) * distTol; int count = 0; double maxDesc = nBands * 256.0; //best first match, after nearest neighbors // TODO: consider optimal bipartite matching when have an // implementation of multi-level-buckets float[] costA = new float[n2]; float[] costDesc = new float[n2]; float[] costDist = new float[n2]; int[] indexes = new int[n2]; for (int k = 0; k < n2; ++k) { if (skip2.contains(k)) { continue; } int x1Tr = a2TrTo1.getX(k); int y1Tr = a2TrTo1.getY(k); if (x1Tr < 0 || y1Tr < 0) { continue; } int kpIdx2 = p2KPIndexMap.get(new PairInt(a2.getX(k), a2.getY(k))); Set<PairInt> nearest = nn1.findClosest(x1Tr, y1Tr, distTol); int minC = Integer.MAX_VALUE; PairInt minCP1 = null; int minCIdx1 = 0; if (nearest != null && !nearest.isEmpty()) { for (PairInt p1 : nearest) { int kpIdx1 = p1KPIndexMap.get(p1); int c = cost[kpIdx1][kpIdx2]; if (c < minC) { minC = c; minCP1 = p1; minCIdx1 = kpIdx1; } } } if (minCP1 != null) { double costNorm = minC / maxDesc; double dist = ORBMatcher.distance(x1Tr, y1Tr, minCP1); assert(dist <= distMax); double distNorm = dist / distMax; m1[count] = minCIdx1; m2[count] = k;// index of a2 array costA[count] = (float) (costNorm + distNorm); costDesc[count] = (float) costNorm; costDist[count] = (float) distNorm; indexes[count] = count; count++; } } double sumDesc = 0; double sumDist = 0; if (count > 1) { if (count < costA.length) { costA = Arrays.copyOf(costA, count); indexes = Arrays.copyOf(indexes, count); costDesc = Arrays.copyOf(costDesc, count); costDist = Arrays.copyOf(costDist, count); } QuickSort.sortBy1stArg(costA, indexes); TIntSet set1 = new TIntHashSet(); TIntSet set2 = new TIntHashSet(); PairIntArray matched = new PairIntArray(count); TIntList idxs = new TIntArrayList(); for (int i = 0; i < count; ++i) { int idx = indexes[i]; int idx1 = m1[idx]; int idx2 = m2[idx]; if (set1.contains(idx1) || set2.contains(idx2)) { continue; } idxs.add(idx); matched.add(idx1, idx2); set1.add(idx1); set2.add(idx2); sumDesc += costDesc[idx]; sumDist += costDist[idx]; } count = matched.getN(); for (int i = 0; i < count; ++i) { m1[i] = matched.getX(i); m2[i] = matched.getY(i); } } return new double[]{sumDesc, sumDist, count}; } /** * match left and right using the right transformed to left and nn1 * and return the sum of the descriptor costs, distance differences * and number matched. * NOTE that the each item in a sum has been normalized before adding, * so for example, one item contributes between 0 and 1 to the total sum. * a "+1" or +maxValue was not added for points not matched. * @param a2 * @param a2TrTo1 * @param nn1 * @param p1KPIndexMap * @param p2KPIndexMap * @param img1Width * @param img1Height * @param pixTolerance * @param maxDist * @param m12 output matched indexes * @return */ private static double[] sumKeypointDescAndDist2To1( PairIntArray a2, PairIntArray a2TrTo1, NearestNeighbor2D nn1, TObjectIntMap<PairInt> p1KPIndexMap, TObjectIntMap<PairInt> p2KPIndexMap, int img1Width, int img1Height, int distTol, PairIntArray m12) { int n2 = a2TrTo1.getN(); float distMax = (float)Math.sqrt(2) * distTol; int count = 0; float[] costDist = new float[n2]; int[] indexes = new int[n2]; for (int k = 0; k < n2; ++k) { int x1Tr = a2TrTo1.getX(k); int y1Tr = a2TrTo1.getY(k); if (x1Tr < 0 || y1Tr < 0) { continue; } int kpIdx2 = p2KPIndexMap.get(new PairInt(a2.getX(k), a2.getY(k))); Set<PairInt> nearest = nn1.findClosest(x1Tr, y1Tr, distTol); PairInt minP1 = null; int minIdx1 = 0; if (nearest != null && !nearest.isEmpty()) { minP1 = nearest.iterator().next(); minIdx1 = p1KPIndexMap.get(minP1); } if (minP1 != null) { double dist = ORBMatcher.distance(x1Tr, y1Tr, minP1); assert(dist <= distMax); double distNorm = dist / distMax; m12.add(minIdx1, kpIdx2); costDist[count] = (float) distNorm; indexes[count] = count; count++; } } double sumDist = 0; if (count > 1) { if (count < costDist.length) { indexes = Arrays.copyOf(indexes, count); costDist = Arrays.copyOf(costDist, count); } QuickSort.sortBy1stArg(costDist, indexes); TIntSet set1 = new TIntHashSet(); TIntSet set2 = new TIntHashSet(); PairIntArray matched = new PairIntArray(count); TIntList idxs = new TIntArrayList(); for (int i = 0; i < count; ++i) { int idx = indexes[i]; int idx1 = m12.getX(idx); int idx2 = m12.getY(idx); if (set1.contains(idx1) || set2.contains(idx2)) { continue; } idxs.add(idx); matched.add(idx1, idx2); set1.add(idx1); set2.add(idx2); sumDist += costDist[idx]; } count = matched.getN(); m12.removeRange(0, m12.getN() - 1); for (int i = 0; i < count; ++i) { m12.add(matched.getX(i), matched.getY(i)); } } return new double[]{sumDist, count}; } private static PairIntArray trimToImageBounds(TwoDFloatArray octaveImg, PairIntArray a) { int n0 = octaveImg.a.length; int n1 = octaveImg.a[0].length; return trimToImageBounds(n1, n0, a); } private static PairIntArray trimToImageBounds( int width, int height, PairIntArray a) { PairIntArray b = new PairIntArray(a.getN()); for (int i = 0; i < a.getN(); ++i) { int x = a.getX(i); int y = a.getY(i); if (x < 0 || x > (width - 1)) { continue; } else if (y < 0 || y > (height - 1)) { continue; } b.add(x, y); } return b; } private static PairIntArray reduceBounds(PairIntArray bounds, float scale) { Set<PairInt> added = new HashSet<PairInt>(); PairIntArray out = new PairIntArray(bounds.getN()); for (int i = 0; i < bounds.getN(); ++i) { int x = Math.round((float)bounds.getX(i)/scale); int y = Math.round((float)bounds.getY(i)/scale); PairInt p = new PairInt(x, y); if (added.contains(p)) { continue; } out.add(x, y); added.add(p); } return out; } public static int maxNumberOfGaps(PairIntArray bounds, PartialShapeMatcher.Result r) { TIntSet mIdxs = new TIntHashSet(r.getNumberOfMatches()); for (int i = 0; i < r.getNumberOfMatches(); ++i) { mIdxs.add(r.getIdx1(i)); } int maxGapStartIdx = -1; int maxGap = 0; int cStartIdx = -1; int cGap = 0; // handling for startIdx of 0 to check for wraparound // of gap at end of block int gap0 = 0; for (int i = 0; i < bounds.getN(); ++i) { if (!mIdxs.contains(i)) { // is a gap if (cStartIdx == -1) { cStartIdx = i; } cGap++; if (i == (bounds.getN() - 1)) { if (gap0 > 0) { // 0 1 2 3 4 5 // g g g g // gap0=2 // cGap=2 cStartIdx=4 if (cStartIdx > (gap0 - 1)) { gap0 += cGap; } } if (cGap > maxGap) { maxGap = cGap; maxGapStartIdx = cStartIdx; } if (gap0 > maxGap) { maxGap = gap0; maxGapStartIdx = 0; } } } else { // is not a gap if (cStartIdx > -1) { if (cGap > maxGap) { maxGap = cGap; maxGapStartIdx = cStartIdx; } if (cStartIdx == 0) { gap0 = cGap; } cStartIdx = -1; cGap = 0; } } } return maxGap; } private PairIntArray createOrderedBounds(ORB orb1, Set<PairInt> labeledPoints1, SIGMA sigma) { ImageProcessor imageProcessor = new ImageProcessor(); Set<PairInt> set = new HashSet<PairInt>(); set.addAll(labeledPoints1); PairIntArray bounds = imageProcessor.extractSmoothedOrderedBoundary( set, sigma, orb1.getPyramidImages().get(0).a[0].length, orb1.getPyramidImages().get(0).a.length); return bounds; } private PairIntArray createOrderedBoundsSansSmoothing( Set<PairInt> labeledPoints1) { ImageProcessor imageProcessor = new ImageProcessor(); Set<PairInt> set = new HashSet<PairInt>(); set.addAll(labeledPoints1); PerimeterFinder2 finder = new PerimeterFinder2(); PairIntArray ordered = finder.extractOrderedBorder( set); return ordered; } private PairIntArray getOrCreateOrderedBounds(TwoDFloatArray img, TIntObjectMap<PairIntArray> boundsMap, int segIdx, Set<PairInt> set, SIGMA sigma) { PairIntArray bounds = boundsMap.get(segIdx); if (bounds != null) { return bounds; } ImageProcessor imageProcessor = new ImageProcessor(); bounds = imageProcessor.extractSmoothedOrderedBoundary( new HashSet<PairInt>(set), sigma, img.a[0].length, img.a.length); boundsMap.put(segIdx, bounds); { if (bounds.getN() > 1) { MiscellaneousCurveHelper curveHelper = new MiscellaneousCurveHelper(); double[] xyCen = curveHelper.calculateXYCentroids(bounds); System.out.println("bounds center=" + (int)xyCen[0] + "," + (int)xyCen[1] + " size_full=" + calculateObjectSize(bounds)); } } return bounds; } private PairIntArray getOrCreateOrderedBounds(TwoDFloatArray img, TIntObjectMap<PairIntArray> boundsMap, int segIdx, Set<PairInt> set) { PairIntArray bounds = boundsMap.get(segIdx); if (bounds != null) { return bounds; } Set<PairInt> set2 = new HashSet<PairInt>(); set2.addAll(set); PerimeterFinder2 finder = new PerimeterFinder2(); bounds = finder.extractOrderedBorder(set2); boundsMap.put(segIdx, bounds); { if (bounds.getN() > 1) { MiscellaneousCurveHelper curveHelper = new MiscellaneousCurveHelper(); double[] xyCen = curveHelper.calculateXYCentroids(bounds); System.out.println("bounds center=" + (int)xyCen[0] + "," + (int)xyCen[1] + " size_full=" + calculateObjectSize(bounds) + " segIdx=" + segIdx); } } return bounds; } private double sumDistances(PairFloatArray distances) { double sum = 0; for (int i = 0; i < distances.getN(); ++i) { float d1 = distances.getX(i); float d2 = distances.getY(i); sum += Math.sqrt(d1 * d1 + d2 * d2); } return sum; } /** * from matched points in list 1 to list2, choose 2 pairs that have * small cost and large difference. * @param result * @param costD * @param xPoints1 * @param yPoints1 * @param xPoints2 * @param yPoints2 * @return */ private QuadInt[] choose2ReferencePoints(Result result, PairIntArray bounds1, PairIntArray bounds2, TObjectIntMap<PairInt> point1KP1Map, TObjectIntMap<PairInt> point2KP1Map, int[][] costD) { int n = result.getNumberOfMatches(); float[] costs = new float[n]; PairInt[] points1 = new PairInt[n]; int count = 0; for (int i = 0; i < n; ++i) { int idx1 = result.idx1s.get(i); int idx2 = result.idx2s.get(i); int x1 = bounds1.getX(idx1); int y1 = bounds1.getY(idx1); PairInt p1 = new PairInt(x1, y1); int x2 = bounds2.getX(idx2); int y2 = bounds2.getY(idx2); PairInt p2 = new PairInt(x2, y2); if (point1KP1Map.containsKey(p1) && point2KP1Map.containsKey(p2)) { int kpIdx1 = point1KP1Map.get(p1); int kpIdx2 = point2KP1Map.get(p2); costs[count] = costD[kpIdx1][kpIdx2]; // these points are in full size reference frae points1[count] = p1; count++; } } if (count > 1) { if (count < n) { costs = Arrays.copyOf(costs, count); points1 = Arrays.copyOf(points1, count); } QuickSort.sortBy1stArg(costs, points1); int end = (int)(0.2 * n); if (end < 10) { end = n; } Set<PairInt> points = new HashSet<PairInt>(); for (int i = 0; i < end; i++) { PairInt p = points1[i]; points.add(p); } FurthestPair fp = new FurthestPair(); PairInt[] furthest = fp.find(points); assert(furthest != null); assert(furthest.length == 2); PairInt[] furthest2 = new PairInt[2]; for (int i = 0; i < n; ++i) { int idx1 = result.idx1s.get(i); int idx2 = result.idx2s.get(i); PairInt p1 = new PairInt(bounds1.getX(idx1), bounds1.getY(idx1)); if (furthest2[0] == null) { if (furthest[0].equals(p1)) { furthest2[0] = new PairInt(bounds2.getX(idx2), bounds2.getY(idx2)); } } if (furthest2[1] == null) { if (furthest[1].equals(p1)) { furthest2[1] = new PairInt(bounds2.getX(idx2), bounds2.getY(idx2)); } } if (furthest2[0] != null && furthest2[1] != null) { break; } } if (furthest2 != null && furthest2.length == 2) { QuadInt[] refs = new QuadInt[2]; refs[0] = new QuadInt(furthest[0], furthest2[0]); refs[1] = new QuadInt(furthest[1], furthest2[1]); return refs; } } // re-do the calculation w/o trying to use descr cost. Set<PairInt> points = new HashSet<PairInt>(n); for (int i = 0; i < n; ++i) { int idx1 = result.idx1s.get(i); PairInt p1 = new PairInt(bounds1.getX(idx1), bounds1.getY(idx1)); points.add(p1); } FurthestPair fp = new FurthestPair(); PairInt[] furthest = fp.find(points); assert(furthest != null); assert(furthest.length == 2); PairInt[] furthest2 = new PairInt[2]; for (int i = 0; i < n; ++i) { int idx1 = result.idx1s.get(i); int idx2 = result.idx2s.get(i); PairInt p1 = new PairInt(bounds1.getX(idx1), bounds1.getY(idx1)); if (furthest2[0] == null) { if (furthest[0].equals(p1)) { furthest2[0] = new PairInt(bounds2.getX(idx2), bounds2.getY(idx2)); } } if (furthest2[1] == null) { if (furthest[1].equals(p1)) { furthest2[1] = new PairInt(bounds2.getX(idx2), bounds2.getY(idx2)); } } if (furthest2[0] != null && furthest2[1] != null) { break; } } assert (furthest2 != null && furthest2.length == 2); QuadInt[] refs = new QuadInt[2]; refs[0] = new QuadInt(furthest[0], furthest2[0]); refs[1] = new QuadInt(furthest[1], furthest2[1]); return refs; } private List<PairInt> matchUsingFM(ORB orb1, ORB orb2, int[][] costD, int octave1, int octave2, TObjectIntMap<PairInt> keypoints1IndexMap, TObjectIntMap<PairInt> keypoints2IndexMap, SimpleMatrix fm, PairIntArray unmatchedKP1, PairIntArray unmatchedKP2, TObjectIntMap<PairInt> unmatchedKP1Idxs, TObjectIntMap<PairInt> unmatchedKP2Idxs, int nBands, float distTol, double[] output) { float maxDesc = nBands * 256.0f; int distTolMax = (int)Math.round(Math.sqrt(2) * distTol); // output variable to hold sums and count // 0 = totalDistance // 1 = max avg total dist // 2 = totalDescrSum // 3 = nDescr double maxAvgDist = Double.MIN_VALUE; List<PairInt> addedKPIdxs = new ArrayList<PairInt>(); EpipolarTransformer eTransformer = new EpipolarTransformer(); SimpleMatrix unmatchedLeft = eTransformer.rewriteInto3ColumnMatrix(unmatchedKP1); SimpleMatrix unmatchedRight = eTransformer.rewriteInto3ColumnMatrix(unmatchedKP2); SimpleMatrix rightEpipolarLines = fm.mult(unmatchedLeft); SimpleMatrix leftEpipolarLines = fm.transpose().mult(unmatchedRight); float[] outputDist = new float[2]; int nLeftUnmatched = unmatchedLeft.numCols(); int nRightUnmatched = unmatchedRight.numCols(); float dist, descCost; double d; TFloatList totalCost = new TFloatArrayList(); TIntList indexes = new TIntArrayList(); TFloatList eDist = new TFloatArrayList(); TFloatList dCost = new TFloatArrayList(); TIntList idx1s = new TIntArrayList(); TIntList idx2s = new TIntArrayList(); for (int i = 0; i < nLeftUnmatched; ++i) { PairInt p1 = new PairInt(unmatchedKP1.getX(i), unmatchedKP1.getY(i)); int kp1Idx = unmatchedKP1Idxs.get(p1); for (int j = 0; j < nRightUnmatched; ++j) { PairInt p2 = new PairInt(unmatchedKP2.getX(j), unmatchedKP2.getY(j)); int kp2Idx = unmatchedKP2Idxs.get(p2); eTransformer.calculatePerpDistFromLines(unmatchedLeft, unmatchedRight, rightEpipolarLines, leftEpipolarLines, i, j, outputDist); if (outputDist[0] <= distTol && outputDist[1] <= distTol) { d = Math.sqrt(outputDist[0] * outputDist[0] + outputDist[1] * outputDist[1]); dist = (float)d/distTolMax; // normalized descriptor cost descCost = 1.f - ((nBands * 256.f - costD[kp1Idx][kp2Idx]) /maxDesc); eDist.add(dist); dCost.add(descCost); totalCost.add((float)Math.sqrt(dist*dist + descCost*descCost)); indexes.add(indexes.size()); idx1s.add(kp1Idx); idx2s.add(kp2Idx); } } } QuickSort.sortBy1stArg(totalCost, indexes); // new matched keypoint indexes TIntSet added1 = new TIntHashSet(); TIntSet added2 = new TIntHashSet(); for (int j = 0; j < totalCost.size(); ++j) { int idx = indexes.get(j); int kpIdx1 = idx1s.get(idx); int kpIdx2 = idx2s.get(idx); if (added1.contains(kpIdx1) || added2.contains(kpIdx2)) { continue; } // output variable to hold sums and count // 0 = totalDistance // 1 = max avg total dist // 2 = totalDescrSum // 3 = nDescr added1.add(kpIdx1); added2.add(kpIdx2); addedKPIdxs.add(new PairInt(kpIdx1, kpIdx2)); output[0] += eDist.get(idx); d = eDist.get(idx); if (d > maxAvgDist) { maxAvgDist = d; } output[2] += dCost.get(idx); output[3]++; } output[1] = maxAvgDist; return addedKPIdxs; } // sum, avg, maxAvg private double[] sumAndMaxEPDist(SimpleMatrix fm, PairIntArray m1, PairIntArray m2) { EpipolarTransformer eTransformer = new EpipolarTransformer(); SimpleMatrix matchedLeft = eTransformer.rewriteInto3ColumnMatrix(m1); SimpleMatrix matchedRight = eTransformer.rewriteInto3ColumnMatrix(m2); // this goes into total epipolar distances at end of block // NOTE: this method needs testing. // currently no normalization is used internally PairFloatArray distances = eTransformer .calculateDistancesFromEpipolar(fm, matchedLeft, matchedRight); double max = Double.MIN_VALUE; double sum = 0; double d; for (int i = 0; i < distances.getN(); ++i) { float d1 = distances.getX(i); float d2 = distances.getY(i); d = Math.sqrt(d1*d1 + d2*d2); if (d > max) { max = d; } sum += d; } double avg = sum/(double)distances.getN(); return new double[]{sum, avg, max}; } /** assumptions such as transformation being near the expected scale of scale1/scale2 are made * @param segIdx * @param left * @param right * @param nBands * @param costD * @param nn1 * @param keypoints1IndexMap point indexes lookup w.r.t. entire keypoints1 list * which has same indexes as costD first dimension. note that the * template object dataset, a.k.a. left or a1 includes all points of * keypoints1...no segmentation dividing the points into more than one * array list. nn1 contains all keypoints1 points. * @param keypoints2IndexMap point indexes lookup w.r.t. entire keypoints2 list * which has same indexes as costD second dimension. these indexes are not the same * indexes as a2 indexes. * @param outLeft * @param outRight * @param img1Width * @param img1Height * @param distTol * @param extr1 * @param extr2 * @param nnExtr1 * @param extr1IndexMap * @param extr2IndexMap * @param scale1 * @param scale2 * @param outputNormalizedCost * @return */ private TransformationParameters matchGreedy( int segIdx, PairIntArray left, PairIntArray right, int nBands, int[][] costD, NearestNeighbor2D nn1, TObjectIntMap<PairInt> keypoints1IndexMap, TObjectIntMap<PairInt> keypoints2IndexMap, PairIntArray keypoints2, PairIntArray outLeft, PairIntArray outRight, int img1Width, int img1Height, int distTol, PairIntArray bounds1, TObjectIntMap<PairInt> keypoints2LabelMap, float scale1, float scale2, double[] xyCenlabeled2, TObjectIntMap<PairInt> label2PairSizes, List<Set<PairInt>> label2Sets, double[] outputNormalizedCost) { // NOTE that all coordinates are in the full reference frame // and remain that way through this method float expectedScale = scale1/scale2; float maxDesc = nBands * 256.0f; int n1 = left.getN(); int n2 = right.getN(); int sz1 = calculateObjectSize(left); int sz1LimitSq = Math.round(1.3f * sz1); sz1LimitSq *= sz1LimitSq; /* // for each left, find the best matching right int[] b = new int[n1]; int[] indexes = new int[n1]; float[] costs = new float[n1]; double c; for (int i = 0; i < n1; ++i) { double bestCost = Double.MAX_VALUE; int bestIdx2 = -1; PairInt p1 = new PairInt(left.getX(i), left.getY(i)); int kpIdx1 = keypoints1IndexMap.get(p1); assert(keypoints1IndexMap.containsKey(p1)); for (int j = 0; j < n2; ++j) { PairInt p2 = new PairInt(right.getX(j), right.getY(j)); int kpIdx2 = keypoints2IndexMap.get(p2); assert(keypoints2IndexMap.containsKey(p2)); c = costD[kpIdx1][kpIdx2]; if (c < bestCost) { bestCost = c; bestIdx2 = j; } } b[i] = bestIdx2; // index w.r.t. right array indexes[i] = i; costs[i] = (float)bestCost; } */ //TODO: this may be revised after more tests float costLimit = (nBands * 256) * 0.5f; //int n12 = (n1 * n2) - ((n1 - 1) * Math.abs(n1 - n2)); int n12 = n1 * n2; int[] idxs1 = new int[n12]; int[] idxs2 = new int[n12]; int[] indexes = new int[n12]; float[] costs = new float[n12]; int count = 0; double c; for (int i = 0; i < n1; ++i) { PairInt p1 = new PairInt(left.getX(i), left.getY(i)); int kpIdx1 = keypoints1IndexMap.get(p1); assert(keypoints1IndexMap.containsKey(p1)); for (int j = 0; j < n2; ++j) { PairInt p2 = new PairInt(right.getX(j), right.getY(j)); int kpIdx2 = keypoints2IndexMap.get(p2); assert(keypoints2IndexMap.containsKey(p2)); c = costD[kpIdx1][kpIdx2]; if (c > costLimit) { continue; } idxs1[count] = i; idxs2[count] = j; indexes[count] = count; costs[count] = (float)c; count++; } } if (count < n12) { idxs1 = Arrays.copyOf(idxs1, count); idxs2 = Arrays.copyOf(idxs2, count); indexes = Arrays.copyOf(indexes, count); costs = Arrays.copyOf(costs, count); } QuickSort.sortBy1stArg(costs, indexes); int topK = 20; //if (topK > n1) { topK = count; MatchedPointsTransformationCalculator tc = new MatchedPointsTransformationCalculator(); Transformer transformer = new Transformer(); double bestCost = Double.MAX_VALUE; double bestCost2 = -1; int[] bestMIdx1s = null; int[] bestMIdx2s = null; int bestN = -1; TransformationParameters bestParams = null; for (int i = 0; i < topK; ++i) { int idx = indexes[i]; int idxI1 = idxs1[idx]; int idxJ1 = idxs2[idx]; int leftX1 = left.getX(idxI1); int leftY1 = left.getY(idxI1); int rightX1 = right.getX(idxJ1); int rightY1 = right.getY(idxJ1); for (int j = (i + 1); j < topK; ++j) { int idx2 = indexes[j]; int idxI2 = idxs1[idx2]; int idxJ2 = idxs2[idx2]; int leftX2 = left.getX(idxI2); int leftY2 = left.getY(idxI2); int rightX2 = right.getX(idxJ2); int rightY2 = right.getY(idxJ2); assert(!(leftX1 != leftX2 && leftY1 != leftY1)); assert(!(rightX1 != rightX2 && rightY1 != rightY1)); // transform dataset 2 into frame 1 // (direction is 2 to 1 to be able to reuse nearest // neighbors containing dataset1 keypoints TransformationParameters params = tc.calulateEuclidean( rightX1, rightY1, rightX2, rightY2, leftX1, leftY1, leftX2, leftY2, 0, 0); if (params == null) { continue; } float scale = params.getScale(); if (((scale >= expectedScale) && (scale/expectedScale) > 1.2) || ((scale < expectedScale) && (expectedScale/scale) > 1.2)) { continue; } // distTol is w.r.t. scale1=1, so if scale1 > 1, need to adjust // NOTE that distTol is applied to pixels in dataset1 reference frame. int distTol2 = Math.round((float)distTol/scale1); if (distTol2 < 1) { distTol2 = 1; } PairIntArray keypoints2Tr = transformer.applyTransformation( params, keypoints2); double[] xyCenTr = transformer.applyTransformation(params, xyCenlabeled2[0], xyCenlabeled2[1]); // to transformed points within tolerance, // need to filter out points that are further from // a factor times object distance from the center of // the current index for the fast first size filter. // -- because the transformation is now known, more than // the maximum dimension can be used. // -- after keypoints of adjacent labeled regions are // added, // can inspect the number and distribution of // key points in the implied added labeled regions // and if the matched keypoints are only present // at the adjacent border and not the other borders, // can determine that that additional region and // it's keypoints should not be added to this // set of maches for segIdx. // TODO: implement this later portion. // filter out keypoints further than 2*sz1 or so // from the center of segIdx region. // to keep indexes correcting, making a skip set instead TIntSet skip = new TIntHashSet(); for (int jj = 0; jj < keypoints2Tr.getN(); ++jj) { double diffX = keypoints2Tr.getX(jj) - xyCenTr[0]; double diffY = keypoints2Tr.getY(jj) - xyCenTr[1]; double d = diffX * diffX + diffY * diffY; if (d > sz1LimitSq) { skip.add(jj); } else { // check if adding these 2 labeled regions is too large int label2 = keypoints2LabelMap.get( new PairInt(keypoints2.getX(jj), keypoints2.getY(jj))); if (label2 == segIdx) { continue; } PairInt labels = (segIdx < label2) ? new PairInt(segIdx, label2) : new PairInt(label2, segIdx); int sz2; if (label2PairSizes.containsKey(labels)) { sz2 = label2PairSizes.get(labels); } else { Set<PairInt> comb = new HashSet<PairInt>( label2Sets.get(segIdx)); comb.addAll(label2Sets.get(label2)); sz2 = calculateObjectSize(comb); label2PairSizes.put(labels, sz2); } sz2 *= params.getScale(); if ((sz2 * sz2) > sz1LimitSq) { skip.add(jj); } } } // filled with indexes w.r.t left and right arrays int[] mIdx1s = new int[keypoints2LabelMap.size()]; int[] mIdx2s = new int[keypoints2LabelMap.size()]; //sums is []{sumDesc, sumDist, count} // where sumDesc is the sum of normalized descriptors // each with a value of 0 to 1 and summed over // count number of them. (so max is <= count) // same for sumDist double[] sums = sumKeypointDescAndDist2To1(costD, nBands, keypoints2, keypoints2Tr, nn1, keypoints1IndexMap, keypoints2IndexMap, skip, distTol2, mIdx1s, mIdx2s); final int nMatched = (int)sums[2]; if (nMatched < 3) { continue; } double sumDescr = sums[0]; double sumDist = sums[1]; float descCost = (float)sumDescr/(float)nMatched; float distCost = (float)sumDist/(float)nMatched; float d1 = descCost; float d2 = distCost; final float f1 = 1.f - ((float)nMatched/(float)n1); float tot = d1*d1 + d2*d2 + 2.f * f1 * f1; tot = d1 * d1 + f1 * f1; if (tot < bestCost) { String str1 = String.format( "< lbl=%d trRot=%d scl=%.2f nm=%d", segIdx, (int)params.getRotationInDegrees(), params.getScale(), nMatched); String str2 = String.format( " dc=%.2f dt=%.2f f1=%.2f tot=%.2f", d1, d2, f1, tot); System.out.println(str1 + str2); bestCost = tot; // 0 = the salukwzde distance, that is the normalized tot cost // 1 = sum of normalized keypoint descriptors // 2 = sum of normalized keypoint distances from transformations // 3 = number of keypoint matches (not incl boundary that aren't // 4 = sum of normalized bounds distances from transformations // 5 = number of normalized bounds matches outputNormalizedCost[0] = bestCost; outputNormalizedCost[1] = sumDescr; outputNormalizedCost[2] = sumDist; outputNormalizedCost[3] = nMatched; bestMIdx1s = mIdx1s; bestMIdx2s = mIdx2s; bestN = nMatched; bestParams = params; } } } if (bestMIdx1s != null) { Set<PairInt> addedLeft = new HashSet<PairInt>(); Set<PairInt> addedRight = new HashSet<PairInt>(); for (int i = 0; i < bestN; ++i) { int kpIdx1 = bestMIdx1s[i]; int kpIdx2 = bestMIdx2s[i]; PairInt pLeft = new PairInt(left.getX(kpIdx1), left.getY(kpIdx1)); PairInt pRight = new PairInt(keypoints2.getX(kpIdx2), keypoints2.getY(kpIdx2)); if (addedLeft.contains(pLeft) || addedRight.contains(pRight)) { continue; } addedLeft.add(pLeft); addedRight.add(pRight); outLeft.add(pLeft.getX(), pLeft.getY()); outRight.add(pRight.getX(), pRight.getY()); } } return bestParams; } private double[] addUnmatchedKeypoints(TransformationParameters params, PairIntArray m1, PairIntArray m2, int nBands, int[][] costD, PairIntArray keypoints1, TObjectIntMap<PairInt> keypoints1IndexMap, TObjectIntMap<PairInt> keypoints2IndexMap, int imageWidth, int imageHeight, int distTol, float scale1, float scale2) { if (m1.getN() == keypoints1.getN()) { // all keypoints have been matched return new double[]{0, 0, 0}; } //TODO: could improve this by reducing the unmatched2 points // to only those within sz1 transformed size of center of // the labeled region. float maxDesc = nBands * 256.0f; float distTolMax = (float)Math.sqrt(2) * distTol; // find all transformed keypoints2 that are unmatched, and match // a left unmatched point within distTol. // then sort those by total cost and assign uniquely. // then add results to m1, m2 and // put the costs in return array. /* output: // 0 = sum of normalized keypoint descriptors // 1 = sum of normalized keypoint distances from transformations // 2 = number of keypoint matches added */ // find unmatched keypoints1 and put in a nearest neighbor instance Set<PairInt> matched1 = new HashSet<PairInt>(); Set<PairInt> matched2 = new HashSet<PairInt>(); for (int j = 0; j < m1.getN(); ++j) { // NOTE: m1,m2 are keypoints and boundary points int x1 = m1.getX(j); int y1 = m1.getY(j); int x2 = m2.getX(j); int y2 = m2.getY(j); matched1.add(new PairInt(x1, y1)); matched2.add(new PairInt(x2, y2)); } PairIntArray unmatched1 = new PairIntArray(); for (int j = 0; j < keypoints1.getN(); ++j) { PairInt p = new PairInt(keypoints1.getX(j), keypoints1.getY(j)); if (!matched1.contains(p)) { unmatched1.add(p.getX(), p.getY()); } } int[] minMaxXY1 = MiscMath.findMinMaxXY(unmatched1); NearestNeighbor2D nn1 = new NearestNeighbor2D(Misc.convert(unmatched1), minMaxXY1[1] + distTol + 2, minMaxXY1[3] + distTol + 2); List<PairInt> mc1 = new ArrayList<PairInt>(); List<PairInt> mc2 = new ArrayList<PairInt>(); TFloatList descCosts = new TFloatArrayList(); TFloatList distances = new TFloatArrayList(); TFloatList totalCosts = new TFloatArrayList(); TIntList indexes = new TIntArrayList(); Transformer transformer = new Transformer(); // visit all keypoint2 and if not matched, transform point // and find nearest unmatched1 neighbor TObjectIntIterator<PairInt> iter2 = keypoints2IndexMap.iterator(); for (int i = 0; i < keypoints2IndexMap.size(); ++i) { iter2.advance(); PairInt p2 = iter2.key(); if (matched2.contains(p2)) { continue; } double[] tr = transformer.applyTransformation(params, p2.getX(), p2.getY()); int x2Tr = (int) Math.round(tr[0]); int y2Tr = (int) Math.round(tr[1]); if (x2Tr < 0 || y2Tr < 0 || (x2Tr > (imageWidth - 1)) || (y2Tr > (imageHeight - 1))) { continue; } PairInt p2Tr = new PairInt(x2Tr, y2Tr); Set<PairInt> nearest = nn1.findClosest(x2Tr, y2Tr, distTol); if (nearest == null || nearest.isEmpty()) { continue; } int kpIdx2 = keypoints2IndexMap.get(p2); PairInt p1Closest = null; if (nearest.size() == 1) { p1Closest = nearest.iterator().next(); } else { // find closest in terms of descriptor float minCost = Float.MAX_VALUE; PairInt minCostP = null; for (PairInt p3 : nearest) { int kpIdx1 = keypoints1IndexMap.get(p3); float c = costD[kpIdx1][kpIdx2]; if (c < minCost) { minCost = c; minCostP = p3; } } assert(minCostP != null); p1Closest = minCostP; } assert(p1Closest != null); int kpIdx1 = keypoints1IndexMap.get(p1Closest); float c = costD[kpIdx1][kpIdx2]; float dist = distance(p2Tr, p1Closest); assert(dist <= distTolMax); float costNorm = c / maxDesc; float distNorm = dist / distTolMax; assert(!matched1.contains(p1Closest)); assert(!matched2.contains(p2)); mc1.add(p1Closest); mc2.add(p2); descCosts.add(costNorm); distances.add(distNorm); // could square these, but not necessary for this comparison: totalCosts.add(costNorm + distNorm); indexes.add(indexes.size()); } QuickSort.sortBy1stArg(totalCosts, indexes); Set<PairInt> added1 = new HashSet<PairInt>(); Set<PairInt> added2 = new HashSet<PairInt>(); double sumDist = 0; double sumDesc = 0; int nAdded = 0; // adding directly to m1 and m2, uniquely for (int i = 0; i < indexes.size(); ++i) { int idx = indexes.get(i); PairInt p1 = mc1.get(idx); PairInt p2 = mc2.get(idx); if (added1.contains(p1) || added2.contains(p2)) { continue; } added1.add(p1); added2.add(p2); m1.add(p1.getX(), p1.getY()); m2.add(p2.getX(), p2.getY()); sumDesc += descCosts.get(idx); sumDist += distances.get(idx); nAdded++; } return new double[] {sumDesc, sumDist, nAdded}; } private List<CorrespondenceList> aggregatedShapeMatch( ORB orb1, ORB orb2, int nBands, Set<PairInt> labeledPoints1, List<Set<PairInt>> labeledPoints2, TIntList octs1, TIntList octs2, TIntList segIdxs, TFloatList scales1, TFloatList scales2) { System.out.println("aggregatedShapeMatch for " + octs1.size() + " results"); TIntObjectMap<Set<PairInt>> octave1ScaledSets = createSetsForOctaves(octs1, labeledPoints1, scales1); TIntObjectMap<PairIntArray> octave1ScaledBounds = createBounds(octave1ScaledSets, orb1.getPyramidImages().get(0).a[0].length, orb1.getPyramidImages().get(0).a.length); TIntObjectMap<TIntObjectMap<Set<PairInt>>> octave2ScaledSets = createSetsForOctaves(octs2, labeledPoints2, scales2); TIntObjectMap<Map<OneDIntArray, PairIntArray>> keybounds2Maps = initializeMaps(octs2); int n = octs1.size(); // store each ShapeFinder2.ShapeFinderResult result // need to compare results from different octaves // diff chord sum // number matched // max matchable for octave pair (==n1) // max avg chord diff for octave pair // the differences in chords for true match shapes should not change // with scale (excepting due to resolution affecting the shapes), // so the maximum difference in the avg chord can be // used on all of the results when re-normalizing and re-calculating dist. // The number of matches possible for each scale does change with scale // and that is handled in the "fraction of whole term" already. // so a "re-normalization" to calculate new salukvazde costs just needs // to use the maximum avg chord sum diff for all. TIntList shapeResultIdxs = new TIntArrayList(); List<ShapeFinder2.ShapeFinderResult> shapeResults = new ArrayList<ShapeFinder2.ShapeFinderResult>(); double maxChordDiff = Double.MIN_VALUE; for (int i = 0; i < n; ++i) { int octave1 = octs1.get(i); int octave2 = octs2.get(i); int segIdx = segIdxs.get(i); float scale1 = scales1.get(octave1); float scale2 = scales2.get(octave2); PairIntArray bounds1 = octave1ScaledBounds.get(octave1); float sz1 = calculateObjectSize(bounds1); TIntObjectMap<Set<PairInt>> mapOfSets2 = new TIntObjectHashMap<Set<PairInt>>(octave2ScaledSets.get(octave2)); float factor = 2.f; // removing any set that, when combined with set for segIdx, // has dimensions larger than twice the size of bounds1 removeSetsByCombinedSize(bounds1, segIdx, mapOfSets2, factor); removeSetsNotConnected(segIdx, mapOfSets2); Map<OneDIntArray, PairIntArray> keyBoundsMap2 = keybounds2Maps.get(octave2); int xMax1 = orb1.getPyramidImages().get(octave1).a[0].length -1; int yMax1 = orb1.getPyramidImages().get(octave1).a.length - 1; int xMax2 = orb2.getPyramidImages().get(octave2).a[0].length -1; int yMax2 = orb2.getPyramidImages().get(octave2).a.length - 1; System.out.println("start shape search for octave1=" + octave1 + " octave2=" + octave2 + " segIdx=" + segIdx); ShapeFinder2 shapeFinder = new ShapeFinder2(bounds1, scale1, sz1, xMax1, yMax1, mapOfSets2, scale2, keyBoundsMap2, xMax2, yMax2); ShapeFinder2.ShapeFinderResult result = shapeFinder.findAggregated(segIdx); if (result == null) { continue; } System.out.println("shapeFinder result for segIdx=" + + segIdx + " " + result.toString()); shapeResultIdxs.add(i); shapeResults.add(result); double cda = result.getChordDiffSum()/(double)result.getNumberOfMatches(); if (cda > maxChordDiff) { maxChordDiff = cda; } {//DEBUG ShapeFinder2.ShapeFinderResult r = result; Image img1 = ORB.convertToImage( orb1.getPyramidImages().get(octave1)); Image img2 = ORB.convertToImage( orb2.getPyramidImages().get(octave2)); try { CorrespondencePlotter plotter = new CorrespondencePlotter( r.bounds1, r.bounds2); //img1, img2); for (int ii = 0; ii < r.getNumberOfMatches(); ++ii) { int idx1 = r.getIdx1(ii); int idx2 = r.getIdx2(ii); int x1 = r.bounds1.getX(idx1); int y1 = r.bounds1.getY(idx1); int x2 = r.bounds2.getX(idx2); int y2 = r.bounds2.getY(idx2); if ((ii % 4) == 0) { plotter.drawLineInAlternatingColors(x1, y1, x2, y2, 0); } } String str = octave1 + "_" + octave2 + "_" + segIdx + "_" + MiscDebug.getCurrentTimeFormatted(); String filePath = plotter.writeImage("_shape_" + str); } catch (Throwable t) { System.err.println(t.getMessage()); } } } float maxDesc = nBands * 256.0f; // sort the results by cost TFloatList shapeCosts = new TFloatArrayList(shapeResultIdxs.size()); TIntList shapeCostIdxs = new TIntArrayList(); for (int i = 0; i < shapeResultIdxs.size(); ++i) { int idx = shapeResultIdxs.get(i); ShapeFinder2.ShapeFinderResult shapeResult = shapeResults.get(i); int octave1 = octs1.get(idx); int octave2 = octs2.get(idx); //int segIdx = segIdxs.get(idx); //float scale1 = scales1.get(octave1); //float scale2 = scales2.get(octave2); float nb1 = shapeResult.bounds1.getN(); float nMatched = shapeResult.getNumberOfMatches(); double chordDiff = shapeResult.getChordDiffSum()/nMatched; double d1 = (chordDiff / maxDesc); double f1 = 1.f - (nMatched/nb1); double sd = d1 * d1 + f1 * f1; shapeCosts.add((float)sd); shapeCostIdxs.add(i); } QuickSort.sortBy1stArg(shapeCosts, shapeCostIdxs); List<CorrespondenceList> results = new ArrayList<CorrespondenceList>(); for (int i = 0; i < shapeCostIdxs.size(); ++i) { int idx0 = shapeCostIdxs.get(i); int idx = shapeResultIdxs.get(idx0); ShapeFinder2.ShapeFinderResult shapeResult = shapeResults.get(idx0); int np = shapeResult.getNumberOfMatches(); int octave1 = octs1.get(idx); int octave2 = octs2.get(idx); //int segIdx = segIdxs.get(idx); float scale1 = scales1.get(octave1); float scale2 = scales2.get(octave2); PairIntArray bounds1 = shapeResult.bounds1; PairIntArray bounds2 = shapeResult.bounds2; // shapeResult points need to be scaled back up to full reference // frame List<QuadInt> qs = new ArrayList<QuadInt>(); for (int j = 0; j < np; ++j) { int idx1 = shapeResult.idx1s.get(j); int idx2 = shapeResult.idx2s.get(j); int x1 = Math.round((float)bounds1.getX(idx1) * scale1); int y1 = Math.round((float)bounds1.getY(idx1) * scale1); int x2 = Math.round((float)bounds2.getX(idx2) * scale2); int y2 = Math.round((float)bounds2.getY(idx2) * scale2); qs.add(new QuadInt(x1, y1, x2, y2)); } // points are in full reference frame results.add(new CorrespondenceList(qs)); } return results; } private TIntObjectMap<Set<PairInt>> createSetsForOctaves(TIntList octaves, Set<PairInt> labeledPoints, TFloatList scales) { TIntObjectMap<Set<PairInt>> output = new TIntObjectHashMap<Set<PairInt>>(); for (int i = 0; i < octaves.size(); ++i) { int octave = octaves.get(i); if (output.containsKey(octave)) { continue; } float scale = scales.get(octave); Set<PairInt> set2 = new HashSet<PairInt>(); for (PairInt p : labeledPoints) { int x = Math.round((float)p.getX()/scale); int y = Math.round((float)p.getY()/scale); set2.add(new PairInt(x, y)); } output.put(octave, set2); } return output; } private TIntObjectMap<TIntObjectMap<Set<PairInt>>> createSetsForOctaves( TIntList octaves, List<Set<PairInt>> labeledPoints, TFloatList scales) { TIntObjectMap<TIntObjectMap<Set<PairInt>>> output = new TIntObjectHashMap<TIntObjectMap<Set<PairInt>>>(); for (int i = 0; i < octaves.size(); ++i) { int octave = octaves.get(i); if (output.containsKey(octave)) { continue; } float scale = scales.get(octave); TIntObjectMap<Set<PairInt>> labeledOctaveMap = new TIntObjectHashMap<Set<PairInt>>(); int n = labeledPoints.size(); for (int segIdx = 0; segIdx < n; ++segIdx) { Set<PairInt> set = labeledPoints.get(segIdx); Set<PairInt> set2 = new HashSet<PairInt>(); for (PairInt p : set) { int x = Math.round((float)p.getX()/scale); int y = Math.round((float)p.getY()/scale); set2.add(new PairInt(x, y)); } labeledOctaveMap.put(segIdx, set2); } output.put(octave, labeledOctaveMap); } return output; } private TIntObjectMap<PairIntArray> createBounds( TIntObjectMap<Set<PairInt>> octaveScaledSets, int imgWidth, int imgHeight) { TIntObjectMap<PairIntArray> output = new TIntObjectHashMap<PairIntArray>(); SIGMA sigma = SIGMA.ZEROPOINTFIVE; ImageProcessor imageProcessor = new ImageProcessor(); TIntObjectIterator<Set<PairInt>> iter = octaveScaledSets.iterator(); for (int i = 0; i < octaveScaledSets.size(); ++i) { iter.advance(); int segIdx = iter.key(); Set<PairInt> set = iter.value(); PairIntArray bounds = imageProcessor.extractSmoothedOrderedBoundary( new HashSet<PairInt>(set), sigma, imgWidth, imgHeight); output.put(segIdx, bounds); } return output; } private TIntObjectMap<Map<OneDIntArray, PairIntArray>> initializeMaps( TIntList octaves) { TIntObjectMap<Map<OneDIntArray, PairIntArray>> output = new TIntObjectHashMap<Map<OneDIntArray, PairIntArray>>(); for (int i = 0; i < octaves.size(); ++i) { int octave = octaves.get(i); output.put(octave, new HashMap<OneDIntArray, PairIntArray>()); } return output; } private void removeSetsByCombinedSize(PairIntArray bounds1, int segIdx2, TIntObjectMap<Set<PairInt>> mapOfBounds2, float factor) { float sz1 = calculateObjectSize(bounds1); TIntSet rm = new TIntHashSet(); Set<PairInt> set2 = mapOfBounds2.get(segIdx2); TIntObjectIterator<Set<PairInt>> iter = mapOfBounds2.iterator(); for (int i = 0; i < mapOfBounds2.size(); ++i) { iter.advance(); int segIdx3 = iter.key(); Set<PairInt> set3 = iter.value(); Set<PairInt> combined = new HashSet<PairInt>(set2); combined.addAll(set3); float sz2 = calculateObjectSize(combined); if (sz2 > factor * sz1) { rm.add(segIdx3); } } TIntIterator iter2 = rm.iterator(); while (iter2.hasNext()) { int rmIdx = iter2.next(); mapOfBounds2.remove(rmIdx); } } private void removeSetsNotConnected(int segIdx, TIntObjectMap<Set<PairInt>> mapOfSets) { TObjectIntMap<PairInt> pointIndexMap = new TObjectIntHashMap<PairInt>(); TIntObjectIterator<Set<PairInt>> iter = mapOfSets.iterator(); for (int i = 0; i < mapOfSets.size(); ++i) { iter.advance(); int idx = iter.key(); for (PairInt p : iter.value()) { pointIndexMap.put(p, idx); } } TIntSet connected = new TIntHashSet(); Stack<Integer> stack = new Stack<Integer>(); stack.add(Integer.valueOf(segIdx)); int[] dxs = Misc.dx4; int[] dys = Misc.dy4; TIntSet addedToStack = new TIntHashSet(); TIntSet visited = new TIntHashSet(); while (!stack.isEmpty()) { int idx = stack.pop().intValue(); if (visited.contains(idx)) { continue; } connected.add(idx); Set<PairInt> set = mapOfSets.get(idx); for (PairInt p : set) { int x = p.getX(); int y = p.getY(); for (int k = 0; k < dxs.length; ++k) { int x2 = x + dxs[k]; int y2 = y + dys[k]; PairInt p2 = new PairInt(x2, y2); if (pointIndexMap.containsKey(p2)) { int idx2 = pointIndexMap.get(p2); if (!addedToStack.contains(idx2) && !visited.contains(idx2)) { addedToStack.add(idx2); stack.add(Integer.valueOf(idx2)); } } } } visited.add(idx); } /* // looks like this removes the item, but just in case the // values are left in the heap, will remove singly // until can test for it. int n = mapOfSets.size(); TIntSet keys = mapOfSets.keySet(); keys.removeAll(connected); int n2 = mapOfSets.size(); */ TIntSet rm = new TIntHashSet(mapOfSets.keySet()); rm.removeAll(connected); TIntIterator iter2 = rm.iterator(); while (iter2.hasNext()) { int rmIdx = iter2.next(); mapOfSets.remove(rmIdx); } } private int[] extractAndSortLabels(int segIdx, List<QuadInt> matched12, TObjectIntMap<PairInt> keypoints2LabelMap, TIntObjectMap<VeryLongBitString> label2AdjacencyMap) { TIntSet labelSet = new TIntHashSet(); for(int i = 0; i < matched12.size(); ++i) { QuadInt qs = matched12.get(i); PairInt p2 = new PairInt(qs.getC(), qs.getD()); assert(keypoints2LabelMap.containsKey(p2)); int label2 = keypoints2LabelMap.get(p2); labelSet.add(label2); } //NOTE: this may change: for now, starting with src=segIdx, making a // DFS traversal of neighbors within labelSet to keep labelList // contiguous. // Might consider adding the intersection of members in labelSet // to include labels not in labelSet that connect a label which would // otherwise be excluded from labelList...caveat is not to include // external labels that would result in the wrong boundary. TIntSet added = new TIntHashSet(); TIntSet visited = new TIntHashSet(); TIntList labelList = new TIntArrayList(); labelList.add(segIdx); Stack<Integer> stack = new Stack<Integer>(); stack.add(segIdx); while (!stack.isEmpty()) { int label = stack.pop().intValue(); if (visited.contains(label)) { continue; } int[] nbrLabels = label2AdjacencyMap.get(label).getSetBits(); for (int label2 : nbrLabels) { if (!added.contains(label2) && labelSet.contains(label2)) { labelList.add(label2); stack.add(Integer.valueOf(label2)); added.add(label2); } } visited.add(label); } labelList.sort(); int[] labels = labelList.toArray(new int[labelList.size()]); return labels; } private PairIntArray extractKeypoints(ORB orb, int octave) { int n = orb.getKeyPoint0List().get(octave).size(); PairIntArray out = new PairIntArray(n); for (int i = 0; i < n; ++i) { out.add(orb.getKeyPoint1List().get(octave).get(i), orb.getKeyPoint0List().get(octave).get(i)); } return out; } private TIntObjectMap<VeryLongBitString> createAdjacencyMap( List<Set<PairInt>> labeledPoints) { int n = labeledPoints.size(); TObjectIntMap<PairInt> pointIndexMap = new TObjectIntHashMap<PairInt>(); for (int i = 0; i < n; ++i) { for (PairInt p : labeledPoints.get(i)) { pointIndexMap.put(p, i); } } TIntObjectMap<VeryLongBitString> output = new TIntObjectHashMap<VeryLongBitString>(); int[] dxs = Misc.dx4; int[] dys = Misc.dy4; for (int label = 0; label < n; ++label) { Set<PairInt> set = labeledPoints.get(label); VeryLongBitString nbrs = new VeryLongBitString(n); output.put(label, nbrs); for (PairInt p : set) { int x = p.getX(); int y = p.getY(); for (int k = 0; k < dxs.length; ++k) { int x2 = x + dxs[k]; int y2 = y + dys[k]; PairInt p2 = new PairInt(x2, y2); if (pointIndexMap.containsKey(p2)) { int label2 = pointIndexMap.get(p2); if (label2 != label) { nbrs.setBit(label2); } } } } } return output; } /** * calculate patch SSD costs, add to some subset of previous cost terms, * and trim and re-sort the given results. * * @param results * @param resultCosts * @param dataIndexes * @param orb1 * @param orb2 * @param octs1 * @param octs2 * @param segIdxs * @param labeledPoints1 * @param labeledPoints2 * @param bounds1 * @param bounds2s * @param sortedKeysMap * @param transformations * @param limitFactor * @return */ private List<CorrespondenceList> refineCostsWithColor( TIntObjectMap<CorrespondenceList> results, TFloatList resultCosts, TIntList sortedDataIndexes, ORB orb1, ORB orb2, TIntIntMap octs1, TIntIntMap octs2, TIntIntMap segIdxs, Set<PairInt> labeledPoints1, List<Set<PairInt>> labeledPoints2, PairIntArray bounds1, TIntIntMap nb1s, TIntObjectMap<PairIntArray> bounds2s, Map<TrioInt, OneDIntArray> sortedKeysMap, TIntObjectMap<TransformationParameters> transformations, float limitFactor) { TFloatList costs2 = new TFloatArrayList(); // coordinates are in the reference frame of the full size octave 0 images // row major format: TwoDFloatArray imgH1 = orb1.getPyramidImagesH().get(0); TwoDFloatArray imgS1 = orb1.getPyramidImagesS().get(0); TwoDFloatArray imgV1 = orb1.getPyramidImagesV().get(0); // row major format: TwoDFloatArray imgH2 = orb2.getPyramidImagesH().get(0); TwoDFloatArray imgS2 = orb2.getPyramidImagesS().get(0); TwoDFloatArray imgV2 = orb2.getPyramidImagesV().get(0); Transformer transformer = new Transformer(); int[] dxs = Misc.dx8; int[] dys = Misc.dy8; float limitCost = (1.f + limitFactor) * resultCosts.get(0); for (int i = 0; i < sortedDataIndexes.size(); ++i) { if (resultCosts.get(i) > limitCost) { // remove remaining results and data indexes int n2 = sortedDataIndexes.size(); for (int j = (n2 - 1); j >= i; --j) { int idx = sortedDataIndexes.get(j); results.remove(idx); sortedDataIndexes.removeAt(j); } break; } int idx = sortedDataIndexes.get(i); int octave1 = octs1.get(idx); int octave2 = octs2.get(idx); int segIdx = segIdxs.get(idx); float scale1 = orb1.getScalesList().get(octave1).get(0); OneDIntArray sortedKeys = sortedKeysMap.get( new TrioInt(octave1, octave2, segIdx)); TransformationParameters params = transformations.get(idx); PairIntArray bounds2 = bounds2s.get(idx); Set<PairInt> combinedSet2 = new HashSet<PairInt>(); for (int label2 : sortedKeys.a) { combinedSet2.addAll(labeledPoints2.get(label2)); } // NOTE, because of possibility of projection and the // resulting foreshortening along an axis, may need to consider // a more time consuming epipolar solution, then // transformation and nearest neighbor consistent // with bounds along epipolar lines (similar to methods // used in registration). // NOTE also: whichever method is used, it would be faster // to transform the entire combinedSet once // instead of several times for overlapping descrptor // points below. // transform each point in label2 and sum the 8 neighbors // -- compare to the same within bounds in other. // note: nIn12, nIn2 int n12 = 0; double patchSums = 0; float[] h1s = new float[8]; float[] s1s = new float[8]; float[] v1s = new float[8]; float[] h2s = new float[8]; float[] s2s = new float[8]; float[] v2s = new float[8]; for (PairInt p2 : combinedSet2) { // transform the 8 neighbor region into reference frame // of image 1 and store for normalization int count = 0; double sum = 0; // to speed this up, could use the rotation matrix // use in features package for (int k = 0; k < dxs.length; ++k) { int x3 = p2.getX() + dxs[k]; int y3 = p2.getY() + dys[k]; PairInt p3 = new PairInt(x3, y3); if (!combinedSet2.contains(p3)) { continue; } double[] tr = transformer.applyTransformation(params, x3, y3); int xTr = (int) Math.round(tr[0]); int yTr = (int) Math.round(tr[1]); PairInt pTr = new PairInt(xTr, yTr); if (!labeledPoints1.contains(pTr)) { continue; } h1s[count] = imgH1.a[yTr][xTr]; h2s[count] = imgH2.a[y3][x3]; s1s[count] = imgS1.a[yTr][xTr]; s2s[count] = imgS2.a[y3][x3]; v1s[count] = imgV1.a[yTr][xTr]; v2s[count] = imgV2.a[y3][x3]; count++; } if (count == 0) { continue; } // calc mean and substr it for the brighness arrays? calcMeanAndSubtr(v1s, count); calcMeanAndSubtr(v2s, count); double hSum = 0; double sSum = 0; double vSum = 0; for (int j = 0; j < count; ++j) { float diffH = h1s[j] - h2s[j]; float diffS = s1s[j] - s2s[j]; float diffV = v1s[j] - v2s[j]; hSum += (diffH * diffH); sSum += (diffS * diffS); vSum += (diffV * diffV); } hSum /= (double)count; sSum /= (double)count; vSum /= (double)count; patchSums += ((hSum + sSum + vSum)/3.); n12++; } // each h,s,v image is scaled to values from 0 to 1. // so max difference possible is "1". // then the normalization is count * 1 patchSums /= (double)n12; //everything is scaled to reference frame of octave1=0 // but when object matches a larger octave1, the area matchable is // decreased float nb1 = labeledPoints1.size(); int nMaxMatchable = Math.round(nb1/(float)(scale1 * scale1)); float d6 = (float)patchSums; float f6 = 1.f - ((float)n12/nMaxMatchable); float tot2 = d6 * d6 + f6 * f6; System.out.format( "segIdx=%d oct1=%d oct2=%d d6=%.2f f6=%.2f sd6=%.2f (rot=%.2f, s=%.2f)\n", segIdx, octave1, octave2, d6, f6, tot2, params.getRotationInDegrees(), params.getScale()); costs2.add(tot2); } int n = costs2.size(); assert(n == results.size()); QuickSort.sortBy1stArg(costs2, sortedDataIndexes); List<CorrespondenceList> output = new ArrayList<CorrespondenceList>(); for (int i = 0; i < sortedDataIndexes.size(); ++i) { int key = sortedDataIndexes.get(i); output.add(results.get(key)); } return output; } private void calcMeanAndSubtr(float[] a, int count) { double sum = 0; for (int i = 0; i < count; ++i) { sum += a[i]; } float avg = (float)sum/(float)count; for (int i = 0; i < count; ++i) { a[i] -= avg; } } private static class PObject { final PartialShapeMatcher.Result r; final PairIntArray bounds1; final PairIntArray bounds2; final float scale1; final float scale2; public PObject(PartialShapeMatcher.Result result, PairIntArray b1, PairIntArray b2, float s1, float s2) { r = result; bounds1 = b1; bounds2 = b2; scale1 = s1; scale2 = s2; } } private static class CObject implements Comparable<CObject> { final double cost; final CorrespondenceList cCor; final PairIntArray transformedTemplate; public CObject(double cost, CorrespondenceList cL, PairIntArray templTr) { this.cost = cost; this.cCor = cL; this.transformedTemplate = templTr; } @Override public int compareTo(CObject other) { if (cost < other.cost) { return -1; } else if (cost > other.cost) { return 1; } else { int n1 = cCor.getPoints1().size(); int n2 = other.cCor.getPoints1().size(); if (n1 > n2) { return -1; } else if (n1 < n2) { return 1; } } return 0; } } private static class CObject4 implements Comparable<CObject4> { final double cost; final TransformationParameters params; final QuadInt q; public CObject4(double sum, TransformationParameters params, QuadInt q) { this.cost = sum; this.q = q; this.params = params; } @Override public int compareTo(CObject4 other) { if (cost < other.cost) { return -1; } else if (cost > other.cost) { return 1; } return 0; } } private static class CObject3 implements Comparable<CObject3> { final double cost; final double costDesc; final double costDist; final double costCount; final int index; final PairInt[] m1; final PairInt[] m2; final double sumPatch; final TransformationParameters params; QuadInt q; int keypointCount; public CObject3(CObject2 cObject2, double sum, double sumPatch, TransformationParameters params) { this.sumPatch = sumPatch; this.cost = sum; this.costDesc = cObject2.costDesc; this.costDist = cObject2.costDist; this.costCount = cObject2.costCount; this.index = cObject2.index; this.m1 = cObject2.m1; this.m2 = cObject2.m2; this.params = params; } @Override public int compareTo(CObject3 other) { if (cost < other.cost) { return -1; } else if (cost > other.cost) { return 1; } return 0; } } private static class CObject2 implements Comparable<CObject2> { final double cost; final double costDesc; final double costDist; final double costCount; final int index; final PairInt[] m1; final PairInt[] m2; public CObject2(int index, double cost, double costDesc, double costDist, double costCount, PairInt[] matched1, PairInt[] matched2) { this.cost = cost; this.index = index; this.m1 = matched1; this.m2 = matched2; this.costDesc = costDesc; this.costDist = costDist; this.costCount = costCount; } @Override public int compareTo(CObject2 other) { if (cost < other.cost) { return -1; } else if (cost > other.cost) { return 1; } return 0; } } private static void debugPlot(int i, int j, FixedSizeSortedVector<CObject> vec, TwoDFloatArray pyr1, TwoDFloatArray pyr2, float s1, float s2) { Image img1 = convertToImage(pyr1); Image img2 = convertToImage(pyr2); try { CorrespondenceList cor = vec.getArray()[0].cCor; Image img1Cp = img1.copyImage(); Image img2Cp = img2.copyImage(); CorrespondencePlotter plotter = new CorrespondencePlotter( img1Cp, img2Cp); for (int ii = 0; ii < cor.getPoints1().size(); ++ii) { PairInt p1 = cor.getPoints1().get(ii); PairInt p2 = cor.getPoints2().get(ii); int x1 = Math.round(p1.getX() / s1); int y1 = Math.round(p1.getY() / s1); int x2 = Math.round(p2.getX() / s2); int y2 = Math.round(p2.getY() / s2); plotter.drawLineInAlternatingColors(x1, y1, x2, y2, 0); } String strI = Integer.toString(i); while (strI.length() < 3) { strI = "0" + strI; } String strJ = Integer.toString(j); while (strJ.length() < 3) { strJ = "0" + strJ; } String str = strI + "_" + strJ + "_"; plotter.writeImage("_MATCH_" + str); } catch (Exception e) { } } private static void debugPlot2(int i, int j, FixedSizeSortedVector<CObject3> vec, TwoDFloatArray pyr1, TwoDFloatArray pyr2, float s1, float s2) { Image img1 = convertToImage(pyr1); Image img2 = convertToImage(pyr2); try { PairInt[] m1 = vec.getArray()[0].m1; PairInt[] m2 = vec.getArray()[0].m2; Image img1Cp = img1.copyImage(); Image img2Cp = img2.copyImage(); CorrespondencePlotter plotter = new CorrespondencePlotter( img1Cp, img2Cp); for (int ii = 0; ii < m1.length; ++ii) { PairInt p1 = m1[ii]; PairInt p2 = m2[ii]; int x1 = Math.round(p1.getX() / s1); int y1 = Math.round(p1.getY() / s1); int x2 = Math.round(p2.getX() / s2); int y2 = Math.round(p2.getY() / s2); plotter.drawLineInAlternatingColors(x1, y1, x2, y2, 0); } String strI = Integer.toString(i); while (strI.length() < 3) { strI = "0" + strI; } String strJ = Integer.toString(j); while (strJ.length() < 3) { strJ = "0" + strJ; } String str = strI + "_" + strJ + "_"; plotter.writeImage("_MATCH_" + str); } catch (Exception e) { } } private static void debugPlot(int i, int j, FixedSizeSortedVector<CObject> vecD, FixedSizeSortedVector<CObject> vecF, TwoDFloatArray pyr1, TwoDFloatArray pyr2, float s1, float s2) { Image img1 = convertToImage(pyr1); Image img2 = convertToImage(pyr2); try { for (int i0 = 0; i0 < 2; ++i0) { CorrespondenceList cor = null; if (i0 == 0) { cor = vecD.getArray()[0].cCor; } else { cor = vecF.getArray()[0].cCor; } Image img1Cp = img1.copyImage(); Image img2Cp = img2.copyImage(); CorrespondencePlotter plotter = new CorrespondencePlotter( img1Cp, img2Cp); for (int ii = 0; ii < cor.getPoints1().size(); ++ii) { PairInt p1 = cor.getPoints1().get(ii); PairInt p2 = cor.getPoints2().get(ii); int x1 = Math.round(p1.getX()/s1); int y1 = Math.round(p1.getY()/s1); int x2 = Math.round(p2.getX()/s2); int y2 = Math.round(p2.getY()/s2); plotter.drawLineInAlternatingColors(x1, y1, x2, y2, 0); } String strI = Integer.toString(i); while (strI.length() < 3) { strI = "0" + strI; } String strJ = Integer.toString(j); while (strJ.length() < 3) { strJ = "0" + strJ; } String str = strI + "_" + strJ + "_"; if (i0 == 0) { str = str + "factor"; } else { str = str + "divisor"; } plotter.writeImage("_MATCH_" + str); } } catch(Exception e) {} } }