answer
stringlengths
17
10.2M
package org.jgroups.protocols.pbcast; import org.jgroups.*; import org.jgroups.protocols.PingData; import org.jgroups.util.Promise; import org.jgroups.util.Util; import org.jgroups.util.Digest; import org.jgroups.util.MutableDigest; import java.util.*; /** * Client part of GMS. Whenever a new member wants to join a group, it starts in the CLIENT role. * No multicasts to the group will be received and processed until the member has been joined and * turned into a SERVER (either coordinator or participant, mostly just participant). This class * only implements <code>Join</code> (called by clients who want to join a certain group, and * <code>ViewChange</code> which is called by the coordinator that was contacted by this client, to * tell the client what its initial membership is. * @author Bela Ban * @version $Revision: 1.78 $ */ public class ClientGmsImpl extends GmsImpl { private final Promise<JoinRsp> join_promise=new Promise<JoinRsp>(); public ClientGmsImpl(GMS g) { super(g); } public void init() throws Exception { super.init(); join_promise.reset(); } public void join(Address address,boolean useFlushIfPresent) { joinInternal(address, false,useFlushIfPresent); } public void joinWithStateTransfer(Address local_addr, boolean useFlushIfPresent) { joinInternal(local_addr,true,useFlushIfPresent); } /** * Joins this process to a group. Determines the coordinator and sends a * unicast handleJoin() message to it. The coordinator returns a JoinRsp and * then broadcasts the new view, which contains a message digest and the * current membership (including the joiner). The joiner is then supposed to * install the new view and the digest and starts accepting mcast messages. * Previous mcast messages were discarded (this is done in PBCAST). * <p> * If successful, impl is changed to an instance of ParticipantGmsImpl. * Otherwise, we continue trying to send join() messages to the coordinator, * until we succeed (or there is no member in the group. In this case, we * create our own singleton group). * <p> * When GMS.disable_initial_coord is set to true, then we won't become * coordinator on receiving an initial membership of 0, but instead will * retry (forever) until we get an initial membership of > 0. * * @param mbr Our own address (assigned through SET_LOCAL_ADDRESS) */ private void joinInternal(Address mbr, boolean joinWithStateTransfer,boolean useFlushIfPresent) { Address coord=null; JoinRsp rsp=null; View tmp_view; leaving=false; join_promise.reset(); while(!leaving) { if(rsp == null && !join_promise.hasResult()) { // null responses means that the discovery was cancelled List<PingData> responses=findInitialMembers(join_promise); if (responses == null) { // gray: we've seen this NPE here. not sure of the cases but wanted to add more debugging info throw new NullPointerException("responses returned by findInitialMembers for " + join_promise + " is null"); } /*// Sept 2008 (bela): break if we got a belated JoinRsp (https://jira.jboss.org/jira/browse/JGRP-687) if(join_promise.hasResult()) { rsp=join_promise.getResult(gms.join_timeout); // clears the result continue; }*/ if(log.isDebugEnabled()) log.debug("initial_mbrs are " + responses); if(responses == null || responses.isEmpty()) { if(gms.disable_initial_coord) { if(log.isTraceEnabled()) log.trace("received an initial membership of 0, but cannot become coordinator " + "(disable_initial_coord=true), will retry fetching the initial membership"); continue; } if(log.isDebugEnabled()) log.debug("no initial members discovered: creating group as first member"); becomeSingletonMember(mbr); return; } coord=determineCoord(responses); if(coord == null) { // e.g. because we have all clients only if(gms.handle_concurrent_startup == false) { if(log.isTraceEnabled()) log.trace("handle_concurrent_startup is false; ignoring responses of initial clients"); becomeSingletonMember(mbr); return; } if(log.isTraceEnabled()) log.trace("could not determine coordinator from responses " + responses); // so the member to become singleton member (and thus coord) is the first of all clients Set<Address> clients=new TreeSet<Address>(); // sorted clients.add(mbr); // add myself again (was removed by findInitialMembers()) for(PingData response: responses) { Address client_addr=response.getAddress(); if(client_addr != null) clients.add(client_addr); } if(log.isTraceEnabled()) log.trace("clients to choose new coord from are: " + clients); Address new_coord=clients.iterator().next(); if(new_coord.equals(mbr)) { if(log.isTraceEnabled()) log.trace("I (" + mbr + ") am the first of the clients, will become coordinator"); becomeSingletonMember(mbr); return; } else { if(log.isTraceEnabled()) log.trace("I (" + mbr + ") am not the first of the clients, waiting for another client to become coordinator"); Util.sleep(500); } continue; } if(log.isDebugEnabled()) log.debug("sending handleJoin(" + mbr + ") to " + coord); sendJoinMessage(coord, mbr, joinWithStateTransfer,useFlushIfPresent); } try { if(rsp == null) rsp=join_promise.getResult(gms.join_timeout); if(rsp == null) { if(log.isWarnEnabled()) log.warn("join(" + mbr + ") sent to " + coord + " timed out (after " + gms.join_timeout + " ms), retrying"); continue; } // 1. check whether JOIN was rejected String failure=rsp.getFailReason(); if(failure != null) throw new SecurityException(failure); // 2. Install digest if(rsp.getDigest() == null || rsp.getDigest().getSenders() == null) { if(log.isWarnEnabled()) log.warn("digest response has no senders: digest=" + rsp.getDigest()); rsp=null; // just skip the response we guess continue; } MutableDigest tmp_digest=new MutableDigest(rsp.getDigest()); tmp_view=rsp.getView(); if(tmp_view == null) { if(log.isErrorEnabled()) log.error("JoinRsp has a null view, skipping it"); rsp=null; } else { if(!tmp_digest.contains(gms.local_addr)) { throw new IllegalStateException("digest returned from " + coord + " with JOIN_RSP does not contain myself (" + gms.local_addr + "): join response: " + rsp); } tmp_digest.incrementHighestDeliveredSeqno(coord); // see doc/design/varia2.txt for details tmp_digest.seal(); gms.setDigest(tmp_digest); if(log.isDebugEnabled()) log.debug("[" + gms.local_addr + "]: JoinRsp=" + tmp_view + " [size=" + tmp_view.size() + "]\n\n"); if(!installView(tmp_view)) { if(log.isErrorEnabled()) log.error("view installation failed, retrying to join group"); rsp=null; continue; } // send VIEW_ACK to sender of view Message view_ack=new Message(coord, null, null); view_ack.setFlag(Message.OOB); GMS.GmsHeader tmphdr=new GMS.GmsHeader(GMS.GmsHeader.VIEW_ACK); view_ack.putHeader(gms.getId(), tmphdr); gms.getDownProtocol().down(new Event(Event.MSG, view_ack)); return; } } catch(SecurityException security_ex) { throw security_ex; } catch(IllegalArgumentException illegal_arg) { throw illegal_arg; } catch(Throwable e) { if(log.isDebugEnabled()) log.debug("exception=" + e + ", retrying", e); rsp=null; } } } @SuppressWarnings("unchecked") private List<PingData> findInitialMembers(Promise<JoinRsp> promise) { List<PingData> responses=(List<PingData>)gms.getDownProtocol().down(new Event(Event.FIND_INITIAL_MBRS, promise)); if(responses != null) { for(Iterator<PingData> iter=responses.iterator(); iter.hasNext();) { Address address=iter.next().getAddress(); if(address != null && address.equals(gms.local_addr)) iter.remove(); } } return responses; } public void leave(Address mbr) { leaving=true; wrongMethod("leave"); } public void handleJoinResponse(JoinRsp join_rsp) { join_promise.setResult(join_rsp); // will wake up join() method } /** * Called by join(). Installs the view returned by calling Coord.handleJoin() and * becomes coordinator. */ private boolean installView(View new_view) { Vector<Address> mems=new_view.getMembers(); if(log.isDebugEnabled()) log.debug("new_view=" + new_view); if(gms.local_addr == null || mems == null || !mems.contains(gms.local_addr)) { if(log.isErrorEnabled()) log.error("I (" + gms.local_addr + ") am not member of " + mems + ", will not install view"); return false; } gms.installView(new_view); gms.becomeParticipant(); gms.getUpProtocol().up(new Event(Event.BECOME_SERVER)); gms.getDownProtocol().down(new Event(Event.BECOME_SERVER)); return true; } void sendJoinMessage(Address coord, Address mbr,boolean joinWithTransfer, boolean useFlushIfPresent) { Message msg; GMS.GmsHeader hdr; msg=new Message(coord, null, null); msg.setFlag(Message.OOB); if(joinWithTransfer) hdr=new GMS.GmsHeader(GMS.GmsHeader.JOIN_REQ_WITH_STATE_TRANSFER, mbr,useFlushIfPresent); else hdr=new GMS.GmsHeader(GMS.GmsHeader.JOIN_REQ, mbr,useFlushIfPresent); msg.putHeader(gms.getId(), hdr); gms.getDownProtocol().down(new Event(Event.MSG, msg)); } /** The coordinator is determined by a majority vote. If there are an equal number of votes for more than 1 candidate, we determine the winner randomly. */ private Address determineCoord(List<PingData> mbrs) { int count, most_votes; Address winner=null, tmp; if(mbrs == null || mbrs.size() < 1) return null; Map<Address,Integer> votes=new HashMap<Address,Integer>(5); // count *all* the votes (unlike the 2000 election) for(PingData mbr:mbrs) { if(mbr.hasCoord()) { if(!votes.containsKey(mbr.getCoordAddress())) votes.put(mbr.getCoordAddress(), 1); else { count=votes.get(mbr.getCoordAddress()); votes.put(mbr.getCoordAddress(), count + 1); } } } // we have seen members say someone else is coordinator but they disagree for(PingData mbr:mbrs) { // remove members who don't agree with the election (Florida) if (votes.containsKey(mbr.getAddress()) && (!mbr.isCoord())) { votes.remove(mbr.getAddress()); } } if(votes.size() > 1) { if(log.isWarnEnabled()) log.warn("there was more than 1 candidate for coordinator: " + votes); } else { if(log.isDebugEnabled()) log.debug("election results: " + votes); } // determine who got the most votes most_votes=0; for(Map.Entry<Address,Integer> entry: votes.entrySet()) { tmp=entry.getKey(); count=entry.getValue(); if(count > most_votes) { winner=tmp; // fixed July 15 2003 (patch submitted by Darren Hobbs, patch-id=771418) most_votes=count; } } votes.clear(); return winner; } void becomeSingletonMember(Address mbr) { Digest initial_digest; ViewId view_id; Vector<Address> mbrs=new Vector<Address>(1); // set the initial digest (since I'm the first member) initial_digest=new Digest(gms.local_addr, 0, 0); // initial seqno mcast by me will be 1 (highest seen +1) gms.setDigest(initial_digest); view_id=new ViewId(mbr); // create singleton view with mbr as only member mbrs.addElement(mbr); View new_view=new View(view_id, mbrs); gms.up(new Event(Event.PREPARE_VIEW,new_view)); gms.down(new Event(Event.PREPARE_VIEW,new_view)); gms.installView(new_view); gms.becomeCoordinator(); // not really necessary - installView() should do it gms.getUpProtocol().up(new Event(Event.BECOME_SERVER)); gms.getDownProtocol().down(new Event(Event.BECOME_SERVER)); if(log.isDebugEnabled()) log.debug("created group (first member). My view is " + gms.view_id + ", impl is " + gms.getImpl().getClass().getName()); } }
package org.openchaos.android.fooping; import org.openchaos.android.fooping.service.PingService; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; public class BootReceiver extends BroadcastReceiver { private static final String tag = "BootReceiver"; @Override public void onReceive(Context context, Intent intent) { Log.d(tag, "onReceive()"); // Note: Intent filters should not be considered a security feature // ACTION_BOOT_COMPLETED is a protected intent and should be safe enough if (intent.getAction() != Intent.ACTION_BOOT_COMPLETED) { Log.w(tag, "Invalid intent!"); return; } Context appContext = context.getApplicationContext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext); if (prefs.getBoolean("StartOnBoot", false)) { long updateInterval = Long.valueOf(prefs.getString("UpdateInterval", "-1")); if (updateInterval > 0) { Log.d(tag, "Starting alarm"); ((AlarmManager)context.getSystemService(Context.ALARM_SERVICE)) .setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, updateInterval * 1000, updateInterval * 1000, PendingIntent.getService(appContext, 0, new Intent(appContext, PingService.class), PendingIntent.FLAG_CANCEL_CURRENT)); } } } }
package org.shotlogger.example; import org.shotlogger.Log; /** * * @author shotbygun */ public class RandomShitGenerator implements Runnable { int loops, sleep, i; String name; public RandomShitGenerator(String name, int loops, int sleep) { this.name = name; this.loops = loops; this.sleep = sleep; i = 0; } @Override public void run() { String randomText; while(i++ < loops) { try { //Thread.sleep(sleep); try { //randomText = RandomStringUtils.random(100, true, true); randomText = Long.toHexString(System.currentTimeMillis()); throw new Exception(randomText); } catch (Exception ex) { Log.log("testerRandomData", Log.DEBUG, getClass().getSimpleName(), "test", ex); } } catch (Exception uex) { Log.log(name, Log.CRITICAL, getClass().getSimpleName(), "unexpected exception", uex); } } System.out.println(name + " done"); } public void start() { Thread thread = new Thread(this); thread.setPriority(3); thread.setName(name); thread.setDaemon(true); thread.start(); } }
package org.vitrivr.cineast.core.util.dsp.fft; import org.vitrivr.cineast.core.util.dsp.fft.windows.WindowFunction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * @author rgasser * @version 1.0 * @created 04.02.17 */ public class STFT { /** Sampling rate with which the samples have been sampled. */ private final float samplingrate; /** Window function to use when calculating the FFT. */ private final WindowFunction windowFunction; /** Size of the FFT window. Must be a power of 2 (e.g. 512, 1024, 2048, 4096). */ private final int windowsize; /** Overlap in samples between two subsequent windows. */ private final int overlap; /** Width of the STFT (i.e. the number of timepoints or FFT's). */ private int width; /** Height of the STFT (i.e. the number of frequency bins per FFT). */ private int height; /** Frequency labels in ascending order (for all FFTs). */ private final float[] frequencies; /** Time labels in ascending order (for each entry in the stft list). */ private final float[] time; /** List containing one FFT entry per timepoint. Same order as time[] */ private final List<FFT> stft; /** * * @param windowsize * @param overlap * @param function * @param samplingrate */ public STFT(int windowsize, int overlap, WindowFunction function, float samplingrate) { /* Make sure that the windowsize is a power of two. */ if (!FFTUtil.isPowerOf2(windowsize)) throw new IllegalArgumentException("The provided window size of " + windowsize + " is not a power of two!"); /* Store the local variables. */ this.samplingrate = samplingrate; /* Store the window size and window function. */ this.windowFunction = function; this.windowsize = windowsize; this.overlap = overlap; this.height = windowsize/2; /* Prepares empty array for STFT. */ this.stft = new ArrayList<>(); this.frequencies = FFTUtil.binCenterFrequencies(windowsize, samplingrate); this.time = FFTUtil.time(this.width, windowsize, samplingrate); } /** * Performs a forward fourier transformation on the provided, real valued data and appends it to the FFT. The caller * of this function must make sure, that the data conforms to the properties specified upon construction of this class. * Otherwise, some results may be unexpected! * * <strong>Important: </strong>Every call to forward() appends a time-local DFT to the current STFT. The existing * data will be kept. * * @param samples */ public void forward(double[] samples) { /* Derive properties from the available information. */ this.width += (int) Math.ceil((float) samples.length / (windowsize - overlap)); /* Outer-loop: Create a sliding window and move it across the samples. * * For each iteration, forward the FFT for the samples in the Window and add it to the list. */ double window[] = new double[windowsize]; for (int i = 0; i < this.width; i++) { int start = i * (windowsize - overlap); int end = start + windowsize; /* Copy the samples into the window. */ if (end <= samples.length) { System.arraycopy(samples, start, window, 0, windowsize); } else { System.arraycopy(samples, start, window, 0, samples.length - start); Arrays.fill(window, samples.length - start + 1, window.length - 1, 0.0); } /* Create Forward FFT entries for each window. */ FFT fft = new FFT(); fft.forward(window, this.samplingrate, this.windowFunction); this.stft.add(fft); } } /** * Assembles a list of power-spectra (one per FFT contained in this STFT) * and returns it. * * @return List of power-spectra */ public List<Spectrum> getPowerSpectrum() { List<Spectrum> spectrum = new ArrayList<>(this.stft.size()); for (FFT fft : this.stft) { spectrum.add(fft.getPowerSpectrum()); } return spectrum; } /** * Assembles a list of magnitude-spectra (one per FFT contained in this STFT) * and returns it. * * @return List of magnitude-spectra */ public List<Spectrum> getMagnitudeSpectrum() { List<Spectrum> spectrum = new ArrayList<>(this.stft.size()); for (FFT fft : this.stft) { spectrum.add(fft.getMagnitudeSpectrum()); } return spectrum; } /** * Getter for frequency bin labels. * * @return */ public final float[] getFrequencies() { return frequencies; } /** * Returns the number of frequency-bins. */ public final int getNumberOfBins() { return this.frequencies.length; } /** * Returns the size / width of an individual frequency bin. * * @return */ public final float getBinSize() { return (this.samplingrate/this.windowsize); } /** * Getter for time labels. * * @return */ public final float[] getTime() { return time; } /** * Getter for STFT. * * @return */ public final List<FFT> getStft() { return Collections.unmodifiableList(this.stft); } /** * Getter for window-size. * * @return */ public final int getWindowsize() { return this.windowsize; } /** * Getter for overlap value. * * @return */ public int getOverlap() { return this.overlap; } /** * Getter for sampling rate. * * @return */ public final float getSamplingrate() { return this.samplingrate; } /** * * @return */ public WindowFunction getWindowFunction() { return windowFunction; } /** * * @return */ public int getWidth() { return this.width; } /** * * @return */ public int getHeight() { return this.height; } }
package jade.core.messaging; //#MIDP_EXCLUDE_FILE import java.util.Date; import jade.domain.FIPAAgentManagement.Envelope; import jade.core.VerticalCommand; import jade.core.AgentContainer; import jade.core.Filter; import jade.core.AID; import jade.lang.acl.ACLMessage; import jade.lang.acl.ACLCodec; import jade.lang.acl.StringACLCodec; import jade.lang.acl.LEAPACLCodec; import jade.util.leap.Iterator; import jade.util.leap.Map; /** * Class that filters outgoing commands related to the encoding of ACL messages * * @author Jerome Picault - Motorola Labs * @author Nicolas Lhuillier - Motorola Labs * @version $Date$ $Revision$ */ public class OutgoingEncodingFilter extends Filter { private Map messageEncodings; private AgentContainer myAgentContainer; private MessagingService myService; public OutgoingEncodingFilter(Map m, AgentContainer ac, MessagingService ms){ messageEncodings = m; myAgentContainer = ac; myService = ms; setPreferredPosition(10); } /** * Receive a command object for processing. * * @param cmd A <code>VerticalCommand</code> describing what operation has * been requested from previous layers (that can be the actual * prime source of the command or previous filters in the chain). */ public boolean accept(VerticalCommand cmd) { String name = cmd.getName(); Object[] params = cmd.getParams(); // The awaited command should contain an ACLMessage if(name.equals(MessagingSlice.SEND_MESSAGE)) { // DEBUG //System.out.println("-- Filtering a SEND_MESSAGE command (outgoing)--"); GenericMessage gmsg = (GenericMessage)params[1]; AID sender = (AID) params[0]; AID receiver = (AID) params[2]; ACLMessage msg = gmsg.getACLMessage(); // Set the sender unless already set try { if (msg.getSender().getName().length() < 1) msg.setSender(sender); } catch (NullPointerException e) { msg.setSender(sender); } //DEBUG //System.out.println(gmsg); // check if the agent is on the same container or not synchronized (myAgentContainer){ if (myAgentContainer.acquireLocalAgent(receiver)!=null){ // local container myAgentContainer.releaseLocalAgent(receiver); // message should not be encoded // command is not modified //DEBUG // System.out.println("[EncodingService] Local message"); return true; } else { // add necessary fields to the envelope prepareEnvelope(msg, receiver, gmsg); } } // in both cases (intra and inter), encode the message // using the specified encoding try{ byte[] payload = encodeMessage(msg); // DEBUG // System.out.println("[EncodingService] msg encoded."); Envelope env = msg.getEnvelope(); if (env!=null) env.setPayloadLength(new Long(payload.length)); // update the ACLMessage: some information is kept because it is // required in other services ((GenericMessage)cmd.getParams()[1]).update(msg,env,payload); } catch (MessagingService.UnknownACLEncodingException ee){ //FIXME ee.printStackTrace(); } } return true; } /** * This method puts into the envelope the missing information */ public void prepareEnvelope(ACLMessage msg, AID receiver, GenericMessage gmsg) { Envelope env = msg.getEnvelope(); String defaultRepresentation = null; if (myService.livesHere(receiver)) { // The agent lives in the platform if (env == null) { // Nothing to do return; } else { defaultRepresentation = LEAPACLCodec.NAME; } } else { gmsg.setForeignReceiver(true); if (env == null) { // The agent lives outside the platform msg.setDefaultEnvelope(); env = msg.getEnvelope(); } else { defaultRepresentation = StringACLCodec.NAME; } } // If no ACL representation is found, then default one (LEAP for // local receivers, String for foreign receivers) String rep = env.getAclRepresentation(); if(rep == null) env.setAclRepresentation(defaultRepresentation); // If no 'to' slot is present, copy the 'to' slot from the // 'receiver' slot of the ACL message Iterator itTo = env.getAllTo(); if(!itTo.hasNext()) { Iterator itReceiver = msg.getAllReceiver(); while(itReceiver.hasNext()) env.addTo((AID)itReceiver.next()); } // If no 'from' slot is present, copy the 'from' slot from the // 'sender' slot of the ACL message AID from = env.getFrom(); if(from == null) { env.setFrom(msg.getSender()); } // Set the 'date' slot to 'now' if not present already Date d = env.getDate(); if(d == null) env.setDate(new Date()); // Write 'intended-receiver' slot as per 'FIPA Agent Message // Transport Service Specification': this ACC splits all // multicasts, since JADE has already split them in the // handleSend() method env.clearAllIntendedReceiver(); env.addIntendedReceiver(receiver); Long payloadLength = env.getPayloadLength(); if(payloadLength == null) env.setPayloadLength(new Long(-1)); } /** * Encodes an ACL message according to the acl-representation described * in the envelope. If there is no explicit acl-representation in the * envelope, uses the String representation * @param msg the message to be encoded * @return the payload of the message */ public byte[] encodeMessage(ACLMessage msg) throws MessagingService.UnknownACLEncodingException{ Envelope env = msg.getEnvelope(); String enc = (env != null ? env.getAclRepresentation() : LEAPACLCodec.NAME); if(enc != null) { // A Codec was selected ACLCodec codec =(ACLCodec)messageEncodings.get(enc.toLowerCase()); if(codec!=null) { // Supported Codec // FIXME: should verify that the receivers supports this Codec String charset; if ((env == null) || ((charset = env.getPayloadEncoding()) == null)) { charset = ACLCodec.DEFAULT_CHARSET; } return codec.encode(msg,charset); } else { // Unsupported Codec //FIXME: find the best according to the supported, the MTP (and the receivers Codec) throw new MessagingService.UnknownACLEncodingException("Unknown ACL encoding: " + enc + "."); } } else { // no codec indicated. //FIXME: find the better according to the supported Codec, the MTP (and the receiver codec) throw new MessagingService.UnknownACLEncodingException("No ACL encoding set."); } } } // End of EncodingOutgoingFilter class
package fr.jayasoft.ivy.util; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; import fr.jayasoft.ivy.Artifact; import fr.jayasoft.ivy.ArtifactOrigin; import fr.jayasoft.ivy.DefaultArtifact; import fr.jayasoft.ivy.Ivy; import fr.jayasoft.ivy.IvyContext; import fr.jayasoft.ivy.ModuleRevisionId; /** * @author x.hanin * @author Maarten Coene (for the optional part management) */ public class IvyPatternHelper { public static final String CONF_KEY = "conf"; public static final String TYPE_KEY = "type"; public static final String EXT_KEY = "ext"; public static final String ARTIFACT_KEY = "artifact"; public static final String REVISION_KEY = "revision"; public static final String MODULE_KEY = "module"; public static final String ORGANISATION_KEY = "organisation"; public static final String ORGANISATION_KEY2 = "organization"; public static final String ORIGINAL_ARTIFACTNAME_KEY = "originalname"; private static final Pattern PARAM_PATTERN = Pattern.compile("\\@\\{(.*?)\\}"); private static final Pattern VAR_PATTERN = Pattern.compile("\\$\\{(.*?)\\}"); public static String substitute(String pattern, ModuleRevisionId moduleRevision) { return substitute(pattern, moduleRevision.getOrganisation(), moduleRevision.getName(), moduleRevision.getRevision(), "ivy", "ivy", "xml", null, moduleRevision.getAttributes()); } public static String substitute(String pattern, ModuleRevisionId moduleRevision, String artifact, String type, String ext) { return substitute(pattern, moduleRevision, new DefaultArtifact(moduleRevision, null, artifact, type, ext), null); } public static String substitute(String pattern, Artifact artifact) { return substitute(pattern, artifact, (String) null); } public static String substitute(String pattern, Artifact artifact, ArtifactOrigin origin) { return substitute(pattern, artifact.getModuleRevisionId(), artifact, null, origin); } public static String substitute(String pattern, Artifact artifact, String conf) { return substitute(pattern, artifact.getModuleRevisionId(), artifact, conf); } public static String substitute(String pattern, ModuleRevisionId mrid, Artifact artifact) { return substitute(pattern, mrid, artifact, null); } public static String substitute(String pattern, ModuleRevisionId mrid, Artifact artifact, String conf) { return substitute(pattern, mrid, artifact, conf, null); } public static String substitute(String pattern, ModuleRevisionId mrid, Artifact artifact, String conf, ArtifactOrigin origin) { Map attributes = new HashMap(); attributes.putAll(mrid.getAttributes()); attributes.putAll(artifact.getAttributes()); return substitute(pattern, mrid.getOrganisation(), mrid.getName(), mrid.getRevision(), artifact.getName(), artifact.getType(), artifact.getExt(), conf, origin, attributes); } public static String substitute(String pattern, String org, String module, String revision, String artifact, String type, String ext) { return substitute(pattern, org, module, revision, artifact, type, ext, null); } public static String substitute(String pattern, String org, String module, String revision, String artifact, String type, String ext, String conf) { return substitute(pattern, org, module, revision, artifact, type, ext, conf, null); } public static String substitute(String pattern, String org, String module, String revision, String artifact, String type, String ext, String conf, Map extraAttributes) { return substitute(pattern, org, module, revision, artifact, type, ext, conf, null, extraAttributes); } public static String substitute(String pattern, String org, String module, String revision, String artifact, String type, String ext, String conf, ArtifactOrigin origin, Map extraAttributes) { Map tokens = new HashMap(extraAttributes == null ? Collections.EMPTY_MAP : extraAttributes); tokens.put(ORGANISATION_KEY, org==null?"":org); tokens.put(ORGANISATION_KEY2, org==null?"":org); tokens.put(MODULE_KEY, module==null?"":module); tokens.put(REVISION_KEY, revision==null?"":revision); tokens.put(ARTIFACT_KEY, artifact==null?module:artifact); tokens.put(TYPE_KEY, type==null?"jar":type); tokens.put(EXT_KEY, ext==null?"jar":ext); tokens.put(CONF_KEY, conf==null?"default":conf); tokens.put(ORIGINAL_ARTIFACTNAME_KEY, origin==null?new OriginalArtifactNameValue(org, module, revision, artifact, type, ext):new OriginalArtifactNameValue(origin)); return substituteTokens(pattern, tokens); } public static String substitute(String pattern, Map variables, Map tokens) { return substituteTokens(substituteVariables(pattern, variables), tokens); } public static String substituteVariables(String pattern, Map variables) { return substituteVariables(pattern, variables, new Stack()); } private static String substituteVariables(String pattern, Map variables, Stack substituting) { // if you supply null, null is what you get if (pattern == null) { return null; } Matcher m = VAR_PATTERN.matcher(pattern); StringBuffer sb = new StringBuffer(); while (m.find()) { String var = m.group(1); String val = (String)variables.get(var); if (val != null) { int index; if ((index = substituting.indexOf(var)) != -1) { List cycle = new ArrayList(substituting.subList(index, substituting.size())); cycle.add(var); throw new IllegalArgumentException("cyclic variable definition: cycle = "+cycle); } substituting.push(var); val = substituteVariables(val, variables, substituting); substituting.pop(); } else { val = m.group(); } m.appendReplacement(sb, val.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\$", "\\\\\\$")); } m.appendTail(sb); return sb.toString(); } public static String substituteTokens(String pattern, Map tokens) { StringBuffer buffer = new StringBuffer(); char[] chars = pattern.toCharArray(); StringBuffer optionalPart = null; StringBuffer tokenBuffer = null; boolean insideOptionalPart = false; boolean insideToken = false; boolean tokenHadValue = false; for (int i = 0; i < chars.length; i++) { switch (chars[i]) { case '(': if (insideOptionalPart) { throw new IllegalArgumentException("invalid start of optional part at position " + i + " in pattern " + pattern); } optionalPart = new StringBuffer(); insideOptionalPart = true; tokenHadValue = false; break; case ')': if (!insideOptionalPart || insideToken) { throw new IllegalArgumentException("invalid end of optional part at position " + i + " in pattern " + pattern); } if (tokenHadValue) { buffer.append(optionalPart.toString()); } insideOptionalPart = false; break; case '[': if (insideToken) { throw new IllegalArgumentException("invalid start of token at position " + i + " in pattern " + pattern); } tokenBuffer = new StringBuffer(); insideToken = true; break; case ']': if (!insideToken) { throw new IllegalArgumentException("invalid end of token at position " + i + " in pattern " + pattern); } String token = tokenBuffer.toString(); Object tokenValue = tokens.get(token); String value = (tokenValue == null) ? null : tokenValue.toString(); if (insideOptionalPart) { tokenHadValue = (value != null) && (value.length() > 0); optionalPart.append(value); } else { if (value == null) { // the token wasn't set, it's kept as is value = "["+token+"]"; } buffer.append(value); } insideToken = false; break; default: if (insideToken) { tokenBuffer.append(chars[i]); } else if (insideOptionalPart) { optionalPart.append(chars[i]); } else { buffer.append(chars[i]); } break; } } if (insideToken) { throw new IllegalArgumentException("last token hasn't been closed in pattern " + pattern); } if (insideOptionalPart) { throw new IllegalArgumentException("optional part hasn't been closed in pattern " + pattern); } return buffer.toString(); } public static String substituteVariable(String pattern, String variable, String value) { StringBuffer buf = new StringBuffer(pattern); substituteVariable(buf, variable, value); return buf.toString(); } public static void substituteVariable(StringBuffer buf, String variable, String value) { String from = "${"+variable+"}"; int fromLength = from.length(); for (int index = buf.indexOf(from); index != -1; index = buf.indexOf(from, index)) { buf.replace(index, index + fromLength, value); } } public static String substituteToken(String pattern, String token, String value) { StringBuffer buf = new StringBuffer(pattern); substituteToken(buf, token, value); return buf.toString(); } public static void substituteToken(StringBuffer buf, String token, String value) { String from = getTokenString(token); int fromLength = from.length(); for (int index = buf.indexOf(from); index != -1; index = buf.indexOf(from, index)) { buf.replace(index, index + fromLength, value); } } public static String getTokenString(String token) { return "["+token+"]"; } public static String substituteParams(String pattern, Map params) { return substituteParams(pattern, params, new Stack()); } private static String substituteParams(String pattern, Map params, Stack substituting) { //TODO : refactor this with substituteVariables // if you supply null, null is what you get if (pattern == null) { return null; } Matcher m = PARAM_PATTERN.matcher(pattern); StringBuffer sb = new StringBuffer(); while (m.find()) { String var = m.group(1); String val = (String)params.get(var); if (val != null) { int index; if ((index = substituting.indexOf(var)) != -1) { List cycle = new ArrayList(substituting.subList(index, substituting.size())); cycle.add(var); throw new IllegalArgumentException("cyclic param definition: cycle = "+cycle); } substituting.push(var); val = substituteVariables(val, params, substituting); substituting.pop(); } else { val = m.group(); } m.appendReplacement(sb, val.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\@", "\\\\\\@")); } m.appendTail(sb); return sb.toString(); } public static void main(String[] args) { String pattern = "[organisation]/[module]/build/archives/[type]s/[artifact]-[revision].[ext]"; System.out.println("pattern= "+pattern); System.out.println("resolved= "+substitute(pattern, "jayasoft", "Test", "1.0", "test", "jar", "jar")); Map variables = new HashMap(); variables.put("test", "mytest"); variables.put("test2", "${test}2"); pattern = "${test} ${test2} ${nothing}"; System.out.println("pattern= "+pattern); System.out.println("resolved= "+substituteVariables(pattern, variables)); } /** * This class returns the original name of the artifact 'on demand'. This is done to avoid * having to read the cached datafile containing the original location of the artifact if we * don't need it. */ private static class OriginalArtifactNameValue { // module properties private String org; private String moduleName; private String revision; // artifact properties private String artifactName; private String artifactType; private String artifactExt; // cached origin; private ArtifactOrigin origin; public OriginalArtifactNameValue(String org, String moduleName, String revision, String artifactName, String artifactType, String artifactExt) { this.org = org; this.moduleName = moduleName; this.revision = revision; this.artifactName = artifactName; this.artifactType = artifactType; this.artifactExt = artifactExt; } /** * @param origin */ public OriginalArtifactNameValue(ArtifactOrigin origin) { this.origin = origin; } // Called by substituteTokens only if the original artifact name is needed public String toString() { if (origin == null) { ModuleRevisionId revId = ModuleRevisionId.newInstance(org, moduleName, revision); Artifact artifact = new DefaultArtifact(revId, null, artifactName, artifactType, artifactExt); Ivy ivy = IvyContext.getContext().getIvy(); File cache = IvyContext.getContext().getCache(); origin = ivy.getSavedArtifactOrigin(cache, artifact); if (origin == null) { Message.debug("no artifact origin found for "+artifact+" in "+cache); return null; } } // we assume that the original filename is the last part of the original file location String location = origin.getLocation(); int lastPathIndex = location.lastIndexOf('/'); if (lastPathIndex == -1) { lastPathIndex = location.lastIndexOf('\\'); } int lastColonIndex = location.lastIndexOf('.'); return location.substring(lastPathIndex + 1, lastColonIndex); } } }
package org.apache.lucene.search; import java.io.IOException; import java.util.Vector; import org.apache.lucene.index.IndexReader; /** A Query that matches documents matching boolean combinations of other queries, typically {@link TermQuery}s or {@link PhraseQuery}s. */ public class BooleanQuery extends Query { private Vector clauses = new Vector(); /** Constructs an empty boolean query. */ public BooleanQuery() {} /** Adds a clause to a boolean query. Clauses may be: <ul> <li><code>required</code> which means that documents which <i>do not</i> match this sub-query will <i>not</i> match the boolean query; <li><code>prohibited</code> which means that documents which <i>do</i> match this sub-query will <i>not</i> match the boolean query; or <li>neither, in which case matched documents are neither prohibited from nor required to match the sub-query. </ul> It is an error to specify a clause as both <code>required</code> and <code>prohibited</code>. */ public void add(Query query, boolean required, boolean prohibited) { clauses.addElement(new BooleanClause(query, required, prohibited)); } /** Adds a clause to a boolean query. */ public void add(BooleanClause clause) { clauses.addElement(clause); } /** Returns the set of clauses in this query. */ public BooleanClause[] getClauses() { return (BooleanClause[])clauses.toArray(new BooleanClause[0]); } private class BooleanWeight implements Weight { private Searcher searcher; private float norm; private Vector weights = new Vector(); public BooleanWeight(Searcher searcher) { this.searcher = searcher; for (int i = 0 ; i < clauses.size(); i++) { BooleanClause c = (BooleanClause)clauses.elementAt(i); weights.add(c.query.createWeight(searcher)); } } public Query getQuery() { return BooleanQuery.this; } public float getValue() { return getBoost(); } public float sumOfSquaredWeights() throws IOException { float sum = 0.0f; for (int i = 0 ; i < weights.size(); i++) { BooleanClause c = (BooleanClause)clauses.elementAt(i); Weight w = (Weight)weights.elementAt(i); if (!c.prohibited) sum += w.sumOfSquaredWeights(); // sum sub weights } sum *= getBoost() * getBoost(); // boost each sub-weight return sum ; } public void normalize(float norm) { norm *= getBoost(); // incorporate boost for (int i = 0 ; i < weights.size(); i++) { BooleanClause c = (BooleanClause)clauses.elementAt(i); Weight w = (Weight)weights.elementAt(i); if (!c.prohibited) w.normalize(norm); } } public Scorer scorer(IndexReader reader) throws IOException { BooleanScorer result = new BooleanScorer(searcher.getSimilarity()); for (int i = 0 ; i < weights.size(); i++) { BooleanClause c = (BooleanClause)clauses.elementAt(0); Weight w = (Weight)weights.elementAt(i); Scorer subScorer = w.scorer(reader); if (subScorer != null) result.add(subScorer, c.required, c.prohibited); else if (c.required) return null; } return result; } public Explanation explain(IndexReader reader, int doc) throws IOException { Explanation sumExpl = new Explanation(); sumExpl.setDescription("sum of:"); int coord = 0; int maxCoord = 0; float sum = 0.0f; for (int i = 0 ; i < weights.size(); i++) { BooleanClause c = (BooleanClause)clauses.elementAt(0); Weight w = (Weight)weights.elementAt(i); Explanation e = w.explain(reader, doc); if (!c.prohibited) maxCoord++; if (e.getValue() > 0) { if (!c.prohibited) { sumExpl.addDetail(e); sum += e.getValue(); coord++; } else { return new Explanation(0.0f, "match prohibited"); } } else if (c.required) { return new Explanation(0.0f, "match required"); } } sumExpl.setValue(sum); if (coord == 1) // only one clause matched sumExpl = sumExpl.getDetails()[0]; // eliminate wrapper float coordFactor = searcher.getSimilarity().coord(coord, maxCoord); if (coordFactor == 1.0f) // coord is no-op return sumExpl; // eliminate wrapper else { Explanation result = new Explanation(); result.setDescription("product of:"); result.addDetail(sumExpl); result.addDetail(new Explanation(coordFactor, "coord("+coord+"/"+maxCoord+")")); result.setValue(sum*coordFactor); return result; } } } protected Weight createWeight(Searcher searcher) { return new BooleanWeight(searcher); } public Query rewrite(IndexReader reader) throws IOException { if (clauses.size() == 1) { // optimize 1-clause queries BooleanClause c = (BooleanClause)clauses.elementAt(0); if (!c.prohibited) { // just return clause Query query = c.query; if (getBoost() != 1.0f) { // have to clone to boost query = (Query)query.clone(); query.setBoost(getBoost() * query.getBoost()); } return query; } } BooleanQuery clone = null; // recursively rewrite for (int i = 0 ; i < clauses.size(); i++) { BooleanClause c = (BooleanClause)clauses.elementAt(i); Query query = c.query.rewrite(reader); if (query != c.query) { // clause rewrote: must clone if (clone == null) clone = (BooleanQuery)this.clone(); clone.clauses.setElementAt (new BooleanClause(query, c.required, c.prohibited), i); } } if (clone != null) { return clone; // some clauses rewrote } else return this; // no clauses rewrote } public Object clone() { BooleanQuery clone = (BooleanQuery)super.clone(); clone.clauses = (Vector)this.clauses.clone(); return clone; } /** Prints a user-readable version of this query. */ public String toString(String field) { StringBuffer buffer = new StringBuffer(); if (getBoost() != 1.0) { buffer.append("("); } for (int i = 0 ; i < clauses.size(); i++) { BooleanClause c = (BooleanClause)clauses.elementAt(i); if (c.prohibited) buffer.append("-"); else if (c.required) buffer.append("+"); Query subQuery = c.query; if (subQuery instanceof BooleanQuery) { // wrap sub-bools in parens buffer.append("("); buffer.append(c.query.toString(field)); buffer.append(")"); } else buffer.append(c.query.toString(field)); if (i != clauses.size()-1) buffer.append(" "); } if (getBoost() != 1.0) { buffer.append(")^"); buffer.append(getBoost()); } return buffer.toString(); } /** Returns true iff <code>o</code> is equal to this. */ public boolean equals(Object o) { if (!(o instanceof BooleanQuery)) return false; BooleanQuery other = (BooleanQuery)o; return (this.getBoost() == other.getBoost()) && this.clauses.equals(other.clauses); } /** Returns a hash code value for this object.*/ public int hashCode() { return Float.floatToIntBits(getBoost()) ^ clauses.hashCode(); } }
package org.joda.time.field; import java.util.Locale; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.ReadablePartial; /** * BaseDateTimeField provides the common behaviour for DateTimeField * implementations. * <p> * This class should generally not be used directly by API users. The * DateTimeField class should be used when different kinds of DateTimeField * objects are to be referenced. * <p> * BaseDateTimeField is thread-safe and immutable, and its subclasses must * be as well. * * @author Brian S O'Neill * @since 1.0 * @see DecoratedDateTimeField */ public abstract class BaseDateTimeField extends DateTimeField { /** The field type. */ private final DateTimeFieldType iType; /** * Constructor. */ protected BaseDateTimeField(DateTimeFieldType type) { super(); if (type == null) { throw new IllegalArgumentException("The type must not be null"); } iType = type; } public final DateTimeFieldType getType() { return iType; } public final String getName() { return iType.getName(); } /** * @return true always */ public final boolean isSupported() { return true; } // Main access API /** * Get the value of this field from the milliseconds. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @return the value of the field, in the units of the field */ public abstract int get(long instant); /** * Get the human-readable, text value of this field from the milliseconds. * If the specified locale is null, the default locale is used. * <p> * The default implementation returns getAsText(get(instant), locale). * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @param locale the locale to use for selecting a text symbol, null means default * @return the text value of the field */ public String getAsText(long instant, Locale locale) { return getAsText(get(instant), locale); } /** * Get the human-readable, text value of this field from the milliseconds. * <p> * The default implementation calls {@link #getAsText(long, Locale)}. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @return the text value of the field */ public final String getAsText(long instant) { return getAsText(instant, null); } /** * Get the human-readable, text value of this field from a partial instant. * If the specified locale is null, the default locale is used. * <p> * The default implementation returns getAsText(fieldValue, locale). * * @param partial the partial instant to query * @param fieldValue the field value of this field, provided for performance * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ public String getAsText(ReadablePartial partial, int fieldValue, Locale locale) { return getAsText(fieldValue, locale); } /** * Get the human-readable, text value of this field from a partial instant. * If the specified locale is null, the default locale is used. * <p> * The default implementation calls {@link ReadablePartial#get(DateTimeField)} * and {@link #getAsText(ReadablePartial, int, Locale)}. * * @param partial the partial instant to query * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ public final String getAsText(ReadablePartial partial, Locale locale) { return getAsText(partial, partial.get(getType()), locale); } /** * Get the human-readable, text value of this field from the field value. * If the specified locale is null, the default locale is used. * <p> * The default implementation returns Integer.toString(get(instant)). * <p> * Note: subclasses that override this method should also override * getMaximumTextLength. * * @param fieldValue the numeric value to convert to text * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ protected String getAsText(int fieldValue, Locale locale) { return Integer.toString(fieldValue); } /** * Get the human-readable, short text value of this field from the milliseconds. * If the specified locale is null, the default locale is used. * <p> * The default implementation returns getAsShortText(get(instant), locale). * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @param locale the locale to use for selecting a text symbol, null means default * @return the text value of the field */ public String getAsShortText(long instant, Locale locale) { return getAsShortText(get(instant), locale); } /** * Get the human-readable, short text value of this field from the milliseconds. * <p> * The default implementation calls {@link #getAsShortText(long, Locale)}. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @return the text value of the field */ public final String getAsShortText(long instant) { return getAsShortText(instant, null); } /** * Get the human-readable, short text value of this field from a partial instant. * If the specified locale is null, the default locale is used. * <p> * The default implementation returns getAsShortText(fieldValue, locale). * * @param partial the partial instant to query * @param fieldValue the field value of this field, provided for performance * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ public String getAsShortText(ReadablePartial partial, int fieldValue, Locale locale) { return getAsShortText(fieldValue, locale); } /** * Get the human-readable, short text value of this field from a partial instant. * If the specified locale is null, the default locale is used. * <p> * The default implementation calls {@link ReadablePartial#get(DateTimeField)} * and {@link #getAsText(ReadablePartial, int, Locale)}. * * @param partial the partial instant to query * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ public final String getAsShortText(ReadablePartial partial, Locale locale) { return getAsShortText(partial, partial.get(getType()), locale); } /** * Get the human-readable, short text value of this field from the field value. * If the specified locale is null, the default locale is used. * <p> * The default implementation returns getAsText(fieldValue, locale). * <p> * Note: subclasses that override this method should also override * getMaximumShortTextLength. * * @param fieldValue the numeric value to convert to text * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ protected String getAsShortText(int fieldValue, Locale locale) { return getAsText(fieldValue, locale); } /** * Adds a value (which may be negative) to the instant value, * overflowing into larger fields if necessary. * <p> * The value will be added to this field. If the value is too large to be * added solely to this field, larger fields will increase as required. * Smaller fields should be unaffected, except where the result would be * an invalid value for a smaller field. In this case the smaller field is * adjusted to be in range. * <p> * For example, in the ISO chronology:<br> * 2000-08-20 add six months is 2001-02-20<br> * 2000-08-20 add twenty months is 2002-04-20<br> * 2000-08-20 add minus nine months is 1999-11-20<br> * 2001-01-31 add one month is 2001-02-28<br> * 2001-01-31 add two months is 2001-03-31<br> * * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to * @param value the value to add, in the units of the field * @return the updated milliseconds */ public long add(long instant, int value) { return getDurationField().add(instant, value); } public long add(long instant, long value) { return getDurationField().add(instant, value); } public int[] add(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd) { if (valueToAdd == 0) { return values; } // there are more efficient algorithms than this (especially for time only fields) // trouble is when dealing with days and months, so we use this technique of // adding/removing one from the larger field at a time DateTimeField nextField = null; while (valueToAdd > 0) { int max = getMaximumValue(instant, values); long proposed = values[fieldIndex] + valueToAdd; if (proposed <= max) { values[fieldIndex] = (int) proposed; break; } if (nextField == null) { if (fieldIndex == 0) { throw new IllegalArgumentException("Maximum value exceeded for add"); } nextField = instant.getField(fieldIndex - 1); // test only works if this field is UTC (ie. local) if (getRangeDurationField() != nextField.getDurationField()) { throw new IllegalArgumentException("Fields invalid for add"); } } valueToAdd -= (max + 1) - values[fieldIndex]; values = nextField.add(instant, fieldIndex - 1, values, 1); values[fieldIndex] = getMinimumValue(instant, values); } while (valueToAdd < 0) { int min = getMinimumValue(instant, values); long proposed = values[fieldIndex] + valueToAdd; if (proposed >= min) { values[fieldIndex] = (int) proposed; break; } if (nextField == null) { if (fieldIndex == 0) { throw new IllegalArgumentException("Maximum value exceeded for add"); } nextField = instant.getField(fieldIndex - 1); if (getRangeDurationField() != nextField.getDurationField()) { throw new IllegalArgumentException("Fields invalid for add"); } } valueToAdd -= (min - 1) - values[fieldIndex]; values = nextField.add(instant, fieldIndex - 1, values, -1); values[fieldIndex] = getMaximumValue(instant, values); } return set(instant, fieldIndex, values, values[fieldIndex]); // adjusts smaller fields } /** * Adds a value (which may be negative) to the instant value, * wrapping within this field. * <p> * The value will be added to this field. If the value is too large to be * added solely to this field then it wraps. Larger fields are always * unaffected. Smaller fields should be unaffected, except where the * result would be an invalid value for a smaller field. In this case the * smaller field is adjusted to be in range. * <p> * For example, in the ISO chronology:<br> * 2000-08-20 addWrapField six months is 2000-02-20<br> * 2000-08-20 addWrapField twenty months is 2000-04-20<br> * 2000-08-20 addWrapField minus nine months is 2000-11-20<br> * 2001-01-31 addWrapField one month is 2001-02-28<br> * 2001-01-31 addWrapField two months is 2001-03-31<br> * <p> * The default implementation internally calls set. Subclasses are * encouraged to provide a more efficient implementation. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to * @param value the value to add, in the units of the field * @return the updated milliseconds */ public long addWrapField(long instant, int value) { int current = get(instant); int wrapped = FieldUtils.getWrappedValue (current, value, getMinimumValue(instant), getMaximumValue(instant)); return set(instant, wrapped); } public int[] addWrapField(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd) { int current = values[fieldIndex]; int wrapped = FieldUtils.getWrappedValue (current, valueToAdd, getMinimumValue(instant), getMaximumValue(instant)); return set(instant, fieldIndex, values, wrapped); // adjusts smaller fields } /** * Computes the difference between two instants, as measured in the units * of this field. Any fractional units are dropped from the result. Calling * getDifference reverses the effect of calling add. In the following code: * * <pre> * long instant = ... * int v = ... * int age = getDifference(add(instant, v), instant); * </pre> * * The value 'age' is the same as the value 'v'. * * @param minuendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract from * @param subtrahendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract off the minuend * @return the difference in the units of this field */ public int getDifference(long minuendInstant, long subtrahendInstant) { return getDurationField().getDifference(minuendInstant, subtrahendInstant); } /** * Computes the difference between two instants, as measured in the units * of this field. Any fractional units are dropped from the result. Calling * getDifference reverses the effect of calling add. In the following code: * * <pre> * long instant = ... * long v = ... * long age = getDifferenceAsLong(add(instant, v), instant); * </pre> * * The value 'age' is the same as the value 'v'. * * @param minuendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract from * @param subtrahendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract off the minuend * @return the difference in the units of this field */ public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return getDurationField().getDifferenceAsLong(minuendInstant, subtrahendInstant); } public abstract long set(long instant, int value); public int[] set(ReadablePartial partial, int fieldIndex, int[] values, int newValue) { FieldUtils.verifyValueBounds(this, newValue, getMinimumValue(partial, values), getMaximumValue(partial, values)); values[fieldIndex] = newValue; // may need to adjust smaller fields for (int i = fieldIndex + 1; i < partial.size(); i++) { DateTimeField field = partial.getField(i); if (values[i] > field.getMaximumValue(partial, values)) { values[i] = field.getMaximumValue(partial, values); } if (values[i] < field.getMinimumValue(partial, values)) { values[i] = field.getMinimumValue(partial, values); } } return values; } public long set(long instant, String text, Locale locale) { int value = convertText(text, locale); return set(instant, value); } public final long set(long instant, String text) { return set(instant, text, null); } public int[] set(ReadablePartial instant, int fieldIndex, int[] values, String text, Locale locale) { int value = convertText(text, locale); return set(instant, fieldIndex, values, value); } protected int convertText(String text, Locale locale) { try { return Integer.parseInt(text); } catch (NumberFormatException ex) { throw new IllegalArgumentException("Invalid " + getName() + " text: " + text); } } // Extra information API /** * Returns the duration per unit value of this field. For example, if this * field represents "hour of day", then the unit duration is an hour. * * @return the duration of this field, or UnsupportedDurationField if field * has no duration */ public abstract DurationField getDurationField(); /** * Returns the range duration of this field. For example, if this field * represents "hour of day", then the range duration is a day. * * @return the range duration of this field, or null if field has no range */ public abstract DurationField getRangeDurationField(); /** * Returns whether this field is 'leap' for the specified instant. * <p> * For example, a leap year would return true, a non leap year would return * false. * <p> * This implementation returns false. * * @return true if the field is 'leap' */ public boolean isLeap(long instant) { return false; } /** * Gets the amount by which this field is 'leap' for the specified instant. * <p> * For example, a leap year would return one, a non leap year would return * zero. * <p> * This implementation returns zero. */ public int getLeapAmount(long instant) { return 0; } /** * If this field were to leap, then it would be in units described by the * returned duration. If this field doesn't ever leap, null is returned. * <p> * This implementation returns null. */ public DurationField getLeapDurationField() { return null; } /** * Get the minimum allowable value for this field. * * @return the minimum valid value for this field, in the units of the * field */ public abstract int getMinimumValue(); /** * Get the minimum value for this field evaluated at the specified time. * <p> * This implementation returns the same as {@link #getMinimumValue()}. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @return the minimum value for this field, in the units of the field */ public int getMinimumValue(long instant) { return getMinimumValue(); } /** * Get the minimum value for this field evaluated at the specified instant. * <p> * This implementation returns the same as {@link #getMinimumValue()}. * * @param instant the partial instant to query * @return the minimum value for this field, in the units of the field */ public int getMinimumValue(ReadablePartial instant) { return getMinimumValue(); } /** * Get the minimum value for this field using the partial instant and * the specified values. * <p> * This implementation returns the same as {@link #getMinimumValue(ReadablePartial)}. * * @param instant the partial instant to query * @param values the values to use * @return the minimum value for this field, in the units of the field */ public int getMinimumValue(ReadablePartial instant, int[] values) { return getMinimumValue(instant); } /** * Get the maximum allowable value for this field. * * @return the maximum valid value for this field, in the units of the * field */ public abstract int getMaximumValue(); /** * Get the maximum value for this field evaluated at the specified time. * <p> * This implementation returns the same as {@link #getMaximumValue()}. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @return the maximum value for this field, in the units of the field */ public int getMaximumValue(long instant) { return getMaximumValue(); } /** * Get the maximum value for this field evaluated at the specified instant. * <p> * This implementation returns the same as {@link #getMaximumValue()}. * * @param instant the partial instant to query * @return the maximum value for this field, in the units of the field */ public int getMaximumValue(ReadablePartial instant) { return getMaximumValue(); } /** * Get the maximum value for this field using the partial instant and * the specified values. * <p> * This implementation returns the same as {@link #getMaximumValue(ReadablePartial)}. * * @param instant the partial instant to query * @param values the values to use * @return the maximum value for this field, in the units of the field */ public int getMaximumValue(ReadablePartial instant, int[] values) { return getMaximumValue(instant); } /** * Get the maximum text value for this field. The default implementation * returns the equivalent of Integer.toString(getMaximumValue()).length(). * * @param locale the locale to use for selecting a text symbol * @return the maximum text length */ public int getMaximumTextLength(Locale locale) { int max = getMaximumValue(); if (max >= 0) { if (max < 10) { return 1; } else if (max < 100) { return 2; } else if (max < 1000) { return 3; } } return Integer.toString(max).length(); } /** * Get the maximum short text value for this field. The default * implementation returns getMaximumTextLength(). * * @param locale the locale to use for selecting a text symbol * @return the maximum short text length */ public int getMaximumShortTextLength(Locale locale) { return getMaximumTextLength(locale); } // Calculation API /** * Round to the lowest whole unit of this field. After rounding, the value * of this field and all fields of a higher magnitude are retained. The * fractional millis that cannot be expressed in whole increments of this * field are set to minimum. * <p> * For example, a datetime of 2002-11-02T23:34:56.789, rounded to the * lowest whole hour is 2002-11-02T23:00:00.000. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @return rounded milliseconds */ public abstract long roundFloor(long instant); /** * Round to the highest whole unit of this field. The value of this field * and all fields of a higher magnitude may be incremented in order to * achieve this result. The fractional millis that cannot be expressed in * whole increments of this field are set to minimum. * <p> * For example, a datetime of 2002-11-02T23:34:56.789, rounded to the * highest whole hour is 2002-11-03T00:00:00.000. * <p> * The default implementation calls roundFloor, and if the instant is * modified as a result, adds one field unit. Subclasses are encouraged to * provide a more efficient implementation. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @return rounded milliseconds */ public long roundCeiling(long instant) { long newInstant = roundFloor(instant); if (newInstant != instant) { instant = add(newInstant, 1); } return instant; } /** * Round to the nearest whole unit of this field. If the given millisecond * value is closer to the floor or is exactly halfway, this function * behaves like roundFloor. If the millisecond value is closer to the * ceiling, this function behaves like roundCeiling. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @return rounded milliseconds */ public long roundHalfFloor(long instant) { long floor = roundFloor(instant); long ceiling = roundCeiling(instant); long diffFromFloor = instant - floor; long diffToCeiling = ceiling - instant; if (diffFromFloor <= diffToCeiling) { // Closer to the floor, or halfway - round floor return floor; } else { return ceiling; } } /** * Round to the nearest whole unit of this field. If the given millisecond * value is closer to the floor, this function behaves like roundFloor. If * the millisecond value is closer to the ceiling or is exactly halfway, * this function behaves like roundCeiling. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @return rounded milliseconds */ public long roundHalfCeiling(long instant) { long floor = roundFloor(instant); long ceiling = roundCeiling(instant); long diffFromFloor = instant - floor; long diffToCeiling = ceiling - instant; if (diffToCeiling <= diffFromFloor) { // Closer to the ceiling, or halfway - round ceiling return ceiling; } else { return floor; } } /** * Round to the nearest whole unit of this field. If the given millisecond * value is closer to the floor, this function behaves like roundFloor. If * the millisecond value is closer to the ceiling, this function behaves * like roundCeiling. * <p> * If the millisecond value is exactly halfway between the floor and * ceiling, the ceiling is chosen over the floor only if it makes this * field's value even. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @return rounded milliseconds */ public long roundHalfEven(long instant) { long floor = roundFloor(instant); long ceiling = roundCeiling(instant); long diffFromFloor = instant - floor; long diffToCeiling = ceiling - instant; if (diffFromFloor < diffToCeiling) { // Closer to the floor - round floor return floor; } else if (diffToCeiling < diffFromFloor) { // Closer to the ceiling - round ceiling return ceiling; } else { // Round to the instant that makes this field even. If both values // make this field even (unlikely), favor the ceiling. if ((get(ceiling) & 1) == 0) { return ceiling; } return floor; } } /** * Returns the fractional duration milliseconds of this field. In other * words, calling remainder returns the duration that roundFloor would * subtract. * <p> * For example, on a datetime of 2002-11-02T23:34:56.789, the remainder by * hour is 34 minutes and 56.789 seconds. * <p> * The default implementation computes * <code>instant - roundFloor(instant)</code>. Subclasses are encouraged to * provide a more efficient implementation. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to get the * remainder * @return remainder duration, in milliseconds */ public long remainder(long instant) { return instant - roundFloor(instant); } /** * Get a suitable debug string. * * @return debug string */ public String toString() { return "DateTimeField[" + getName() + ']'; } }
package org.jsimpledb.kv.sql; import com.google.common.base.Preconditions; import java.io.Closeable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.Future; import org.jsimpledb.kv.AbstractKVStore; import org.jsimpledb.kv.KVPair; import org.jsimpledb.kv.KVTransaction; import org.jsimpledb.kv.KVTransactionException; import org.jsimpledb.kv.StaleTransactionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * {@link SQLKVDatabase} transaction. */ public class SQLKVTransaction extends AbstractKVStore implements KVTransaction { protected final Logger log = LoggerFactory.getLogger(this.getClass()); protected final SQLKVDatabase database; protected final Connection connection; private long timeout; private boolean closed; private boolean stale; /** * Constructor. * * @param database the associated database * @param connection the {@link Connection} for the transaction * @throws SQLException if an SQL error occurs */ public SQLKVTransaction(SQLKVDatabase database, Connection connection) throws SQLException { Preconditions.checkArgument(database != null, "null database"); Preconditions.checkArgument(connection != null, "null connection"); this.database = database; this.connection = connection; } @Override public SQLKVDatabase getKVDatabase() { return this.database; } @Override public void setTimeout(long timeout) { Preconditions.checkArgument(timeout >= 0, "timeout < 0"); this.timeout = timeout; } @Override public Future<Void> watchKey(byte[] key) { throw new UnsupportedOperationException(); } @Override public synchronized byte[] get(byte[] key) { if (this.stale) throw new StaleTransactionException(this); Preconditions.checkArgument(key != null, "null key"); return this.queryBytes(StmtType.GET, key); } @Override public synchronized KVPair getAtLeast(byte[] minKey) { if (this.stale) throw new StaleTransactionException(this); return minKey != null ? this.queryKVPair(StmtType.GET_AT_LEAST_SINGLE, minKey) : this.queryKVPair(StmtType.GET_FIRST); } @Override public synchronized KVPair getAtMost(byte[] maxKey) { if (this.stale) throw new StaleTransactionException(this); return maxKey != null ? this.queryKVPair(StmtType.GET_AT_MOST_SINGLE, maxKey) : this.queryKVPair(StmtType.GET_LAST); } @Override public synchronized Iterator<KVPair> getRange(byte[] minKey, byte[] maxKey, boolean reverse) { if (this.stale) throw new StaleTransactionException(this); if (minKey == null && maxKey == null) return this.queryIterator(reverse ? StmtType.GET_ALL_REVERSE : StmtType.GET_ALL_FORWARD); if (minKey == null) return this.queryIterator(reverse ? StmtType.GET_AT_MOST_REVERSE : StmtType.GET_AT_MOST_FORWARD, maxKey); if (maxKey == null) return this.queryIterator(reverse ? StmtType.GET_AT_LEAST_REVERSE : StmtType.GET_AT_LEAST_FORWARD, minKey); else return this.queryIterator(reverse ? StmtType.GET_RANGE_REVERSE : StmtType.GET_RANGE_FORWARD, minKey, maxKey); } @Override public synchronized void put(byte[] key, byte[] value) { Preconditions.checkArgument(key != null, "null key"); Preconditions.checkArgument(value != null, "null value"); if (this.stale) throw new StaleTransactionException(this); this.update(StmtType.PUT, key, value, value); } @Override public synchronized void remove(byte[] key) { Preconditions.checkArgument(key != null, "null key"); if (this.stale) throw new StaleTransactionException(this); this.update(StmtType.REMOVE, key); } @Override public synchronized void removeRange(byte[] minKey, byte[] maxKey) { if (this.stale) throw new StaleTransactionException(this); if (minKey == null && maxKey == null) this.update(StmtType.REMOVE_ALL); else if (minKey == null) this.update(StmtType.REMOVE_AT_MOST, maxKey); else if (maxKey == null) this.update(StmtType.REMOVE_AT_LEAST, minKey); else this.update(StmtType.REMOVE_RANGE, minKey, maxKey); } @Override public synchronized void commit() { if (this.stale) throw new StaleTransactionException(this); this.stale = true; try { this.connection.commit(); } catch (SQLException e) { throw this.handleException(e); } finally { this.closeConnection(); } } @Override public synchronized void rollback() { if (this.stale) return; this.stale = true; try { this.connection.rollback(); } catch (SQLException e) { throw this.handleException(e); } finally { this.closeConnection(); } } /** * Handle an unexpected SQL exception. * * <p> * The implementation in {@link SQLKVTransaction} rolls back the SQL transaction, closes the associated {@link Connection}, * and wraps the exception via {@link SQLKVDatabase#wrapException SQLKVDatabase.wrapException()}. * </p> * * @param e original exception * @return key/value transaction exception */ protected KVTransactionException handleException(SQLException e) { this.stale = true; try { this.connection.rollback(); } catch (SQLException e2) { // ignore } finally { this.closeConnection(); } return this.database.wrapException(this, e); } /** * Close the {@link Connection} associated with this instance, if it's not already closed. * This method is idempotent. */ protected void closeConnection() { if (this.closed) return; this.closed = true; try { this.connection.close(); } catch (SQLException e) { // ignore } } @Override protected void finalize() throws Throwable { try { if (!this.stale) this.log.warn(this + " leaked without commit() or rollback()"); this.closeConnection(); } finally { super.finalize(); } } // Helper methods private byte[] queryBytes(StmtType stmtType, byte[]... params) { return this.query(stmtType, new ResultSetFunction<byte[]>() { @Override public byte[] apply(PreparedStatement preparedStatement, ResultSet resultSet) throws SQLException { return resultSet.next() ? resultSet.getBytes(1) : null; } }, true, params); } private KVPair queryKVPair(StmtType stmtType, byte[]... params) { return this.query(stmtType, new ResultSetFunction<KVPair>() { @Override public KVPair apply(PreparedStatement preparedStatement, ResultSet resultSet) throws SQLException { return resultSet.next() ? new KVPair(resultSet.getBytes(1), resultSet.getBytes(2)) : null; } }, true, params); } private Iterator<KVPair> queryIterator(StmtType stmtType, byte[]... params) { return this.query(stmtType, new ResultSetFunction<Iterator<KVPair>>() { @Override public Iterator<KVPair> apply(PreparedStatement preparedStatement, ResultSet resultSet) throws SQLException { return new ResultSetIterator(preparedStatement, resultSet); } }, false, params); } private <T> T query(StmtType stmtType, ResultSetFunction<T> resultSetFunction, boolean close, byte[]... params) { try { final PreparedStatement preparedStatement = stmtType.create(this.database, this.connection); for (int i = 0; i < params.length; i++) preparedStatement.setBytes(i + 1, params[i]); preparedStatement.setQueryTimeout((int)((this.timeout + 999) / 1000)); if (this.log.isTraceEnabled()) this.log.trace("SQL query: " + preparedStatement); final ResultSet resultSet = preparedStatement.executeQuery(); final T result = resultSetFunction.apply(preparedStatement, resultSet); if (close) { resultSet.close(); preparedStatement.close(); } return result; } catch (SQLException e) { throw this.handleException(e); } } private void update(StmtType stmtType, byte[]... params) { try { final PreparedStatement preparedStatement = stmtType.create(this.database, this.connection); for (int i = 0; i < params.length; i++) preparedStatement.setBytes(i + 1, params[i]); preparedStatement.setQueryTimeout((int)((this.timeout + 999) / 1000)); if (this.log.isTraceEnabled()) this.log.trace("SQL update: " + preparedStatement); preparedStatement.executeUpdate(); preparedStatement.close(); } catch (SQLException e) { throw this.handleException(e); } } // ResultSetFunction private interface ResultSetFunction<T> { T apply(PreparedStatement preparedStatement, ResultSet resultSet) throws SQLException; } // ResultSetIterator private class ResultSetIterator implements Iterator<KVPair>, Closeable { private final PreparedStatement preparedStatement; private final ResultSet resultSet; private boolean ready; private boolean closed; private byte[] removeKey; ResultSetIterator(PreparedStatement preparedStatement, ResultSet resultSet) { assert preparedStatement != null; assert resultSet != null; this.resultSet = resultSet; this.preparedStatement = preparedStatement; } // Iterator @Override public synchronized boolean hasNext() { if (this.closed) return false; if (this.ready) return true; try { this.ready = this.resultSet.next(); } catch (SQLException e) { throw SQLKVTransaction.this.handleException(e); } if (!this.ready) this.close(); return this.ready; } @Override public synchronized KVPair next() { if (!this.hasNext()) throw new NoSuchElementException(); final byte[] key; final byte[] value; try { key = this.resultSet.getBytes(1); value = this.resultSet.getBytes(2); } catch (SQLException e) { throw SQLKVTransaction.this.handleException(e); } this.removeKey = key.clone(); this.ready = false; return new KVPair(key, value); } @Override public synchronized void remove() { if (this.closed || this.removeKey == null) throw new IllegalStateException(); SQLKVTransaction.this.remove(this.removeKey); this.removeKey = null; } // Closeable @Override public synchronized void close() { if (this.closed) return; this.closed = true; try { this.resultSet.close(); } catch (Exception e) { // ignore } try { this.preparedStatement.close(); } catch (Exception e) { // ignore } } // Object @Override protected void finalize() throws Throwable { try { this.close(); } finally { super.finalize(); } } } // StmtType abstract static class StmtType { static final StmtType GET = new StmtType() { @Override PreparedStatement create(SQLKVDatabase db, Connection c) throws SQLException { return c.prepareStatement(db.createGetStatement()); }; }; static final StmtType GET_AT_LEAST_SINGLE = new StmtType() { @Override PreparedStatement create(SQLKVDatabase db, Connection c) throws SQLException { return c.prepareStatement(db.limitSingleRow(db.createGetAtLeastStatement(false))); }; }; static final StmtType GET_AT_MOST_SINGLE = new StmtType() { @Override PreparedStatement create(SQLKVDatabase db, Connection c) throws SQLException { return c.prepareStatement(db.limitSingleRow(db.createGetAtMostStatement(false))); }; }; static final StmtType GET_FIRST = new StmtType() { @Override PreparedStatement create(SQLKVDatabase db, Connection c) throws SQLException { return c.prepareStatement(db.limitSingleRow(db.createGetAllStatement(false))); }; }; static final StmtType GET_LAST = new StmtType() { @Override PreparedStatement create(SQLKVDatabase db, Connection c) throws SQLException { return c.prepareStatement(db.limitSingleRow(db.createGetAllStatement(true))); }; }; static final StmtType GET_AT_LEAST_FORWARD = new StmtType() { @Override PreparedStatement create(SQLKVDatabase db, Connection c) throws SQLException { return c.prepareStatement(db.createGetAtLeastStatement(false)); }; }; static final StmtType GET_AT_LEAST_REVERSE = new StmtType() { @Override PreparedStatement create(SQLKVDatabase db, Connection c) throws SQLException { return c.prepareStatement(db.createGetAtLeastStatement(true)); }; }; static final StmtType GET_AT_MOST_FORWARD = new StmtType() { @Override PreparedStatement create(SQLKVDatabase db, Connection c) throws SQLException { return c.prepareStatement(db.createGetAtMostStatement(false)); }; }; static final StmtType GET_AT_MOST_REVERSE = new StmtType() { @Override PreparedStatement create(SQLKVDatabase db, Connection c) throws SQLException { return c.prepareStatement(db.createGetAtMostStatement(true)); }; }; static final StmtType GET_RANGE_FORWARD = new StmtType() { @Override PreparedStatement create(SQLKVDatabase db, Connection c) throws SQLException { return c.prepareStatement(db.createGetRangeStatement(false)); }; }; static final StmtType GET_RANGE_REVERSE = new StmtType() { @Override PreparedStatement create(SQLKVDatabase db, Connection c) throws SQLException { return c.prepareStatement(db.createGetRangeStatement(true)); }; }; static final StmtType GET_ALL_FORWARD = new StmtType() { @Override PreparedStatement create(SQLKVDatabase db, Connection c) throws SQLException { return c.prepareStatement(db.createGetAllStatement(false)); }; }; static final StmtType GET_ALL_REVERSE = new StmtType() { @Override PreparedStatement create(SQLKVDatabase db, Connection c) throws SQLException { return c.prepareStatement(db.createGetAllStatement(true)); }; }; static final StmtType PUT = new StmtType() { @Override PreparedStatement create(SQLKVDatabase db, Connection c) throws SQLException { return c.prepareStatement(db.createPutStatement()); }; }; static final StmtType REMOVE = new StmtType() { @Override PreparedStatement create(SQLKVDatabase db, Connection c) throws SQLException { return c.prepareStatement(db.createRemoveStatement()); }; }; static final StmtType REMOVE_RANGE = new StmtType() { @Override PreparedStatement create(SQLKVDatabase db, Connection c) throws SQLException { return c.prepareStatement(db.createRemoveRangeStatement()); }; }; static final StmtType REMOVE_AT_LEAST = new StmtType() { @Override PreparedStatement create(SQLKVDatabase db, Connection c) throws SQLException { return c.prepareStatement(db.createRemoveAtLeastStatement()); }; }; static final StmtType REMOVE_AT_MOST = new StmtType() { @Override PreparedStatement create(SQLKVDatabase db, Connection c) throws SQLException { return c.prepareStatement(db.createRemoveAtMostStatement()); }; }; static final StmtType REMOVE_ALL = new StmtType() { @Override PreparedStatement create(SQLKVDatabase db, Connection c) throws SQLException { return c.prepareStatement(db.createRemoveAllStatement()); }; }; abstract PreparedStatement create(SQLKVDatabase db, Connection c) throws SQLException; } }
/* * Este codigo pertenece a miguel.navarrovera@gmail.com * Su uso esta prohibido para uso comercial. * Si tienes interes en usarlo, ponte en contacto conmigo, Gracias. :D */ package org.mig.java.Commands; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.mig.java.BLL.ProductosBLL; import org.mig.java.Entities.Imagenes_productos; import org.mig.java.Entities.Productos; import org.mig.java.Entities.Usuarios; /** * @author miguelangel */ public class WishListCommand extends ICommand { @Override public String executePage(HttpServletRequest request, HttpServletResponse response) throws Exception { ProductosBLL productoBll = new ProductosBLL(); Usuarios usuario = (Usuarios) request.getSession().getAttribute("clienteSesion"); List<Productos> listaWishItems = new ArrayList<>(); listaWishItems = productoBll.WishList(usuario); List<Imagenes_productos> listadoImagenesProductos = productoBll.listaImagenesProductos(); request.setAttribute("listadoImagenesProductos", listadoImagenesProductos); request.getSession().setAttribute("listaWish", listaWishItems); return "WishList.jsp"; } }
package krasa.grepconsole.grep; import com.intellij.execution.ExecutionHelper; import com.intellij.execution.impl.ConsoleViewImpl; import com.intellij.execution.ui.ConsoleView; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.openapi.project.Project; import com.intellij.ui.AppUIUtil; import com.intellij.util.Alarm; import com.intellij.util.SingleAlarm; import krasa.grepconsole.utils.FocusUtils; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; public class PinnedGrepsReopener { private final SingleAlarm myUpdateAlarm; public static volatile boolean enabled = true; public PinnedGrepsReopener(Project project, WeakReference<ConsoleView> consoleViewWeakReference) { AtomicInteger atomicInteger = new AtomicInteger(); myUpdateAlarm = new SingleAlarm(new Runnable() { @Override public void run() { ConsoleView consoleView = consoleViewWeakReference.get(); if (consoleView == null) { return; } if (project.isDisposed()) { return; } AppUIUtil.invokeOnEdt(() -> { if (project.isDisposed()) { return; } Collection<RunContentDescriptor> descriptors = ExecutionHelper.findRunningConsole(project, dom -> FocusUtils.isSameConsole(dom, consoleView, false)); if (!descriptors.isEmpty()) { if (descriptors.size() == 1) { RunContentDescriptor runContentDescriptor = (RunContentDescriptor) descriptors.toArray()[0]; PinnedGrepConsolesState.RunConfigurationRef key = new PinnedGrepConsolesState.RunConfigurationRef( runContentDescriptor.getDisplayName(), runContentDescriptor.getIcon()); PinnedGrepConsolesState.Pins state = PinnedGrepConsolesState.getInstance(project).getPins(key); if (state != null && !state.getPins().isEmpty() && consoleView instanceof ConsoleViewImpl) { if (project.isDisposed()) { return; } try { enabled = false; List<PinnedGrepConsolesState.Pin> list = state.getPins(); for (PinnedGrepConsolesState.Pin pin : list) { if (pin.getParentConsoleUUID() == null) { initConsole(pin, (ConsoleViewImpl) consoleView, list); } } } finally { enabled = true; } } } } else if (atomicInteger.incrementAndGet() < 3) { myUpdateAlarm.cancelAndRequest(); } }); } public void initConsole(PinnedGrepConsolesState.Pin pin, ConsoleViewImpl parent, List<PinnedGrepConsolesState.Pin> list) { ConsoleViewImpl foo = new OpenGrepConsoleAction().createGrepConsole(project, parent, pin.getGrepModel(), null, pin.getConsoleUUID()); for (PinnedGrepConsolesState.Pin childPin : list) { if (pin.getConsoleUUID().equals(childPin.getParentConsoleUUID())) { initConsole(childPin, foo, list); } } } }, 100, Alarm.ThreadToUse.POOLED_THREAD, project); myUpdateAlarm.request(); } }
package com.haulmont.cuba.web; import com.haulmont.cuba.core.global.*; import com.haulmont.cuba.core.sys.AppContext; import com.haulmont.cuba.gui.AppConfig; import com.haulmont.cuba.security.global.LoginException; import com.haulmont.cuba.security.global.UserSession; import com.haulmont.cuba.web.exception.*; import com.haulmont.cuba.web.gui.WebTimer; import com.haulmont.cuba.web.log.AppLog; import com.haulmont.cuba.web.sys.ActiveDirectoryHelper; import com.haulmont.cuba.web.sys.LinkHandler; import com.haulmont.cuba.web.sys.WebSecurityUtils; import com.haulmont.cuba.web.toolkit.Timer; import com.vaadin.Application; import com.vaadin.service.ApplicationContext; import com.vaadin.terminal.Terminal; import com.vaadin.terminal.ExternalResource; import com.vaadin.terminal.gwt.server.AbstractApplicationServlet; import com.vaadin.terminal.gwt.server.HttpServletRequestListener; import com.vaadin.ui.Window; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.exception.ExceptionUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Cookie; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.io.FileOutputStream; /** * Main class of the web application. Each client connection has its own App. * Use {@link #getInstance()} static method to obtain the reference to the current App instance * throughout the application code. * <p> * Specific application should inherit from this class and set derived class name * in <code>application</code> servlet parameter of <code>web.xml</code> */ public class App extends Application implements ConnectionListener, ApplicationContext.TransactionListener, HttpServletRequestListener { private static final long serialVersionUID = -3435976475534930050L; private static final Pattern WIN_PATTERN = Pattern.compile("win([0-9]{1,4})"); private Log log = LogFactory.getLog(App.class); public static final String THEME_NAME = "blacklabel"; protected Connection connection; private WebWindowManager windowManager; private AppLog appLog; protected ExceptionHandlers exceptionHandlers; private static ThreadLocal<App> currentApp = new ThreadLocal<App>(); private ThreadLocal<String> currentWindowName = new ThreadLocal<String>(); private boolean principalIsWrong; private LinkHandler linkHandler; protected Map<Window, WindowTimers> windowTimers = new WeakHashMap<Window, WindowTimers>(); protected Map<Timer, Window> timerWindow = new WeakHashMap<Timer, Window>(); protected Map<Object, Long> requestStartTimes = new WeakHashMap<Object, Long>(); private static volatile boolean viewsDeployed; private volatile String contextName; private HttpServletResponse response; private AppCookies cookies; static { AppContext.setProperty(AppConfig.CLIENT_TYPE_PROP, ClientType.WEB.toString()); } public App() { appLog = new AppLog(); connection = new Connection(); connection.addListener(this); windowManager = createWindowManager(); exceptionHandlers = new ExceptionHandlers(this); cookies = new AppCookies() { protected void addCookie(Cookie cookie) { response.addCookie(cookie); } }; cookies.setCookiesEnabled(true); } public void onRequestStart(HttpServletRequest request, HttpServletResponse response) { this.response = response; cookies.updateCookies(request); } public void onRequestEnd(HttpServletRequest request, HttpServletResponse response) { //do nothing } public static Application.SystemMessages getSystemMessages() { String webContext = AppContext.getProperty("cuba.webContextName"); Application.CustomizedSystemMessages msgs = new Application.CustomizedSystemMessages(); msgs.setInternalErrorURL("/" + webContext + "?restartApplication"); msgs.setOutOfSyncNotificationEnabled(false); return msgs; } /** * Can be overridden in descendant to create an application-specific {@link WebWindowManager} */ protected WebWindowManager createWindowManager() { return new WebWindowManager(this); } public void init() { log.debug("Initializing application"); AppConfig.getInstance().addGroovyImport(PersistenceHelper.class); ApplicationContext appContext = getContext(); appContext.addTransactionListener(this); LoginWindow window = createLoginWindow(); setMainWindow(window); if (!viewsDeployed) { deployViews(); viewsDeployed = true; } String themeName = AppContext.getProperty(AppConfig.THEME_NAME_PROP); if (themeName == null) themeName = THEME_NAME; setTheme(themeName); } /** * Current App instance. Can be invoked anywhere in application code. */ public static App getInstance() { App app = currentApp.get(); if (app == null) throw new IllegalStateException("No App bound to the current thread. This may be the result of hot-deployment."); return app; } /** * Can be overridden in descendant to add application-specific exception handlers */ protected void initExceptionHandlers(boolean isConnected) { if (isConnected) { exceptionHandlers.addHandler(new NoUserSessionHandler()); // must be the first handler exceptionHandlers.addHandler(new SilentExceptionHandler()); exceptionHandlers.addHandler(new UniqueConstraintViolationHandler()); exceptionHandlers.addHandler(new AccessDeniedHandler()); exceptionHandlers.addHandler(new NoSuchScreenHandler()); exceptionHandlers.addHandler(new DeletePolicyHandler()); exceptionHandlers.addHandler(new NumericOverflowExceptionHandler()); exceptionHandlers.addHandler(new OptimisticExceptionHandler()); exceptionHandlers.addHandler(new JPAOptimisticExceptionHandler()); } else { exceptionHandlers.getHandlers().clear(); } } /** * Should be overridden in descendant to create an application-specific login window */ protected LoginWindow createLoginWindow() { LoginWindow window = new LoginWindow(this, connection); return window; } /** * Should be overridden in descendant to deploy views needed for main window */ protected void deployViews() { MetadataProvider.getViewRepository().deployViews("/com/haulmont/cuba/web/app.views.xml"); } /** * Should be overridden in descendant to create an application-specific main window */ protected AppWindow createAppWindow() { AppWindow appWindow = new AppWindow(connection); return appWindow; } public AppWindow getAppWindow() { String name = currentWindowName.get(); //noinspection deprecation return (AppWindow) (name == null ? getMainWindow() : getWindow(name)); } /** * Don't use this method in application code.<br> * Use {@link #getAppWindow} instead */ @Deprecated @Override public Window getMainWindow() { return super.getMainWindow(); } @Override public void removeWindow(Window window) { super.removeWindow(window); if (window instanceof AppWindow) { connection.removeListener((AppWindow) window); } } /** * Get current connection object */ public Connection getConnection() { return connection; } public WebWindowManager getWindowManager() { return windowManager; } public AppLog getAppLog() { return appLog; } public void connectionStateChanged(Connection connection) throws LoginException { if (connection.isConnected()) { log.debug("Creating AppWindow"); stopTimers(); String name = GlobalUtils.generateWebWindowName(); Window window = getWindow(name); setMainWindow(window); currentWindowName.set(window.getName()); initExceptionHandlers(true); if (linkHandler != null) { linkHandler.handle(); linkHandler = null; } } else { log.debug("Closing all windows"); getWindowManager().closeAll(); stopTimers(); for (Object win : new ArrayList(getWindows())) { removeWindow((Window) win); } String name = GlobalUtils.generateWebWindowName(); Window window = createLoginWindow(); window.setName(name); setMainWindow(window); currentWindowName.set(window.getName()); initExceptionHandlers(false); } } public void userSubstituted(Connection connection) { } public void terminalError(Terminal.ErrorEvent event) { GlobalConfig config = ConfigProvider.getConfig(GlobalConfig.class); if (config.getTestMode()) { String fileName = AppContext.getProperty("cuba.testModeExceptionLog"); if (!StringUtils.isBlank(fileName)) { try { FileOutputStream stream = new FileOutputStream(fileName); try { stream.write(ExceptionUtils.getStackTrace(event.getThrowable()).getBytes()); } finally { stream.close(); } } catch (Exception e) { log.debug(e); } } } if (event instanceof AbstractApplicationServlet.RequestError) { log.error("RequestError:", event.getThrowable()); } else { exceptionHandlers.handle(event); getAppLog().log(event); } } @Override public Window getWindow(String name) { Window window = super.getWindow(name); // it does not exist yet, create it. if (window == null/* && name.startsWith("window")*/) { if (connection.isConnected()) { final AppWindow appWindow = createAppWindow(); appWindow.setName(name); addWindow(appWindow); connection.addListener(appWindow); return appWindow; } else { /* //noinspection deprecation return getMainWindow(); */ String newWindowName = GlobalUtils.generateWebWindowName(); final Window loginWindow = createLoginWindow(); loginWindow.setName(newWindowName); addWindow(loginWindow); loginWindow.open(new ExternalResource(loginWindow.getURL())); return loginWindow; } } return window; } public void transactionStart(Application application, Object transactionData) { HttpServletRequest request = (HttpServletRequest) transactionData; if (log.isTraceEnabled()) { log.trace("requestStart: [@" + Integer.toHexString(System.identityHashCode(request)) + "] " + request.getRequestURI() + (request.getUserPrincipal() != null ? " [" + request.getUserPrincipal() + "]" : "") + " from " + request.getRemoteAddr()); } if (application == App.this) { currentApp.set((App) application); } application.setLocale(request.getLocale()); if (contextName == null) { contextName = request.getContextPath().substring(1); } String requestURI = request.getRequestURI(); setupCurrentWindowName(requestURI); if (!connection.isConnected() && request.getUserPrincipal() != null && !principalIsWrong && ActiveDirectoryHelper.useActiveDirectory() && !(requestURI.endsWith("/login") || requestURI.endsWith("/UIDL/"))) { String userName = request.getUserPrincipal().getName(); log.debug("Trying to login ActiveDirectory as " + userName); try { connection.loginActiveDirectory(userName); principalIsWrong = false; setupCurrentWindowName(requestURI); } catch (LoginException e) { principalIsWrong = true; } } if (connection.isConnected()) { UserSession userSession = connection.getSession(); if (userSession != null) { WebSecurityUtils.setSecurityAssociation(userSession.getUser().getLogin(), userSession.getId()); application.setLocale(userSession.getLocale()); } requestStartTimes.put(transactionData, System.currentTimeMillis()); } processExternalLink(request, requestURI); } private void setupCurrentWindowName(String requestURI) { //noinspection deprecation currentWindowName.set(getMainWindow() == null ? null : getMainWindow().getName()); if (connection.isConnected()) { String[] parts = requestURI.split("/"); boolean contextFound = false; for (String part : parts) { if (StringUtils.isEmpty(part)) { continue; } if (part.equals(contextName) && !contextFound) { contextFound = true; continue; } if (contextFound && part.equals("UIDL")) { continue; } Matcher m = WIN_PATTERN.matcher(part); if (m.matches()) { currentWindowName.set(part); break; } } } } /* private void setupCurrentWindowName(String requestURI) { //noinspection deprecation currentWindowName.set(getMainWindow() == null ? null : getMainWindow().getName()); if (connection.isConnected()) { String[] parts = requestURI.split("/"); boolean contextFound = false; for (String part : parts) { if (StringUtils.isEmpty(part)) { continue; } if (part.equals(contextName) && !contextFound) { contextFound = true; continue; } if (contextFound && part.equals("UIDL")) { continue; } if (!part.startsWith("open")) { currentWindowName.set(part); } break; } } }*/ private void processExternalLink(HttpServletRequest request, String requestURI) { if (requestURI.endsWith("/open") && !requestURI.contains("/UIDL/")) { Map<String, String> params = new HashMap<String, String>(); Enumeration parameterNames = request.getParameterNames(); while (parameterNames.hasMoreElements()) { String name = (String) parameterNames.nextElement(); params.put(name, request.getParameter(name)); } LinkHandler linkHandler = new LinkHandler(this, params); if (connection.isConnected()) linkHandler.handle(); else this.linkHandler = linkHandler; } } public void transactionEnd(Application application, Object transactionData) { Long start = requestStartTimes.remove(transactionData); if (start != null) { long t = System.currentTimeMillis() - start; WebConfig config = ConfigProvider.getConfig(WebConfig.class); if (t > (config.getLogLongRequestsThresholdSec() * 1000)) { log.warn(String.format("Too long request processing [%d ms]: ip=%s, url=%s", t, ((HttpServletRequest)transactionData).getRemoteAddr(), ((HttpServletRequest)transactionData).getRequestURI())); } } if (application == App.this) { currentApp.set(null); currentApp.remove(); } WebSecurityUtils.clearSecurityAssociation(); if (log.isTraceEnabled()) { log.trace("requestEnd: [@" + Integer.toHexString(System.identityHashCode(transactionData)) + "]"); } } /** * Adds a timer on the application level * @param timer new timer */ public void addTimer(final Timer timer) { addTimer(timer, null, getCurrentWindow()); } /** * Adds a timer for the defined window * @param timer new timer * @param owner component that owns a timer */ public void addTimer(final Timer timer, com.haulmont.cuba.gui.components.Window owner) { addTimer(timer, owner, getCurrentWindow()); } /** * Do not use this method in application code */ public void addTimer(final Timer timer, Window mainWindow) { addTimer(timer, null, mainWindow); } /** * Do not use this method in application code */ public void addTimer(final Timer timer, com.haulmont.cuba.gui.components.Window owner, Window mainWindow) { WindowTimers wt = windowTimers.get(mainWindow); if (wt == null) { wt = new WindowTimers(); windowTimers.put(mainWindow, wt); } if (wt.timers.add(timer)) { timerWindow.put(timer, mainWindow); timer.addListener(new Timer.Listener() { public void onTimer(Timer timer) { } public void onStopTimer(Timer timer) { Window window = timerWindow.get(timer); if (window != null) { WindowTimers wt = windowTimers.get(window); if (wt != null) { wt.timers.remove(timer); if (timer instanceof WebTimer) { wt.idTimers.remove(((WebTimer) timer).getId()); } } } } }); if (timer instanceof WebTimer) { final WebTimer webTimer = (WebTimer) timer; if (owner != null) { owner.addListener(new com.haulmont.cuba.gui.components.Window.CloseListener() { public void windowClosed(String actionId) { timer.stopTimer(); } }); } if (webTimer.getId() != null) { wt.idTimers.put(webTimer.getId(), webTimer); } } } } private void stopTimers() { Set<Timer> timers = new HashSet<Timer>(timerWindow.keySet()); for (final Timer timer : timers) { if (timer != null && !timer.isStopped()) { timer.stopTimer(); } } } /** * Returns a timer by id * @param id timer id * @return timer or <code>null</code> */ public Timer getTimer(String id) { Window currentWindow = getCurrentWindow(); WindowTimers wt = windowTimers.get(currentWindow); if (wt != null) { return wt.idTimers.get(id); } else { return null; } } /** * Do not use this method in application code * @param currentWindow current window * @return collection of timers that applied for the current window */ public Collection<Timer> getAppTimers(Window currentWindow) { WindowTimers wt = windowTimers.get(currentWindow); if (wt != null) { return Collections.unmodifiableSet(wt.timers); } else { return Collections.emptySet(); } } protected static class WindowTimers { protected Map<String, Timer> idTimers = new HashMap<String, Timer>(); protected Set<Timer> timers = new HashSet<Timer>(); } private Window getCurrentWindow() { String name = currentWindowName.get(); return (name == null ? getMainWindow() : getWindow(name)); } public AppCookies getCookies() { return cookies; } public String getCookieValue(String name) { return cookies.getCookieValue(name); } public int getCookieMaxAge(String name) { return cookies.getCookieMaxAge(name); } public void addCookie(String name, String value, int maxAge) { cookies.addCookie(name, value, maxAge); } public void addCookie(String name, String value) { cookies.addCookie(name, value); } public void removeCookie(String name) { cookies.removeCookie(name); } public boolean isCookiesEnabled() { return cookies.isCookiesEnabled(); } public void setCookiesEnabled(boolean cookiesEnabled) { cookies.setCookiesEnabled(cookiesEnabled); } }
package ameba.http.session; import ameba.core.Requests; import ameba.mvc.assets.AssetsResource; import ameba.util.Cookies; import ameba.util.Times; import com.google.common.base.Charsets; import com.google.common.hash.Hashing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Priority; import javax.inject.Singleton; import javax.ws.rs.Priorities; import javax.ws.rs.container.*; import javax.ws.rs.core.*; import java.lang.invoke.MethodHandle; import java.util.List; import java.util.UUID; /** * @author icode */ @PreMatching @Priority(Priorities.AUTHENTICATION - 500) @Singleton public class SessionFilter implements ContainerRequestFilter, ContainerResponseFilter { private static final Logger logger = LoggerFactory.getLogger(SessionFilter.class); private static final String SET_COOKIE_KEY = SessionFilter.class.getName() + ".__SET_SESSION_COOKIE__"; static String SESSION_ID_COOKIE_KEY = "s"; static long SESSION_TIMEOUT = Times.parseDuration("2h"); static int COOKIE_MAX_AGE = NewCookie.DEFAULT_MAX_AGE; static MethodHandle METHOD_HANDLE; @Context private UriInfo uriInfo; private boolean isIgnore() { List<Object> resources = uriInfo.getMatchedResources(); return resources.size() != 0 && AssetsResource.class.isAssignableFrom(resources.get(0).getClass()); } @Override @SuppressWarnings("unchecked") public void filter(ContainerRequestContext requestContext) { if (isIgnore()) { return; } Cookie cookie = requestContext.getCookies().get(SESSION_ID_COOKIE_KEY); boolean isNew = false; if (cookie == null || Cookies.DELETED_COOKIE_VALUE.equals(cookie.getValue())) { isNew = true; cookie = newCookie(requestContext); } AbstractSession session; String host = Requests.getRemoteRealAddr(); if (host == null || host.equals("unknown")) { host = Requests.getRemoteAddr(); } String sessionId = cookie.getValue(); if (METHOD_HANDLE != null) { try { session = (AbstractSession) METHOD_HANDLE.invoke(sessionId, host, SESSION_TIMEOUT, isNew); } catch (Throwable throwable) { throw new SessionExcption("new session instance error"); } } else { session = new CacheSession(sessionId, host, SESSION_TIMEOUT, isNew); } if (!session.isNew()) { try { checkSession(session, requestContext); } catch (Exception e) { logger.warn("get session error", e); } } Session.sessionThreadLocal.set(session); } private void checkSession(AbstractSession session, ContainerRequestContext requestContext) { if (session.isInvalid()) { Cookie cookie = newCookie(requestContext); session.setId(cookie.getValue()); } else { session.touch(); session.flush(); } } protected String newSessionId() { return Hashing.sha1() .hashString( UUID.randomUUID().toString() + Math.random() + this.hashCode() + System.nanoTime(), Charsets.UTF_8 ) .toString(); } private NewCookie newCookie(ContainerRequestContext requestContext) { // URI uri = requestContext.getUriInfo().getBaseUri(); // String domain = uri.getHost(); // // localhost domain must be null // if (domain.equalsIgnoreCase("localhost")) { // domain = null; NewCookie cookie = new NewCookie( SESSION_ID_COOKIE_KEY, newSessionId(), "/", null, Cookie.DEFAULT_VERSION, null, COOKIE_MAX_AGE, null, requestContext.getSecurityContext().isSecure(), true); requestContext.setProperty(SET_COOKIE_KEY, cookie); return cookie; } @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) { if (isIgnore()) { return; } try { Session.flush(); } catch (Exception e) { logger.warn("flush session error", e); } NewCookie cookie = (NewCookie) requestContext.getProperty(SET_COOKIE_KEY); if (cookie == null && Session.isInvalid()) { cookie = Cookies.newDeletedCookie(SESSION_ID_COOKIE_KEY); } if (cookie != null) responseContext.getHeaders().add(HttpHeaders.SET_COOKIE, cookie); Session.sessionThreadLocal.remove(); } }
package cn.effine.contants; public class PageConstants { private PageConstants(){} public static final String SIGNUP = "signup"; }
package com.airbnb.plog; import com.google.common.cache.*; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageDecoder; import lombok.extern.slf4j.Slf4j; import java.util.List; /* TODO(pierre): much more instrumentation */ @Slf4j public class PlogDefragmenter extends MessageToMessageDecoder<MultiPartMessageFragment> { private final StatisticsReporter stats; private final Cache<Long, PartialMultiPartMessage> incompleteMessages; public PlogDefragmenter(StatisticsReporter stats, int maxSize) { this.stats = stats; incompleteMessages = CacheBuilder.newBuilder() .maximumWeight(maxSize) .weigher(new Weigher<Long, PartialMultiPartMessage>() { @Override public int weigh(Long id, PartialMultiPartMessage msg) { return msg.length(); } }) .removalListener(new RemovalListener<Long, PartialMultiPartMessage>() { @Override public void onRemoval(RemovalNotification<Long, PartialMultiPartMessage> notification) { // TODO(pierre): statistics! let's make sure we can discrimate complete messages // from evictions with if (notification.wasEvicted()) } }) .build(); } public CacheStats getCacheStats() { return incompleteMessages.stats(); } private synchronized PartialMultiPartMessage ingestIntoIncompleteMessage(MultiPartMessageFragment fragment) { final long id = fragment.getMsgId(); final PartialMultiPartMessage fromMap = incompleteMessages.getIfPresent(id); if (fromMap != null) { fromMap.ingestFragment(fragment); if (fromMap.isComplete()) { log.debug("complete message"); incompleteMessages.invalidate(fragment.getMsgId()); } else { log.debug("incomplete message"); } return fromMap; } else { PartialMultiPartMessage message = PartialMultiPartMessage.fromFragment(fragment); incompleteMessages.put(id, message); return message; } } @Override protected void decode(ChannelHandlerContext ctx, MultiPartMessageFragment fragment, List<Object> out) throws Exception { PartialMultiPartMessage message; if (fragment.isAlone()) { log.debug("1-packet multipart message"); out.add(fragment.getPayload()); stats.receivedV0MultipartMessage(); } else { log.debug("multipart message"); message = ingestIntoIncompleteMessage(fragment); if (message.isComplete()) { out.add(message.getPayload()); stats.receivedV0MultipartMessage(); } } } }
package com.annimon.ownlang.lib; import com.annimon.ownlang.exceptions.TypeException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.function.Consumer; /** * * @author aNNiMON */ public class MapValue implements Value, Iterable<Map.Entry<Value, Value>> { public static final MapValue EMPTY = new MapValue(1); public static MapValue merge(MapValue map1, MapValue map2) { final MapValue result = new MapValue(map1.size() + map2.size()); result.map.putAll(map1.map); result.map.putAll(map2.map); return result; } private final Map<Value, Value> map; public MapValue(int size) { this.map = new LinkedHashMap<>(size); } public MapValue(Map<Value, Value> map) { this.map = map; } public boolean ifPresent(String key, Consumer<Value> consumer) { return ifPresent(new StringValue(key), consumer); } public boolean ifPresent(Value key, Consumer<Value> consumer) { if (map.containsKey(key)) { consumer.accept(map.get(key)); return true; } return false; } public ArrayValue toPairs() { final int size = map.size(); final ArrayValue result = new ArrayValue(size); int index = 0; for (Map.Entry<Value, Value> entry : map.entrySet()) { result.set(index++, new ArrayValue(new Value[] { entry.getKey(), entry.getValue() })); } return result; } @Override public int type() { return Types.MAP; } public int size() { return map.size(); } public boolean containsKey(Value key) { return map.containsKey(key); } public Value get(Value key) { return map.get(key); } public void set(String key, Value value) { set(new StringValue(key), value); } public void set(String key, Function function) { set(new StringValue(key), new FunctionValue(function)); } public void set(Value key, Value value) { map.put(key, value); } public Map<Value, Value> getMap() { return map; } @Override public Object raw() { return map; } @Override public int asInt() { throw new TypeException("Cannot cast map to integer"); } @Override public double asNumber() { throw new TypeException("Cannot cast map to number"); } @Override public String asString() { return map.toString(); } @Override public Iterator<Map.Entry<Value, Value>> iterator() { return map.entrySet().iterator(); } @Override public int hashCode() { int hash = 5; hash = 37 * hash + Objects.hashCode(this.map); return hash; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final MapValue other = (MapValue) obj; return Objects.equals(this.map, other.map); } @Override public int compareTo(Value o) { if (o.type() == Types.MAP) { final int lengthCompare = Integer.compare(size(), ((MapValue) o).size()); if (lengthCompare != 0) return lengthCompare; } return asString().compareTo(o.asString()); } @Override public String toString() { return asString(); } }
package com.attask.jenkins; import hudson.*; import hudson.model.*; import hudson.tasks.*; import hudson.tasks.Messages; import hudson.util.ListBoxModel; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.util.*; @ExportedBean public class ScriptBuilder extends Builder { public static final boolean CONTINUE = true; public static final boolean ABORT = false; private final String scriptName; //will be an absolute path private final List<Parameter> parameters; private final boolean abortOnFailure; private final ErrorMode errorMode; private final String errorRange; private final ErrorMode unstableMode; private final String unstableRange; private final String injectProperties; private final boolean runOnMaster; @DataBoundConstructor public ScriptBuilder(String scriptName, List<Parameter> parameters, boolean abortOnFailure, ErrorMode errorMode, String errorRange, ErrorMode unstableMode, String unstableRange, String injectProperties, boolean runOnMaster) { this.scriptName = scriptName; if (parameters == null) { this.parameters = Collections.emptyList(); } else { this.parameters = Collections.unmodifiableList(new ArrayList<Parameter>(parameters)); } this.abortOnFailure = abortOnFailure; this.errorMode = errorMode; this.errorRange = errorRange; this.unstableMode = unstableMode; this.unstableRange = unstableRange; this.injectProperties = injectProperties; this.runOnMaster = runOnMaster; } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, final BuildListener listener) throws InterruptedException, IOException { return runScript(build, launcher, listener); } private boolean runScript(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { Result result; final Map<String, Script> runnableScripts = findRunnableScripts(); Script script = runnableScripts.get(scriptName); if (script != null) { //If we want to run it on master, do so. But if the job is already running on master, just run it as if the run on master flag isn't set. if (this.runOnMaster && !(launcher instanceof Launcher.LocalLauncher)) { FilePath workspace = Jenkins.getInstance().getRootPath().createTempDir("Workspace", "Temp"); try { Launcher masterLauncher = new Launcher.RemoteLauncher(listener, workspace.getChannel(), true); result = execute(build, masterLauncher, listener, script); } finally { workspace.deleteRecursive(); } } else { result = execute(build, launcher, listener, script); } } else { listener.error("'" + scriptName + "' doesn't exist anymore. Failing."); result = Result.FAILURE; } injectProperties(build, listener); build.setResult(result); boolean failed = result.isWorseOrEqualTo(Result.FAILURE); if(failed) { if(abortOnFailure) { listener.getLogger().println("Abort on Failure is enabled: Aborting."); return ABORT; } else { listener.getLogger().println("Abort on Failure is disabled: Continuing."); return CONTINUE; } } else { return CONTINUE; } } private Map<String, String> injectParameters(List<Parameter> parameters, EnvVars envVars) { Map<String, String> result = new HashMap<String, String>(); for (Parameter parameter : parameters) { String key = parameter.getParameterKey(); String value = envVars.expand(parameter.getParameterValue()); result.put(key, value); } return result; } private Result execute(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener, Script script) throws IOException, InterruptedException { String scriptContents = script.findScriptContents(); int exitCode; CommandInterpreter commandInterpreter; if (launcher.isUnix()) { commandInterpreter = new Shell(scriptContents); } else { commandInterpreter = new BatchFile(scriptContents); } PrintStream logger = listener.getLogger(); logger.println("========================================"); logger.println("Executing: " + script.getFile().getName()); logger.println(" long startTime = System.currentTimeMillis(); exitCode = executeScript(build, launcher, listener, commandInterpreter); long runTime = System.currentTimeMillis() - startTime; Result result = ExitCodeParser.findResult(exitCode, errorMode, errorRange, unstableMode, unstableRange); logger.println(" logger.println(script.getFile().getName() + " finished in " + runTime + "ms."); logger.println("Exit code was " + exitCode + ". " + result + "."); return result; } /** * <p> * This method is simply an inline of * {@link CommandInterpreter#perform(hudson.model.AbstractBuild, hudson.Launcher, hudson.model.TaskListener)}, * but returning the exit code instead of a boolean. * Also, I've cleaned up the code a bit. * Tried to remove any inspection warnings, renamed variables so they would be useful, and added curly braces. * </p> * <p> * If that method ever gets updated, this one should be too. * Obviously the better solution is to change the CommandInterpreter to have two public methods, * one that returns the integer value. * </p> * <p> * The reason I do this is because the exit code provides useful user customization. * So now the user can define if the script fails or goes unstable or even remains successful for certain exit codes. * </p> */ private int executeScript(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener, CommandInterpreter command) throws InterruptedException, IOException { FilePath ws = build.getWorkspace(); FilePath script = null; try { try { script = command.createScriptFile(ws); } catch (IOException e) { Util.displayIOException(e, listener); e.printStackTrace(listener.fatalError(Messages.CommandInterpreter_UnableToProduceScript())); return -2; } int exitCode; try { EnvVars envVars = build.getEnvironment(listener); Map<String, String> varsToInject = injectParameters(parameters, envVars); envVars.putAll(varsToInject); // on Windows environment variables are converted to all upper case, // but no such conversions are done on Unix, so to make this cross-platform, // convert variables to all upper cases. for (Map.Entry<String, String> e : build.getBuildVariables().entrySet()) { envVars.put(e.getKey(), e.getValue()); } exitCode = launcher.launch().cmds(command.buildCommandLine(script)).envs(envVars).stdout(listener).pwd(ws).join(); } catch (IOException e) { Util.displayIOException(e, listener); e.printStackTrace(listener.fatalError(Messages.CommandInterpreter_CommandFailed())); throw e; } return exitCode; } finally { try { if (script != null) { script.delete(); } } catch (IOException e) { Util.displayIOException(e, listener); e.printStackTrace(listener.fatalError(Messages.CommandInterpreter_UnableToDelete(script))); } } } private void injectProperties(AbstractBuild<?, ?> build, BuildListener listener) throws IOException { PrintStream logger = listener.getLogger(); if (getInjectProperties() != null && !getInjectProperties().isEmpty()) { logger.println("injecting properties from " + getInjectProperties()); FilePath filePath = new FilePath(build.getWorkspace(), getInjectProperties()); Properties injectedProperties = new Properties(); InputStream read = filePath.read(); try { injectedProperties.load(read); } finally { read.close(); } Map<String, String> result = new HashMap<String, String>(injectedProperties.size()); for (Map.Entry<Object, Object> entry : injectedProperties.entrySet()) { logger.println("\t" + entry.getKey() + " => " + entry.getValue()); result.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue())); } build.addAction(new InjectPropertiesAction(result)); } logger.println("========================================"); logger.println(); } @Exported public String getScriptName() { return scriptName; } @Exported public List<Parameter> getParameters() { return parameters; } @Exported public boolean getAbortOnFailure() { return abortOnFailure; } @Exported public ErrorMode getErrorMode() { return errorMode; } @Exported public String getErrorRange() { return errorRange; } @Exported public ErrorMode getUnstableMode() { return unstableMode; } @Exported public String getUnstableRange() { return unstableRange; } @Exported public String getInjectProperties() { return injectProperties; } /** * If true the script runs on the master node in a temporary directory rather than on the machine the build is running on. */ @Exported public boolean getRunOnMaster() { return runOnMaster; } @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl) super.getDescriptor(); } public Map<String, Script> findRunnableScripts() throws IOException, InterruptedException { FilePath rootPath = Jenkins.getInstance().getRootPath(); FilePath userContent = new FilePath(rootPath, "userContent"); DescriptorImpl descriptor = getDescriptor(); return descriptor.findRunnableScripts(userContent); } @Extension public static final class DescriptorImpl extends BuildStepDescriptor<Builder> { public String fileTypes; @Override public boolean configure(StaplerRequest request, JSONObject formData) throws FormException { fileTypes = formData.getString("fileTypes"); save(); return super.configure(request, formData); } public String getFileTypes() { load(); if (fileTypes == null || fileTypes.isEmpty()) { return ".*"; } return fileTypes; } @Exported public ListBoxModel doFillScriptNameItems() { FilePath rootPath = Jenkins.getInstance().getRootPath(); FilePath userContent = new FilePath(rootPath, "userContent"); ListBoxModel items = new ListBoxModel(); for (Script script : findRunnableScripts(userContent).values()) { //Pretty up the name String path = script.getFile().getRemote(); path = path.substring(userContent.getRemote().length() + 1); items.add(path, script.getFile().getRemote()); } return items; } @Exported public String getGuid() { return UUID.randomUUID().toString().replaceAll("-", ""); } private Map<String, Script> findRunnableScripts(FilePath userContent) { final List<String> fileTypes = Arrays.asList(this.getFileTypes().split("\\s+")); try { return userContent.act(new FindScriptsOnMaster(userContent, fileTypes)); } catch (IOException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } } public ListBoxModel doFillErrorModeItems() { ListBoxModel items = new ListBoxModel(); for (ErrorMode errorMode : ErrorMode.values()) { items.add(errorMode.getHumanReadable(), errorMode.toString()); } return items; } @Exported public ListBoxModel doFillUnstableModeItems() { return doFillErrorModeItems(); } @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; } @Override public String getDisplayName() { return "Execute UserContent Script"; } } }
package com.easycamera; import android.graphics.SurfaceTexture; import android.hardware.Camera; import android.view.SurfaceHolder; import java.io.IOException; public class DefaultEasyCamera implements EasyCamera { private Camera camera; public static final EasyCamera open() { return new DefaultEasyCamera(Camera.open()); } public static final EasyCamera open(int id) { return new DefaultEasyCamera(Camera.open(id)); } private DefaultEasyCamera(Camera camera) { this.camera = camera; } @Override public CameraActions startPreview(SurfaceHolder holder) throws IOException { if (holder == null) { throw new NullPointerException("You cannot start preview without a preview surface"); } camera.setPreviewDisplay(holder); return new DefaultCameraActions(camera); } @Override public CameraActions startPreview(SurfaceTexture texture) throws IOException { if (texture == null) { throw new NullPointerException("You cannot start preview without a preview texture"); } camera.setPreviewTexture(texture); return new DefaultCameraActions(camera); } @Override public void close() { camera.release(); } @Override public void unlock() { camera.unlock(); } @Override public void lock() { camera.lock(); } @Override public void reconnect() throws IOException { camera.reconnect(); } @Override public void stopPreview() { camera.stopPreview(); } @Override public void setPreviewCallback(Camera.PreviewCallback cb) { camera.setPreviewCallback(cb); } @Override public void setOneShotPreviewCallback(Camera.PreviewCallback cb) { camera.setOneShotPreviewCallback(cb); } @Override public void setPreviewCallbackWithBuffer(Camera.PreviewCallback cb) { camera.setPreviewCallbackWithBuffer(cb); } @Override public void addCallbackBuffer(byte[] callbackBuffer) { camera.addCallbackBuffer(callbackBuffer); } @Override public void autoFocus(Camera.AutoFocusCallback cb) { camera.autoFocus(cb); } @Override public void cancelAutoFocus() { camera.cancelAutoFocus(); } @Override public void startSmoothZoom(int value) { camera.startSmoothZoom(value); } @Override public void stopSmoothZoom() { camera.stopSmoothZoom(); } @Override public void setDisplayOrientation(int degrees) { camera.setDisplayOrientation(degrees); } @Override public void setZoomChangeListener(Camera.OnZoomChangeListener listener) { camera.setZoomChangeListener(listener); } @Override public void setErrorCallback(Camera.ErrorCallback cb) { camera.setErrorCallback(cb); } @Override public void setParameters(Camera.Parameters parameters) { camera.setParameters(parameters); } @Override public Camera.Parameters getParameters() { return camera.getParameters(); } @Override public Camera getRawCamera() { return camera; } }
package com.extjs.selenium.button; import com.extjs.selenium.ExtJsComponent; import com.extjs.selenium.Utils; import com.sdl.selenium.web.SearchType; import com.sdl.selenium.web.WebDriverConfig; import com.sdl.selenium.web.WebLocator; import org.apache.log4j.Logger; import org.openqa.selenium.Keys; public class Button extends ExtJsComponent { private static final Logger logger = Logger.getLogger(Button.class); public String getIconCls() { return iconCls; } public <T extends Button> T setIconCls(final String iconCls) { this.iconCls = iconCls; return (T) this; } private String iconCls; public Boolean hasIconCls() { return iconCls != null && !iconCls.equals(""); } public Button() { setClassName("Button"); setBaseCls("x-btn"); setTag("table"); setVisibility(true); defaultSearchTextType.add(SearchType.DEEP_CHILD_NODE); } /** * @param cls * @deprecated */ public Button(String cls) { this(); setClasses(cls); } /** * @param container */ public Button(WebLocator container) { this(); setContainer(container); } public Button(WebLocator container, String text) { this(container); setText(text, SearchType.EQUALS); } // Methods @Override protected String getItemPathText() { String selector = hasText() ? super.getItemPathText() : ""; if (hasIconCls()) { /** * TO Be used in extreme cases when simple .click is not working * * @return */ public boolean clickWithExtJS() { String id = getAttributeId(); String script = "return (function(){var b = Ext.getCmp('" + id + "'); if(b) {b.handler.call(b.scope || b, b); return true;} return false;})()"; // logger.debug("clickWithExtJS: "+ script); Object object = executeScript(script); logger.debug("clickWithExtJS result: " + object); return (Boolean) object; } /** * Using XPath only * * @return */ public boolean isDisabled() { return new WebLocator(null, getPath(true)).exists(); } /** * @param milliseconds * @return */ public boolean waitToEnable(long milliseconds) { return waitToRender(milliseconds); } /** * @return */ public boolean isEnabled() { return exists(); } /** * @return */ public boolean showMenu() { // TODO try to find solution without runScript final String id = getAttributeId(); if (id != null && !id.equals("")) { String script = "Ext.getCmp('" + id + "').showMenu()"; Boolean showMenu = (Boolean) executeScript(script); Utils.sleep(200); return showMenu; } return false; } /** * new String[]{"option1", "option2", "option3-click"} * * @param menuOptions * @return */ public boolean clickOnMenu(String[] menuOptions) { logger.debug("clickOnMenu : " + menuOptions[menuOptions.length - 1]); if (click()) { String info = toString(); // logger.info("Click on button " + info); // TODO try to use Menu class for implementing select item WebLocator menu = new WebLocator("x-menu-floating"); if (WebDriverConfig.isIE()) { // menu.isVisible is not considered but is executed and is just consuming time. // if(menu.isVisible()){ // logger.info("In IE is visible"); } else { menu.setStyle("visibility: visible;"); } menu.setInfoMessage("active menu"); ExtJsComponent option = new ExtJsComponent(menu); for (String menuOption : menuOptions) { option.setText(menuOption); if (!option.mouseOver()) { return false; } } if (option.clickAt()) { return true; } else { logger.warn("Could not locate option '" + option.getText() + "'. Performing simple click on button : " + info); doClickAt(); } } return false; } /** * @param option * @return */ public boolean clickOnMenu(String option) { return clickOnMenu(new String[]{option}); } }
package ru.kru.nick; import ru.kru.nick.deck.Deck; import javax.persistence.*; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.regex.MatchResult; @Entity @Table(name = "PLAYERS") public class Player { Long id; Date registerDate; HashMap<Player, Statistics> statistics; String firstName; String lastName; String nickName; List<Player> friends; List<Deck> decks; List<MatchResult> matchHistory; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "PLAYER_ID") public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name = "FIRST_NAME") public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @Column(name = "LAST_NAME") public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Column(name = "NICKNAME") public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } @Column(name = "JOIN_DATE") @Temporal(TemporalType.DATE) public Date getRegisterDate() { return registerDate; } public void setRegisterDate(Date registerDate) { this.registerDate = registerDate; } @ManyToMany @JoinTable(name = "PLAYERS", joinColumns = @JoinColumn(name = "PLAYER_ID"), inverseJoinColumns = @JoinColumn(name = "PLAYER_ID")) public List<Player> getFriends() { return friends; } public void setFriends(List<Player> friends) { this.friends = friends; } @OneToMany(mappedBy = "PLAYERS", cascade = CascadeType.ALL, orphanRemoval = true) public List<Deck> getDecks() { return decks; } public void setDecks(List<Deck> decks) { this.decks = decks; } public HashMap<Player, Statistics> getStatistics() { return statistics; } public void setStatistics(HashMap<Player, Statistics> statistics) { this.statistics = statistics; } @ManyToMany @JoinTable(name = "MATCH_DETAIL", joinColumns = @JoinColumn(name = "PLAYER_ID"), inverseJoinColumns = @JoinColumn(name = "MATCH_ID")) public List<MatchResult> getMatchHistory() { return matchHistory; } public void setMatchHistory(List<MatchResult> matchHistory) { this.matchHistory = matchHistory; } }
// Unless required by applicable law or agreed to in writing, software // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. package com.google.sps.data; import com.google.api.gax.rpc.FixedHeaderProvider; import com.google.api.gax.rpc.HeaderProvider; import com.google.api.gax.rpc.InvalidArgumentException; import com.google.cloud.language.v1.AnalyzeEntitiesRequest; import com.google.cloud.language.v1.AnalyzeEntitiesResponse; import com.google.cloud.language.v1.AnalyzeSyntaxRequest; import com.google.cloud.language.v1.AnalyzeSyntaxResponse; import com.google.cloud.language.v1.ClassificationCategory; import com.google.cloud.language.v1.ClassifyTextRequest; import com.google.cloud.language.v1.ClassifyTextResponse; import com.google.cloud.language.v1.Document; import com.google.cloud.language.v1.Document.Type; import com.google.cloud.language.v1.EncodingType; import com.google.cloud.language.v1.Entity; import com.google.cloud.language.v1.EntityMention; import com.google.cloud.language.v1.LanguageServiceClient; import com.google.cloud.language.v1.LanguageServiceSettings; import com.google.cloud.language.v1.Sentiment; import com.google.cloud.language.v1.Token; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /** * This class creates objects that analyse text by * extracting the categories, the mood, the events. * The scope is to get a final set of the key words * from the text. **/ public final class TextAnalyser { private final String message; private static final double EPSILON = 0.00001; public TextAnalyser(String message) { this.message = message.toLowerCase(); } public final LanguageServiceSettings getSettings() throws IOException { HeaderProvider headerProvider = FixedHeaderProvider.create("X-Goog-User-Project","google.com:gpostcard"); return LanguageServiceSettings.newBuilder() .setHeaderProvider(headerProvider) .build(); } public float getSentimentScore() throws IOException { try (LanguageServiceClient languageService = LanguageServiceClient.create(getSettings())) { Document doc = Document.newBuilder().setContent(message).setType(Document.Type.PLAIN_TEXT).build(); Sentiment sentiment = languageService.analyzeSentiment(doc).getDocumentSentiment(); return sentiment.getScore(); } } public String getMood() throws IOException { float score = getSentimentScore(); if (Math.abs(score - 1) < EPSILON) { return "very happy"; } if (Math.abs(score + 1) < EPSILON) { return "so pessimistic"; } /** * From (-1, 1) the words are displayed on the x axis based on the sentiment score like this: * * pessimistic (-0.9), fatigued (-0.8), bored, depressed, sad, upset, stressed, nervous, tense (-0.1), * neutral(0.0), calm (0.1), relaxed, serene, contented, joyful, happy, delighted, excited, thrilled (0.9) * * If the score is >= 0 then the mood is at position (int) (score * 10) => first 10 moods are ordered * based on the sentiment score of the text from 0.0 to 0.9 (0.1 incrementation) * * If the score is negative, return the mood at position (int) (score * 10) * (-1) + 9 => next 9 moods are ordered * based on the sentiment score of the text from -0.1 to -0.9 (-0.1 incrementation) **/ int position = 0; String[] moods = new String[] {"neutral", "calm", "relaxed", "serene", "contented", "joyful", "happy", "delighted", "excited", "happy", "tense", "nervous", "stressed", "upset", "sad", "depressed", "bored", "fatigued", "pessimistic"}; assert moods.length == 19 : "There can only be 19 moods."; position = (int) (score * 10); if (position < 0) { position = position * (-1) + 9; } return moods[position]; } private ClassifyTextResponse classify() throws InvalidArgumentException, IOException { try (LanguageServiceClient language = LanguageServiceClient.create(getSettings())) { Document document = Document.newBuilder().setContent(message).setType(Type.PLAIN_TEXT).build(); ClassifyTextRequest request = ClassifyTextRequest.newBuilder().setDocument(document).build(); return language.classifyText(request); } } // list of all the categories that text is about public Set<String> getCategories() throws IOException { try { Set<String> categories = new LinkedHashSet<String>(); for (ClassificationCategory category : classify().getCategoriesList()) { String[] listCategories = category.getName().split("/"); for (int i = 0; i < listCategories.length; i++) { categories.add(listCategories[i].toLowerCase()); } } return categories; } catch (InvalidArgumentException e) { e.printStackTrace(); return Collections.emptySet(); } } public Set<String> getEvents() { Set<String> events = new LinkedHashSet<String>(); String[] allEvents = new String[] {"wedding", "baby shower", "travel", "promotion", "holiday", "graduation", "funeral", "party"}; for (int i = 0; i < allEvents.length; i++) { if (message.indexOf(allEvents[i]) != -1) { events.add(allEvents[i]); } } return events; } public Set<String> getGreetings() { Set<String> greetings = new LinkedHashSet<String>(); String[] allGreetings = new String[] {"good morning", "congratulation", "welcome", "good evening", "good night", "happy holiday", "good afternoon", "hello", "hey", "happy birthday", "love you"}; for (int i = 0; i < allGreetings.length; i++) { if (message.indexOf(allGreetings[i]) != -1) { greetings.add(allGreetings[i]); } } return greetings; } /** Identifies entities in the string */ private AnalyzeEntitiesResponse analyzeEntitiesText() throws IOException { try (LanguageServiceClient language = LanguageServiceClient.create(getSettings())) { Document doc = Document.newBuilder().setContent(message).setType(Type.PLAIN_TEXT).build(); AnalyzeEntitiesRequest request = AnalyzeEntitiesRequest.newBuilder() .setDocument(doc) .setEncodingType(EncodingType.UTF16) .build(); return language.analyzeEntities(request); } } public Set<String> getEntities() throws IOException { AnalyzeEntitiesResponse response = analyzeEntitiesText(); Set<String> entities = new LinkedHashSet<String>(); for (Entity entity : response.getEntitiesList()) { entities.add(entity.getName()); } return entities; } public AnalyzeSyntaxResponse analyseSyntaxText() throws IOException { try (LanguageServiceClient language = LanguageServiceClient.create(getSettings())) { Document doc = Document.newBuilder().setContent(message).setType(Type.PLAIN_TEXT).build(); AnalyzeSyntaxRequest request = AnalyzeSyntaxRequest.newBuilder() .setDocument(doc) .setEncodingType(EncodingType.UTF16) .build(); return language.analyzeSyntax(request); } } public Set<String> getAdjectives() throws IOException { Set<String> adjectives = new LinkedHashSet<String>(); for (Token token : analyseSyntaxText().getTokensList()) { String partOfSpeech = token.getPartOfSpeech().getTag().toString(); if(partOfSpeech.equals("ADJ")) { adjectives.add(token.getLemma().toLowerCase()); } } return adjectives; } public String checkInjection() { if (message.indexOf("<script>") != -1 || message.indexOf("</script>") != -1 || message.indexOf("<html>") != -1 || message.indexOf("</html>") != -1) { return "html-injection"; } return "no-html-injection"; } // put all the key words together // use a LinkedHashSet to remove duplicates but maintain order public Set<String> getKeyWords() { try { Set<String> keyWords = new LinkedHashSet<String>(); keyWords.addAll(getGreetings()); keyWords.addAll(getEvents()); keyWords.addAll(getEntities()); keyWords.addAll(getCategories()); keyWords.addAll(getAdjectives()); keyWords.add(getMood()); return keyWords; } catch (IOException e) { // no key words System.err.println("There are no key words."); return Collections.emptySet(); } } }
package com.jayson.utils.jpeg; import com.jayson.utils.Historgram; import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.util.HashMap; import java.util.Map; import java.util.Set; import static com.jayson.utils.jpeg.b2i.i16; public class JPEGParser implements Closeable{ /** * start of image */ public static final int SOI = 0xFFD8; public static final String[] COLORS_GREY = new String[]{"L"}; public static final String[] COLORS_YCrCb = new String[]{" Y", "Cr", "Cb"}; public static final String[] COLORS_CMYK = new String[]{"C", "M", "Y", "K"}; private FileInputStream mIs; public JPEGParser(String filename) throws IOException, InvalidJpegFormatException { mIs = new FileInputStream(filename); byte[] bytes = new byte[2]; try { mIs.read(bytes); } catch (IOException e) { e.printStackTrace(); } if(i16(bytes) != SOI){ throw new InvalidJpegFormatException(); } mIs.read(bytes); } @Override public void close() throws IOException { if (mIs != null){ mIs.close(); mIs = null; } } /** * * @return jpeg(,) * @throws InvalidJpegFormatException */ public JPEGImage parse() throws InvalidJpegFormatException { JPEGImage imgObject = new JPEGImage(); byte[] bytes = new byte[2]; BlockParser parser = new BlockParser(imgObject); try { while (true){ mIs.read(bytes); int marker = i16(bytes); JPEGMarkInfo info = JPEGMarker.getMarkInfo(marker); if(info == null){ System.err.println("null info!"); continue; } System.out.println("block:"+info.mName+" "+info.mDescription); switch (info.mType) { case JPEGMarkInfo.TYPE_APP: parser.parseApp(marker); break; case JPEGMarkInfo.TYPE_DQT: parser.parseDQT(marker); break; case JPEGMarkInfo.TYPE_SOF: parser.parseSOF(marker); break; case JPEGMarkInfo.TYPE_DHT: parser.parseDHT(marker); break; case JPEGMarkInfo.TYPE_DRI: System.err.println("DRI happen!"); parser.parseDRI(marker); break; case JPEGMarkInfo.TYPE_SKIP: parser.parseSkip(marker); break; case JPEGMarkInfo.TYPE_SOS: parser.parseSOS(marker); parser.startScan(); close(); return imgObject; default: System.err.print("unhandled mark:" + marker); break; } } } catch (IOException e) { e.printStackTrace(); return null; } } private class BlockParser{ private JPEGImage mImg; public BlockParser(JPEGImage imgObject) { try { mImg = imgObject; byte[] bytes = new byte[2]; mIs.read(bytes); int num = i16(bytes)-2; bytes = new byte[num]; mIs.read(bytes); } catch (IOException e) { e.printStackTrace(); } } void parseSkip(int marker){ try { byte[] bytes = new byte[2]; mIs.read(bytes); int num = i16(bytes)-2; bytes = new byte[num]; mIs.read(bytes); } catch (IOException e) { e.printStackTrace(); } } void parseApp(int marker){ try { byte[] bytes = new byte[2]; mIs.read(bytes); int num = i16(bytes)-2; bytes = new byte[num]; mIs.read(bytes); String app = String.format("APP%d", (marker&0xF)); mImg.setAppInfo(app, bytes); if (marker == 0xFFE0 && cmpByte2Str(bytes,0,"JFIF\0")){ // JFIF int version = i16(bytes, 5); String jfif_unit; switch (bytes[7]){ case 1: jfif_unit = "points/inch"; break; case 2: jfif_unit = "points/cm"; break; default: jfif_unit = "None"; break; } int jfif_destiny_x,jfif_destiny_y; jfif_destiny_x = i16(bytes, 8); jfif_destiny_y = i16(bytes, 10); mImg.setJFIFInfo(version, jfif_unit, jfif_destiny_x, jfif_destiny_y); int thumbnail_horizontal_pixels, thumbnail_vertical_pixels; thumbnail_horizontal_pixels = bytes[12]; thumbnail_vertical_pixels = bytes[13]; int thumbnail_size = 3*thumbnail_horizontal_pixels*thumbnail_vertical_pixels; int[] thumbnail_RGB_bitmap = new int[thumbnail_size]; for (int i = 0; i != thumbnail_size; ++i){ thumbnail_RGB_bitmap[i] = (bytes[i+14] & 0xff); } mImg.setThumbnail(thumbnail_horizontal_pixels, thumbnail_vertical_pixels, thumbnail_RGB_bitmap); }else if(marker == 0xFFE1 && cmpByte2Str(bytes,0,"Exif\0")){ // TODO exif }else if(marker == 0xFFE2 && cmpByte2Str(bytes,0,"FPXR\0")){ // TODO FlashPix }else if(marker == 0xFFE2 && cmpByte2Str(bytes,0,"ICC_PROFILE\0")){ // TODO ICC profile() // # Since an ICC profile can be larger than the maximum size of // # a JPEG marker (64K), we need provisions to split it into // # multiple markers. The format defined by the ICC specifies // # one or more APP2 markers containing the following data: // # Identifying string ASCII "ICC_PROFILE\0" (12 bytes) // # Marker sequence number 1, 2, etc (1 byte) // # Number of markers Total of APP2's used (1 byte) // # Profile data (remainder of APP2 data) // # Decoders should use the marker sequence numbers to // # reassemble the profile, rather than assuming that the APP2 // # markers appear in the correct sequence. // self.icclist.append(s) }else if(marker == 0xFFEE && cmpByte2Str(bytes,0,"Adobe\0")){ // TODO Adobe int adobe = i16(bytes,5); int adobe_transform = bytes[1]; } } catch (IOException e) { e.printStackTrace(); } } void parseDQT(int marker) { try { byte[] bytes = new byte[2]; mIs.read(bytes); int num = i16(bytes)-2; bytes = new byte[num]; mIs.read(bytes); // DQT int[] scan_index = new int[]{0}; while (scan_index[0] < num){ JPEGDQT dqt = new JPEGDQT(bytes, scan_index); mImg.setDQT(dqt); } } catch (IOException e) { e.printStackTrace(); } } void parseSOF(int marker) throws InvalidJpegFormatException { try { byte[] bytes = new byte[2]; mIs.read(bytes); int num = i16(bytes)-2; bytes = new byte[num]; mIs.read(bytes); int precision = bytes[0]; if (precision != 8){ throw new InvalidJpegFormatException(":"+precision+".8"); } int height = i16(bytes, 1); int width = i16(bytes, 3); mImg.setSize(width, height); switch (bytes[5]) { case 1: mImg.setColors(COLORS_GREY); break; case 3: mImg.setColors(COLORS_YCrCb); break; case 4: mImg.setColors(COLORS_CMYK); break; default: throw new InvalidJpegFormatException(); } for(int i=6;i!=bytes.length;i+=3){ // idid int color_id = bytes[i]; int v_samp = bytes[i+1] >>> 4; int h_samp = bytes[i+1] & 0x0f; int DQT_id = bytes[i+2]; mImg.setLayer(new JPEGImage.JPEGLayer(color_id, v_samp, h_samp, DQT_id)); } } catch (IOException e) { e.printStackTrace(); } } void parseDHT(int marker){ try { byte[] bytes = new byte[2]; mIs.read(bytes); int num = i16(bytes)-2; bytes = new byte[num]; mIs.read(bytes); int[] scan_index = new int[]{0}; while (scan_index[0] < num) { JPEGHuffman ht = new JPEGHuffman(bytes, scan_index); mImg.setHuffman(ht); } } catch (IOException e) { e.printStackTrace(); } } void parseSOS(int marker) throws InvalidJpegFormatException { try { byte[] bytes = new byte[2]; mIs.read(bytes); int num = i16(bytes)-2; bytes = new byte[num]; mIs.read(bytes); int color_type = bytes[0]; for(int i=0,base=1;i!=color_type;++i,base+=2){ int color_id = bytes[base] ; int dc_huffman_id = bytes[base+1] >>> 4; int ac_huffman_id = bytes[base+1] & 0xf; JPEGImage.JPEGLayer layer = mImg.getLayer(color_id); layer.setHuffman(dc_huffman_id, ac_huffman_id); } } catch (IOException e) { e.printStackTrace(); } } public void parseDRI(int marker) { } private void startScan(){ try { JPEGBitInputStream bis = new JPEGBitInputStream(mIs); Set<Integer> color_ids = mImg.getColorIDs(); Map<Integer, Integer> dc_base = new HashMap<Integer, Integer>(); while (true) { scanColorUnit(bis, color_ids, dc_base); } } catch (IOException e) { e.printStackTrace(); } catch (MarkAppearException e) { // EOI.End of Image System.out.println("End of Image."); } } private void scanColorUnit(JPEGBitInputStream bis, Set<Integer> color_ids, Map<Integer, Integer> dc_base) throws MarkAppearException, IOException { for (int color_id : color_ids) { JPEGImage.JPEGLayer layer = mImg.getLayer(color_id); for (int i = 0; i != layer.mHSamp*layer.mVSamp; ++i){ // System.out.print(mImg.getColors()[color - 1] + ":"); int dc_new = 0; try { dc_new = scanColor(bis, layer, dc_base.getOrDefault(color_id, 0)); // base dc_base.put(color_id, dc_new); } catch (MarkAppearException e){ // EOI if (e.mark == 0xd9){ throw e; } // RSTn,base FIXME : ? System.err.println("Mark : RSTn "+e.mark+" color:"+color_id); dc_base.put(color_id, 0); } } } } private int scanColor(JPEGBitInputStream bis, JPEGImage.JPEGLayer layer, int dc_base) throws MarkAppearException, IOException { JPEGHuffman huffman; StringBuffer buf = new StringBuffer(); Integer weight; int[] unit = new int[64]; // DC diffbit do { buf.append(bis.readBit()); huffman = mImg.getHuffman(JPEGHuffman.TYPE_DC, layer.mDCHuffmanID); weight = huffman.find(buf.toString()); }while (weight == null); // DCdiff()+UnitDC int dc_val = dc_base + convert(bis.readBitsString(weight)); unit[0] = dc_val; // System.out.print(String.format("DC:%3d",dc_val)); // System.out.print(" AC:"); for (int i = 1; i < 64; ++i){ buf = new StringBuffer(); do { buf.append(bis.readBit()); huffman = mImg.getHuffman(JPEGHuffman.TYPE_AC, layer.mACHuffmanID); weight = huffman.find(buf.toString()); }while ( weight == null ); if(weight == 0){ // System.out.print(String.format(", 0x%02x:",weight)); // 0AC0 for ( ; i < 64; ++i){ unit[i] = 0; } break; } int pre_zeros = weight >>> 4; for (int j = 0; j != pre_zeros; ++j){ unit[i+pre_zeros] = 0; } // i64 i += pre_zeros; // 4ACbit int nBit_read = weight & 0x0f; int ac_val = convert(bis.readBitsString(nBit_read)); unit[i] = ac_val; // System.out.print(String.format(", 0x%02x:(%2d, %2d)", // weight, pre_zeros, ac_val)); } mImg.addDataUnit(unit); // System.out.println(" END"); return dc_val; } private int convert(String nStr){ if (nStr == null || nStr.length()==0){ return 0; } int num = Integer.parseInt(nStr, 2); int max_val = 1<<(nStr.length()-1); if (num < max_val ){ num = -(max_val<<1) + num+1; } return num; } private boolean cmpByte2Str(byte[] bytes, int offset, String str){ for (int i=0;i!=str.length();++i){ if(str.charAt(i) != bytes[offset+i]){ return false; } } return true; } } public static class InvalidJpegFormatException extends Exception{ InvalidJpegFormatException(){ super(); } InvalidJpegFormatException(String message){ super(message); } } public static class MarkAppearException extends Exception{ public int mark; MarkAppearException(int mark){ super(String.format("Mark 0xFF%02x Appear!", mark)); this.mark = mark; } } public static void main(String[] args){ BufferedOutputStream os = null; PrintStream ps = null; // try { // os = new BufferedOutputStream(new FileOutputStream("result_my.txt"), 1024); // ps = new PrintStream(os, false); // System.setOut(ps); // } catch (FileNotFoundException e) { // e.printStackTrace(); String[] pics = { "/Users/JaySon/Desktop/test.jpg", "/Users/JaySon/Pictures/IMG_20140508_085331.jpg", "/Users/JaySon/Pictures/IMG_20140508_085558.jpg", "/Users/JaySon/Pictures/IMG_20140508_090150.jpg", "/Users/JaySon/Pictures/IMG_20140508_092000.jpg", "/Users/JaySon/Pictures/IMG_20140508_115427.jpg", "/Users/JaySon/Pictures/IMG_20140508_140426.jpg", "/Users/JaySon/Pictures/IMG_20140810_122739.jpg", "/Users/JaySon/Pictures/IMG_20140810_122739_1.jpg", "/Users/JaySon/Pictures/IMG_20140810_122741.jpg", "/Users/JaySon/Pictures/IMG_20140810_151927.jpg", "/Users/JaySon/Pictures/PANO_20140613_191243.jpg", "/Users/JaySon/Pictures/ .jpg" }; JPEGParser parser = null; try { Historgram[] historgrams = new Historgram[64]; for (String pic : pics) { System.out.println("Parsing:"+pic); parser = new JPEGParser(pic); JPEGImage img = parser.parse(); for (int i = 0; i != historgrams.length; ++i) { historgrams[i] = new Historgram(); } for (int[] dataUnit : img.getDataUnits()) { // System.out.println("["); for (int i = 0; i != 8; ++i) { for (int j = 0; j != 8; ++j) { historgrams[i * 8 + j].addN(dataUnit[i * 8 + j]); // System.out.print(String.format("%3d ,", dataUnit[i*8+j])); } // System.out.println(); } // System.out.println("]"); } for (int i = 0; i != 64; ++i) { System.out.print(String.format("%3d:", i)); historgrams[i].print(System.out); } System.out.println("total:" + img.getDataUnits().size() + " units"); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (InvalidJpegFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (ps != null) { ps.close(); } try { if (parser != null) { parser.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.services.KalturaAccessControlProfileService; import com.kaltura.client.services.KalturaAccessControlService; import com.kaltura.client.services.KalturaAdminUserService; import com.kaltura.client.services.KalturaAppTokenService; import com.kaltura.client.services.KalturaBaseEntryService; import com.kaltura.client.services.KalturaBulkUploadService; import com.kaltura.client.services.KalturaCategoryEntryService; import com.kaltura.client.services.KalturaCategoryService; import com.kaltura.client.services.KalturaCategoryUserService; import com.kaltura.client.services.KalturaConversionProfileAssetParamsService; import com.kaltura.client.services.KalturaConversionProfileService; import com.kaltura.client.services.KalturaDataService; import com.kaltura.client.services.KalturaDeliveryProfileService; import com.kaltura.client.services.KalturaDocumentService; import com.kaltura.client.services.KalturaEmailIngestionProfileService; import com.kaltura.client.services.KalturaEntryServerNodeService; import com.kaltura.client.services.KalturaFileAssetService; import com.kaltura.client.services.KalturaFlavorAssetService; import com.kaltura.client.services.KalturaFlavorParamsOutputService; import com.kaltura.client.services.KalturaFlavorParamsService; import com.kaltura.client.services.KalturaGroupUserService; import com.kaltura.client.services.KalturaLiveChannelSegmentService; import com.kaltura.client.services.KalturaLiveChannelService; import com.kaltura.client.services.KalturaLiveReportsService; import com.kaltura.client.services.KalturaLiveStatsService; import com.kaltura.client.services.KalturaLiveStreamService; import com.kaltura.client.services.KalturaMediaInfoService; import com.kaltura.client.services.KalturaMediaService; import com.kaltura.client.services.KalturaMixingService; import com.kaltura.client.services.KalturaNotificationService; import com.kaltura.client.services.KalturaPartnerService; import com.kaltura.client.services.KalturaPermissionItemService; import com.kaltura.client.services.KalturaPermissionService; import com.kaltura.client.services.KalturaPlaylistService; import com.kaltura.client.services.KalturaReportService; import com.kaltura.client.services.KalturaResponseProfileService; import com.kaltura.client.services.KalturaSchemaService; import com.kaltura.client.services.KalturaSearchService; import com.kaltura.client.services.KalturaServerNodeService; import com.kaltura.client.services.KalturaSessionService; import com.kaltura.client.services.KalturaStatsService; import com.kaltura.client.services.KalturaStorageProfileService; import com.kaltura.client.services.KalturaSyndicationFeedService; import com.kaltura.client.services.KalturaSystemService; import com.kaltura.client.services.KalturaThumbAssetService; import com.kaltura.client.services.KalturaThumbParamsOutputService; import com.kaltura.client.services.KalturaThumbParamsService; import com.kaltura.client.services.KalturaUiConfService; import com.kaltura.client.services.KalturaUploadService; import com.kaltura.client.services.KalturaUploadTokenService; import com.kaltura.client.services.KalturaUserEntryService; import com.kaltura.client.services.KalturaUserRoleService; import com.kaltura.client.services.KalturaUserService; import com.kaltura.client.services.KalturaWidgetService; import com.kaltura.client.services.KalturaXInternalService; import com.kaltura.client.services.KalturaMetadataService; import com.kaltura.client.services.KalturaMetadataProfileService; import com.kaltura.client.services.KalturaDocumentsService; import com.kaltura.client.services.KalturaSystemPartnerService; import com.kaltura.client.services.KalturaEntryAdminService; import com.kaltura.client.services.KalturaUiConfAdminService; import com.kaltura.client.services.KalturaReportAdminService; import com.kaltura.client.services.KalturaKalturaInternalToolsSystemHelperService; import com.kaltura.client.services.KalturaVirusScanProfileService; import com.kaltura.client.services.KalturaDistributionProfileService; import com.kaltura.client.services.KalturaEntryDistributionService; import com.kaltura.client.services.KalturaDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderActionService; import com.kaltura.client.services.KalturaCuePointService; import com.kaltura.client.services.KalturaAnnotationService; import com.kaltura.client.services.KalturaQuizService; import com.kaltura.client.services.KalturaShortLinkService; import com.kaltura.client.services.KalturaBulkService; import com.kaltura.client.services.KalturaDropFolderService; import com.kaltura.client.services.KalturaDropFolderFileService; import com.kaltura.client.services.KalturaCaptionAssetService; import com.kaltura.client.services.KalturaCaptionParamsService; import com.kaltura.client.services.KalturaCaptionAssetItemService; import com.kaltura.client.services.KalturaAttachmentAssetService; import com.kaltura.client.services.KalturaTagService; import com.kaltura.client.services.KalturaLikeService; import com.kaltura.client.services.KalturaVarConsoleService; import com.kaltura.client.services.KalturaEventNotificationTemplateService; import com.kaltura.client.services.KalturaExternalMediaService; import com.kaltura.client.services.KalturaScheduledTaskProfileService; import com.kaltura.client.services.KalturaIntegrationService; import com.kaltura.client.services.KalturaScheduleEventService; import com.kaltura.client.services.KalturaScheduleResourceService; import com.kaltura.client.services.KalturaScheduleEventResourceService; import com.kaltura.client.types.KalturaBaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaClient extends KalturaClientBase { public KalturaClient(KalturaConfiguration config) { super(config); this.setClientTag("java:16-04-16"); this.setApiVersion("3.3.0"); } protected KalturaAccessControlProfileService accessControlProfileService; public KalturaAccessControlProfileService getAccessControlProfileService() { if(this.accessControlProfileService == null) this.accessControlProfileService = new KalturaAccessControlProfileService(this); return this.accessControlProfileService; } protected KalturaAccessControlService accessControlService; public KalturaAccessControlService getAccessControlService() { if(this.accessControlService == null) this.accessControlService = new KalturaAccessControlService(this); return this.accessControlService; } protected KalturaAdminUserService adminUserService; public KalturaAdminUserService getAdminUserService() { if(this.adminUserService == null) this.adminUserService = new KalturaAdminUserService(this); return this.adminUserService; } protected KalturaAppTokenService appTokenService; public KalturaAppTokenService getAppTokenService() { if(this.appTokenService == null) this.appTokenService = new KalturaAppTokenService(this); return this.appTokenService; } protected KalturaBaseEntryService baseEntryService; public KalturaBaseEntryService getBaseEntryService() { if(this.baseEntryService == null) this.baseEntryService = new KalturaBaseEntryService(this); return this.baseEntryService; } protected KalturaBulkUploadService bulkUploadService; public KalturaBulkUploadService getBulkUploadService() { if(this.bulkUploadService == null) this.bulkUploadService = new KalturaBulkUploadService(this); return this.bulkUploadService; } protected KalturaCategoryEntryService categoryEntryService; public KalturaCategoryEntryService getCategoryEntryService() { if(this.categoryEntryService == null) this.categoryEntryService = new KalturaCategoryEntryService(this); return this.categoryEntryService; } protected KalturaCategoryService categoryService; public KalturaCategoryService getCategoryService() { if(this.categoryService == null) this.categoryService = new KalturaCategoryService(this); return this.categoryService; } protected KalturaCategoryUserService categoryUserService; public KalturaCategoryUserService getCategoryUserService() { if(this.categoryUserService == null) this.categoryUserService = new KalturaCategoryUserService(this); return this.categoryUserService; } protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService; public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() { if(this.conversionProfileAssetParamsService == null) this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this); return this.conversionProfileAssetParamsService; } protected KalturaConversionProfileService conversionProfileService; public KalturaConversionProfileService getConversionProfileService() { if(this.conversionProfileService == null) this.conversionProfileService = new KalturaConversionProfileService(this); return this.conversionProfileService; } protected KalturaDataService dataService; public KalturaDataService getDataService() { if(this.dataService == null) this.dataService = new KalturaDataService(this); return this.dataService; } protected KalturaDeliveryProfileService deliveryProfileService; public KalturaDeliveryProfileService getDeliveryProfileService() { if(this.deliveryProfileService == null) this.deliveryProfileService = new KalturaDeliveryProfileService(this); return this.deliveryProfileService; } protected KalturaDocumentService documentService; public KalturaDocumentService getDocumentService() { if(this.documentService == null) this.documentService = new KalturaDocumentService(this); return this.documentService; } protected KalturaEmailIngestionProfileService EmailIngestionProfileService; public KalturaEmailIngestionProfileService getEmailIngestionProfileService() { if(this.EmailIngestionProfileService == null) this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this); return this.EmailIngestionProfileService; } protected KalturaEntryServerNodeService entryServerNodeService; public KalturaEntryServerNodeService getEntryServerNodeService() { if(this.entryServerNodeService == null) this.entryServerNodeService = new KalturaEntryServerNodeService(this); return this.entryServerNodeService; } protected KalturaFileAssetService fileAssetService; public KalturaFileAssetService getFileAssetService() { if(this.fileAssetService == null) this.fileAssetService = new KalturaFileAssetService(this); return this.fileAssetService; } protected KalturaFlavorAssetService flavorAssetService; public KalturaFlavorAssetService getFlavorAssetService() { if(this.flavorAssetService == null) this.flavorAssetService = new KalturaFlavorAssetService(this); return this.flavorAssetService; } protected KalturaFlavorParamsOutputService flavorParamsOutputService; public KalturaFlavorParamsOutputService getFlavorParamsOutputService() { if(this.flavorParamsOutputService == null) this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this); return this.flavorParamsOutputService; } protected KalturaFlavorParamsService flavorParamsService; public KalturaFlavorParamsService getFlavorParamsService() { if(this.flavorParamsService == null) this.flavorParamsService = new KalturaFlavorParamsService(this); return this.flavorParamsService; } protected KalturaGroupUserService groupUserService; public KalturaGroupUserService getGroupUserService() { if(this.groupUserService == null) this.groupUserService = new KalturaGroupUserService(this); return this.groupUserService; } protected KalturaLiveChannelSegmentService liveChannelSegmentService; public KalturaLiveChannelSegmentService getLiveChannelSegmentService() { if(this.liveChannelSegmentService == null) this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this); return this.liveChannelSegmentService; } protected KalturaLiveChannelService liveChannelService; public KalturaLiveChannelService getLiveChannelService() { if(this.liveChannelService == null) this.liveChannelService = new KalturaLiveChannelService(this); return this.liveChannelService; } protected KalturaLiveReportsService liveReportsService; public KalturaLiveReportsService getLiveReportsService() { if(this.liveReportsService == null) this.liveReportsService = new KalturaLiveReportsService(this); return this.liveReportsService; } protected KalturaLiveStatsService liveStatsService; public KalturaLiveStatsService getLiveStatsService() { if(this.liveStatsService == null) this.liveStatsService = new KalturaLiveStatsService(this); return this.liveStatsService; } protected KalturaLiveStreamService liveStreamService; public KalturaLiveStreamService getLiveStreamService() { if(this.liveStreamService == null) this.liveStreamService = new KalturaLiveStreamService(this); return this.liveStreamService; } protected KalturaMediaInfoService mediaInfoService; public KalturaMediaInfoService getMediaInfoService() { if(this.mediaInfoService == null) this.mediaInfoService = new KalturaMediaInfoService(this); return this.mediaInfoService; } protected KalturaMediaService mediaService; public KalturaMediaService getMediaService() { if(this.mediaService == null) this.mediaService = new KalturaMediaService(this); return this.mediaService; } protected KalturaMixingService mixingService; public KalturaMixingService getMixingService() { if(this.mixingService == null) this.mixingService = new KalturaMixingService(this); return this.mixingService; } protected KalturaNotificationService notificationService; public KalturaNotificationService getNotificationService() { if(this.notificationService == null) this.notificationService = new KalturaNotificationService(this); return this.notificationService; } protected KalturaPartnerService partnerService; public KalturaPartnerService getPartnerService() { if(this.partnerService == null) this.partnerService = new KalturaPartnerService(this); return this.partnerService; } protected KalturaPermissionItemService permissionItemService; public KalturaPermissionItemService getPermissionItemService() { if(this.permissionItemService == null) this.permissionItemService = new KalturaPermissionItemService(this); return this.permissionItemService; } protected KalturaPermissionService permissionService; public KalturaPermissionService getPermissionService() { if(this.permissionService == null) this.permissionService = new KalturaPermissionService(this); return this.permissionService; } protected KalturaPlaylistService playlistService; public KalturaPlaylistService getPlaylistService() { if(this.playlistService == null) this.playlistService = new KalturaPlaylistService(this); return this.playlistService; } protected KalturaReportService reportService; public KalturaReportService getReportService() { if(this.reportService == null) this.reportService = new KalturaReportService(this); return this.reportService; } protected KalturaResponseProfileService responseProfileService; public KalturaResponseProfileService getResponseProfileService() { if(this.responseProfileService == null) this.responseProfileService = new KalturaResponseProfileService(this); return this.responseProfileService; } protected KalturaSchemaService schemaService; public KalturaSchemaService getSchemaService() { if(this.schemaService == null) this.schemaService = new KalturaSchemaService(this); return this.schemaService; } protected KalturaSearchService searchService; public KalturaSearchService getSearchService() { if(this.searchService == null) this.searchService = new KalturaSearchService(this); return this.searchService; } protected KalturaServerNodeService serverNodeService; public KalturaServerNodeService getServerNodeService() { if(this.serverNodeService == null) this.serverNodeService = new KalturaServerNodeService(this); return this.serverNodeService; } protected KalturaSessionService sessionService; public KalturaSessionService getSessionService() { if(this.sessionService == null) this.sessionService = new KalturaSessionService(this); return this.sessionService; } protected KalturaStatsService statsService; public KalturaStatsService getStatsService() { if(this.statsService == null) this.statsService = new KalturaStatsService(this); return this.statsService; } protected KalturaStorageProfileService storageProfileService; public KalturaStorageProfileService getStorageProfileService() { if(this.storageProfileService == null) this.storageProfileService = new KalturaStorageProfileService(this); return this.storageProfileService; } protected KalturaSyndicationFeedService syndicationFeedService; public KalturaSyndicationFeedService getSyndicationFeedService() { if(this.syndicationFeedService == null) this.syndicationFeedService = new KalturaSyndicationFeedService(this); return this.syndicationFeedService; } protected KalturaSystemService systemService; public KalturaSystemService getSystemService() { if(this.systemService == null) this.systemService = new KalturaSystemService(this); return this.systemService; } protected KalturaThumbAssetService thumbAssetService; public KalturaThumbAssetService getThumbAssetService() { if(this.thumbAssetService == null) this.thumbAssetService = new KalturaThumbAssetService(this); return this.thumbAssetService; } protected KalturaThumbParamsOutputService thumbParamsOutputService; public KalturaThumbParamsOutputService getThumbParamsOutputService() { if(this.thumbParamsOutputService == null) this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this); return this.thumbParamsOutputService; } protected KalturaThumbParamsService thumbParamsService; public KalturaThumbParamsService getThumbParamsService() { if(this.thumbParamsService == null) this.thumbParamsService = new KalturaThumbParamsService(this); return this.thumbParamsService; } protected KalturaUiConfService uiConfService; public KalturaUiConfService getUiConfService() { if(this.uiConfService == null) this.uiConfService = new KalturaUiConfService(this); return this.uiConfService; } protected KalturaUploadService uploadService; public KalturaUploadService getUploadService() { if(this.uploadService == null) this.uploadService = new KalturaUploadService(this); return this.uploadService; } protected KalturaUploadTokenService uploadTokenService; public KalturaUploadTokenService getUploadTokenService() { if(this.uploadTokenService == null) this.uploadTokenService = new KalturaUploadTokenService(this); return this.uploadTokenService; } protected KalturaUserEntryService userEntryService; public KalturaUserEntryService getUserEntryService() { if(this.userEntryService == null) this.userEntryService = new KalturaUserEntryService(this); return this.userEntryService; } protected KalturaUserRoleService userRoleService; public KalturaUserRoleService getUserRoleService() { if(this.userRoleService == null) this.userRoleService = new KalturaUserRoleService(this); return this.userRoleService; } protected KalturaUserService userService; public KalturaUserService getUserService() { if(this.userService == null) this.userService = new KalturaUserService(this); return this.userService; } protected KalturaWidgetService widgetService; public KalturaWidgetService getWidgetService() { if(this.widgetService == null) this.widgetService = new KalturaWidgetService(this); return this.widgetService; } protected KalturaXInternalService xInternalService; public KalturaXInternalService getXInternalService() { if(this.xInternalService == null) this.xInternalService = new KalturaXInternalService(this); return this.xInternalService; } protected KalturaMetadataService metadataService; public KalturaMetadataService getMetadataService() { if(this.metadataService == null) this.metadataService = new KalturaMetadataService(this); return this.metadataService; } protected KalturaMetadataProfileService metadataProfileService; public KalturaMetadataProfileService getMetadataProfileService() { if(this.metadataProfileService == null) this.metadataProfileService = new KalturaMetadataProfileService(this); return this.metadataProfileService; } protected KalturaDocumentsService documentsService; public KalturaDocumentsService getDocumentsService() { if(this.documentsService == null) this.documentsService = new KalturaDocumentsService(this); return this.documentsService; } protected KalturaSystemPartnerService systemPartnerService; public KalturaSystemPartnerService getSystemPartnerService() { if(this.systemPartnerService == null) this.systemPartnerService = new KalturaSystemPartnerService(this); return this.systemPartnerService; } protected KalturaEntryAdminService entryAdminService; public KalturaEntryAdminService getEntryAdminService() { if(this.entryAdminService == null) this.entryAdminService = new KalturaEntryAdminService(this); return this.entryAdminService; } protected KalturaUiConfAdminService uiConfAdminService; public KalturaUiConfAdminService getUiConfAdminService() { if(this.uiConfAdminService == null) this.uiConfAdminService = new KalturaUiConfAdminService(this); return this.uiConfAdminService; } protected KalturaReportAdminService reportAdminService; public KalturaReportAdminService getReportAdminService() { if(this.reportAdminService == null) this.reportAdminService = new KalturaReportAdminService(this); return this.reportAdminService; } protected KalturaKalturaInternalToolsSystemHelperService kalturaInternalToolsSystemHelperService; public KalturaKalturaInternalToolsSystemHelperService getKalturaInternalToolsSystemHelperService() { if(this.kalturaInternalToolsSystemHelperService == null) this.kalturaInternalToolsSystemHelperService = new KalturaKalturaInternalToolsSystemHelperService(this); return this.kalturaInternalToolsSystemHelperService; } protected KalturaVirusScanProfileService virusScanProfileService; public KalturaVirusScanProfileService getVirusScanProfileService() { if(this.virusScanProfileService == null) this.virusScanProfileService = new KalturaVirusScanProfileService(this); return this.virusScanProfileService; } protected KalturaDistributionProfileService distributionProfileService; public KalturaDistributionProfileService getDistributionProfileService() { if(this.distributionProfileService == null) this.distributionProfileService = new KalturaDistributionProfileService(this); return this.distributionProfileService; } protected KalturaEntryDistributionService entryDistributionService; public KalturaEntryDistributionService getEntryDistributionService() { if(this.entryDistributionService == null) this.entryDistributionService = new KalturaEntryDistributionService(this); return this.entryDistributionService; } protected KalturaDistributionProviderService distributionProviderService; public KalturaDistributionProviderService getDistributionProviderService() { if(this.distributionProviderService == null) this.distributionProviderService = new KalturaDistributionProviderService(this); return this.distributionProviderService; } protected KalturaGenericDistributionProviderService genericDistributionProviderService; public KalturaGenericDistributionProviderService getGenericDistributionProviderService() { if(this.genericDistributionProviderService == null) this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this); return this.genericDistributionProviderService; } protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService; public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() { if(this.genericDistributionProviderActionService == null) this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this); return this.genericDistributionProviderActionService; } protected KalturaCuePointService cuePointService; public KalturaCuePointService getCuePointService() { if(this.cuePointService == null) this.cuePointService = new KalturaCuePointService(this); return this.cuePointService; } protected KalturaAnnotationService annotationService; public KalturaAnnotationService getAnnotationService() { if(this.annotationService == null) this.annotationService = new KalturaAnnotationService(this); return this.annotationService; } protected KalturaQuizService quizService; public KalturaQuizService getQuizService() { if(this.quizService == null) this.quizService = new KalturaQuizService(this); return this.quizService; } protected KalturaShortLinkService shortLinkService; public KalturaShortLinkService getShortLinkService() { if(this.shortLinkService == null) this.shortLinkService = new KalturaShortLinkService(this); return this.shortLinkService; } protected KalturaBulkService bulkService; public KalturaBulkService getBulkService() { if(this.bulkService == null) this.bulkService = new KalturaBulkService(this); return this.bulkService; } protected KalturaDropFolderService dropFolderService; public KalturaDropFolderService getDropFolderService() { if(this.dropFolderService == null) this.dropFolderService = new KalturaDropFolderService(this); return this.dropFolderService; } protected KalturaDropFolderFileService dropFolderFileService; public KalturaDropFolderFileService getDropFolderFileService() { if(this.dropFolderFileService == null) this.dropFolderFileService = new KalturaDropFolderFileService(this); return this.dropFolderFileService; } protected KalturaCaptionAssetService captionAssetService; public KalturaCaptionAssetService getCaptionAssetService() { if(this.captionAssetService == null) this.captionAssetService = new KalturaCaptionAssetService(this); return this.captionAssetService; } protected KalturaCaptionParamsService captionParamsService; public KalturaCaptionParamsService getCaptionParamsService() { if(this.captionParamsService == null) this.captionParamsService = new KalturaCaptionParamsService(this); return this.captionParamsService; } protected KalturaCaptionAssetItemService captionAssetItemService; public KalturaCaptionAssetItemService getCaptionAssetItemService() { if(this.captionAssetItemService == null) this.captionAssetItemService = new KalturaCaptionAssetItemService(this); return this.captionAssetItemService; } protected KalturaAttachmentAssetService attachmentAssetService; public KalturaAttachmentAssetService getAttachmentAssetService() { if(this.attachmentAssetService == null) this.attachmentAssetService = new KalturaAttachmentAssetService(this); return this.attachmentAssetService; } protected KalturaTagService tagService; public KalturaTagService getTagService() { if(this.tagService == null) this.tagService = new KalturaTagService(this); return this.tagService; } protected KalturaLikeService likeService; public KalturaLikeService getLikeService() { if(this.likeService == null) this.likeService = new KalturaLikeService(this); return this.likeService; } protected KalturaVarConsoleService varConsoleService; public KalturaVarConsoleService getVarConsoleService() { if(this.varConsoleService == null) this.varConsoleService = new KalturaVarConsoleService(this); return this.varConsoleService; } protected KalturaEventNotificationTemplateService eventNotificationTemplateService; public KalturaEventNotificationTemplateService getEventNotificationTemplateService() { if(this.eventNotificationTemplateService == null) this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this); return this.eventNotificationTemplateService; } protected KalturaExternalMediaService externalMediaService; public KalturaExternalMediaService getExternalMediaService() { if(this.externalMediaService == null) this.externalMediaService = new KalturaExternalMediaService(this); return this.externalMediaService; } protected KalturaScheduledTaskProfileService scheduledTaskProfileService; public KalturaScheduledTaskProfileService getScheduledTaskProfileService() { if(this.scheduledTaskProfileService == null) this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this); return this.scheduledTaskProfileService; } protected KalturaIntegrationService integrationService; public KalturaIntegrationService getIntegrationService() { if(this.integrationService == null) this.integrationService = new KalturaIntegrationService(this); return this.integrationService; } protected KalturaScheduleEventService scheduleEventService; public KalturaScheduleEventService getScheduleEventService() { if(this.scheduleEventService == null) this.scheduleEventService = new KalturaScheduleEventService(this); return this.scheduleEventService; } protected KalturaScheduleResourceService scheduleResourceService; public KalturaScheduleResourceService getScheduleResourceService() { if(this.scheduleResourceService == null) this.scheduleResourceService = new KalturaScheduleResourceService(this); return this.scheduleResourceService; } protected KalturaScheduleEventResourceService scheduleEventResourceService; public KalturaScheduleEventResourceService getScheduleEventResourceService() { if(this.scheduleEventResourceService == null) this.scheduleEventResourceService = new KalturaScheduleEventResourceService(this); return this.scheduleEventResourceService; } /** * @param String $clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return (String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param String $apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return (String) this.clientConfiguration.get("apiVersion"); } return null; } /** * Impersonated partner id * * @param Integer $partnerId */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return (Integer) this.requestConfiguration.get("partnerId"); } return null; } /** * Kaltura API session * * @param String $ks */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Kaltura API session * * @param String $sessionId */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Response profile - this attribute will be automatically unset after every API call. * * @param KalturaBaseResponseProfile $responseProfile */ public void setResponseProfile(KalturaBaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return KalturaBaseResponseProfile */ public KalturaBaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } /** * Clear all volatile configuration parameters */ protected void resetRequest(){ this.requestConfiguration.remove("responseProfile"); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.services.KalturaAccessControlProfileService; import com.kaltura.client.services.KalturaAccessControlService; import com.kaltura.client.services.KalturaAdminUserService; import com.kaltura.client.services.KalturaAppTokenService; import com.kaltura.client.services.KalturaBaseEntryService; import com.kaltura.client.services.KalturaBulkUploadService; import com.kaltura.client.services.KalturaCategoryEntryService; import com.kaltura.client.services.KalturaCategoryService; import com.kaltura.client.services.KalturaCategoryUserService; import com.kaltura.client.services.KalturaConversionProfileAssetParamsService; import com.kaltura.client.services.KalturaConversionProfileService; import com.kaltura.client.services.KalturaDataService; import com.kaltura.client.services.KalturaDeliveryProfileService; import com.kaltura.client.services.KalturaDocumentService; import com.kaltura.client.services.KalturaEmailIngestionProfileService; import com.kaltura.client.services.KalturaEntryServerNodeService; import com.kaltura.client.services.KalturaFileAssetService; import com.kaltura.client.services.KalturaFlavorAssetService; import com.kaltura.client.services.KalturaFlavorParamsOutputService; import com.kaltura.client.services.KalturaFlavorParamsService; import com.kaltura.client.services.KalturaGroupUserService; import com.kaltura.client.services.KalturaLiveChannelSegmentService; import com.kaltura.client.services.KalturaLiveChannelService; import com.kaltura.client.services.KalturaLiveReportsService; import com.kaltura.client.services.KalturaLiveStatsService; import com.kaltura.client.services.KalturaLiveStreamService; import com.kaltura.client.services.KalturaMediaInfoService; import com.kaltura.client.services.KalturaMediaService; import com.kaltura.client.services.KalturaMixingService; import com.kaltura.client.services.KalturaNotificationService; import com.kaltura.client.services.KalturaPartnerService; import com.kaltura.client.services.KalturaPermissionItemService; import com.kaltura.client.services.KalturaPermissionService; import com.kaltura.client.services.KalturaPlaylistService; import com.kaltura.client.services.KalturaReportService; import com.kaltura.client.services.KalturaResponseProfileService; import com.kaltura.client.services.KalturaSchemaService; import com.kaltura.client.services.KalturaSearchService; import com.kaltura.client.services.KalturaServerNodeService; import com.kaltura.client.services.KalturaSessionService; import com.kaltura.client.services.KalturaStatsService; import com.kaltura.client.services.KalturaStorageProfileService; import com.kaltura.client.services.KalturaSyndicationFeedService; import com.kaltura.client.services.KalturaSystemService; import com.kaltura.client.services.KalturaThumbAssetService; import com.kaltura.client.services.KalturaThumbParamsOutputService; import com.kaltura.client.services.KalturaThumbParamsService; import com.kaltura.client.services.KalturaUiConfService; import com.kaltura.client.services.KalturaUploadService; import com.kaltura.client.services.KalturaUploadTokenService; import com.kaltura.client.services.KalturaUserEntryService; import com.kaltura.client.services.KalturaUserRoleService; import com.kaltura.client.services.KalturaUserService; import com.kaltura.client.services.KalturaWidgetService; import com.kaltura.client.services.KalturaXInternalService; import com.kaltura.client.services.KalturaMetadataService; import com.kaltura.client.services.KalturaMetadataProfileService; import com.kaltura.client.services.KalturaDocumentsService; import com.kaltura.client.services.KalturaSystemPartnerService; import com.kaltura.client.services.KalturaEntryAdminService; import com.kaltura.client.services.KalturaUiConfAdminService; import com.kaltura.client.services.KalturaReportAdminService; import com.kaltura.client.services.KalturaKalturaInternalToolsSystemHelperService; import com.kaltura.client.services.KalturaVirusScanProfileService; import com.kaltura.client.services.KalturaDistributionProfileService; import com.kaltura.client.services.KalturaEntryDistributionService; import com.kaltura.client.services.KalturaDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderActionService; import com.kaltura.client.services.KalturaCuePointService; import com.kaltura.client.services.KalturaAnnotationService; import com.kaltura.client.services.KalturaQuizService; import com.kaltura.client.services.KalturaShortLinkService; import com.kaltura.client.services.KalturaBulkService; import com.kaltura.client.services.KalturaDropFolderService; import com.kaltura.client.services.KalturaDropFolderFileService; import com.kaltura.client.services.KalturaCaptionAssetService; import com.kaltura.client.services.KalturaCaptionParamsService; import com.kaltura.client.services.KalturaCaptionAssetItemService; import com.kaltura.client.services.KalturaAttachmentAssetService; import com.kaltura.client.services.KalturaTagService; import com.kaltura.client.services.KalturaLikeService; import com.kaltura.client.services.KalturaVarConsoleService; import com.kaltura.client.services.KalturaEventNotificationTemplateService; import com.kaltura.client.services.KalturaExternalMediaService; import com.kaltura.client.services.KalturaScheduledTaskProfileService; import com.kaltura.client.services.KalturaIntegrationService; import com.kaltura.client.services.KalturaScheduleEventService; import com.kaltura.client.services.KalturaScheduleResourceService; import com.kaltura.client.services.KalturaScheduleEventResourceService; import com.kaltura.client.types.KalturaBaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaClient extends KalturaClientBase { public KalturaClient(KalturaConfiguration config) { super(config); this.setClientTag("java:16-04-26"); this.setApiVersion("3.3.0"); } protected KalturaAccessControlProfileService accessControlProfileService; public KalturaAccessControlProfileService getAccessControlProfileService() { if(this.accessControlProfileService == null) this.accessControlProfileService = new KalturaAccessControlProfileService(this); return this.accessControlProfileService; } protected KalturaAccessControlService accessControlService; public KalturaAccessControlService getAccessControlService() { if(this.accessControlService == null) this.accessControlService = new KalturaAccessControlService(this); return this.accessControlService; } protected KalturaAdminUserService adminUserService; public KalturaAdminUserService getAdminUserService() { if(this.adminUserService == null) this.adminUserService = new KalturaAdminUserService(this); return this.adminUserService; } protected KalturaAppTokenService appTokenService; public KalturaAppTokenService getAppTokenService() { if(this.appTokenService == null) this.appTokenService = new KalturaAppTokenService(this); return this.appTokenService; } protected KalturaBaseEntryService baseEntryService; public KalturaBaseEntryService getBaseEntryService() { if(this.baseEntryService == null) this.baseEntryService = new KalturaBaseEntryService(this); return this.baseEntryService; } protected KalturaBulkUploadService bulkUploadService; public KalturaBulkUploadService getBulkUploadService() { if(this.bulkUploadService == null) this.bulkUploadService = new KalturaBulkUploadService(this); return this.bulkUploadService; } protected KalturaCategoryEntryService categoryEntryService; public KalturaCategoryEntryService getCategoryEntryService() { if(this.categoryEntryService == null) this.categoryEntryService = new KalturaCategoryEntryService(this); return this.categoryEntryService; } protected KalturaCategoryService categoryService; public KalturaCategoryService getCategoryService() { if(this.categoryService == null) this.categoryService = new KalturaCategoryService(this); return this.categoryService; } protected KalturaCategoryUserService categoryUserService; public KalturaCategoryUserService getCategoryUserService() { if(this.categoryUserService == null) this.categoryUserService = new KalturaCategoryUserService(this); return this.categoryUserService; } protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService; public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() { if(this.conversionProfileAssetParamsService == null) this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this); return this.conversionProfileAssetParamsService; } protected KalturaConversionProfileService conversionProfileService; public KalturaConversionProfileService getConversionProfileService() { if(this.conversionProfileService == null) this.conversionProfileService = new KalturaConversionProfileService(this); return this.conversionProfileService; } protected KalturaDataService dataService; public KalturaDataService getDataService() { if(this.dataService == null) this.dataService = new KalturaDataService(this); return this.dataService; } protected KalturaDeliveryProfileService deliveryProfileService; public KalturaDeliveryProfileService getDeliveryProfileService() { if(this.deliveryProfileService == null) this.deliveryProfileService = new KalturaDeliveryProfileService(this); return this.deliveryProfileService; } protected KalturaDocumentService documentService; public KalturaDocumentService getDocumentService() { if(this.documentService == null) this.documentService = new KalturaDocumentService(this); return this.documentService; } protected KalturaEmailIngestionProfileService EmailIngestionProfileService; public KalturaEmailIngestionProfileService getEmailIngestionProfileService() { if(this.EmailIngestionProfileService == null) this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this); return this.EmailIngestionProfileService; } protected KalturaEntryServerNodeService entryServerNodeService; public KalturaEntryServerNodeService getEntryServerNodeService() { if(this.entryServerNodeService == null) this.entryServerNodeService = new KalturaEntryServerNodeService(this); return this.entryServerNodeService; } protected KalturaFileAssetService fileAssetService; public KalturaFileAssetService getFileAssetService() { if(this.fileAssetService == null) this.fileAssetService = new KalturaFileAssetService(this); return this.fileAssetService; } protected KalturaFlavorAssetService flavorAssetService; public KalturaFlavorAssetService getFlavorAssetService() { if(this.flavorAssetService == null) this.flavorAssetService = new KalturaFlavorAssetService(this); return this.flavorAssetService; } protected KalturaFlavorParamsOutputService flavorParamsOutputService; public KalturaFlavorParamsOutputService getFlavorParamsOutputService() { if(this.flavorParamsOutputService == null) this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this); return this.flavorParamsOutputService; } protected KalturaFlavorParamsService flavorParamsService; public KalturaFlavorParamsService getFlavorParamsService() { if(this.flavorParamsService == null) this.flavorParamsService = new KalturaFlavorParamsService(this); return this.flavorParamsService; } protected KalturaGroupUserService groupUserService; public KalturaGroupUserService getGroupUserService() { if(this.groupUserService == null) this.groupUserService = new KalturaGroupUserService(this); return this.groupUserService; } protected KalturaLiveChannelSegmentService liveChannelSegmentService; public KalturaLiveChannelSegmentService getLiveChannelSegmentService() { if(this.liveChannelSegmentService == null) this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this); return this.liveChannelSegmentService; } protected KalturaLiveChannelService liveChannelService; public KalturaLiveChannelService getLiveChannelService() { if(this.liveChannelService == null) this.liveChannelService = new KalturaLiveChannelService(this); return this.liveChannelService; } protected KalturaLiveReportsService liveReportsService; public KalturaLiveReportsService getLiveReportsService() { if(this.liveReportsService == null) this.liveReportsService = new KalturaLiveReportsService(this); return this.liveReportsService; } protected KalturaLiveStatsService liveStatsService; public KalturaLiveStatsService getLiveStatsService() { if(this.liveStatsService == null) this.liveStatsService = new KalturaLiveStatsService(this); return this.liveStatsService; } protected KalturaLiveStreamService liveStreamService; public KalturaLiveStreamService getLiveStreamService() { if(this.liveStreamService == null) this.liveStreamService = new KalturaLiveStreamService(this); return this.liveStreamService; } protected KalturaMediaInfoService mediaInfoService; public KalturaMediaInfoService getMediaInfoService() { if(this.mediaInfoService == null) this.mediaInfoService = new KalturaMediaInfoService(this); return this.mediaInfoService; } protected KalturaMediaService mediaService; public KalturaMediaService getMediaService() { if(this.mediaService == null) this.mediaService = new KalturaMediaService(this); return this.mediaService; } protected KalturaMixingService mixingService; public KalturaMixingService getMixingService() { if(this.mixingService == null) this.mixingService = new KalturaMixingService(this); return this.mixingService; } protected KalturaNotificationService notificationService; public KalturaNotificationService getNotificationService() { if(this.notificationService == null) this.notificationService = new KalturaNotificationService(this); return this.notificationService; } protected KalturaPartnerService partnerService; public KalturaPartnerService getPartnerService() { if(this.partnerService == null) this.partnerService = new KalturaPartnerService(this); return this.partnerService; } protected KalturaPermissionItemService permissionItemService; public KalturaPermissionItemService getPermissionItemService() { if(this.permissionItemService == null) this.permissionItemService = new KalturaPermissionItemService(this); return this.permissionItemService; } protected KalturaPermissionService permissionService; public KalturaPermissionService getPermissionService() { if(this.permissionService == null) this.permissionService = new KalturaPermissionService(this); return this.permissionService; } protected KalturaPlaylistService playlistService; public KalturaPlaylistService getPlaylistService() { if(this.playlistService == null) this.playlistService = new KalturaPlaylistService(this); return this.playlistService; } protected KalturaReportService reportService; public KalturaReportService getReportService() { if(this.reportService == null) this.reportService = new KalturaReportService(this); return this.reportService; } protected KalturaResponseProfileService responseProfileService; public KalturaResponseProfileService getResponseProfileService() { if(this.responseProfileService == null) this.responseProfileService = new KalturaResponseProfileService(this); return this.responseProfileService; } protected KalturaSchemaService schemaService; public KalturaSchemaService getSchemaService() { if(this.schemaService == null) this.schemaService = new KalturaSchemaService(this); return this.schemaService; } protected KalturaSearchService searchService; public KalturaSearchService getSearchService() { if(this.searchService == null) this.searchService = new KalturaSearchService(this); return this.searchService; } protected KalturaServerNodeService serverNodeService; public KalturaServerNodeService getServerNodeService() { if(this.serverNodeService == null) this.serverNodeService = new KalturaServerNodeService(this); return this.serverNodeService; } protected KalturaSessionService sessionService; public KalturaSessionService getSessionService() { if(this.sessionService == null) this.sessionService = new KalturaSessionService(this); return this.sessionService; } protected KalturaStatsService statsService; public KalturaStatsService getStatsService() { if(this.statsService == null) this.statsService = new KalturaStatsService(this); return this.statsService; } protected KalturaStorageProfileService storageProfileService; public KalturaStorageProfileService getStorageProfileService() { if(this.storageProfileService == null) this.storageProfileService = new KalturaStorageProfileService(this); return this.storageProfileService; } protected KalturaSyndicationFeedService syndicationFeedService; public KalturaSyndicationFeedService getSyndicationFeedService() { if(this.syndicationFeedService == null) this.syndicationFeedService = new KalturaSyndicationFeedService(this); return this.syndicationFeedService; } protected KalturaSystemService systemService; public KalturaSystemService getSystemService() { if(this.systemService == null) this.systemService = new KalturaSystemService(this); return this.systemService; } protected KalturaThumbAssetService thumbAssetService; public KalturaThumbAssetService getThumbAssetService() { if(this.thumbAssetService == null) this.thumbAssetService = new KalturaThumbAssetService(this); return this.thumbAssetService; } protected KalturaThumbParamsOutputService thumbParamsOutputService; public KalturaThumbParamsOutputService getThumbParamsOutputService() { if(this.thumbParamsOutputService == null) this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this); return this.thumbParamsOutputService; } protected KalturaThumbParamsService thumbParamsService; public KalturaThumbParamsService getThumbParamsService() { if(this.thumbParamsService == null) this.thumbParamsService = new KalturaThumbParamsService(this); return this.thumbParamsService; } protected KalturaUiConfService uiConfService; public KalturaUiConfService getUiConfService() { if(this.uiConfService == null) this.uiConfService = new KalturaUiConfService(this); return this.uiConfService; } protected KalturaUploadService uploadService; public KalturaUploadService getUploadService() { if(this.uploadService == null) this.uploadService = new KalturaUploadService(this); return this.uploadService; } protected KalturaUploadTokenService uploadTokenService; public KalturaUploadTokenService getUploadTokenService() { if(this.uploadTokenService == null) this.uploadTokenService = new KalturaUploadTokenService(this); return this.uploadTokenService; } protected KalturaUserEntryService userEntryService; public KalturaUserEntryService getUserEntryService() { if(this.userEntryService == null) this.userEntryService = new KalturaUserEntryService(this); return this.userEntryService; } protected KalturaUserRoleService userRoleService; public KalturaUserRoleService getUserRoleService() { if(this.userRoleService == null) this.userRoleService = new KalturaUserRoleService(this); return this.userRoleService; } protected KalturaUserService userService; public KalturaUserService getUserService() { if(this.userService == null) this.userService = new KalturaUserService(this); return this.userService; } protected KalturaWidgetService widgetService; public KalturaWidgetService getWidgetService() { if(this.widgetService == null) this.widgetService = new KalturaWidgetService(this); return this.widgetService; } protected KalturaXInternalService xInternalService; public KalturaXInternalService getXInternalService() { if(this.xInternalService == null) this.xInternalService = new KalturaXInternalService(this); return this.xInternalService; } protected KalturaMetadataService metadataService; public KalturaMetadataService getMetadataService() { if(this.metadataService == null) this.metadataService = new KalturaMetadataService(this); return this.metadataService; } protected KalturaMetadataProfileService metadataProfileService; public KalturaMetadataProfileService getMetadataProfileService() { if(this.metadataProfileService == null) this.metadataProfileService = new KalturaMetadataProfileService(this); return this.metadataProfileService; } protected KalturaDocumentsService documentsService; public KalturaDocumentsService getDocumentsService() { if(this.documentsService == null) this.documentsService = new KalturaDocumentsService(this); return this.documentsService; } protected KalturaSystemPartnerService systemPartnerService; public KalturaSystemPartnerService getSystemPartnerService() { if(this.systemPartnerService == null) this.systemPartnerService = new KalturaSystemPartnerService(this); return this.systemPartnerService; } protected KalturaEntryAdminService entryAdminService; public KalturaEntryAdminService getEntryAdminService() { if(this.entryAdminService == null) this.entryAdminService = new KalturaEntryAdminService(this); return this.entryAdminService; } protected KalturaUiConfAdminService uiConfAdminService; public KalturaUiConfAdminService getUiConfAdminService() { if(this.uiConfAdminService == null) this.uiConfAdminService = new KalturaUiConfAdminService(this); return this.uiConfAdminService; } protected KalturaReportAdminService reportAdminService; public KalturaReportAdminService getReportAdminService() { if(this.reportAdminService == null) this.reportAdminService = new KalturaReportAdminService(this); return this.reportAdminService; } protected KalturaKalturaInternalToolsSystemHelperService kalturaInternalToolsSystemHelperService; public KalturaKalturaInternalToolsSystemHelperService getKalturaInternalToolsSystemHelperService() { if(this.kalturaInternalToolsSystemHelperService == null) this.kalturaInternalToolsSystemHelperService = new KalturaKalturaInternalToolsSystemHelperService(this); return this.kalturaInternalToolsSystemHelperService; } protected KalturaVirusScanProfileService virusScanProfileService; public KalturaVirusScanProfileService getVirusScanProfileService() { if(this.virusScanProfileService == null) this.virusScanProfileService = new KalturaVirusScanProfileService(this); return this.virusScanProfileService; } protected KalturaDistributionProfileService distributionProfileService; public KalturaDistributionProfileService getDistributionProfileService() { if(this.distributionProfileService == null) this.distributionProfileService = new KalturaDistributionProfileService(this); return this.distributionProfileService; } protected KalturaEntryDistributionService entryDistributionService; public KalturaEntryDistributionService getEntryDistributionService() { if(this.entryDistributionService == null) this.entryDistributionService = new KalturaEntryDistributionService(this); return this.entryDistributionService; } protected KalturaDistributionProviderService distributionProviderService; public KalturaDistributionProviderService getDistributionProviderService() { if(this.distributionProviderService == null) this.distributionProviderService = new KalturaDistributionProviderService(this); return this.distributionProviderService; } protected KalturaGenericDistributionProviderService genericDistributionProviderService; public KalturaGenericDistributionProviderService getGenericDistributionProviderService() { if(this.genericDistributionProviderService == null) this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this); return this.genericDistributionProviderService; } protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService; public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() { if(this.genericDistributionProviderActionService == null) this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this); return this.genericDistributionProviderActionService; } protected KalturaCuePointService cuePointService; public KalturaCuePointService getCuePointService() { if(this.cuePointService == null) this.cuePointService = new KalturaCuePointService(this); return this.cuePointService; } protected KalturaAnnotationService annotationService; public KalturaAnnotationService getAnnotationService() { if(this.annotationService == null) this.annotationService = new KalturaAnnotationService(this); return this.annotationService; } protected KalturaQuizService quizService; public KalturaQuizService getQuizService() { if(this.quizService == null) this.quizService = new KalturaQuizService(this); return this.quizService; } protected KalturaShortLinkService shortLinkService; public KalturaShortLinkService getShortLinkService() { if(this.shortLinkService == null) this.shortLinkService = new KalturaShortLinkService(this); return this.shortLinkService; } protected KalturaBulkService bulkService; public KalturaBulkService getBulkService() { if(this.bulkService == null) this.bulkService = new KalturaBulkService(this); return this.bulkService; } protected KalturaDropFolderService dropFolderService; public KalturaDropFolderService getDropFolderService() { if(this.dropFolderService == null) this.dropFolderService = new KalturaDropFolderService(this); return this.dropFolderService; } protected KalturaDropFolderFileService dropFolderFileService; public KalturaDropFolderFileService getDropFolderFileService() { if(this.dropFolderFileService == null) this.dropFolderFileService = new KalturaDropFolderFileService(this); return this.dropFolderFileService; } protected KalturaCaptionAssetService captionAssetService; public KalturaCaptionAssetService getCaptionAssetService() { if(this.captionAssetService == null) this.captionAssetService = new KalturaCaptionAssetService(this); return this.captionAssetService; } protected KalturaCaptionParamsService captionParamsService; public KalturaCaptionParamsService getCaptionParamsService() { if(this.captionParamsService == null) this.captionParamsService = new KalturaCaptionParamsService(this); return this.captionParamsService; } protected KalturaCaptionAssetItemService captionAssetItemService; public KalturaCaptionAssetItemService getCaptionAssetItemService() { if(this.captionAssetItemService == null) this.captionAssetItemService = new KalturaCaptionAssetItemService(this); return this.captionAssetItemService; } protected KalturaAttachmentAssetService attachmentAssetService; public KalturaAttachmentAssetService getAttachmentAssetService() { if(this.attachmentAssetService == null) this.attachmentAssetService = new KalturaAttachmentAssetService(this); return this.attachmentAssetService; } protected KalturaTagService tagService; public KalturaTagService getTagService() { if(this.tagService == null) this.tagService = new KalturaTagService(this); return this.tagService; } protected KalturaLikeService likeService; public KalturaLikeService getLikeService() { if(this.likeService == null) this.likeService = new KalturaLikeService(this); return this.likeService; } protected KalturaVarConsoleService varConsoleService; public KalturaVarConsoleService getVarConsoleService() { if(this.varConsoleService == null) this.varConsoleService = new KalturaVarConsoleService(this); return this.varConsoleService; } protected KalturaEventNotificationTemplateService eventNotificationTemplateService; public KalturaEventNotificationTemplateService getEventNotificationTemplateService() { if(this.eventNotificationTemplateService == null) this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this); return this.eventNotificationTemplateService; } protected KalturaExternalMediaService externalMediaService; public KalturaExternalMediaService getExternalMediaService() { if(this.externalMediaService == null) this.externalMediaService = new KalturaExternalMediaService(this); return this.externalMediaService; } protected KalturaScheduledTaskProfileService scheduledTaskProfileService; public KalturaScheduledTaskProfileService getScheduledTaskProfileService() { if(this.scheduledTaskProfileService == null) this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this); return this.scheduledTaskProfileService; } protected KalturaIntegrationService integrationService; public KalturaIntegrationService getIntegrationService() { if(this.integrationService == null) this.integrationService = new KalturaIntegrationService(this); return this.integrationService; } protected KalturaScheduleEventService scheduleEventService; public KalturaScheduleEventService getScheduleEventService() { if(this.scheduleEventService == null) this.scheduleEventService = new KalturaScheduleEventService(this); return this.scheduleEventService; } protected KalturaScheduleResourceService scheduleResourceService; public KalturaScheduleResourceService getScheduleResourceService() { if(this.scheduleResourceService == null) this.scheduleResourceService = new KalturaScheduleResourceService(this); return this.scheduleResourceService; } protected KalturaScheduleEventResourceService scheduleEventResourceService; public KalturaScheduleEventResourceService getScheduleEventResourceService() { if(this.scheduleEventResourceService == null) this.scheduleEventResourceService = new KalturaScheduleEventResourceService(this); return this.scheduleEventResourceService; } /** * @param String $clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return (String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param String $apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return (String) this.clientConfiguration.get("apiVersion"); } return null; } /** * Impersonated partner id * * @param Integer $partnerId */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return (Integer) this.requestConfiguration.get("partnerId"); } return null; } /** * Kaltura API session * * @param String $ks */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Kaltura API session * * @param String $sessionId */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Response profile - this attribute will be automatically unset after every API call. * * @param KalturaBaseResponseProfile $responseProfile */ public void setResponseProfile(KalturaBaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return KalturaBaseResponseProfile */ public KalturaBaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } /** * Clear all volatile configuration parameters */ protected void resetRequest(){ this.requestConfiguration.remove("responseProfile"); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.services.KalturaAccessControlProfileService; import com.kaltura.client.services.KalturaAccessControlService; import com.kaltura.client.services.KalturaAdminUserService; import com.kaltura.client.services.KalturaAnalyticsService; import com.kaltura.client.services.KalturaAppTokenService; import com.kaltura.client.services.KalturaBaseEntryService; import com.kaltura.client.services.KalturaBulkUploadService; import com.kaltura.client.services.KalturaCategoryEntryService; import com.kaltura.client.services.KalturaCategoryService; import com.kaltura.client.services.KalturaCategoryUserService; import com.kaltura.client.services.KalturaConversionProfileAssetParamsService; import com.kaltura.client.services.KalturaConversionProfileService; import com.kaltura.client.services.KalturaDataService; import com.kaltura.client.services.KalturaDeliveryProfileService; import com.kaltura.client.services.KalturaEmailIngestionProfileService; import com.kaltura.client.services.KalturaEntryServerNodeService; import com.kaltura.client.services.KalturaFileAssetService; import com.kaltura.client.services.KalturaFlavorAssetService; import com.kaltura.client.services.KalturaFlavorParamsOutputService; import com.kaltura.client.services.KalturaFlavorParamsService; import com.kaltura.client.services.KalturaGroupUserService; import com.kaltura.client.services.KalturaLiveChannelSegmentService; import com.kaltura.client.services.KalturaLiveChannelService; import com.kaltura.client.services.KalturaLiveReportsService; import com.kaltura.client.services.KalturaLiveStatsService; import com.kaltura.client.services.KalturaLiveStreamService; import com.kaltura.client.services.KalturaMediaInfoService; import com.kaltura.client.services.KalturaMediaService; import com.kaltura.client.services.KalturaMixingService; import com.kaltura.client.services.KalturaNotificationService; import com.kaltura.client.services.KalturaPartnerService; import com.kaltura.client.services.KalturaPermissionItemService; import com.kaltura.client.services.KalturaPermissionService; import com.kaltura.client.services.KalturaPlaylistService; import com.kaltura.client.services.KalturaReportService; import com.kaltura.client.services.KalturaResponseProfileService; import com.kaltura.client.services.KalturaSchemaService; import com.kaltura.client.services.KalturaSearchService; import com.kaltura.client.services.KalturaServerNodeService; import com.kaltura.client.services.KalturaSessionService; import com.kaltura.client.services.KalturaStatsService; import com.kaltura.client.services.KalturaStorageProfileService; import com.kaltura.client.services.KalturaSyndicationFeedService; import com.kaltura.client.services.KalturaSystemService; import com.kaltura.client.services.KalturaThumbAssetService; import com.kaltura.client.services.KalturaThumbParamsOutputService; import com.kaltura.client.services.KalturaThumbParamsService; import com.kaltura.client.services.KalturaUiConfService; import com.kaltura.client.services.KalturaUploadService; import com.kaltura.client.services.KalturaUploadTokenService; import com.kaltura.client.services.KalturaUserEntryService; import com.kaltura.client.services.KalturaUserRoleService; import com.kaltura.client.services.KalturaUserService; import com.kaltura.client.services.KalturaWidgetService; import com.kaltura.client.services.KalturaMetadataService; import com.kaltura.client.services.KalturaMetadataProfileService; import com.kaltura.client.services.KalturaDocumentsService; import com.kaltura.client.services.KalturaVirusScanProfileService; import com.kaltura.client.services.KalturaDistributionProfileService; import com.kaltura.client.services.KalturaEntryDistributionService; import com.kaltura.client.services.KalturaDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderActionService; import com.kaltura.client.services.KalturaCuePointService; import com.kaltura.client.services.KalturaAnnotationService; import com.kaltura.client.services.KalturaQuizService; import com.kaltura.client.services.KalturaShortLinkService; import com.kaltura.client.services.KalturaBulkService; import com.kaltura.client.services.KalturaDropFolderService; import com.kaltura.client.services.KalturaDropFolderFileService; import com.kaltura.client.services.KalturaCaptionAssetService; import com.kaltura.client.services.KalturaCaptionParamsService; import com.kaltura.client.services.KalturaCaptionAssetItemService; import com.kaltura.client.services.KalturaAttachmentAssetService; import com.kaltura.client.services.KalturaTagService; import com.kaltura.client.services.KalturaLikeService; import com.kaltura.client.services.KalturaVarConsoleService; import com.kaltura.client.services.KalturaEventNotificationTemplateService; import com.kaltura.client.services.KalturaExternalMediaService; import com.kaltura.client.services.KalturaScheduleEventService; import com.kaltura.client.services.KalturaScheduleResourceService; import com.kaltura.client.services.KalturaScheduleEventResourceService; import com.kaltura.client.services.KalturaScheduledTaskProfileService; import com.kaltura.client.services.KalturaIntegrationService; import com.kaltura.client.services.KalturaPollService; import com.kaltura.client.types.KalturaBaseResponseProfile; /** * This class was generated using exec.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaClient extends KalturaClientBase { public KalturaClient(KalturaConfiguration config) { super(config); this.setClientTag("java:17-06-18"); this.setApiVersion("3.3.0"); } protected KalturaAccessControlProfileService accessControlProfileService; public KalturaAccessControlProfileService getAccessControlProfileService() { if(this.accessControlProfileService == null) this.accessControlProfileService = new KalturaAccessControlProfileService(this); return this.accessControlProfileService; } protected KalturaAccessControlService accessControlService; public KalturaAccessControlService getAccessControlService() { if(this.accessControlService == null) this.accessControlService = new KalturaAccessControlService(this); return this.accessControlService; } protected KalturaAdminUserService adminUserService; public KalturaAdminUserService getAdminUserService() { if(this.adminUserService == null) this.adminUserService = new KalturaAdminUserService(this); return this.adminUserService; } protected KalturaAnalyticsService analyticsService; public KalturaAnalyticsService getAnalyticsService() { if(this.analyticsService == null) this.analyticsService = new KalturaAnalyticsService(this); return this.analyticsService; } protected KalturaAppTokenService appTokenService; public KalturaAppTokenService getAppTokenService() { if(this.appTokenService == null) this.appTokenService = new KalturaAppTokenService(this); return this.appTokenService; } protected KalturaBaseEntryService baseEntryService; public KalturaBaseEntryService getBaseEntryService() { if(this.baseEntryService == null) this.baseEntryService = new KalturaBaseEntryService(this); return this.baseEntryService; } protected KalturaBulkUploadService bulkUploadService; public KalturaBulkUploadService getBulkUploadService() { if(this.bulkUploadService == null) this.bulkUploadService = new KalturaBulkUploadService(this); return this.bulkUploadService; } protected KalturaCategoryEntryService categoryEntryService; public KalturaCategoryEntryService getCategoryEntryService() { if(this.categoryEntryService == null) this.categoryEntryService = new KalturaCategoryEntryService(this); return this.categoryEntryService; } protected KalturaCategoryService categoryService; public KalturaCategoryService getCategoryService() { if(this.categoryService == null) this.categoryService = new KalturaCategoryService(this); return this.categoryService; } protected KalturaCategoryUserService categoryUserService; public KalturaCategoryUserService getCategoryUserService() { if(this.categoryUserService == null) this.categoryUserService = new KalturaCategoryUserService(this); return this.categoryUserService; } protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService; public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() { if(this.conversionProfileAssetParamsService == null) this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this); return this.conversionProfileAssetParamsService; } protected KalturaConversionProfileService conversionProfileService; public KalturaConversionProfileService getConversionProfileService() { if(this.conversionProfileService == null) this.conversionProfileService = new KalturaConversionProfileService(this); return this.conversionProfileService; } protected KalturaDataService dataService; public KalturaDataService getDataService() { if(this.dataService == null) this.dataService = new KalturaDataService(this); return this.dataService; } protected KalturaDeliveryProfileService deliveryProfileService; public KalturaDeliveryProfileService getDeliveryProfileService() { if(this.deliveryProfileService == null) this.deliveryProfileService = new KalturaDeliveryProfileService(this); return this.deliveryProfileService; } protected KalturaEmailIngestionProfileService EmailIngestionProfileService; public KalturaEmailIngestionProfileService getEmailIngestionProfileService() { if(this.EmailIngestionProfileService == null) this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this); return this.EmailIngestionProfileService; } protected KalturaEntryServerNodeService entryServerNodeService; public KalturaEntryServerNodeService getEntryServerNodeService() { if(this.entryServerNodeService == null) this.entryServerNodeService = new KalturaEntryServerNodeService(this); return this.entryServerNodeService; } protected KalturaFileAssetService fileAssetService; public KalturaFileAssetService getFileAssetService() { if(this.fileAssetService == null) this.fileAssetService = new KalturaFileAssetService(this); return this.fileAssetService; } protected KalturaFlavorAssetService flavorAssetService; public KalturaFlavorAssetService getFlavorAssetService() { if(this.flavorAssetService == null) this.flavorAssetService = new KalturaFlavorAssetService(this); return this.flavorAssetService; } protected KalturaFlavorParamsOutputService flavorParamsOutputService; public KalturaFlavorParamsOutputService getFlavorParamsOutputService() { if(this.flavorParamsOutputService == null) this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this); return this.flavorParamsOutputService; } protected KalturaFlavorParamsService flavorParamsService; public KalturaFlavorParamsService getFlavorParamsService() { if(this.flavorParamsService == null) this.flavorParamsService = new KalturaFlavorParamsService(this); return this.flavorParamsService; } protected KalturaGroupUserService groupUserService; public KalturaGroupUserService getGroupUserService() { if(this.groupUserService == null) this.groupUserService = new KalturaGroupUserService(this); return this.groupUserService; } protected KalturaLiveChannelSegmentService liveChannelSegmentService; public KalturaLiveChannelSegmentService getLiveChannelSegmentService() { if(this.liveChannelSegmentService == null) this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this); return this.liveChannelSegmentService; } protected KalturaLiveChannelService liveChannelService; public KalturaLiveChannelService getLiveChannelService() { if(this.liveChannelService == null) this.liveChannelService = new KalturaLiveChannelService(this); return this.liveChannelService; } protected KalturaLiveReportsService liveReportsService; public KalturaLiveReportsService getLiveReportsService() { if(this.liveReportsService == null) this.liveReportsService = new KalturaLiveReportsService(this); return this.liveReportsService; } protected KalturaLiveStatsService liveStatsService; public KalturaLiveStatsService getLiveStatsService() { if(this.liveStatsService == null) this.liveStatsService = new KalturaLiveStatsService(this); return this.liveStatsService; } protected KalturaLiveStreamService liveStreamService; public KalturaLiveStreamService getLiveStreamService() { if(this.liveStreamService == null) this.liveStreamService = new KalturaLiveStreamService(this); return this.liveStreamService; } protected KalturaMediaInfoService mediaInfoService; public KalturaMediaInfoService getMediaInfoService() { if(this.mediaInfoService == null) this.mediaInfoService = new KalturaMediaInfoService(this); return this.mediaInfoService; } protected KalturaMediaService mediaService; public KalturaMediaService getMediaService() { if(this.mediaService == null) this.mediaService = new KalturaMediaService(this); return this.mediaService; } protected KalturaMixingService mixingService; public KalturaMixingService getMixingService() { if(this.mixingService == null) this.mixingService = new KalturaMixingService(this); return this.mixingService; } protected KalturaNotificationService notificationService; public KalturaNotificationService getNotificationService() { if(this.notificationService == null) this.notificationService = new KalturaNotificationService(this); return this.notificationService; } protected KalturaPartnerService partnerService; public KalturaPartnerService getPartnerService() { if(this.partnerService == null) this.partnerService = new KalturaPartnerService(this); return this.partnerService; } protected KalturaPermissionItemService permissionItemService; public KalturaPermissionItemService getPermissionItemService() { if(this.permissionItemService == null) this.permissionItemService = new KalturaPermissionItemService(this); return this.permissionItemService; } protected KalturaPermissionService permissionService; public KalturaPermissionService getPermissionService() { if(this.permissionService == null) this.permissionService = new KalturaPermissionService(this); return this.permissionService; } protected KalturaPlaylistService playlistService; public KalturaPlaylistService getPlaylistService() { if(this.playlistService == null) this.playlistService = new KalturaPlaylistService(this); return this.playlistService; } protected KalturaReportService reportService; public KalturaReportService getReportService() { if(this.reportService == null) this.reportService = new KalturaReportService(this); return this.reportService; } protected KalturaResponseProfileService responseProfileService; public KalturaResponseProfileService getResponseProfileService() { if(this.responseProfileService == null) this.responseProfileService = new KalturaResponseProfileService(this); return this.responseProfileService; } protected KalturaSchemaService schemaService; public KalturaSchemaService getSchemaService() { if(this.schemaService == null) this.schemaService = new KalturaSchemaService(this); return this.schemaService; } protected KalturaSearchService searchService; public KalturaSearchService getSearchService() { if(this.searchService == null) this.searchService = new KalturaSearchService(this); return this.searchService; } protected KalturaServerNodeService serverNodeService; public KalturaServerNodeService getServerNodeService() { if(this.serverNodeService == null) this.serverNodeService = new KalturaServerNodeService(this); return this.serverNodeService; } protected KalturaSessionService sessionService; public KalturaSessionService getSessionService() { if(this.sessionService == null) this.sessionService = new KalturaSessionService(this); return this.sessionService; } protected KalturaStatsService statsService; public KalturaStatsService getStatsService() { if(this.statsService == null) this.statsService = new KalturaStatsService(this); return this.statsService; } protected KalturaStorageProfileService storageProfileService; public KalturaStorageProfileService getStorageProfileService() { if(this.storageProfileService == null) this.storageProfileService = new KalturaStorageProfileService(this); return this.storageProfileService; } protected KalturaSyndicationFeedService syndicationFeedService; public KalturaSyndicationFeedService getSyndicationFeedService() { if(this.syndicationFeedService == null) this.syndicationFeedService = new KalturaSyndicationFeedService(this); return this.syndicationFeedService; } protected KalturaSystemService systemService; public KalturaSystemService getSystemService() { if(this.systemService == null) this.systemService = new KalturaSystemService(this); return this.systemService; } protected KalturaThumbAssetService thumbAssetService; public KalturaThumbAssetService getThumbAssetService() { if(this.thumbAssetService == null) this.thumbAssetService = new KalturaThumbAssetService(this); return this.thumbAssetService; } protected KalturaThumbParamsOutputService thumbParamsOutputService; public KalturaThumbParamsOutputService getThumbParamsOutputService() { if(this.thumbParamsOutputService == null) this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this); return this.thumbParamsOutputService; } protected KalturaThumbParamsService thumbParamsService; public KalturaThumbParamsService getThumbParamsService() { if(this.thumbParamsService == null) this.thumbParamsService = new KalturaThumbParamsService(this); return this.thumbParamsService; } protected KalturaUiConfService uiConfService; public KalturaUiConfService getUiConfService() { if(this.uiConfService == null) this.uiConfService = new KalturaUiConfService(this); return this.uiConfService; } protected KalturaUploadService uploadService; public KalturaUploadService getUploadService() { if(this.uploadService == null) this.uploadService = new KalturaUploadService(this); return this.uploadService; } protected KalturaUploadTokenService uploadTokenService; public KalturaUploadTokenService getUploadTokenService() { if(this.uploadTokenService == null) this.uploadTokenService = new KalturaUploadTokenService(this); return this.uploadTokenService; } protected KalturaUserEntryService userEntryService; public KalturaUserEntryService getUserEntryService() { if(this.userEntryService == null) this.userEntryService = new KalturaUserEntryService(this); return this.userEntryService; } protected KalturaUserRoleService userRoleService; public KalturaUserRoleService getUserRoleService() { if(this.userRoleService == null) this.userRoleService = new KalturaUserRoleService(this); return this.userRoleService; } protected KalturaUserService userService; public KalturaUserService getUserService() { if(this.userService == null) this.userService = new KalturaUserService(this); return this.userService; } protected KalturaWidgetService widgetService; public KalturaWidgetService getWidgetService() { if(this.widgetService == null) this.widgetService = new KalturaWidgetService(this); return this.widgetService; } protected KalturaMetadataService metadataService; public KalturaMetadataService getMetadataService() { if(this.metadataService == null) this.metadataService = new KalturaMetadataService(this); return this.metadataService; } protected KalturaMetadataProfileService metadataProfileService; public KalturaMetadataProfileService getMetadataProfileService() { if(this.metadataProfileService == null) this.metadataProfileService = new KalturaMetadataProfileService(this); return this.metadataProfileService; } protected KalturaDocumentsService documentsService; public KalturaDocumentsService getDocumentsService() { if(this.documentsService == null) this.documentsService = new KalturaDocumentsService(this); return this.documentsService; } protected KalturaVirusScanProfileService virusScanProfileService; public KalturaVirusScanProfileService getVirusScanProfileService() { if(this.virusScanProfileService == null) this.virusScanProfileService = new KalturaVirusScanProfileService(this); return this.virusScanProfileService; } protected KalturaDistributionProfileService distributionProfileService; public KalturaDistributionProfileService getDistributionProfileService() { if(this.distributionProfileService == null) this.distributionProfileService = new KalturaDistributionProfileService(this); return this.distributionProfileService; } protected KalturaEntryDistributionService entryDistributionService; public KalturaEntryDistributionService getEntryDistributionService() { if(this.entryDistributionService == null) this.entryDistributionService = new KalturaEntryDistributionService(this); return this.entryDistributionService; } protected KalturaDistributionProviderService distributionProviderService; public KalturaDistributionProviderService getDistributionProviderService() { if(this.distributionProviderService == null) this.distributionProviderService = new KalturaDistributionProviderService(this); return this.distributionProviderService; } protected KalturaGenericDistributionProviderService genericDistributionProviderService; public KalturaGenericDistributionProviderService getGenericDistributionProviderService() { if(this.genericDistributionProviderService == null) this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this); return this.genericDistributionProviderService; } protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService; public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() { if(this.genericDistributionProviderActionService == null) this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this); return this.genericDistributionProviderActionService; } protected KalturaCuePointService cuePointService; public KalturaCuePointService getCuePointService() { if(this.cuePointService == null) this.cuePointService = new KalturaCuePointService(this); return this.cuePointService; } protected KalturaAnnotationService annotationService; public KalturaAnnotationService getAnnotationService() { if(this.annotationService == null) this.annotationService = new KalturaAnnotationService(this); return this.annotationService; } protected KalturaQuizService quizService; public KalturaQuizService getQuizService() { if(this.quizService == null) this.quizService = new KalturaQuizService(this); return this.quizService; } protected KalturaShortLinkService shortLinkService; public KalturaShortLinkService getShortLinkService() { if(this.shortLinkService == null) this.shortLinkService = new KalturaShortLinkService(this); return this.shortLinkService; } protected KalturaBulkService bulkService; public KalturaBulkService getBulkService() { if(this.bulkService == null) this.bulkService = new KalturaBulkService(this); return this.bulkService; } protected KalturaDropFolderService dropFolderService; public KalturaDropFolderService getDropFolderService() { if(this.dropFolderService == null) this.dropFolderService = new KalturaDropFolderService(this); return this.dropFolderService; } protected KalturaDropFolderFileService dropFolderFileService; public KalturaDropFolderFileService getDropFolderFileService() { if(this.dropFolderFileService == null) this.dropFolderFileService = new KalturaDropFolderFileService(this); return this.dropFolderFileService; } protected KalturaCaptionAssetService captionAssetService; public KalturaCaptionAssetService getCaptionAssetService() { if(this.captionAssetService == null) this.captionAssetService = new KalturaCaptionAssetService(this); return this.captionAssetService; } protected KalturaCaptionParamsService captionParamsService; public KalturaCaptionParamsService getCaptionParamsService() { if(this.captionParamsService == null) this.captionParamsService = new KalturaCaptionParamsService(this); return this.captionParamsService; } protected KalturaCaptionAssetItemService captionAssetItemService; public KalturaCaptionAssetItemService getCaptionAssetItemService() { if(this.captionAssetItemService == null) this.captionAssetItemService = new KalturaCaptionAssetItemService(this); return this.captionAssetItemService; } protected KalturaAttachmentAssetService attachmentAssetService; public KalturaAttachmentAssetService getAttachmentAssetService() { if(this.attachmentAssetService == null) this.attachmentAssetService = new KalturaAttachmentAssetService(this); return this.attachmentAssetService; } protected KalturaTagService tagService; public KalturaTagService getTagService() { if(this.tagService == null) this.tagService = new KalturaTagService(this); return this.tagService; } protected KalturaLikeService likeService; public KalturaLikeService getLikeService() { if(this.likeService == null) this.likeService = new KalturaLikeService(this); return this.likeService; } protected KalturaVarConsoleService varConsoleService; public KalturaVarConsoleService getVarConsoleService() { if(this.varConsoleService == null) this.varConsoleService = new KalturaVarConsoleService(this); return this.varConsoleService; } protected KalturaEventNotificationTemplateService eventNotificationTemplateService; public KalturaEventNotificationTemplateService getEventNotificationTemplateService() { if(this.eventNotificationTemplateService == null) this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this); return this.eventNotificationTemplateService; } protected KalturaExternalMediaService externalMediaService; public KalturaExternalMediaService getExternalMediaService() { if(this.externalMediaService == null) this.externalMediaService = new KalturaExternalMediaService(this); return this.externalMediaService; } protected KalturaScheduleEventService scheduleEventService; public KalturaScheduleEventService getScheduleEventService() { if(this.scheduleEventService == null) this.scheduleEventService = new KalturaScheduleEventService(this); return this.scheduleEventService; } protected KalturaScheduleResourceService scheduleResourceService; public KalturaScheduleResourceService getScheduleResourceService() { if(this.scheduleResourceService == null) this.scheduleResourceService = new KalturaScheduleResourceService(this); return this.scheduleResourceService; } protected KalturaScheduleEventResourceService scheduleEventResourceService; public KalturaScheduleEventResourceService getScheduleEventResourceService() { if(this.scheduleEventResourceService == null) this.scheduleEventResourceService = new KalturaScheduleEventResourceService(this); return this.scheduleEventResourceService; } protected KalturaScheduledTaskProfileService scheduledTaskProfileService; public KalturaScheduledTaskProfileService getScheduledTaskProfileService() { if(this.scheduledTaskProfileService == null) this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this); return this.scheduledTaskProfileService; } protected KalturaIntegrationService integrationService; public KalturaIntegrationService getIntegrationService() { if(this.integrationService == null) this.integrationService = new KalturaIntegrationService(this); return this.integrationService; } protected KalturaPollService pollService; public KalturaPollService getPollService() { if(this.pollService == null) this.pollService = new KalturaPollService(this); return this.pollService; } /** * @param String $clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return (String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param String $apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return (String) this.clientConfiguration.get("apiVersion"); } return null; } /** * Impersonated partner id * * @param Integer $partnerId */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return (Integer) this.requestConfiguration.get("partnerId"); } return null; } /** * Kaltura API session * * @param String $ks */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Kaltura API session * * @param String $sessionId */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Response profile - this attribute will be automatically unset after every API call. * * @param KalturaBaseResponseProfile $responseProfile */ public void setResponseProfile(KalturaBaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return KalturaBaseResponseProfile */ public KalturaBaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } /** * Clear all volatile configuration parameters */ protected void resetRequest(){ this.requestConfiguration.remove("responseProfile"); } }
package com.liminghuang.queue; import java.util.Stack; /** * ProjectName: example * PackageName: com.liminghuang * Description: * . * <p> * CreateTime: 2017/8/15 22:33 * Modifier: Adaministrator * ModifyTime: 2017/8/15 22:33 * Comment: * * @author Adaministrator */ public class StackQueue { private Stack<Integer> originStack; private Stack<Integer> reversalStack; protected StackQueue() { originStack = new Stack<>(); reversalStack = new Stack<>(); } public void enqueue(Integer e) { while (!reversalStack.isEmpty()) { originStack.push(reversalStack.pop()); } // System.out.println("originStack: " + originStack.toString()); originStack.push(e); } public Integer dequeue() { while (!originStack.empty()) { reversalStack.push(originStack.pop()); } // System.out.println("reversalStack: " + reversalStack.toString()); return reversalStack.pop(); } public String toString() { while (!reversalStack.isEmpty()) { originStack.push(reversalStack.pop()); } return originStack.toString(); } public boolean isEmpty() { return reversalStack.isEmpty() && originStack.isEmpty(); } public static void main(String[] args) { StackQueue stackQueue = new StackQueue(); Integer[] array = {1, 2, 3, 4, 5, 0}; for (Integer i : array) { stackQueue.enqueue(i); } System.out.println("queue: " + stackQueue.toString()); System.out.println("dequeue e: " + stackQueue.dequeue()); System.out.println("queue: " + stackQueue.toString()); stackQueue.enqueue(6); stackQueue.enqueue(7); System.out.println("queue: " + stackQueue.toString()); System.out.println("dequeue e: " + stackQueue.dequeue()); System.out.println("queue: " + stackQueue.toString()); } }
package com.mythicmc.mythic.utils; import java.text.SimpleDateFormat; import java.util.Date; public class Logger { public static boolean showThread = true; private static SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); public static void info(String format, Object...objects) { logf("info", format, objects); } public static void warn(String format, Object...objects) { logf("warn", format, objects); } public static void error(String format, Object...objects) { logf("error", format, objects); } public static void debug(String format, Object...objects) { logf("debug", format, objects); } public static void logf(String level, String format, Object...objects) { String tName = "Mythic Main Thread"; if(showThread) tName = Thread.currentThread().getName(); System.out.printf(String.format("[%s] [%s/%s] %s\n",sdf.format(new Date(System.currentTimeMillis())),tName, level.toUpperCase(), format), objects); } }
package com.socrata.datasync; import com.google.common.net.HttpHeaders; import com.socrata.datasync.config.userpreferences.UserPreferences; import org.apache.commons.net.util.Base64; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import java.io.IOException; import java.net.URI; import java.nio.charset.Charset; public class HttpUtility { private CloseableHttpClient httpClient = null; private RequestConfig proxyConfig = null; private String authHeader; private String appToken; private boolean authRequired = false; private static final String datasyncVersionHeader = "X-Socrata-DataSync-Version"; private static final String appHeader = "X-App-Token"; private static final String userAgent = "datasync"; public HttpUtility() { this(null, false); } public HttpUtility(UserPreferences userPrefs, boolean useAuth) { if (useAuth) { authHeader = getAuthHeader(userPrefs.getUsername(), userPrefs.getPassword()); appToken = userPrefs.getAPIKey(); } authRequired = useAuth; if(userPrefs != null && userPrefs.getProxyHost() != null && userPrefs.getProxyPort() != null) { HttpHost proxy = new HttpHost(userPrefs.getProxyHost(), Integer.valueOf(userPrefs.getProxyPort())); proxyConfig = RequestConfig.custom().setProxy(proxy).build(); if (userPrefs.getProxyUsername() != null && userPrefs.getProxyPassword() != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(userPrefs.getProxyHost(), Integer.valueOf(userPrefs.getProxyPort())), new UsernamePasswordCredentials(userPrefs.getProxyUsername(), userPrefs.getProxyPassword())); httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); } } if (httpClient == null) httpClient = HttpClientBuilder.create().build(); } /** * Conducts a basic get, passing the auth information in the header. * @param uri the uri from which the get will be made * @param contentType the expected contentType of the return value * @return the unproccessed query results */ public CloseableHttpResponse get(URI uri, String contentType) throws IOException { HttpGet httpGet = new HttpGet(uri); httpGet.setHeader(HttpHeaders.USER_AGENT, userAgent); httpGet.addHeader(HttpHeaders.ACCEPT, contentType); httpGet.addHeader(datasyncVersionHeader, VersionProvider.getThisVersion()); if (proxyConfig != null) httpGet.setConfig(proxyConfig); if (authRequired) { httpGet.setHeader(appHeader, appToken); httpGet.setHeader(HttpHeaders.AUTHORIZATION, authHeader); } return httpClient.execute(httpGet); } /** * Conducts a basic post of the given entity; auth information is passed in the header. * @param uri the uri to which the entity will be posted * @param entity an entity to post * @return the unprocessed results of the post */ public CloseableHttpResponse post(URI uri, HttpEntity entity) throws IOException { HttpPost httpPost = new HttpPost(uri); httpPost.setHeader(HttpHeaders.USER_AGENT, userAgent); httpPost.setHeader(entity.getContentType()); httpPost.addHeader(datasyncVersionHeader, VersionProvider.getThisVersion()); httpPost.setEntity(entity); if (proxyConfig != null) httpPost.setConfig(proxyConfig); if (authRequired) { httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader); httpPost.setHeader(appHeader, appToken); } return httpClient.execute(httpPost); } public void close() throws IOException { httpClient.close(); } private String getAuthHeader(String username, String password) { String auth = username + ":" + password; byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII"))); return "Basic " + new String(encodedAuth); } }
package com.tomgibara.storage; /** * Exposes methods for manipulating mutability. * * @author Tom Gibara * * @param <T> the underlying type */ public interface Mutability<T> { /** * Whether the object is mutable. * * @return true if mutable, false otherwise */ boolean isMutable(); /** * A copy of the object if it is immutable, or the object itself. This * method is useful when receiving an object of uncertain mutability on * which mutation-based computations are necessary. * * @return the mutable object or a mutable copy */ T mutable(); /** * A mutable copy of the object. Changes to the state of the returned copy * will not modify this object. * * @return a mutable copy of this object */ T mutableCopy(); /** * An immutable copy of the object if it is mutable or the object itself. * This method is useful when returning an object of uncertain mutability * to prevent accidental mutation by the caller. * * @return the immutable object or an immutable copy. */ T immutable(); /** * An immutable copy of this object. * * @return an immutable copy of this object */ T immutableCopy(); /** * An immutable view of this object. The view will exhibit the same state as * this object, and mutations of the state of this object will be reflected * in the view, but mutation via calls on the returned view will be * prohibited. * * @return an immutable view of this object */ T immutableView(); }
package com.untamedears.humbug; import org.bukkit.craftbukkit.v1_6_R3.entity.CraftHorse; import net.minecraft.server.v1_6_R3.AttributeInstance; import net.minecraft.server.v1_6_R3.AttributeRanged; import net.minecraft.server.v1_6_R3.EntityHorse; import net.minecraft.server.v1_6_R3.GenericAttributes; import net.minecraft.server.v1_6_R3.IAttribute; import org.bukkit.entity.Entity; public class Versioned { // Static class private Versioned() {} public static double getHorseSpeed(Entity entity) { if (!(entity instanceof CraftHorse)) { return -1.0000001; } EntityHorse mcHorseAlot = ((CraftHorse)entity).getHandle(); // GenericAttributes.d == generic.movementSpeed return mcHorseAlot.getAttributeInstance(GenericAttributes.d).b(); } public static void setHorseSpeed(Entity entity, double speedModifier) { if (!(entity instanceof CraftHorse)) { return; } EntityHorse mcHorseAlot = ((CraftHorse)entity).getHandle(); mcHorseAlot.getAttributeInstance(GenericAttributes.d).setValue(speedModifier); } }
package de.domisum.lib.auxilium.util; import de.domisum.lib.auxilium.util.java.annotations.API; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * PlaceHolderReplacer. * <p> * Replaces placeholders in strings with supplied values. * <p> * Throws an exception if the number of placeholders in the String does not match the supplied number of objects. * <p> * The names of the class and the static methods are chosen as an acronym * to keep static method calls as short as possible. */ @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public final class PHR implements CharSequence { // CONSTANTS @API public static final String PLACEHOLDER = "{}"; // INPUT private final String text; private final Object[] values; // CACHED private String replaced; // INIT @API public static String r(String text, Object... values) { return rcs(text, values).toString(); } /** * Creates a lazy CharSequence object which will only do the replacing if any of the CharSequence methods or #toString() is * called. This can improve performance when this method is called extremely often in performance critical parts of the code. * * @param text the text with placeholders * @param values the values with which the placeholders shall be replaced * @return a CharSequence which represents the string with placeholders replaced by the supplied values */ @API public static CharSequence rcs(String text, Object... values) { return new PHR(text, values); } // OBJECT @Override public synchronized String toString() { initReplacedIfNeeded(); return replaced; } // REPLACE private void initReplacedIfNeeded() { if(replaced == null) replaced = replacePlaceholders(); } private String replacePlaceholders() { List<Integer> placeholderIndices = determinePlaceholderIndices(text); if(placeholderIndices.size() != values.length) throw new IllegalArgumentException("given values: "+values.length+", found placeholders: "+placeholderIndices.size()); return replacePlaceholdersWithValues(text, placeholderIndices, values); } private static List<Integer> determinePlaceholderIndices(String text) { List<Integer> placeholderIndices = new ArrayList<>(); int searchFrom = 0; while(true) { int index = text.indexOf(PLACEHOLDER, searchFrom); if(index == -1) break; placeholderIndices.add(index); searchFrom = index+1; } return placeholderIndices; } private static String replacePlaceholdersWithValues(String text, List<Integer> placeholderIndices, Object[] values) { String filledInString = text; // iterate from back so inserting string doesn't change the indices of the other placeholders for(int i = placeholderIndices.size()-1; i >= 0; i { int placeholderStartIndex = placeholderIndices.get(i); String beforePlaceholder = filledInString.substring(0, placeholderStartIndex); String valueForPlaceholder = Objects.toString(values[i]); String afterPlaceholder = filledInString.substring(placeholderStartIndex+PLACEHOLDER.length()); filledInString = beforePlaceholder+valueForPlaceholder+afterPlaceholder; } return filledInString; } // CHARSEQUENCE @Override public synchronized int length() { initReplacedIfNeeded(); return replaced.length(); } @Override public synchronized char charAt(int index) { initReplacedIfNeeded(); return replaced.charAt(index); } @Override public synchronized CharSequence subSequence(int start, int end) { initReplacedIfNeeded(); return replaced.subSequence(start, end); } }
package de.mxro.maven.tools; import static org.joox.JOOX.$; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.file.FileSystems; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.joox.JOOX; import org.joox.Match; import org.w3c.dom.Document; import de.mxro.file.FileItem; import de.mxro.file.Jre.FilesJre; import de.mxro.javafileutils.Collect; import de.mxro.javafileutils.Collect.LeafCheck; import de.mxro.process.Spawn; public class MavenProject { private static List<File> orderDirectoriesByBuildOrder(final List<File> directories, final List<Dependency> buildOrder, final boolean addOthers) { final List<File> res = new ArrayList<File>(directories.size()); final List<File> unprocessed = new LinkedList<File>(directories); final Map<String, Dependency> map = new HashMap<String, Dependency>(); for (final Dependency d : buildOrder) { map.put(d.artifactId(), d); } for (final File f : directories) { final Dependency match = map.get(f.getName()); if (match == null) { continue; } unprocessed.remove(f); res.add(f); } // System.out.println(unprocessed.size()); if (addOthers) { res.addAll(unprocessed); } return res; } public static boolean isMavenProject(final File directory) { for (final File child : directory.listFiles()) { if (child.getName().equals("pom.xml")) { return true; } } return false; } public static List<File> orderDirectoriesByBuildOrder(final List<File> directories, final List<Dependency> buildOrder) { return orderDirectoriesByBuildOrder(directories, buildOrder, true); } public static List<File> getDependendProjectsInCorrectOrder(final List<File> directories, final List<Dependency> buildOrder) { return orderDirectoriesByBuildOrder(directories, buildOrder, false); } public static boolean buildSuccessful(final String mavenOutput) { if (mavenOutput.contains("BUILD FAILURE") || !mavenOutput.contains("BUILD SUCCESS")) { return false; } else { return true; } } public static List<Dependency> dependencyBuildOrder(final File project) { final List<Dependency> res = new ArrayList<Dependency>(100); final String dependencyOutput = Spawn.runBashCommand("mvn dependency:tree -o | tail -n 10000", project); final Pattern pattern = Pattern.compile("- ([^:]*):([^:]*):([^:]*):([^:]*):"); final Matcher matcher = pattern.matcher(dependencyOutput); while (matcher.find()) { if (matcher.groupCount() == 4) { final String groupId = matcher.group(1); final String artifactId = matcher.group(2); final String version = matcher.group(4); final Dependency d = new Dependency() { @Override public String groupId() { return groupId; } @Override public String artifactId() { return artifactId; } @Override public String version() { return version; } }; res.add(d); } } Collections.reverse(res); return res; } private static void replaceVersion(final File pomFile, final String newVersion) { try { final List<String> lines = new ArrayList<String>(); final BufferedReader in = new BufferedReader(new FileReader(pomFile)); String line = in.readLine(); boolean found = false; while (line != null) { if (!found && line.contains("<version>")) { lines.add(" <version>" + newVersion + "</version>"); found = true; } else { lines.add(line); } line = in.readLine(); } in.close(); final PrintWriter out = new PrintWriter(pomFile); for (final String l : lines) { out.println(l); } out.close(); } catch (final IOException ex) { throw new RuntimeException(ex); } } private static Dependency retrieveDependency(final File pomFile) { try { final byte[] pomBytes = Files.readAllBytes(FileSystems.getDefault().getPath(pomFile.getAbsolutePath())); final String pom = new String(pomBytes, "UTF-8"); final String groupId; final String artifactId; final String version; { final Pattern pattern = Pattern.compile("<groupId>([^<]*)</groupId>"); final Matcher matcher = pattern.matcher(pom); matcher.find(); groupId = matcher.group(1); } { final Pattern pattern = Pattern.compile("<artifactId>([^<]*)</artifactId>"); final Matcher matcher = pattern.matcher(pom); matcher.find(); artifactId = matcher.group(1); } { final Pattern pattern = Pattern.compile("<version>([^<]*)</version>"); final Matcher matcher = pattern.matcher(pom); matcher.find(); version = matcher.group(1); } return new Dependency() { @Override public String version() { return version; } @Override public String groupId() { return groupId; } @Override public String artifactId() { return artifactId; } }; } catch (final IOException ex) { throw new RuntimeException(ex); } } public static String getVersion(final File projectDir) { for (final File file : projectDir.listFiles()) { if (file.getName().equals("pom.xml")) { return retrieveDependency(file).version(); } } throw new RuntimeException("No pom.xml found in project dir " + projectDir); } public static Dependency getMavenDependency(final File projectDir) { for (final File file : projectDir.listFiles()) { if (file.getName().equals("pom.xml")) { return retrieveDependency(file); } } throw new RuntimeException("No pom.xml found in project dir " + projectDir); } public static void setVersion(final File projectDir, final String version) { for (final File file : projectDir.listFiles()) { if (file.getName().equals("pom.xml")) { replaceVersion(file, version); return; } } throw new RuntimeException("No pom.xml found in project dir " + projectDir); } public static List<File> getProjects(final File rootDir) { return Collect.getLeafDirectoriesRecursively(rootDir, new LeafCheck() { @Override public boolean isLeaf(final File f) { if (!f.isDirectory()) { return false; } return f.listFiles(new FileFilter() { @Override public boolean accept(final File pathname) { return pathname.getName().equals("pom.xml"); } }).length > 0; } }); } /** * * <p> * Replace a dependency for a maven project. * <p> * If properties of the provided oldDependency are <code>null</code>, any * dependency of the project will be matched. * <p> * If properties of newDependency are <code>null</code>, the specific * property will not be replaced. * * @param projectDir * @param oldDependency * @param newDependency * @return */ public static boolean replaceDependency(final File projectDir, final Dependency oldDependency, final Dependency newDependency) { final FileItem pom = FilesJre.wrap(projectDir).get("pom.xml"); if (!pom.exists()) { throw new IllegalArgumentException("Specified directory does not contain a pom.xml file: " + projectDir); } Document document; try { document = $(JOOX.builder().parse(new File(pom.getPath()))).document(); } catch (final Exception e2) { throw new RuntimeException(e2); } final Match root = $(document); final Match project = root.first(); if (project.size() != 1) { throw new RuntimeException("Illegal pom [" + pom + "]. Element project cannot be found."); } final Match dependencies = project.child("dependencies"); if (dependencies.size() != 1) { throw new RuntimeException("Illegal pom [" + pom + "]"); } // System.out.println(dependencies); final Match children = dependencies.children("dependency"); // System.out.println(children); boolean changed = false; for (final org.w3c.dom.Element e : children) { final String groupId = $(e).child("groupId").content(); final String artifactId = $(e).child("artifactId").content(); final String version = $(e).child("version").content(); if (oldDependency.groupId() != null && !oldDependency.groupId().equals(groupId)) { continue; } if (oldDependency.artifactId() != null && !oldDependency.artifactId().equals(artifactId)) { continue; } if (oldDependency.version() != null && !oldDependency.version().equals(version)) { continue; } if (newDependency.version() != null) { $(e).child("version").content(newDependency.version()); changed = true; } if (newDependency.groupId() != null) { $(e).child("groupId").content(newDependency.groupId()); changed = true; } if (newDependency.artifactId() != null) { $(e).child("artifactId").content(newDependency.artifactId()); changed = true; } } if (changed) { try { final TransformerFactory tf = TransformerFactory.newInstance(); final Transformer transformer = tf.newTransformer(); // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, // "yes"); final StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(writer)); final String output = writer.getBuffer().toString(); // System.out.println("Defining new pom\n"); // System.out.println(output); pom.setText(output); } catch (final TransformerException e1) { throw new RuntimeException(e1); } } return changed; } }
package eu.lp0.cursus.db.dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import eu.lp0.cursus.db.DatabaseSession; import eu.lp0.cursus.db.data.AbstractEntity; public abstract class AbstractDAO<E extends AbstractEntity> { protected final Class<E> clazz; public AbstractDAO(Class<E> clazz) { this.clazz = clazz; } EntityManager getEntityManager() { return DatabaseSession.getEntityManager(); } /** * Save/update transient/persisted (but not detached) entity */ public void persist(E entity) { DatabaseSession.getEntityManager().persist(entity); } /** * Copy detached entity to an updated persisted entity, merging all changes * * Merge behaviour may cause unexpected changes (override with DIY merge) */ protected E merge(E entity) { return DatabaseSession.getEntityManager().merge(entity); } /** * Remove persisted entity */ public void remove(E entity) { DatabaseSession.getEntityManager().remove(entity); } /** * Detach persisted entity */ public void detach(E entity) { DatabaseSession.getEntityManager().detach(entity); } public E get(E entity) { EntityManager em = getEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<E> q = cb.createQuery(clazz); Root<E> s = q.from(clazz); q.select(s); q.where(cb.equal(s.get("id"), entity.getId())); //$NON-NLS-1$ TypedQuery<E> tq = em.createQuery(q); return tq.getSingleResult(); } public List<E> findAll() { EntityManager em = getEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<E> q = cb.createQuery(clazz); Root<E> s = q.from(clazz); q.select(s); TypedQuery<E> tq = em.createQuery(q); return tq.getResultList(); } }
package hudson.remoting; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; /** * {@link InputStream} that reads bits from an exported * {@link InputStream} on a remote machine. * * <p> * TODO: pre-fetch bytes in advance * * @author Kohsuke Kawaguchi */ final class ProxyInputStream extends InputStream { private Channel channel; private int oid; /** * Creates an already connected {@link ProxyOutputStream}. * * @param oid * The object id of the exported {@link OutputStream}. */ public ProxyInputStream(Channel channel, int oid) throws IOException { this.channel = channel; this.oid = oid; } @Override public int read() throws IOException { try { Buffer buf = _read(1); if(buf.len==1) // byte->int expansion needs to be done carefully becaue byte in Java is signed // whose idea was it to make byte signed, anyway!? return ((int)buf.buf[0])&0xFF; else return -1; } catch (InterruptedException e) { // pretend EOF Thread.currentThread().interrupt(); // process interrupt later close(); return -1; } } private synchronized Buffer _read(int len) throws IOException, InterruptedException { return new Chunk(oid, len).call(channel); } @Override public int read(byte b[], int off, int len) throws IOException { try { Buffer buf = _read(len); if(buf.len==-1) return -1; System.arraycopy(buf.buf,0,b,off,buf.len); return buf.len; } catch (InterruptedException e) { // pretend EOF Thread.currentThread().interrupt(); // process interrupt later close(); return -1; } } @Override public synchronized void close() throws IOException { if(channel!=null) { channel.send(new EOF(oid)); channel = null; oid = -1; } } private static final class Buffer implements Serializable { byte[] buf; int len; public Buffer(int len) { this.buf = new byte[len]; } public void read(InputStream in) throws IOException { len = in.read(buf,0,buf.length); } private static final long serialVersionUID = 1L; } /** * Command to fetch bytes. */ private static final class Chunk extends Request<Buffer,IOException> { private final int oid; private final int len; public Chunk(int oid, int len) { this.oid = oid; this.len = len; } protected Buffer perform(Channel channel) throws IOException { InputStream in = (InputStream) channel.getExportedObject(oid); Buffer buf = new Buffer(len); buf.read(in); return buf; } private static final long serialVersionUID = 1L; } /** * {@link Command} for sending EOF. */ private static final class EOF extends Command { private final int oid; public EOF(int oid) { this.oid = oid; } protected void execute(Channel channel) { InputStream in = (InputStream) channel.getExportedObject(oid); channel.unexport(oid); try { in.close(); } catch (IOException e) { // ignore errors } } public String toString() { return "EOF("+oid+")"; } private static final long serialVersionUID = 1L; } }
package io.taig.android.dp; import android.annotation.TargetApi; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.*; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.ColorInt; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.widget.TextView; import static android.os.Build.VERSION_CODES.LOLLIPOP; /** * Circular progress widget */ public class DonutProgress extends View { interface OnProgressChangedListener { String update( int current, int max ); } private Paint backgroundPaint; private Paint progressPaint; private int progressColorStart; private int progressColorEnd; private int progressCurrent; private int progressMax; private int progressStartAngle; private OnProgressChangedListener onProgressChangedListener = new OnProgressChangedListener() { @Override public String update( int current, int max ) { return Math.min( Math.round( (float) current / max * 100 ), 100 ) + "%"; } }; private int labelColorDefault; private int labelColorEmpty; private String labelText; private boolean labelSize = false; private float labelYOffset = 0; private Paint labelPaint; private boolean thickness = false; private RectF cacheRect = new RectF(); public DonutProgress( Context context ) { super( context ); init( context, null, 0, 0 ); } public DonutProgress( Context context, AttributeSet attrs ) { super( context, attrs ); init( context, attrs, 0, 0 ); } public DonutProgress( Context context, AttributeSet attrs, int defStyleAttr ) { super( context, attrs, defStyleAttr ); init( context, attrs, defStyleAttr, 0 ); } @TargetApi( LOLLIPOP ) public DonutProgress( Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes ) { super( context, attrs, defStyleAttr, defStyleRes ); init( context, attrs, defStyleAttr, defStyleRes ); } @SuppressWarnings( "deprecation" ) private void init( Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes ) { TypedValue value = new TypedValue(); Resources.Theme theme = context.getTheme(); TypedArray array = theme.obtainStyledAttributes( attrs, R.styleable.DonutProgress, defStyleAttr, defStyleRes ); try { int colorGrey; if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) { colorGrey = getContext().getColor( R.color.donut_progress_background ); } else { colorGrey = getContext().getResources().getColor( R.color.donut_progress_background ); } int colorText = new TextView( getContext() ).getTextColors().getDefaultColor(); this.backgroundPaint = new Paint(); this.backgroundPaint.setAntiAlias( true ); this.backgroundPaint.setColor( colorGrey ); this.backgroundPaint.setStyle( Paint.Style.STROKE ); this.progressPaint = new Paint( this.backgroundPaint ); this.progressColorStart = array.getColor( R.styleable.DonutProgress_donut_progress_colorStart, -1 ); if( this.progressColorStart == -1 ) { theme.resolveAttribute( R.attr.colorPrimary, value, true ); this.progressColorStart = value.data; } this.progressColorEnd = array.getColor( R.styleable.DonutProgress_donut_progress_colorEnd, -1 ); if( this.progressColorEnd == -1 ) { theme.resolveAttribute( R.attr.colorPrimaryDark, value, true ); this.progressColorEnd = value.data; } this.progressCurrent = array.getInt( R.styleable.DonutProgress_donut_progress_current, 0 ); this.progressMax = array.getInt( R.styleable.DonutProgress_donut_progress_max, 100 ); this.progressStartAngle = array.getInt( R.styleable.DonutProgress_donut_progress_startAngle, 0 ); theme.resolveAttribute( android.R.attr.textColor, value, true ); this.labelColorDefault = array.getColor( R.styleable.DonutProgress_donut_progress_labelColorDefault, -1 ); if( this.labelColorDefault == -1 ) { if( value.type != TypedValue.TYPE_NULL ) { this.labelColorDefault = value.data; } else { this.labelColorDefault = colorText; } } this.labelColorEmpty = array.getColor( R.styleable.DonutProgress_donut_progress_labelColorEmpty, colorGrey ); this.labelText = render(); this.labelPaint = new Paint(); this.labelPaint.setAntiAlias( true ); this.labelPaint.setTextAlign( Paint.Align.CENTER ); float labelSize = array.getDimension( R.styleable.DonutProgress_donut_progress_labelSize, -1 ); if( labelSize != -1 ) { setLabelSize( labelSize ); } float thickness = array.getDimension( R.styleable.DonutProgress_donut_progress_thickness, -1 ); if( thickness != -1 ) { setThickness( thickness ); } } finally { array.recycle(); } } /** * Use the {@link #onProgressChangedListener} to render the current progress to a String * * @return A String representation of the current progress, or <code>null</code> if {@link * #onProgressChangedListener} is null */ private String render() { if( onProgressChangedListener != null ) { return onProgressChangedListener.update( progressCurrent, progressMax ); } else { return null; } } /** * Get the progress ring start color * <p/> * The progress bar allows to render a circular gradient. This color is the gradient's start color. * * @return Progress ring start color value */ public int getProgressStartColor() { return progressColorStart; } /** * Set the progress ring start color * <p/> * The progress bar allows to render a circular gradient. This color is the gradient's start color. * <p/> * Apply the same color value to {@link #setProgressStartColor(int)} and {@link #setProgressEndColor(int)} to * disable the gradient. * * @param color Color int value * @see #setProgressEndColor(int) */ public void setProgressStartColor( @ColorInt int color ) { this.progressColorStart = color; invalidate(); } /** * Get the progress ring end color * <p/> * The progress bar allows to render a circular gradient. This color is the gradient's end color. * <p/> * Apply the same color value to {@link #setProgressStartColor(int)} and {@link #setProgressEndColor(int)} to * disable the gradient. * * @return Progress ring end color value */ public int getProgressEndColor() { return progressColorEnd; } /** * Set the progress ring end color * <p/> * The progress bar allows to render a circular gradient. This color is the gradient's end color. * * @param color Color int value * @see #setProgressStartColor(int) */ public void setProgressEndColor( @ColorInt int color ) { this.progressColorEnd = color; invalidate(); } /** * Get the current progress * <p/> * This is an absolute int value, not a percentage. * * @return Current progress value */ public int getCurrentProgress() { return progressCurrent; } public void setCurrentProgress( int value ) { if( value < 0 ) { throw new IllegalArgumentException( "Current progress must be >= 0" ); } else if( value > progressMax ) { throw new IllegalArgumentException( "Current progress must be <= max progress" ); } progressCurrent = value; labelText = render(); invalidate(); } /** * Get the max progress * * @return Max progress value */ public int getMaxProgress() { return progressMax; } public void setMaxProgress( int value ) { if( value < 0 ) { throw new IllegalArgumentException( "Max progress must be >= 0" ); } if( progressCurrent > value ) { progressCurrent = value; } progressMax = value; labelText = render(); invalidate(); } /** * Get the progress ring start angle * <p/> * The angle defines where the progress ring starts to draw. By default it is set to 0, which is at the top. * * @return Progress ring start angle value */ public int getProgressStartAngle() { return progressStartAngle; } public void setProgressStartAngle( int value ) { if( value < 0 || value > 360 ) { throw new IllegalArgumentException( "Value must be 0 <= x <= 360" ); } progressStartAngle = value; invalidate(); } /** * Get the {@link OnProgressChangedListener} * * @return {@link OnProgressChangedListener} or <code>null</code> if none applied */ public OnProgressChangedListener getOnProgressChangedListener() { return onProgressChangedListener; } /** * Set the {@link OnProgressChangedListener} * <p/> * By default, a listener is set that renders percentage strings (such as "0%", "38%" or "100%"). * * @param onProgressChangedListener Listener or <code>null</code> to disable label rendering */ public void setOnProgressChangedListener( @Nullable OnProgressChangedListener onProgressChangedListener ) { this.onProgressChangedListener = onProgressChangedListener; labelText = render(); invalidate(); } /** * Get the default label color * <p/> * The default color is used when the current progress is > 0. * * @return Default label color value */ public int getLabelDefaultColor() { return labelColorDefault; } /** * Set the default label color * <p/> * The default color is used when the current progress is > 0. * * @param color Default label color value */ public void setLabelDefaultColor( @ColorInt int color ) { this.labelColorDefault = color; invalidate(); } /** * Get the empty label color * <p/> * The empty color is used when the current progress is == 0. * * @return Empty label color value */ public int getLabelEmptyColor() { return labelColorEmpty; } /** * Set the empty label color * <p/> * The empty color is used when the current progress is == 0. * * @param color Empty label color value */ public void setLabelEmptyColor( @ColorInt int color ) { this.labelColorEmpty = color; invalidate(); } /** * Get the currently displayed label text * * @return Currently displayed label text, or <code>null</code> if no text is visible */ public String getLabelText() { return labelText; } /** * Get the label size * * @return Label size value, or <code>null</code> if no size is specified */ public Float getLabelSize() { if( labelSize ) { return labelPaint.getTextSize(); } else { return null; } } /** * Set the label size * * @param value Label size value, or <code>null</code> for automatic size (25% of the view's height) */ public void setLabelSize( @Nullable Float value ) { if( value == null ) { labelSize = false; } else { labelSize = true; labelPaint.setTextSize( value ); Rect rect = new Rect(); labelPaint.getTextBounds( "100%", 0, 4, rect ); labelYOffset = rect.height() / 2f; } invalidate(); } /** * Get the ring thickness * * @return Thickness value, or <code>null</code> of no thickness is specified */ public Float getThickness() { if( thickness ) { return backgroundPaint.getStrokeWidth(); } else { return null; } } /** * Set the ring thickness * * @param value Thickness value, or <code>nukk</code> for automatic size (10% of the view's smallest dimension) */ public void setThickness( @Nullable Float value ) { if( value == null ) { thickness = false; } else { backgroundPaint.setStrokeWidth( value ); progressPaint.setStrokeWidth( value ); thickness = true; } invalidate(); } @Override protected void onSizeChanged( int width, int height, int oldWidth, int oldHeight ) { super.onSizeChanged( width, height, oldWidth, oldHeight ); if( !labelSize ) { setLabelSize( height / 4f ); labelSize = false; } if( !thickness ) { setThickness( Math.min( width, height ) / 10f ); thickness = false; } } @Override protected void onDraw( Canvas canvas ) { super.onDraw( canvas ); int width = canvas.getWidth(); int height = canvas.getHeight(); float margin = backgroundPaint.getStrokeWidth() / 2f; float progress = (float) progressCurrent / progressMax; cacheRect.left = margin; cacheRect.top = margin; cacheRect.right = width - margin; cacheRect.bottom = height - margin; progressPaint.setShader( new SweepGradient( width / 2f, height / 2f, new int[] { progressColorStart, progressColorEnd }, new float[] { 0, progress } ) ); canvas.save(); canvas.rotate( progressStartAngle - 90, width / 2f, height / 2f ); canvas.drawArc( cacheRect, 0, 360, false, backgroundPaint ); canvas.drawArc( cacheRect, 0, progress * 360, false, progressPaint ); canvas.restore(); if( onProgressChangedListener != null ) { if( progressCurrent == 0 ) { labelPaint.setColor( labelColorEmpty ); } else { labelPaint.setColor( labelColorDefault ); } canvas.drawText( labelText, width / 2f, height / 2f + labelYOffset, labelPaint ); } } @Override protected Parcelable onSaveInstanceState() { State state = new State( super.onSaveInstanceState() ); state.current = progressCurrent; state.max = progressMax; return state; } @Override protected void onRestoreInstanceState( Parcelable parcelable ) { if( parcelable instanceof State ) { State state = ( (State) parcelable ); progressCurrent = state.current; progressMax = state.max; super.onRestoreInstanceState( state.getSuperState() ); } else { super.onRestoreInstanceState( parcelable ); } } public static class State extends BaseSavedState { int current; int max; State( Parcelable superState ) { super( superState ); } protected State( Parcel in ) { super( in ); current = in.readInt(); max = in.readInt(); } @Override public void writeToParcel( Parcel out, int flags ) { super.writeToParcel( out, flags ); out.writeInt( current ); out.writeInt( max ); } public static final Creator<State> CREATOR = new Creator<State>() { public State createFromParcel( Parcel in ) { return new State( in ); } public State[] newArray( int size ) { return new State[size]; } }; } }
package javaslang.collection; import javaslang.Tuple2; import javaslang.Kind; import javaslang.algebra.Monoid; import javaslang.control.Match; import javaslang.control.None; import javaslang.control.Option; import javaslang.control.Some; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.function.*; import java.util.stream.StreamSupport; public interface Traversable<M extends Traversable<M, ?>, T> extends Kind<M, T>, Iterable<T> { /** * Calculates the average of this elements. Returns {@code None} if this is empty, otherwise {@code Some(average)}. * Supported component types are {@code Byte}, {@code Double}, {@code Float}, {@code Integer}, {@code Long}, * {@code Short}, {@code BigInteger} and {@code BigDecimal}. * <p> * Examples: * <pre> * <code> * List.empty().average() // = None * List.of(1, 2, 3).average() // = Some(2.0) * List.of(0.1, 0.2, 0.3).average() // = Some(0.2) * List.of("apple", "pear").average() // throws * </code> * </pre> * * @return {@code Some(average)} or {@code None}, if there are no elements * @throws UnsupportedOperationException if this elements are not numeric */ @SuppressWarnings("unchecked") default Option<Double> average() { if (isEmpty()) { return None.instance(); } else { final OptionalDouble average = Match .when((byte t) -> ((java.util.stream.Stream<Byte>) toJavaStream()).mapToInt(Number::intValue).average()) .when((double t) -> ((java.util.stream.Stream<Double>) toJavaStream()).mapToDouble(Number::doubleValue).average()) .when((float t) -> ((java.util.stream.Stream<Float>) toJavaStream()).mapToDouble(Number::doubleValue).average()) .when((int t) -> ((java.util.stream.Stream<Integer>) toJavaStream()).mapToInt(Number::intValue).average()) .when((long t) -> ((java.util.stream.Stream<Long>) toJavaStream()).mapToLong(Number::longValue).average()) .when((short t) -> ((java.util.stream.Stream<Short>) toJavaStream()).mapToInt(Number::intValue).average()) .when((BigInteger t) -> ((java.util.stream.Stream<BigInteger>) toJavaStream()).mapToLong(Number::longValue).average()) .when((BigDecimal t) -> ((java.util.stream.Stream<BigDecimal>) toJavaStream()).mapToDouble(Number::doubleValue).average()) .orElse(() -> { throw new UnsupportedOperationException("not numeric"); }) .apply(head()); return new Some<>(average.getAsDouble()); } } /** * Returns an empty version of this traversable, i.e. {@code this.clear().isEmpty() == true}. * * @return an empty Traversable. */ Traversable<M, T> clear(); /** * Returns the union of all combinations from k = 0 to length(). * <p> * Examples: * <pre> * <code> * [].combinations() = [[]] * * [1,2,3].combinations() = [ * [], // k = 0 * [1], [2], [3], // k = 1 * [1,2], [1,3], [2,3], // k = 2 * [1,2,3] // k = 3 * ] * </code> * </pre> * * @return the combinations of this */ Traversable<M, ? extends Traversable<M, T>> combinations(); Traversable<M, ? extends Traversable<M, T>> combinations(int k); /** * Tests if this Traversable contains a given value. * * @param element An Object of type A, may be null. * @return true, if element is in this Traversable, false otherwise. */ default boolean contains(T element) { return findFirst(e -> java.util.Objects.equals(e, element)).isDefined(); } /** * <p> * Tests if this Traversable contains all given elements. * </p> * <p> * The result is equivalent to * {@code elements.isEmpty() ? true : contains(elements.head()) && containsAll(elements.tail())} but implemented * without recursion. * </p> * * @param elements A List of values of type E. * @return true, if this List contains all given elements, false otherwise. * @throws NullPointerException if {@code elements} is null */ default boolean containsAll(Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); return List.ofAll(elements) .distinct() .findFirst(e -> !this.contains(e)) .isEmpty(); } /** * Returns a new version of this which contains no duplicates. Elements are compared using {@code equals}. * * @return a new {@code Traversable} containing this elements without duplicates */ Traversable<M, T> distinct(); /** * Returns a new version of this which contains no duplicates. Elements mapped to keys which are compared using * {@code equals}. * <p> * The elements of the result are determined in the order of their occurrence - first match wins. * * @param keyExtractor A key extractor * @param <U> key type * @return a new {@code Traversable} containing this elements without duplicates * @throws NullPointerException if {@code keyExtractor} is null */ <U> Traversable<M, T> distinct(Function<? super T, ? extends U> keyExtractor); /** * Drops the first n elements of this or all elements, if this length &lt; n. * * @param n The number of elements to drop. * @return a new instance consisting of all elements of this except the first n ones, or else the empty instance, * if this has less than n elements. */ Traversable<M, T> drop(int n); /** * Drops the last n elements of this or all elements, if this length &lt; n. * * @param n The number of elements to drop. * @return a new instance consisting of all elements of this except the last n ones, or else the empty instance, * if this has less than n elements. */ Traversable<M, T> dropRight(int n); /** * Drops elements while the predicate holds for the current element. * * @param predicate A condition tested subsequently for this elements starting with the first. * @return a new instance consisting of all elements starting from the first one which does not satisfy the * given predicate. * @throws NullPointerException if {@code predicate} is null */ Traversable<M, T> dropWhile(Predicate<? super T> predicate); /** * Checks, if at least one element exists such that the predicate holds. * * @param predicate A Predicate * @return true, if predicate holds for an element of this, false otherwise * @throws NullPointerException if {@code predicate} is null */ default boolean exists(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); for (T t : this) { if (predicate.test(t)) { return true; } } return false; } /** * Checks, if a unique elements exists such that the predicate holds. * * @param predicate A Predicate * @return true, if predicate holds for a unique element of this, false otherwise * @throws NullPointerException if {@code predicate} is null */ default boolean existsUnique(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); boolean exists = false; for (T t : this) { if (predicate.test(t)) { if (exists) { return false; } else { exists = true; } } } return exists; } /** * Returns a new traversable consisting of all elements of this which satisfy the given predicate. * * @param predicate A predicate * @return a new traversable * @throws NullPointerException if {@code predicate} is null */ Traversable<M, T> filter(Predicate<? super T> predicate); /** * Essentially the same as {@link #filter(Predicate)} but the result type may differ, * i.e. tree.findAll() may be a List. * * @param predicate A predicate. * @return all elements of this which satisfy the given predicate. * @throws NullPointerException if {@code predicate} is null */ Traversable<M, T> findAll(Predicate<? super T> predicate); /** * Returns the first element of this which satisfies the given predicate. * * @param predicate A predicate. * @return Some(element) or None, where element may be null (i.e. {@code List.of(null).findFirst(e -> e == null)}). * @throws NullPointerException if {@code predicate} is null */ default Option<T> findFirst(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); for (T a : this) { if (predicate.test(a)) { return new Some<>(a); // may be Some(null) } } return Option.none(); } /** * <p> * Returns the last element of this which satisfies the given predicate. * </p> * <p> * Same as {@code reverse().findFirst(predicate)}. * </p> * * @param predicate A predicate. * @return Some(element) or None, where element may be null (i.e. {@code List.of(null).findFirst(e -> e == null)}). * @throws NullPointerException if {@code predicate} is null */ default Option<T> findLast(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return reverse().findFirst(predicate); } <U> Traversable<M, U> flatMap(Function<? super T, ? extends Kind<M, U>> mapper); /** * Flattens a {@code Traversable} using a function. * * @param <U> component type of the result {@code Traversable} * @param f a function which maps elements of this Traversable to Traversables * @return a new {@code Traversable} * @throws NullPointerException if {@code f} is null */ <U> Traversable<M, U> flatten(Function<? super T, ? extends Kind<M, U>> f); /** * <p> * Accumulates the elements of this Traversable by successively calling the given operator {@code op}. * </p> * <p> * Example: {@code List("a", "b", "c").fold("", (a, b) -> a + b) = "abc"} * </p> * * @param zero Value to start the accumulation with. * @param op The accumulator operator. * @return an accumulated version of this. * @throws NullPointerException if {@code op} is null */ default T fold(T zero, BiFunction<? super T, ? super T, ? extends T> op) { Objects.requireNonNull(op, "op is null"); return foldLeft(zero, op); } /** * <p> * Accumulates the elements of this Traversable by successively calling the given function {@code f} from the left, * starting with a value {@code zero} of type B. * </p> * <p> * Example: {@code List.of("a", "b", "c").foldLeft("", (xs, x) -> xs + x) = "abc"} * </p> * * @param zero Value to start the accumulation with. * @param f The accumulator function. * @param <U> Result type of the accumulator. * @return an accumulated version of this. * @throws NullPointerException if {@code f} is null */ default <U> U foldLeft(U zero, BiFunction<? super U, ? super T, ? extends U> f) { Objects.requireNonNull(f, "f is null"); U xs = zero; for (T x : this) { xs = f.apply(xs, x); } return xs; } /** * Maps this elements to a Monoid and applies foldLeft, starting with monoid.zero(): * <pre> * <code>foldLeft(monoid.zero(), (ys, x) -&gt; monoid.combine(ys, mapper.apply(x)))</code> * </pre> * * @param monoid A Monoid * @param mapper A mapper * @param <U> Component type of the given monoid. * @return the folded monoid value. * @throws NullPointerException if {@code monoid} or {@code mapper} is null */ default <U> U foldMap(Monoid<U> monoid, Function<? super T, ? extends U> mapper) { Objects.requireNonNull(monoid, "monoid is null"); Objects.requireNonNull(mapper, "mapper is null"); return foldLeft(monoid.zero(), (ys, x) -> monoid.combine(ys, mapper.apply(x))); } /** * <p> * Accumulates the elements of this Traversable by successively calling the given function {@code f} from the right, * starting with a value {@code zero} of type B. * </p> * <p> * Example: {@code List.of("a", "b", "c").foldRight("", (x, xs) -> x + xs) = "abc"} * </p> * <p> * In order to prevent recursive calls, foldRight is implemented based on reverse and foldLeft. A recursive variant * is based on foldMap, using the monoid of function composition (endo monoid). * </p> * <pre> * <code> * foldRight = reverse().foldLeft(zero, (b, a) -&gt; f.apply(a, b)); * foldRight = foldMap(Algebra.Monoid.endoMonoid(), a -&gt; b -&gt; f.apply(a, b)).apply(zero); * </code> * </pre> * * @param zero Value to start the accumulation with. * @param f The accumulator function. * @param <U> Result type of the accumulator. * @return an accumulated version of this. * @throws NullPointerException if {@code f} is null */ default <U> U foldRight(U zero, BiFunction<? super T, ? super U, ? extends U> f) { Objects.requireNonNull(f, "f is null"); return reverse().foldLeft(zero, (xs, x) -> f.apply(x, xs)); } @Override default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action, "action is null"); Iterable.super.forEach(action); } /** * Checks, if the given predicate holds for all elements of this. * * @param predicate A Predicate * @return true, if the predicate holds for all elements of this, false otherwise * @throws NullPointerException if {@code predicate} is null */ default boolean forAll(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); for (T t : this) { if (!predicate.test(t)) { return false; } } return true; } Traversable<M, ? extends Traversable<M, T>> grouped(int size); /** * Returns the first element of a non-empty Traversable. * * @return The first element of this Traversable. * @throws NoSuchElementException if this is empty */ T head(); /** * Returns the first element of a non-empty Traversable as {@code Option}. * * @return {@code Some(element)} or {@code None} if this is empty. */ Option<T> headOption(); /** * Dual of {@linkplain #tail()}, returning all elements except the last. * * @return a new instance containing all elements except the last. * @throws UnsupportedOperationException if this is empty */ Traversable<M, T> init(); /** * Dual of {@linkplain #tailOption()}, returning all elements except the last as {@code Option}. * * @return {@code Some(traversable)} or {@code None} if this is empty. */ Option<? extends Traversable<M, T>> initOption(); /** * Inserts an element between all elements of this Traversable. * * @param element An element. * @return an interspersed version of this */ Traversable<M, T> intersperse(T element); /** * Checks if this Traversable is empty. * * @return true, if this Traversable contains no elements, falso otherwise. */ boolean isEmpty(); @Override default Iterator<T> iterator() { return new Iterator<T>() { Traversable<M, T> traversable = Traversable.this; @Override public boolean hasNext() { return !traversable.isEmpty(); } @Override public T next() { if (traversable.isEmpty()) { throw new NoSuchElementException(); } else { final T result = traversable.head(); traversable = traversable.tail(); return result; } } }; } /** * Joins the elements of this by concatenating their string representations. * <p> * This has the same effect as calling {@code join("", "", "")}. * * @return a new String */ default String join() { return join("", "", ""); } /** * Joins the string representations of this elements using a specific delimiter. * <p> * This has the same effect as calling {@code join(delimiter, "", "")}. * * @param delimiter A delimiter string put between string representations of elements of this * @return A new String */ default String join(CharSequence delimiter) { return join(delimiter, "", ""); } /** * Joins the string representations of this elements using a specific delimiter, prefix and suffix. * <p> * Example: {@code List.of("a", "b", "c").join(", ", "Chars(", ")") = "Chars(a, b, c)"} * * @param delimiter A delimiter string put between string representations of elements of this * @param prefix prefix of the resulting string * @param suffix suffix of the resulting string * @return a new String */ default String join(CharSequence delimiter, CharSequence prefix, CharSequence suffix) { final StringBuilder builder = new StringBuilder(prefix); map(String::valueOf).intersperse(String.valueOf(delimiter)).forEach(builder::append); return builder.append(suffix).toString(); } /** * Dual of {@linkplain #head()}, returning the last element. * * @return the last element. * @throws NoSuchElementException is this is empty */ default T last() { if (isEmpty()) { throw new NoSuchElementException("last of empty Traversable"); } else { Traversable<M, T> traversable = this; { // don't let escape tail Traversable<M, T> tail; while (!(tail = traversable.tail()).isEmpty()) { traversable = tail; } } return traversable.head(); } } /** * Dual of {@linkplain #headOption()}, returning the last element as {@code Opiton}. * * @return {@code Some(element)} or {@code None} if this is empty. */ default Option<T> lastOption() { return isEmpty() ? None.instance() : new Some<>(last()); } /** * Computes the number of elements of this. * * @return the number of elements */ default int length() { return foldLeft(0, (n, ignored) -> n + 1); } /** * Maps the elements of this traversable to elements of a new type preserving their order, if any. * * @param mapper A mapper. * @param <U> Component type of the target Traversable * @return a mapped Traversable * @throws NullPointerException if {@code mapper} is null */ <U> Traversable<M, U> map(Function<? super T, ? extends U> mapper); /** * Creates a partition of this {@code Traversable} by splitting this elements in two in distinct tarversables * according to a predicate. * * @param predicate A predicate which classifies an element if it is in the first or the second traversable. * @return A disjoint union of two traversables. The first {@code Traversable} contains all elements that satisfy the given {@code predicate}, the second {@code Traversable} contains all elements that don't. The original order of elements is preserved. * @throws NullPointerException if predicate is null */ Tuple2<? extends Traversable<M, T>, ? extends Traversable<M, T>> partition(Predicate<? super T> predicate); /** * Calculates the maximum of this elements according to their natural order. * * @return {@code Some(maximum)} of this elements or {@code None} if this is empty or this elements are not comparable */ @SuppressWarnings("unchecked") default Option<T> max() { if (isEmpty() || !(head() instanceof Comparable)) { return None.instance(); } else { return maxBy((o1, o2) -> ((Comparable<T>) o1).compareTo(o2)); } } /** * Calculates the maximum of this elements using a specific comparator. * * @param comparator A non-null element comparator * @return {@code Some(maximum)} of this elements or {@code None} if this is empty * @throws NullPointerException if {@code comparator} is null */ default Option<T> maxBy(Comparator<? super T> comparator) { Objects.requireNonNull(comparator, "comparator is null"); if (isEmpty()) { return None.instance(); } else { final T value = reduce((t1, t2) -> comparator.compare(t1, t2) >= 0 ? t1 : t2); return new Some<>(value); } } /** * Calculates the minimum of this elements according to their natural order. * * @return {@code Some(minimum)} of this elements or {@code None} if this is empty or this elements are not comparable */ @SuppressWarnings("unchecked") default Option<T> min() { if (isEmpty() || !(head() instanceof Comparable)) { return None.instance(); } else { return minBy((o1, o2) -> ((Comparable<T>) o1).compareTo(o2)); } } /** * Calculates the minimum of this elements using a specific comparator. * * @param comparator A non-null element comparator * @return {@code Some(minimum)} of this elements or {@code None} if this is empty * @throws NullPointerException if {@code comparator} is null */ default Option<T> minBy(Comparator<? super T> comparator) { Objects.requireNonNull(comparator, "comparator is null"); if (isEmpty()) { return None.instance(); } else { final T value = reduce((t1, t2) -> comparator.compare(t1, t2) <= 0 ? t1 : t2); return new Some<>(value); } } Traversable<M, T> peek(Consumer<? super T> action); /** * Calculates the product of this elements. Supported component types are {@code Byte}, {@code Double}, {@code Float}, * {@code Integer}, {@code Long}, {@code Short}, {@code BigInteger} and {@code BigDecimal}. * <p> * Examples: * <pre> * <code> * List.empty().product() // = 1 * List.of(1, 2, 3).product() // = 6 * List.of(0.1, 0.2, 0.3).product() // = 0.006 * List.of("apple", "pear").product() // throws * </code> * </pre> * * @return a {@code Number} representing the sum of this elements * @throws UnsupportedOperationException if this elements are not numeric */ @SuppressWarnings("unchecked") default Number product() { if (isEmpty()) { return 1; } else { return Match.ofType(Number.class) .when((byte t) -> ((java.util.stream.Stream<Byte>) toJavaStream()).mapToInt(Number::intValue).reduce(1, (i1, i2) -> i1 * i2)) .when((double t) -> ((java.util.stream.Stream<Double>) toJavaStream()).mapToDouble(Number::doubleValue).reduce(1.0, (d1, d2) -> d1 * d2)) .when((float t) -> ((java.util.stream.Stream<Float>) toJavaStream()).mapToDouble(Number::doubleValue).reduce(1.0, (d1, d2) -> d1 * d2)) .when((int t) -> ((java.util.stream.Stream<Integer>) toJavaStream()).mapToInt(Number::intValue).reduce(1, (i1, i2) -> i1 * i2)) .when((long t) -> ((java.util.stream.Stream<Long>) toJavaStream()).mapToLong(Number::longValue).reduce(1L, (l1, l2) -> l1 * l2)) .when((short t) -> ((java.util.stream.Stream<Short>) toJavaStream()).mapToInt(Number::intValue).reduce(1, (i1, i2) -> i1 * i2)) .when((BigInteger t) -> ((java.util.stream.Stream<BigInteger>) toJavaStream()).mapToLong(Number::longValue).reduce(1L, (l1, l2) -> l1 * l2)) .when((BigDecimal t) -> ((java.util.stream.Stream<BigDecimal>) toJavaStream()).mapToDouble(Number::doubleValue).reduce(1.0, (d1, d2) -> d1 * d2)) .orElse(() -> { throw new UnsupportedOperationException("not numeric"); }) .apply(head()); } } /** * Removes the first occurrence of the given element. * * @param element An element to be removed from this Traversable. * @return a Traversable containing all elements of this without the first occurrence of the given element. */ Traversable<M, T> remove(T element); /** * Removes all occurrences of the given element. * * @param element An element to be removed from this Traversable. * @return a Traversable containing all elements of this but not the given element. */ Traversable<M, T> removeAll(T element); /** * Removes all occurrences of the given elements. * * @param elements Elements to be removed from this Traversable. * @return a Traversable containing all elements of this but none of the given elements. * @throws NullPointerException if {@code elements} is null */ Traversable<M, T> removeAll(Iterable<? extends T> elements); /** * Accumulates the elements of this Traversable by successively calling the given operation {@code op}. * The order of element iteration is undetermined. * * @param op A BiFunction of type T * @return the reduced value. * @throws UnsupportedOperationException if this is empty * @throws NullPointerException if {@code op} is null */ default T reduce(BiFunction<? super T, ? super T, ? extends T> op) { Objects.requireNonNull(op, "op is null"); return reduceLeft(op); } /** * Accumulates the elements of this Traversable by successively calling the given operation {@code op} from the left. * * @param op A BiFunction of type T * @return the reduced value. * @throws NoSuchElementException if this is empty * @throws NullPointerException if {@code op} is null */ default T reduceLeft(BiFunction<? super T, ? super T, ? extends T> op) { Objects.requireNonNull(op, "op is null"); if (isEmpty()) { throw new NoSuchElementException("reduceLeft on Nil"); } else { return tail().foldLeft(head(), op); } } /** * Accumulates the elements of this Traversable by successively calling the given operation {@code op} from the right. * * @param op An operation of type T * @return the reduced value. * @throws NoSuchElementException if this is empty * @throws NullPointerException if {@code op} is null */ default T reduceRight(BiFunction<? super T, ? super T, ? extends T> op) { Objects.requireNonNull(op, "op is null"); if (isEmpty()) { throw new NoSuchElementException("reduceRight on empty List"); } else { final Traversable<M, T> reversed = reverse(); return reversed.tail().foldLeft(reversed.head(), (xs, x) -> op.apply(x, xs)); } } /** * Replaces the first occurrence (if exists) of the given currentElement with newElement. * * @param currentElement An element to be substituted. * @param newElement A replacement for currentElement. * @return a Traversable containing all elements of this where the first occurrence of currentElement is replaced with newELement. */ Traversable<M, T> replace(T currentElement, T newElement); /** * Replaces all occurrences of the given currentElement with newElement. * * @param currentElement An element to be substituted. * @param newElement A replacement for currentElement. * @return a Traversable containing all elements of this where all occurrences of currentElement are replaced with newELement. */ Traversable<M, T> replaceAll(T currentElement, T newElement); /** * Replaces all occurrences of this Traversable by applying the given operator to the elements, which is * essentially a special case of {@link #map(Function)}. * * @param operator An operator. * @return a Traversable containing all elements of this transformed within the same domain. * @throws NullPointerException if {@code operator} is null */ Traversable<M, T> replaceAll(UnaryOperator<T> operator); /** * Keeps all occurrences of the given elements from this. * * @param elements Elements to be kept. * @return a Traversable containing all occurreces of the given elements. * @throws NullPointerException if {@code elements} is null */ Traversable<M, T> retainAll(Iterable<? extends T> elements); /** * Reverses the order of elements. * * @return the reversed elements. */ Traversable<M, T> reverse(); Traversable<M, ? extends Traversable<M, T>> sliding(int size); Traversable<M, ? extends Traversable<M, T>> sliding(int size, int step); /** * Returns a tuple where the first element is the longest prefix of elements that satisfy p and the second element is the remainder. * * @param predicate A predicate. * @return a Tuple containing the longest prefix of elements that satisfy p and the remainder. * @throws NullPointerException if {@code predicate} is null */ Tuple2<? extends Traversable<M, T>, ? extends Traversable<M, T>> span(Predicate<? super T> predicate); /** * Calculates the sum of this elements. Supported component types are {@code Byte}, {@code Double}, {@code Float}, * {@code Integer}, {@code Long}, {@code Short}, {@code BigInteger} and {@code BigDecimal}. * <p> * Examples: * <pre> * <code> * List.empty().sum() // = 0 * List.of(1, 2, 3).sum() // = 6 * List.of(0.1, 0.2, 0.3).sum() // = 0.6 * List.of("apple", "pear").sum() // throws * </code> * </pre> * * @return a {@code Number} representing the sum of this elements * @throws UnsupportedOperationException if this elements are not numeric */ @SuppressWarnings("unchecked") default Number sum() { if (isEmpty()) { return 0; } else { return Match.ofType(Number.class) .when((byte t) -> ((java.util.stream.Stream<Byte>) toJavaStream()).mapToInt(Number::intValue).sum()) .when((double t) -> ((java.util.stream.Stream<Double>) toJavaStream()).mapToDouble(Number::doubleValue).sum()) .when((float t) -> ((java.util.stream.Stream<Float>) toJavaStream()).mapToDouble(Number::doubleValue).sum()) .when((int t) -> ((java.util.stream.Stream<Integer>) toJavaStream()).mapToInt(Number::intValue).sum()) .when((long t) -> ((java.util.stream.Stream<Long>) toJavaStream()).mapToLong(Number::longValue).sum()) .when((short t) -> ((java.util.stream.Stream<Short>) toJavaStream()).mapToInt(Number::intValue).sum()) .when((BigInteger t) -> ((java.util.stream.Stream<BigInteger>) toJavaStream()).mapToLong(Number::longValue).sum()) .when((BigDecimal t) -> ((java.util.stream.Stream<BigDecimal>) toJavaStream()).mapToDouble(Number::doubleValue).sum()) .orElse(() -> { throw new UnsupportedOperationException("not numeric"); }) .apply(head()); } } default void stderr() { for (T t : this) { System.err.println(String.valueOf(t)); if (System.err.checkError()) { throw new IllegalStateException("Error writing to stderr"); } } } default void stdout() { for (T t : this) { System.out.println(String.valueOf(t)); if (System.out.checkError()) { throw new IllegalStateException("Error writing to stdout"); } } } /** * Drops the first element of a non-empty Traversable. * * @return A new instance of Traversable containing all elements except the first. * @throws UnsupportedOperationException if this is empty */ Traversable<M, T> tail(); /** * Drops the first element of a non-empty Traversable and returns an {@code Option}. * * @return {@code Some(traversable)} or {@code None} if this is empty. */ Option<? extends Traversable<M, T>> tailOption(); /** * Takes the first n elements of this or all elements, if this length &lt; n. * <p> * The result is equivalent to {@code sublist(0, max(0, min(length(), n)))} but does not throw if {@code n < 0} or * {@code n > length()}. * <p> * In the case of {@code n < 0} the empty instance is returned, in the case of {@code n > length()} this is returned. * * @param n The number of elements to take. * @return A new instance consisting the first n elements of this or all elements, if this has less than n elements. */ Traversable<M, T> take(int n); /** * Takes the last n elements of this or all elements, if this length &lt; n. * <p> * The result is equivalent to {@code sublist(max(0, min(length(), length() - n)), n)}, i.e. takeRight will not * throw if {@code n < 0} or {@code n > length()}. * <p> * In the case of {@code n < 0} the empty instance is returned, in the case of {@code n > length()} this is returned. * * @param n The number of elements to take. * @return A new instance consisting the first n elements of this or all elements, if this has less than n elements. */ Traversable<M, T> takeRight(int n); /** * Takes elements while the predicate holds for the current element. * * @param predicate A condition tested subsequently for this elements starting with the last. * @return a new instance consisting of all elements starting from the last one which does not satisfy the * given predicate. * @throws NullPointerException if {@code predicate} is null */ Traversable<M, T> takeWhile(Predicate<? super T> predicate); /** * Converts this to a Java array. * <p> * Tip: Given a {@code Traversable<M<T>> t} use {@code t.toJavaArray((Class<M<T>>) (Class) M.class)}. * * @param componentType Type of resulting array's elements. * @return a new array containing this elements * @throws NullPointerException if {@code componentType} is null */ default T[] toJavaArray(Class<T> componentType) { Objects.requireNonNull(componentType, "componentType is null"); final java.util.List<T> list = toJavaList(); @SuppressWarnings("unchecked") final T[] array = list.toArray((T[]) java.lang.reflect.Array.newInstance(componentType, list.size())); return array; } /** * Converts this to a {@link java.util.List}. * * @return a new {@linkplain java.util.ArrayList} containing this elements */ default java.util.List<T> toJavaList() { final java.util.List<T> result = new java.util.ArrayList<>(); for (T a : this) { result.add(a); } return result; } /** * Converts this to a {@link java.util.Map} by converting this elements to key-value pairs. * * @param <K> key type * @param <V> value type * @param f a function which converts elements of this to key-value pairs inserted into the resulting Map * @return a new {@linkplain java.util.HashMap} containing this key-value representations of this elements * @throws NullPointerException if {@code f} is null */ default <K, V> java.util.Map<K, V> toJavaMap(Function<? super T, Tuple2<K, V>> f) { Objects.requireNonNull(f, "f is null"); final java.util.Map<K, V> map = new java.util.HashMap<>(); for (T a : this) { final Tuple2<K, V> entry = f.apply(a); map.put(entry._1, entry._2); } return map; } /** * Converts this to a {@link java.util.Set}. * * @return a new {@linkplain java.util.HashSet} containing this elements */ default java.util.Set<T> toJavaSet() { final java.util.Set<T> result = new java.util.HashSet<>(); for (T a : this) { result.add(a); } return result; } /** * Converts this to a sequential {@link java.util.stream.Stream} by calling {@code this.toJavaList().stream()}. * * @return a new {@linkplain java.util.stream.Stream} containing this elements */ default java.util.stream.Stream<T> toJavaStream() { return StreamSupport.stream(spliterator(), false); } /** * Unzips this elements by mapping this elements to pairs which are subsequentially split into to distinct * traversables. * * @param unzipper a function which converts elements of this to pairs * @param <T1> 1st element type of a pair returned by unzipper * @param <T2> 2nd element type of a pair returned by unzipper * @return A pair of traversables containing elements split by unzipper * @throws NullPointerException if {@code unzipper} is null */ <T1, T2> Tuple2<? extends Traversable<M, T1>, ? extends Traversable<M, T2>> unzip(Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper); /** * Returns a Traversable formed from this Traversable and another Iterable collection by combining corresponding elements * in pairs. If one of the two Traversables is longer than the other, its remaining elements are ignored. * <p> * The length of the returned collection is the minimum of the lengths of this Traversable and that. * * @param <U> The type of the second half of the returned pairs. * @param that The Iterable providing the second half of each result pair. * @return a new Traversable containing pairs consisting of corresponding elements of this list and that. * @throws NullPointerException if {@code that} is null */ <U> Traversable<M, Tuple2<T, U>> zip(Iterable<U> that); /** * Returns a Traversable formed from this Traversable and another Iterable by combining corresponding elements in * pairs. If one of the two collections is shorter than the other, placeholder elements are used to extend the * shorter collection to the length of the longer. * <p> * The length of the returned Traversable is the maximum of the lengths of this Traversable and that. * If this Traversable is shorter than that, thisElem values are used to fill the result. * If that is shorter than this Traversable, thatElem values are used to fill the result. * * @param <U> The type of the second half of the returned pairs. * @param that The Iterable providing the second half of each result pair. * @param thisElem The element to be used to fill up the result if this Traversable is shorter than that. * @param thatElem The element to be used to fill up the result if that is shorter than this Traversable. * @return A new Traversable containing pairs consisting of corresponding elements of this Traversable and that. * @throws NullPointerException if {@code that} is null */ <U> Traversable<M, Tuple2<T, U>> zipAll(Iterable<U> that, T thisElem, U thatElem); /** * Zips this List with its indices. * * @return A new List containing all elements of this List paired with their index, starting with 0. */ Traversable<M, Tuple2<T, Integer>> zipWithIndex(); }
package me.coley.recaf.ui; import javafx.application.Platform; import javafx.scene.control.*; import javafx.stage.FileChooser; import javafx.stage.Window; import me.coley.recaf.control.gui.GuiController; import me.coley.recaf.decompile.DecompileImpl; import me.coley.recaf.plugin.PluginsManager; import me.coley.recaf.plugin.api.ContextMenuInjector; import me.coley.recaf.search.StringMatchMode; import me.coley.recaf.ui.controls.ActionMenuItem; import me.coley.recaf.ui.controls.IconView; import me.coley.recaf.ui.controls.RenamingTextField; import me.coley.recaf.ui.controls.SearchPane; import me.coley.recaf.ui.controls.ViewportTabs; import me.coley.recaf.ui.controls.popup.YesNoWindow; import me.coley.recaf.ui.controls.tree.JavaResourceTree; import me.coley.recaf.ui.controls.view.BytecodeViewport; import me.coley.recaf.ui.controls.view.ClassViewport; import me.coley.recaf.ui.controls.view.FileViewport; import me.coley.recaf.util.*; import me.coley.recaf.workspace.JavaResource; import org.objectweb.asm.ClassReader; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Map; import static me.coley.recaf.util.LangUtil.translate; /** * Context menu builder. * * @author Matt */ public class ContextBuilder { private static final int SKIP = ClassReader.SKIP_DEBUG | ClassReader.SKIP_CODE; private static PluginsManager plugins = PluginsManager.getInstance(); private GuiController controller; private JavaResource resource; // class ctx options private ClassViewport classView; private TreeView<?> treeView; private boolean declaration; private ClassReader reader; // file ctx options private FileViewport fileView; /** * @return Context menu builder. */ public static ContextBuilder menu() { return new ContextBuilder(); } /** * @param controller * Controller context. * * @return Builder. */ public ContextBuilder controller(GuiController controller) { this.controller = controller; return this; } /** * @param classView * Class viewport containing the class/declaring-class. * * @return Builder. */ public ContextBuilder view(ClassViewport classView) { this.classView = classView; return this; } /** * @param fileView * File viewport containing the file. * * @return Builder. */ public ContextBuilder view(FileViewport fileView) { this.fileView = fileView; return this; } /** * @param treeView * Tree viewport containing the class. * * @return Builder. */ public ContextBuilder tree(TreeView<?> treeView) { this.treeView = treeView; return this; } /** * @param declaration * If the member is a declaration <i>(As opposed to a reference)</i> * * @return Builder. */ public ContextBuilder declaration(boolean declaration) { this.declaration = declaration; return this; } /** * @param name * Class name. * * @return {@code true} if the containing resource can be found and a class-reader * generated. */ private boolean setupClass(String name) { resource = controller.getWorkspace().getContainingResourceForClass(name); if(resource == null) return false; // Try to fetch class reader = controller.getWorkspace().getClassReader(name); if(reader == null) try { reader = new ClassReader(name); } catch(Exception ex) { return false; } return true; } /** * @return {@code true} when the item is a declaration instead of a reference. * Otherwise, {@code false}. */ public boolean isDeclaration() { return declaration; } /** * @return The viewport the item resides in. * Will be {@code null} if the item does not belong to a class viewport. */ public ClassViewport getClassView() { return classView; } /** * @return The viewport the item resides in. * Will be {@code null} if the item does not belong to a file viewport. */ public FileViewport getFileView() { return fileView; } /** * @return The UI controller. */ public GuiController getController() { return controller; } /** * @return The class reader of the item. * Will be {@code null} if the item does not relate to a class file. */ public ClassReader getReader() { return reader; } /** * @return The resource the item belongs to. * Will be {@code null} if the item does not relate to a class or file in one of the loaded resources. */ public JavaResource getResource() { return resource; } /** * @return The host tree view that holds the item we're adding the context menu to. * Will be {@code null} if the item does not belong to a tree-view. */ public TreeView<?> getTreeView() { return treeView; } /** * @return {@code true} when the {@link #treeView} belongs to a resource tree * <i>(Inside the workspace navigator)</i>. */ public boolean isWorkspaceTree() { return treeView != null && treeView.getParent() instanceof JavaResourceTree; } /** * @param name * Class name. * * @return Context menu for classes. */ public ContextMenu ofClass(String name) { if(!setupClass(name)) return null; // Create header int access = reader.getAccess(); MenuItem header = new MenuItem(shorten(name)); header.getStyleClass().add("context-menu-header"); header.setGraphic(UiUtil.createClassGraphic(access)); header.setDisable(true); ContextMenu menu = new ContextMenu(); menu.getItems().add(header); // Add options for classes we have knowledge of if(hasClass(controller, name)) { if (declaration) { MenuItem rename = new ActionMenuItem(LangUtil.translate("ui.edit.method.rename"), () -> { Window main = controller.windows().getMainWindow().getStage(); RenamingTextField popup = RenamingTextField.forClass(controller, name); popup.show(main); }); menu.getItems().add(rename); } else { MenuItem jump = new ActionMenuItem(LangUtil.translate("ui.edit.method.goto"), () -> { controller.windows().getMainWindow().openClass(resource, name); }); menu.getItems().add(jump); } // Allow searching for class references MenuItem search = new ActionMenuItem(LangUtil.translate("ui.edit.search"), () -> { SearchPane sp = controller.windows().getMainWindow().getMenubar().searchClassReference(); sp.setInput("ui.search.cls_reference.name", name); sp.setInput("ui.search.matchmode", StringMatchMode.EQUALS); sp.search(); }); menu.getItems().add(search); // Add workspace-navigator specific items, but only for primary classes if (isWorkspaceTree() && controller.getWorkspace().getPrimary().getClasses().containsKey(name)) { MenuItem remove = new ActionMenuItem(LangUtil.translate("misc.remove"), () -> { YesNoWindow.prompt(LangUtil.translate("misc.confirm.message"), () -> { controller.getWorkspace().getPrimary().getClasses().remove(name); controller.windows().getMainWindow().getTabs().closeTab(name); }, null).show(treeView); }); menu.getItems().add(remove); } } // Inject plugin menus plugins.ofType(ContextMenuInjector.class).forEach(injector -> injector.forClass(this, menu, name)); return menu; } /** * @param owner * Declaring class name. * @param name * Field name. * @param desc * Field descriptor. * * @return Context menu for fields. */ public ContextMenu ofField(String owner, String name, String desc) { if(!setupClass(owner)) return null; // Fetch field FieldNode node = ClassUtil.getField(reader, SKIP, name, desc); if(node == null) return null; int access = node.access; // Create header MenuItem header = new MenuItem(name); header.getStyleClass().add("context-menu-header"); header.setGraphic(UiUtil.createFieldGraphic(access)); header.setDisable(true); ContextMenu menu = new ContextMenu(); menu.getItems().add(header); // Add options for fields we have knowledge of if(hasClass(controller, owner)) { if (declaration) { MenuItem rename = new ActionMenuItem(LangUtil.translate("ui.edit.method.rename"), () -> { Window main = controller.windows().getMainWindow().getStage(); RenamingTextField popup = RenamingTextField.forMember(controller, owner, name, desc); popup.show(main); }); MenuItem remove = new ActionMenuItem(LangUtil.translate("misc.remove"), () -> { YesNoWindow.prompt(LangUtil.translate("misc.confirm.message"), () -> { byte[] updated = ClassUtil.removeField(reader, node.name, node.desc); getResource().getClasses().put(reader.getClassName(), updated); getClassView().updateView(); }, null).show(classView); }); menu.getItems().add(rename); menu.getItems().add(remove); } else { MenuItem jump = new ActionMenuItem(LangUtil.translate("ui.edit.method.goto"), () -> { ClassViewport view = controller.windows().getMainWindow().openClass(resource, owner); Platform.runLater(() -> view.selectMember(name, desc)); }); menu.getItems().add(jump); } // Allow searching for references to this member MenuItem search = new ActionMenuItem(LangUtil.translate("ui.edit.search"), () -> { SearchPane sp = controller.windows().getMainWindow().getMenubar().searchMemberReference(); sp.setInput("ui.search.mem_reference.owner", owner); sp.setInput("ui.search.mem_reference.name", name); sp.setInput("ui.search.mem_reference.desc", desc); sp.setInput("ui.search.matchmode", StringMatchMode.EQUALS); sp.search(); }); menu.getItems().add(search); } // Add other edit options if(declaration && resource.isPrimary()) { MenuItem edit = new ActionMenuItem(LangUtil.translate("ui.edit.method.editasm"), () -> { BytecodeViewport view = new BytecodeViewport(controller, classView, resource, owner, name, desc); view.updateView(); controller.windows().window(name, view, 500, 100).show(); }); menu.getItems().add(edit); // TODO: // - Remove // - Duplicate } // Inject plugin menus plugins.ofType(ContextMenuInjector.class).forEach(injector -> injector.forField(this, menu, owner, name, desc)); return menu; } /** * @param owner * Declaring class name. * @param name * Method name. * @param desc * Method descriptor. * * @return Context menu for methods. */ public ContextMenu ofMethod(String owner, String name, String desc) { if(!setupClass(owner)) return null; // Fetch method MethodNode node = ClassUtil.getMethod(reader, SKIP, name, desc); if(node == null) return null; int access = node.access; // Create header MenuItem header = new MenuItem(name); header.getStyleClass().add("context-menu-header"); header.setGraphic(UiUtil.createMethodGraphic(access)); header.setDisable(true); ContextMenu menu = new ContextMenu(); menu.getItems().add(header); // Add options for methods we have knowledge of if(hasClass(controller, owner)) { if (declaration) { MenuItem rename = new ActionMenuItem(LangUtil.translate("ui.edit.method.rename"), () -> { Window main = controller.windows().getMainWindow().getStage(); RenamingTextField popup = RenamingTextField.forMember(controller, owner, name, desc); popup.show(main); }); MenuItem remove = new ActionMenuItem(LangUtil.translate("misc.remove"), () -> { YesNoWindow.prompt(LangUtil.translate("misc.confirm.message"), () -> { byte[] updated = ClassUtil.removeMethod(reader, node.name, node.desc); getResource().getClasses().put(reader.getClassName(), updated); getClassView().updateView(); }, null).show(classView);; }); menu.getItems().add(rename); menu.getItems().add(remove); } else { MenuItem jump = new ActionMenuItem(LangUtil.translate("ui.edit.method.goto"), () -> { ClassViewport view = controller.windows().getMainWindow().openClass(resource, owner); new Thread(() -> view.selectMember(name, desc)).start(); }); menu.getItems().add(jump); } // Allow searching for references to this member MenuItem search = new ActionMenuItem(LangUtil.translate("ui.edit.search"), () -> { SearchPane sp = controller.windows().getMainWindow().getMenubar().searchMemberReference(); sp.setInput("ui.search.mem_reference.owner", owner); sp.setInput("ui.search.mem_reference.name", name); sp.setInput("ui.search.mem_reference.desc", desc); sp.setInput("ui.search.matchmode", StringMatchMode.EQUALS); sp.search(); }); menu.getItems().add(search); } // Add edit options if(declaration && resource.isPrimary()) { MenuItem edit = new ActionMenuItem(LangUtil.translate("ui.edit.method.editasm"), () -> { BytecodeViewport view = new BytecodeViewport(controller, classView, resource, owner, name, desc); view.updateView(); controller.windows().window(name + desc, view, 600, 600).show(); }); menu.getItems().add(edit); // TODO: // - Remove // - Duplicate } // Inject plugin menus plugins.ofType(ContextMenuInjector.class) .forEach(injector -> injector.forMethod(this, menu, owner, name, desc)); return menu; } /** * @param name * Package name. * * @return Context menu for packages. */ public ContextMenu ofPackage(String name) { MenuItem header = new MenuItem(shorten(name)); header.getStyleClass().add("context-menu-header"); header.setGraphic(UiUtil.createFileGraphic(name.replace('/', '.'))); header.setDisable(true); ContextMenu menu = new ContextMenu(); menu.getItems().add(header); String packagePrefix = name + '/'; // Add workspace-navigator specific items, but only for primary files if(isWorkspaceTree() && controller.getWorkspace().getPrimaryClassNames().stream() .anyMatch(cls -> cls.startsWith(packagePrefix))) { MenuItem rename = new ActionMenuItem(LangUtil.translate("ui.edit.method.rename"), () -> { Window main = controller.windows().getMainWindow().getStage(); RenamingTextField popup = RenamingTextField.forPackage(controller, name); popup.show(main); }); MenuItem remove = new ActionMenuItem(LangUtil.translate("misc.remove"), () -> { Map<String, byte[]> classes = controller.getWorkspace().getPrimary().getClasses(); ViewportTabs tabs = controller.windows().getMainWindow().getTabs(); YesNoWindow.prompt(LangUtil.translate("misc.confirm.message"), () -> { new HashSet<>(classes.keySet()).forEach(cls -> { if (cls.startsWith(packagePrefix)) { classes.remove(cls); tabs.closeTab(cls); } }); }, null).show(treeView); }); menu.getItems().add(rename); menu.getItems().add(remove); } // Inject plugin menus plugins.ofType(ContextMenuInjector.class).forEach(injector -> injector.forPackage(this, menu, name)); return menu; } /** * @param name * File name. * * @return Context menu for files. */ public ContextMenu ofFile(String name) { // Setup resource resource = controller.getWorkspace().getContainingResourceForClass(name); // Create the menu MenuItem header = new MenuItem(shorten(name)); header.getStyleClass().add("context-menu-header"); header.setGraphic(UiUtil.createFileGraphic(name)); header.setDisable(true); ContextMenu menu = new ContextMenu(); menu.getItems().add(header); // Add workspace-navigator specific items, but only for primary files if (isWorkspaceTree() && controller.getWorkspace().getPrimary().getFiles().containsKey(name)) { MenuItem remove = new ActionMenuItem(LangUtil.translate("misc.remove"), () -> { YesNoWindow.prompt(LangUtil.translate("misc.confirm.message"), () -> { controller.getWorkspace().getPrimary().getFiles().remove(name); controller.windows().getMainWindow().getTabs().closeTab(name); }, null).show(treeView); }); menu.getItems().add(remove); } // Inject plugin menus plugins.ofType(ContextMenuInjector.class).forEach(injector -> injector.forFile(this, menu, name)); return menu; } /** * @param resource * Root resource. * * @return Context menu for resource roots. */ public ContextMenu ofRoot(JavaResource resource) { this.resource = resource; String name = resource.toString(); MenuItem header = new MenuItem(shorten(name)); header.getStyleClass().add("context-menu-header"); header.setGraphic(new IconView(UiUtil.getResourceIcon(resource))); header.setDisable(true); ContextMenu menu = new ContextMenu(); menu.getItems().add(header); // Add workspace-navigator specific items, but only for primary files if(isWorkspaceTree()) { FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter(translate("ui.fileprompt.open.extensions"), "*.jar", "*.zip", "*.tar", "*.tar.gz"); FileChooser loader = new FileChooser(); loader.setTitle(translate("ui.filepropt.open")); loader.getExtensionFilters().add(filter); loader.setSelectedExtensionFilter(filter); loader.setInitialDirectory(controller.config().backend().getRecentLoadDir()); MenuItem addDoc = new ActionMenuItem(LangUtil.translate("ui.load.adddocs"), () -> { File file = loader.showOpenDialog(null); if (file != null) { try { resource.setClassDocs(file); } catch(IOException ex) { Log.error(ex, "Failed to set resource documentation"); } } }); MenuItem addSrc = new ActionMenuItem(LangUtil.translate("ui.load.addsrc"), () -> { File file = loader.showOpenDialog(null); if (file != null) { try { resource.setClassSources(file); } catch(IOException ex) { Log.error(ex, "Failed to set resource sources"); } } }); menu.getItems().add(addDoc); menu.getItems().add(addSrc); } // Inject plugin menus plugins.ofType(ContextMenuInjector.class).forEach(injector -> injector.forResourceRoot(this, menu, resource)); return menu; } /** * @return Context menu for tabs of {@link ClassViewport ClassViewports}. */ public ContextMenu ofClassTab() { // No header necessary Menu menuDecompile = new Menu(LangUtil.translate("decompile.decompiler.name")); for (DecompileImpl impl : DecompileImpl.values()) menuDecompile.getItems().add(new ActionMenuItem(impl.toString(), () -> classView.setOverrideDecompiler(impl))); Menu menuMode = new Menu(LangUtil.translate("display.classmode.name")); for (ClassViewport.ClassMode mode : ClassViewport.ClassMode.values()) menuMode.getItems().add(new ActionMenuItem(mode.toString(), () -> classView.setOverrideMode(mode))); // Create menu ContextMenu menu = new ContextMenu(); menu.getItems().add(menuDecompile); menu.getItems().add(menuMode); // Inject plugin menus plugins.ofType(ContextMenuInjector.class).forEach(injector -> injector.forClassTab(this, menu)); return menu; } /** * @return Context menu for tabs of {@link ClassViewport ClassViewports}. */ public ContextMenu ofFileTab() { // No header necessary Menu menuMode = new Menu(LangUtil.translate("display.classmode.name")); for (FileViewport.FileMode mode : FileViewport.FileMode.values()) menuMode.getItems().add(new ActionMenuItem(mode.toString(), () -> fileView.setOverrideMode(mode))); // Create menu ContextMenu menu = new ContextMenu(); menu.getItems().add(menuMode); // Inject plugin menus plugins.ofType(ContextMenuInjector.class).forEach(injector -> injector.forFileTab(this, menu)); return menu; } private static String shorten(String name) { return name.contains("/") ? name.substring(name.lastIndexOf("/") + 1) : name; } private static boolean hasClass(GuiController controller, String name) { return controller.getWorkspace().hasClass(name); } }
package me.mgerdes.raytracer.World; import me.mgerdes.raytracer.Color.RGBColor; import me.mgerdes.raytracer.GeometricObjects.GeometricObject; import me.mgerdes.raytracer.GeometricObjects.Sphere; import me.mgerdes.raytracer.Light.Light; import me.mgerdes.raytracer.Light.PointLight; import me.mgerdes.raytracer.Material.Material; import me.mgerdes.raytracer.Material.Reflective; import me.mgerdes.raytracer.Maths.Point; import me.mgerdes.raytracer.Maths.Ray; import me.mgerdes.raytracer.Maths.Vector; import me.mgerdes.raytracer.Tracers.Tracer; import me.mgerdes.raytracer.Tracers.WhittedTracer; import me.mgerdes.raytracer.Utilities.HitInfo; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; public class World { private List<GeometricObject> objects; private List<Light> lights; private RGBColor backgroundColor; private RGBColor[][] imageColors; private Tracer tracer; public World() { objects = new ArrayList<>(); lights = new ArrayList<>(); backgroundColor = new RGBColor(0, 0, 0); tracer = new WhittedTracer(this, 20); } public List<GeometricObject> getObjects() { return objects; } public List<Light> getLights() { return lights; } public RGBColor getBackgroundColor() { return backgroundColor; } public Tracer getTracer() { return tracer; } public void buildScene() { double scale = 300; double length = 1.6329932 * scale; Point[] vertices = { new Point( 0.000 * scale, 0.000 * scale,-1.000 * scale), new Point( 0.943 * scale, 0.000 * scale,-0.333 * scale), new Point(-0.471 * scale, 0.816 * scale,-0.333 * scale), new Point(-0.471 * scale,-0.816 * scale,-0.333 * scale) }; Material m1 = new Reflective(new RGBColor(Math.random()*250, Math.random()*250, Math.random()*250), 0.20, 0.60, 0.20, 5, 12); Sphere s1 = new Sphere(vertices[0], length / 2, m1); objects.add(s1); Material m2 = new Reflective(new RGBColor(Math.random()*250, Math.random()*250, Math.random()*250), 0.20, 0.60, 0.20, 5, 12); Sphere s2 = new Sphere(vertices[1], length / 2, m2); objects.add(s2); Material m3 = new Reflective(new RGBColor(Math.random()*250, Math.random()*250, Math.random()*250), 0.20, 0.60, 0.20, 5, 12); Sphere s3 = new Sphere(vertices[2], length / 2, m3); objects.add(s3); Material m4 = new Reflective(new RGBColor(Math.random()*250, Math.random()*250, Math.random()*250), 0.20, 0.60, 0.20, 5, 12); Sphere s4 = new Sphere(vertices[3], length / 2, m4); objects.add(s4); PointLight pointLight = new PointLight(new Point(100, 100, 1000)); lights.add(pointLight); } public void renderScene() throws FileNotFoundException, UnsupportedEncodingException { double z = 1000.0; int width = 1000; int height = 1000; double maxRed = 0; double maxGreen = 0; double maxBlue = 0; double s = 0.25; imageColors = new RGBColor[width][height]; double lastPercent = 0; for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { double percentDone = (row * col) / ((double) (width * height)); if (percentDone > lastPercent) { System.out.println(percentDone); lastPercent = percentDone + 0.001; } double x = s * (col - 0.5 * (width - 1.0)); double y = s * (row - 0.5 * (height - 1.0)); Ray r = new Ray(new Vector(x, y, -z).hat(), new Point(0, 0, z)); imageColors[col][row] = tracer.traceRay(r, 0); maxRed = Math.max(maxRed, imageColors[col][row].r); maxGreen = Math.max(maxGreen, imageColors[col][row].g); maxBlue = Math.max(maxBlue, imageColors[col][row].b); } } PrintWriter writer = new PrintWriter("image.ppm", "UTF-8"); writer.printf("P3\n"); writer.printf("%d %d\n", width, height); writer.printf("255\n"); double redScale = 256 / maxRed; double greenScale = 256 / maxGreen; double blueScale = 256 / maxBlue; for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { RGBColor color = imageColors[col][row]; writer.printf("%d %d %d ", (int) (color.r * redScale), (int) (color.g * greenScale), (int) (color.b * blueScale)); } writer.printf("\n"); } } public HitInfo hitObjects(Ray r) { HitInfo minHit = new HitInfo(false); minHit.setTime(Double.MAX_VALUE); for (GeometricObject g : objects) { HitInfo h = g.hit(r); if (h.isHit() && h.getTime() < minHit.getTime()) { h.setWorld(this); minHit = h; } } return minHit; } }
package mil.dds.anet.utils; import com.codahale.metrics.MetricRegistry; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import mil.dds.anet.AnetObjectEngine; import mil.dds.anet.beans.ApprovalStep; import mil.dds.anet.beans.AuthorizationGroup; import mil.dds.anet.beans.Comment; import mil.dds.anet.beans.Location; import mil.dds.anet.beans.Note; import mil.dds.anet.beans.NoteRelatedObject; import mil.dds.anet.beans.Organization; import mil.dds.anet.beans.Person; import mil.dds.anet.beans.PersonPositionHistory; import mil.dds.anet.beans.Position; import mil.dds.anet.beans.Report; import mil.dds.anet.beans.ReportAction; import mil.dds.anet.beans.ReportPerson; import mil.dds.anet.beans.ReportSensitiveInformation; import mil.dds.anet.beans.Tag; import mil.dds.anet.beans.Task; import org.dataloader.BatchLoader; import org.dataloader.DataLoader; import org.dataloader.DataLoaderOptions; import org.dataloader.DataLoaderRegistry; import org.dataloader.stats.SimpleStatisticsCollector; import org.dataloader.stats.Statistics; public final class BatchingUtils { private BatchingUtils() {} public static DataLoaderRegistry registerDataLoaders(AnetObjectEngine engine, boolean batchingEnabled, boolean cachingEnabled) { final DataLoaderOptions dataLoaderOptions = DataLoaderOptions.newOptions() .setStatisticsCollector(() -> new SimpleStatisticsCollector()) .setBatchingEnabled(batchingEnabled).setCachingEnabled(cachingEnabled) .setMaxBatchSize(1000); final DataLoaderRegistry dataLoaderRegistry = new DataLoaderRegistry(); // Give each registry its own thread pool final ExecutorService dispatcherService = Executors.newFixedThreadPool(3); dataLoaderRegistry.register("approvalSteps", new DataLoader<>(new BatchLoader<String, ApprovalStep>() { @Override public CompletionStage<List<ApprovalStep>> load(List<String> keys) { return CompletableFuture.supplyAsync(() -> engine.getApprovalStepDao().getByIds(keys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("approvalStep.approvers", new DataLoader<>(new BatchLoader<String, List<Position>>() { @Override public CompletionStage<List<List<Position>>> load(List<String> foreignKeys) { return CompletableFuture.supplyAsync( () -> engine.getApprovalStepDao().getApprovers(foreignKeys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("authorizationGroups", new DataLoader<>(new BatchLoader<String, AuthorizationGroup>() { @Override public CompletionStage<List<AuthorizationGroup>> load(List<String> keys) { return CompletableFuture.supplyAsync( () -> engine.getAuthorizationGroupDao().getByIds(keys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("authorizationGroup.positions", new DataLoader<>(new BatchLoader<String, List<Position>>() { @Override public CompletionStage<List<List<Position>>> load(List<String> foreignKeys) { return CompletableFuture.supplyAsync( () -> engine.getAuthorizationGroupDao().getPositions(foreignKeys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("comments", new DataLoader<>(new BatchLoader<String, Comment>() { @Override public CompletionStage<List<Comment>> load(List<String> keys) { return CompletableFuture.supplyAsync(() -> engine.getCommentDao().getByIds(keys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("locations", new DataLoader<>(new BatchLoader<String, Location>() { @Override public CompletionStage<List<Location>> load(List<String> keys) { return CompletableFuture.supplyAsync(() -> engine.getLocationDao().getByIds(keys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("note.noteRelatedObjects", new DataLoader<>(new BatchLoader<String, List<NoteRelatedObject>>() { @Override public CompletionStage<List<List<NoteRelatedObject>>> load(List<String> foreignKeys) { return CompletableFuture.supplyAsync( () -> engine.getNoteDao().getNoteRelatedObjects(foreignKeys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("noteRelatedObject.notes", new DataLoader<>(new BatchLoader<String, List<Note>>() { @Override public CompletionStage<List<List<Note>>> load(List<String> foreignKeys) { return CompletableFuture.supplyAsync(() -> engine.getNoteDao().getNotes(foreignKeys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("organizations", new DataLoader<>(new BatchLoader<String, Organization>() { @Override public CompletionStage<List<Organization>> load(List<String> keys) { return CompletableFuture.supplyAsync(() -> engine.getOrganizationDao().getByIds(keys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("organization.approvalSteps", new DataLoader<>(new BatchLoader<String, List<ApprovalStep>>() { @Override public CompletionStage<List<List<ApprovalStep>>> load(List<String> foreignKeys) { return CompletableFuture.supplyAsync( () -> engine.getApprovalStepDao().getApprovalSteps(foreignKeys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("people", new DataLoader<>(new BatchLoader<String, Person>() { @Override public CompletionStage<List<Person>> load(List<String> keys) { return CompletableFuture.supplyAsync(() -> engine.getPersonDao().getByIds(keys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("person.organizations", new DataLoader<>(new BatchLoader<String, List<Organization>>() { @Override public CompletionStage<List<List<Organization>>> load(List<String> foreignKeys) { return CompletableFuture.supplyAsync( () -> engine.getOrganizationDao().getOrganizations(foreignKeys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("person.personPositionHistory", new DataLoader<>(new BatchLoader<String, List<PersonPositionHistory>>() { @Override public CompletionStage<List<List<PersonPositionHistory>>> load(List<String> foreignKeys) { return CompletableFuture.supplyAsync( () -> engine.getPersonDao().getPersonPositionHistory(foreignKeys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("positions", new DataLoader<>(new BatchLoader<String, Position>() { @Override public CompletionStage<List<Position>> load(List<String> keys) { return CompletableFuture.supplyAsync(() -> engine.getPositionDao().getByIds(keys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("position.currentPositionForPerson", new DataLoader<>(new BatchLoader<String, List<Position>>() { @Override public CompletionStage<List<List<Position>>> load(List<String> foreignKeys) { return CompletableFuture.supplyAsync( () -> engine.getPositionDao().getCurrentPersonForPosition(foreignKeys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("position.personPositionHistory", new DataLoader<>(new BatchLoader<String, List<PersonPositionHistory>>() { @Override public CompletionStage<List<List<PersonPositionHistory>>> load(List<String> foreignKeys) { return CompletableFuture.supplyAsync( () -> engine.getPositionDao().getPersonPositionHistory(foreignKeys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("reports", new DataLoader<>(new BatchLoader<String, Report>() { @Override public CompletionStage<List<Report>> load(List<String> keys) { return CompletableFuture.supplyAsync(() -> engine.getReportDao().getByIds(keys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("report.reportActions", new DataLoader<>(new BatchLoader<String, List<ReportAction>>() { @Override public CompletionStage<List<List<ReportAction>>> load(List<String> foreignKeys) { return CompletableFuture.supplyAsync( () -> engine.getReportActionDao().getReportActions(foreignKeys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("report.attendees", new DataLoader<>(new BatchLoader<String, List<ReportPerson>>() { @Override public CompletionStage<List<List<ReportPerson>>> load(List<String> foreignKeys) { return CompletableFuture.supplyAsync( () -> engine.getReportDao().getAttendees(foreignKeys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("report.reportSensitiveInformation", new DataLoader<>(new BatchLoader<String, List<ReportSensitiveInformation>>() { @Override public CompletionStage<List<List<ReportSensitiveInformation>>> load( List<String> foreignKeys) { return CompletableFuture.supplyAsync(() -> engine.getReportSensitiveInformationDao() .getReportSensitiveInformation(foreignKeys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("report.tags", new DataLoader<>(new BatchLoader<String, List<Tag>>() { @Override public CompletionStage<List<List<Tag>>> load(List<String> foreignKeys) { return CompletableFuture.supplyAsync(() -> engine.getReportDao().getTags(foreignKeys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("report.tasks", new DataLoader<>(new BatchLoader<String, List<Task>>() { @Override public CompletionStage<List<List<Task>>> load(List<String> foreignKeys) { return CompletableFuture.supplyAsync(() -> engine.getReportDao().getTasks(foreignKeys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("tags", new DataLoader<>(new BatchLoader<String, Tag>() { @Override public CompletionStage<List<Tag>> load(List<String> keys) { return CompletableFuture.supplyAsync(() -> engine.getTagDao().getByIds(keys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("tasks", new DataLoader<>(new BatchLoader<String, Task>() { @Override public CompletionStage<List<Task>> load(List<String> keys) { return CompletableFuture.supplyAsync(() -> engine.getTaskDao().getByIds(keys), dispatcherService); } }, dataLoaderOptions)); dataLoaderRegistry.register("task.responsiblePositions", new DataLoader<>(new BatchLoader<String, List<Position>>() { @Override public CompletionStage<List<List<Position>>> load(List<String> foreignKeys) { return CompletableFuture.supplyAsync( () -> engine.getTaskDao().getResponsiblePositions(foreignKeys), dispatcherService); } }, dataLoaderOptions)); return dataLoaderRegistry; } public static void updateStats(MetricRegistry metricRegistry, DataLoaderRegistry dataLoaderRegistry) { // Combined stats for all data loaders updateStats(metricRegistry, "DataLoaderRegistry", dataLoaderRegistry.getStatistics()); for (final String key : dataLoaderRegistry.getKeys()) { // Individual stats per data loader updateStats(metricRegistry, key, dataLoaderRegistry.getDataLoader(key).getStatistics()); } } private static void updateStats(MetricRegistry metricRegistry, String name, Statistics statistics) { metricRegistry.counter(MetricRegistry.name(name, "BatchInvokeCount")) .inc(statistics.getBatchInvokeCount()); metricRegistry.counter(MetricRegistry.name(name, "BatchLoadCount")) .inc(statistics.getBatchLoadCount()); metricRegistry.counter(MetricRegistry.name(name, "BatchLoadExceptionCount")) .inc(statistics.getBatchLoadExceptionCount()); metricRegistry.counter(MetricRegistry.name(name, "CacheHitCount")) .inc(statistics.getCacheHitCount()); metricRegistry.counter(MetricRegistry.name(name, "CacheMissCount")) .inc(statistics.getCacheMissCount()); metricRegistry.counter(MetricRegistry.name(name, "LoadCount")).inc(statistics.getLoadCount()); metricRegistry.counter(MetricRegistry.name(name, "LoadErrorCount")) .inc(statistics.getLoadErrorCount()); } }
package mx.nic.rdap.db.model; import java.io.IOException; import java.net.IDN; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import mx.nic.rdap.IpUtils; import mx.nic.rdap.core.db.Domain; import mx.nic.rdap.core.db.Entity; import mx.nic.rdap.core.db.IpNetwork; import mx.nic.rdap.core.db.Nameserver; import mx.nic.rdap.db.QueryGroup; import mx.nic.rdap.db.Util; import mx.nic.rdap.db.exception.InvalidValueException; import mx.nic.rdap.db.exception.ObjectNotFoundException; import mx.nic.rdap.db.exception.RequiredValueNotFoundException; import mx.nic.rdap.db.objects.DomainDAO; import mx.nic.rdap.db.objects.IpAddressDAO; import mx.nic.rdap.db.struct.SearchResultStruct; /** * Model for the {@link Domain} Object * */ public class DomainModel { private final static Logger logger = Logger.getLogger(DomainModel.class.getName()); private final static String QUERY_GROUP = "Domain"; private static QueryGroup queryGroup = null; private static final String STORE_QUERY = "storeToDatabase"; private static final String STORE_IP_NETWORK_RELATION_QUERY = "storeDomainIpNetworkRelation"; private static final String GET_BY_LDH_QUERY = "getByLdhName"; private static final String EXIST_BY_LDH_QUERY = "existByLdhName"; private static final String GET_BY_ID_QUERY = "getDomainById"; private static final String GET_BY_HANDLE_QUERY = "getByHandle"; private static final String SEARCH_BY_PARTIAL_NAME_WITH_PARTIAL_ZONE_QUERY = "searchByPartialNameWPartialZone"; private static final String SEARCH_BY_NAME_WITH_PARTIAL_ZONE_QUERY = "searchByNameWPartialZone"; private static final String SEARCH_BY_PARTIAL_NAME_WITH_ZONE_QUERY = "searchByPartialNameWZone"; private static final String SEARCH_BY_NAME_WITH_ZONE_QUERY = "searchByNameWZone"; private static final String SEARCH_BY_PARTIAL_NAME_WITHOUT_ZONE_QUERY = "searchByPartialNameWOutZone"; private static final String SEARCH_BY_NAME_WITHOUT_ZONE_QUERY = "searchByNameWOutZone"; private static final String SEARCH_BY_NAMESERVER_LDH_QUERY = "searchByNsLdhName"; private static final String SEARCH_BY_NAMESERVER_IP_QUERY = "searchByNsIp"; private static final String EXIST_BY_PARTIAL_NAME_WITHOUT_ZONE_QUERY = "existByPartialNameWOutZone"; private static final String EXIST_BY_NAME_WITHOUT_ZONE_QUERY = "existByNameWOutZone"; private static final String EXIST_BY_NAME_WITH_ZONE_QUERY = "existByNameWZone"; private static final String EXIST_BY_PARTIAL_NAME_WITH_ZONE_QUERY = "existByPartialNameWZone"; private static final String EXIST_BY_NAME_WITH_PARTIAL_ZONE_QUERY = "existByNameWPartialZone"; private static final String EXIST_BY_PARTIAL_NAME_WITH_PARTIAL_ZONE_QUERY = "existByPartialNameWPartialZone"; private static final String SEARCH_BY_REGEX_NAME_WITH_ZONE = "searchByRegexNameWithZone"; private static final String SEARCH_BY_REGEX_NAME_WITHOUT_ZONE = "searchByRegexNameWithOutZone"; private static final String SEARCH_BY_REGEX_NAMESERVER_LDH_QUERY = "searchByRegexNsLdhName"; static { try { queryGroup = new QueryGroup(QUERY_GROUP); } catch (IOException e) { throw new RuntimeException("Error loading query group"); } } public static Long storeToDatabase(Domain domain, boolean useNameserverAsAttribute, Connection connection) throws SQLException, RequiredValueNotFoundException, ObjectNotFoundException { String query = queryGroup.getQuery(STORE_QUERY); Long domainId; isValidForStore((DomainDAO) domain); try (PreparedStatement statement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) { ((DomainDAO) domain).storeToDatabase(statement); logger.log(Level.INFO, "Executing QUERY: " + statement.toString()); statement.executeUpdate(); ResultSet resultSet = statement.getGeneratedKeys(); resultSet.next(); domainId = resultSet.getLong(1); domain.setId(domainId); } storeNestedObjects(domain, useNameserverAsAttribute, connection); return domainId; } public static void storeNestedObjects(Domain domain, boolean useNameserverAsAttribute, Connection connection) throws SQLException, RequiredValueNotFoundException, ObjectNotFoundException { Long domainId = domain.getId(); RemarkModel.storeDomainRemarksToDatabase(domain.getRemarks(), domainId, connection); EventModel.storeDomainEventsToDatabase(domain.getEvents(), domainId, connection); StatusModel.storeDomainStatusToDatabase(domain.getStatus(), domainId, connection); LinkModel.storeDomainLinksToDatabase(domain.getLinks(), domainId, connection); if (domain.getSecureDNS() != null) { domain.getSecureDNS().setDomainId(domainId); SecureDNSModel.storeToDatabase(domain.getSecureDNS(), connection); } PublicIdModel.storePublicIdByDomain(domain.getPublicIds(), domain.getId(), connection); VariantModel.storeAllToDatabase(domain.getVariants(), domain.getId(), connection); if (domain.getNameServers().size() > 0) { if (useNameserverAsAttribute) { NameserverModel.storeDomainNameserversAsAttributesToDatabase(domain.getNameServers(), domainId, connection); } else { storeDomainNameserversAsObjects(domain.getNameServers(), domainId, connection); } } storeDomainEntities(domain.getEntities(), domainId, connection); if (domain.getIpNetwork() != null) { storeDomainIpNetworkRelationToDatabase(domainId, domain.getIpNetwork().getId(), connection); } } private static void storeDomainNameserversAsObjects(List<Nameserver> nameservers, Long domainId, Connection connection) throws RequiredValueNotFoundException, SQLException, ObjectNotFoundException { if (nameservers.size() > 0) { validateDomainNameservers(nameservers, connection); NameserverModel.storeDomainNameserversToDatabase(nameservers, domainId, connection); } } private static void validateDomainNameservers(List<Nameserver> nameservers, Connection connection) throws RequiredValueNotFoundException, SQLException, ObjectNotFoundException { for (Nameserver ns : nameservers) { Long nsId = NameserverModel.getByHandle(ns.getHandle(), connection).getId(); if (nsId == null) { throw new NullPointerException( "Nameserver: " + ns.getHandle() + "was not inserted previously to the database."); } ns.setId(nsId); } } private static void storeDomainEntities(List<Entity> entities, Long domainId, Connection connection) throws SQLException { if (entities.size() > 0) { EntityModel.validateParentEntities(entities, connection); RolModel.storeDomainEntityRoles(entities, domainId, connection); } } private static void isValidForStore(DomainDAO domain) throws RequiredValueNotFoundException { if (domain.getHandle() == null || domain.getHandle().isEmpty()) throw new RequiredValueNotFoundException("handle", "Domain"); if (domain.getLdhName() == null || domain.getLdhName().isEmpty()) throw new RequiredValueNotFoundException("ldhName", "Domain"); } private static void storeDomainIpNetworkRelationToDatabase(Long domainId, Long ipNetworkId, Connection connection) throws SQLException { String query = queryGroup.getQuery(STORE_IP_NETWORK_RELATION_QUERY); try (PreparedStatement statement = connection.prepareStatement(query)) { statement.setLong(1, domainId); statement.setLong(2, ipNetworkId); logger.log(Level.INFO, "Excuting QUERY:" + statement.toString()); statement.executeUpdate(); } } public static DomainDAO findByLdhName(String name, Integer zoneId, boolean useNameserverAsDomainAttribute, Connection connection) throws SQLException, ObjectNotFoundException { String query = queryGroup.getQuery(GET_BY_LDH_QUERY); try (PreparedStatement statement = connection.prepareStatement(query)) { statement.setString(1, IDN.toASCII(name)); statement.setString(2, IDN.toUnicode(name)); statement.setInt(3, zoneId); logger.log(Level.INFO, "Executing QUERY: " + statement.toString()); try (ResultSet resultSet = statement.executeQuery()) { if (!resultSet.next()) { throw new ObjectNotFoundException("Object not found."); } DomainDAO domain = new DomainDAO(resultSet); loadNestedObjects(domain, useNameserverAsDomainAttribute, connection); return domain; } } } public static void existByLdhName(String name, Integer zoneId, Connection connection) throws SQLException, ObjectNotFoundException { String query = queryGroup.getQuery(EXIST_BY_LDH_QUERY); try (PreparedStatement statement = connection.prepareStatement(query)) { statement.setString(1, IDN.toASCII(name)); statement.setString(2, name); statement.setInt(3, zoneId); logger.log(Level.INFO, "Executing QUERY: " + statement.toString()); try (ResultSet resultSet = statement.executeQuery()) { resultSet.next(); if (resultSet.getInt(1) == 0) { throw new ObjectNotFoundException("Object not found."); } } } } public static Domain getDomainById(Long domainId, boolean useNameserverAsDomainAttribute, Connection connection) throws SQLException, ObjectNotFoundException { try (PreparedStatement statement = connection.prepareStatement(queryGroup.getQuery(GET_BY_ID_QUERY))) { statement.setLong(1, domainId); logger.log(Level.INFO, "Executing QUERY: " + statement.toString()); try (ResultSet resultSet = statement.executeQuery()) { if (!resultSet.next()) { throw new ObjectNotFoundException("Object not found."); } Domain domain = new DomainDAO(resultSet); loadNestedObjects(domain, useNameserverAsDomainAttribute, connection); return domain; } } } public static DomainDAO getByHandle(String handle, boolean useNameserverAsDomainAttribute, Connection connection) throws SQLException, ObjectNotFoundException { try (PreparedStatement statement = connection.prepareStatement(queryGroup.getQuery(GET_BY_HANDLE_QUERY))) { statement.setString(1, handle); logger.log(Level.INFO, "Executing QUERY: " + statement.toString()); try (ResultSet resultSet = statement.executeQuery()) { if (!resultSet.next()) { throw new ObjectNotFoundException("Object not found."); } DomainDAO domain = new DomainDAO(resultSet); loadNestedObjects(domain, useNameserverAsDomainAttribute, connection); return domain; } } } public static SearchResultStruct searchByName(String name, String zone, Integer resultLimit, boolean useNameserverAsDomainAttribute, Connection connection) throws SQLException, ObjectNotFoundException { SearchResultStruct result = new SearchResultStruct(); // Hack to know is there is more domains that the limit, used for // notices resultLimit = resultLimit + 1; boolean isPartialZone = zone.contains("*"); boolean isPartialName = name.contains("*"); String query = null; List<Integer> zoneIds = null; if (isPartialZone) { zoneIds = ZoneModel.getValidZoneIds(); zone = zone.replaceAll("\\*", "%"); if (isPartialName) { name = name.replaceAll("\\*", "%"); query = queryGroup.getQuery(SEARCH_BY_PARTIAL_NAME_WITH_PARTIAL_ZONE_QUERY); query = Util.createDynamicQueryWithInClause(zoneIds.size(), query); } else { query = queryGroup.getQuery(SEARCH_BY_NAME_WITH_PARTIAL_ZONE_QUERY); query = Util.createDynamicQueryWithInClause(zoneIds.size(), query); } } else { if (!ZoneModel.existsZone(zone)) { throw new ObjectNotFoundException("Zone not found."); } if (isPartialName) { name = name.replaceAll("\\*", "%"); query = queryGroup.getQuery(SEARCH_BY_PARTIAL_NAME_WITH_ZONE_QUERY); } else { query = queryGroup.getQuery(SEARCH_BY_NAME_WITH_ZONE_QUERY); } } try (PreparedStatement statement = connection.prepareStatement(query);) { if (isPartialZone) { for (int i = 1; i <= zoneIds.size(); i++) { statement.setInt(i, zoneIds.get(i - 1)); } statement.setString(zoneIds.size() + 1, name); statement.setString(zoneIds.size() + 2, name); statement.setString(zoneIds.size() + 3, zone); statement.setInt(zoneIds.size() + 4, resultLimit); } else { statement.setString(1, name); statement.setString(2, name); Integer zoneId = ZoneModel.getIdByZoneName(zone); statement.setInt(3, zoneId); statement.setInt(4, resultLimit); } logger.log(Level.INFO, "Executing query" + statement.toString()); ResultSet resultSet = statement.executeQuery(); if (!resultSet.next()) { throw new ObjectNotFoundException("Object not found."); } List<DomainDAO> domains = new ArrayList<DomainDAO>(); do { DomainDAO domain = new DomainDAO(resultSet); domains.add(domain); } while (resultSet.next()); resultLimit = resultLimit - 1;// Back to the original limit if (domains.size() > resultLimit) { result.setResultSetWasLimitedByUserConfiguration(true); domains.remove(domains.size() - 1); } for (DomainDAO domain : domains) { loadNestedObjects(domain, useNameserverAsDomainAttribute, connection); } result.setSearchResultsLimitForUser(resultLimit); result.getResults().addAll(domains); return result; } } public static SearchResultStruct searchByName(String domainName, Integer resultLimit, boolean useNameserverAsDomainAttribute, Connection connection) throws SQLException, ObjectNotFoundException { String query; if (domainName.contains("*")) { domainName = domainName.replaceAll("\\*", "%"); query = queryGroup.getQuery(SEARCH_BY_PARTIAL_NAME_WITHOUT_ZONE_QUERY); } else { query = queryGroup.getQuery(SEARCH_BY_NAME_WITHOUT_ZONE_QUERY); } return searchByName(domainName, resultLimit, useNameserverAsDomainAttribute, connection, query); } public static SearchResultStruct searchByRegexName(String regexName, Integer resultLimit, boolean useNameserverAsDomainAttribute, Connection connection) throws SQLException, ObjectNotFoundException { String query = queryGroup.getQuery(SEARCH_BY_REGEX_NAME_WITHOUT_ZONE); return searchByName(regexName, resultLimit, useNameserverAsDomainAttribute, connection, query); } public static SearchResultStruct searchByRegexName(String name, String zone, Integer resultLimit, boolean useNameserverAsDomainAttribute, Connection connection) throws SQLException, ObjectNotFoundException { SearchResultStruct result = new SearchResultStruct(); // Hack to know is there is more domains that the limit, used for // notices resultLimit = resultLimit + 1; String query = queryGroup.getQuery(SEARCH_BY_REGEX_NAME_WITH_ZONE); List<Integer> zoneIds = ZoneModel.getValidZoneIds(); query = Util.createDynamicQueryWithInClause(zoneIds.size(), query); try (PreparedStatement statement = connection.prepareStatement(query);) { for (int i = 1; i <= zoneIds.size(); i++) { statement.setInt(i, zoneIds.get(i - 1)); } statement.setString(zoneIds.size() + 1, name); statement.setString(zoneIds.size() + 2, name); statement.setString(zoneIds.size() + 3, zone); statement.setInt(zoneIds.size() + 4, resultLimit); logger.log(Level.INFO, "Executing query" + statement.toString()); ResultSet resultSet = statement.executeQuery(); if (!resultSet.next()) { throw new ObjectNotFoundException("Object not found."); } List<DomainDAO> domains = new ArrayList<DomainDAO>(); do { DomainDAO domain = new DomainDAO(resultSet); domains.add(domain); } while (resultSet.next()); resultLimit = resultLimit - 1;// Back to the original limit if (domains.size() > resultLimit) { result.setResultSetWasLimitedByUserConfiguration(true); domains.remove(domains.size() - 1); } for (DomainDAO domain : domains) { loadNestedObjects(domain, useNameserverAsDomainAttribute, connection); } result.setSearchResultsLimitForUser(resultLimit); result.getResults().addAll(domains); return result; } } private static SearchResultStruct searchByName(String domainName, Integer resultLimit, boolean useNameserverAsDomainAttribute, Connection connection, String query) throws SQLException, ObjectNotFoundException { SearchResultStruct result = new SearchResultStruct(); // Hack to know is there is more domains that the limit, used for // notices resultLimit = resultLimit + 1; List<Integer> zoneIds = ZoneModel.getValidZoneIds(); query = Util.createDynamicQueryWithInClause(zoneIds.size(), query); try (PreparedStatement statement = connection.prepareStatement(query);) { for (int i = 1; i <= zoneIds.size(); i++) { statement.setInt(i, zoneIds.get(i - 1)); } statement.setString(zoneIds.size() + 1, domainName); statement.setString(zoneIds.size() + 2, domainName); statement.setInt(zoneIds.size() + 3, resultLimit); logger.log(Level.INFO, "Executing query" + statement.toString()); ResultSet resultSet = statement.executeQuery(); if (!resultSet.next()) { throw new ObjectNotFoundException("Object not found."); } List<DomainDAO> domains = new ArrayList<DomainDAO>(); do { DomainDAO domain = new DomainDAO(resultSet); domains.add(domain); } while (resultSet.next()); resultLimit = resultLimit - 1;// Back to the original limit if (domains.size() > resultLimit) { result.setResultSetWasLimitedByUserConfiguration(true); domains.remove(domains.size() - 1); } for (DomainDAO domain : domains) { loadNestedObjects(domain, useNameserverAsDomainAttribute, connection); } result.setSearchResultsLimitForUser(resultLimit); result.getResults().addAll(domains); return result; } } public static SearchResultStruct searchByRegexNsLdhName(String name, Integer resultLimit, boolean useNameserverAsDomainAttribute, Connection connection) throws SQLException, ObjectNotFoundException { String query = queryGroup.getQuery(SEARCH_BY_REGEX_NAMESERVER_LDH_QUERY); return searchByNsLdhName(name, resultLimit, useNameserverAsDomainAttribute, connection, query); } public static SearchResultStruct searchByNsLdhName(String name, Integer resultLimit, boolean useNameserverAsDomainAttribute, Connection connection) throws SQLException, ObjectNotFoundException { String query = queryGroup.getQuery(SEARCH_BY_NAMESERVER_LDH_QUERY); name = name.replace("*", "%"); return searchByNsLdhName(name, resultLimit, useNameserverAsDomainAttribute, connection, query); } /** * Searches all domains with a nameserver by name * * @throws ObjectNotFoundException * */ private static SearchResultStruct searchByNsLdhName(String name, Integer resultLimit, boolean useNameserverAsDomainAttribute, Connection connection, String query) throws SQLException, ObjectNotFoundException { SearchResultStruct result = new SearchResultStruct(); // Hack to know is there is more domains that the limit, used for // notices resultLimit = resultLimit + 1; try (PreparedStatement statement = connection.prepareStatement(query)) { statement.setString(1, name); statement.setString(2, name); statement.setInt(3, resultLimit); logger.log(Level.INFO, "Executing query" + statement.toString()); ResultSet resultSet = statement.executeQuery(); if (!resultSet.next()) { throw new ObjectNotFoundException("Object not found."); } List<DomainDAO> domains = new ArrayList<DomainDAO>(); do { DomainDAO domain = new DomainDAO(resultSet); domains.add(domain); } while (resultSet.next()); resultLimit = resultLimit - 1;// Back to the original limit if (domains.size() > resultLimit) { result.setResultSetWasLimitedByUserConfiguration(true); domains.remove(domains.size() - 1); } for (DomainDAO domain : domains) { loadNestedObjects(domain, useNameserverAsDomainAttribute, connection); } result.setSearchResultsLimitForUser(resultLimit); result.getResults().addAll(domains); return result; } } /** * searches all domains with a nameserver by address * * @throws InvalidValueException * @throws ObjectNotFoundException * */ public static SearchResultStruct searchByNsIp(String ip, Integer resultLimit, boolean useNameserverAsDomainAttribute, Connection connection) throws SQLException, InvalidValueException, ObjectNotFoundException { SearchResultStruct result = new SearchResultStruct(); // Hack to know is there is more domains that the limit, used for // notices resultLimit = resultLimit + 1; IpAddressDAO ipAddress = new IpAddressDAO(); InetAddress address = IpUtils.validateIpAddress(ip); ipAddress.setAddress(address); if (ipAddress.getAddress() instanceof Inet4Address) { ipAddress.setType(4); } else if (ipAddress.getAddress() instanceof Inet6Address) { ipAddress.setType(6); } try (PreparedStatement statement = connection .prepareStatement(queryGroup.getQuery(SEARCH_BY_NAMESERVER_IP_QUERY))) { statement.setInt(1, ipAddress.getType()); statement.setString(2, ipAddress.getAddress().getHostAddress()); statement.setString(3, ipAddress.getAddress().getHostAddress()); statement.setInt(4, resultLimit); logger.log(Level.INFO, "Executing query" + statement.toString()); ResultSet resultSet = statement.executeQuery(); if (!resultSet.next()) { throw new ObjectNotFoundException("Object not found."); } List<DomainDAO> domains = new ArrayList<DomainDAO>(); do { DomainDAO domain = new DomainDAO(resultSet); loadNestedObjects(domain, useNameserverAsDomainAttribute, connection); domains.add(domain); } while (resultSet.next()); resultLimit = resultLimit - 1;// Back to the original limit if (domains.size() > resultLimit) { result.setResultSetWasLimitedByUserConfiguration(true); domains.remove(domains.size() - 1); } for (DomainDAO domain : domains) { loadNestedObjects(domain, useNameserverAsDomainAttribute, connection); } result.setSearchResultsLimitForUser(resultLimit); result.getResults().addAll(domains); return result; } } /** * Load the nested object of the domain * * @param useNameserverAsDomainAttribute * if false, load all the nameserver object * */ public static void loadNestedObjects(Domain domain, boolean useNameserverAsDomainAttribute, Connection connection) throws SQLException { Long domainId = domain.getId(); // Retrieve the events domain.getEvents().addAll(EventModel.getByDomainId(domainId, connection)); // Retrieve the links domain.getLinks().addAll(LinkModel.getByDomainId(domainId, connection)); // Retrieve the status domain.getStatus().addAll(StatusModel.getByDomainId(domainId, connection)); // Retrieve the remarks try { domain.getRemarks().addAll(RemarkModel.getByDomainId(domainId, connection)); } catch (ObjectNotFoundException onfe) { // Do nothing, remarks is not required } // Retrieve the public ids domain.setPublicIds(PublicIdModel.getByDomain(domainId, connection)); // Retrieve the secure dns try { domain.setSecureDNS(SecureDNSModel.getByDomain(domainId, connection)); } catch (ObjectNotFoundException onfe) { // Do nothing, secure dns is not required } // Retrieve the variants try { domain.setVariants(VariantModel.getByDomainId(domainId, connection)); } catch (ObjectNotFoundException onfe) { // Do nothing, variants is not required } // Retrieve the domainsNs domain.getNameServers() .addAll(NameserverModel.getByDomainId(domainId, useNameserverAsDomainAttribute, connection)); // Retrieve the entities domain.getEntities().addAll(EntityModel.getEntitiesByDomainId(domainId, connection)); // Retrieve the ipNetwork try { IpNetwork network = IpNetworkModel.getByDomainId(domainId, connection); domain.setIpNetwork(network); } catch (ObjectNotFoundException e) { // Do nothing, ipNetwork is not requiered } } /** * Validate if the zone of the request domain is managed by the server * */ public static void validateDomainZone(String domainName) throws ObjectNotFoundException { String domainZone; if (ZoneModel.isReverseAddress(domainName)) { domainZone = ZoneModel.getArpaZoneNameFromAddress(domainName); if (domainZone == null) { throw new ObjectNotFoundException("Zone not found."); } } else { int indexOf = domainName.indexOf('.'); if (indexOf <= 0) { throw new ObjectNotFoundException("Zone not found."); } domainZone = domainName.substring(indexOf + 1, domainName.length()); } if (!ZoneModel.existsZone(domainZone)) { throw new ObjectNotFoundException("Zone not found."); } } public static void existByName(String name, String zone, Connection connection) throws SQLException, ObjectNotFoundException { boolean isPartialZone = zone.contains("*"); boolean isPartialName = name.contains("*"); String query = null; List<Integer> zoneIds = null; if (isPartialZone) { zoneIds = ZoneModel.getValidZoneIds(); zone = zone.replaceAll("\\*", "%"); if (isPartialName) { name = name.replaceAll("\\*", "%"); query = queryGroup.getQuery(EXIST_BY_PARTIAL_NAME_WITH_PARTIAL_ZONE_QUERY); query = Util.createDynamicQueryWithInClause(zoneIds.size(), query); } else { query = queryGroup.getQuery(EXIST_BY_NAME_WITH_PARTIAL_ZONE_QUERY); query = Util.createDynamicQueryWithInClause(zoneIds.size(), query); } } else { if (!ZoneModel.existsZone(zone)) { throw new ObjectNotFoundException("Zone not found."); } if (isPartialName) { name = name.replaceAll("\\*", "%"); query = queryGroup.getQuery(EXIST_BY_PARTIAL_NAME_WITH_ZONE_QUERY); } else { query = queryGroup.getQuery(EXIST_BY_NAME_WITH_ZONE_QUERY); } } try (PreparedStatement statement = connection.prepareStatement(query);) { if (isPartialZone) { for (int i = 1; i <= zoneIds.size(); i++) { statement.setInt(i, zoneIds.get(i - 1)); } statement.setString(zoneIds.size() + 1, name); statement.setString(zoneIds.size() + 2, name); statement.setString(zoneIds.size() + 3, zone); } else { statement.setString(1, name); statement.setString(2, name); Integer zoneId = ZoneModel.getIdByZoneName(zone); statement.setInt(3, zoneId); } logger.log(Level.INFO, "Executing query" + statement.toString()); ResultSet resultSet = statement.executeQuery(); resultSet.next(); if (resultSet.getInt(1) == 0) { throw new ObjectNotFoundException("Object not found."); } } } public static void existByName(String domainName, Connection connection) throws SQLException, ObjectNotFoundException { String query = null; if (domainName.contains("*")) { domainName = domainName.replaceAll("\\*", "%"); query = queryGroup.getQuery(EXIST_BY_PARTIAL_NAME_WITHOUT_ZONE_QUERY); } else { query = queryGroup.getQuery(EXIST_BY_NAME_WITHOUT_ZONE_QUERY); } List<Integer> zoneIds = ZoneModel.getValidZoneIds(); query = Util.createDynamicQueryWithInClause(zoneIds.size(), query); try (PreparedStatement statement = connection.prepareStatement(query);) { for (int i = 1; i <= zoneIds.size(); i++) { statement.setInt(i, zoneIds.get(i - 1)); } statement.setString(zoneIds.size() + 1, domainName); statement.setString(zoneIds.size() + 2, domainName); logger.log(Level.INFO, "Executing query" + statement.toString()); ResultSet resultSet = statement.executeQuery(); resultSet.next(); if (resultSet.getInt(1) == 0) { { throw new ObjectNotFoundException("Object not found."); } } } } }
package net.bootsfaces.render; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.faces.FacesException; import javax.faces.component.UIComponent; import javax.faces.component.UIForm; import net.bootsfaces.component.ajax.AJAXRenderer; import net.bootsfaces.component.form.Form; public class Responsive { private static String[] delimiters = new String[] {",", "..." }; private static String[] validValues = new String[] { "xs", "sm", "md", "lg", "tiny-screen", "small-screen", "medium-screen", "large-screen" }; public enum Sizes { xs, sm, md, lg } /** * Create the responsive class combination * @param r * @return */ public static String getResponsiveStyleClass(IResponsive r) { return getResponsiveStyleClass(r, true); } public static String getResponsiveStyleClass(IResponsive r, boolean forceColMd) { if(!shouldRenderResponsiveClasses(r)) { return ""; } int colxs = sizeToInt(getSize(r, Sizes.xs)); int colsm = sizeToInt(getSize(r, Sizes.sm)); int collg = sizeToInt(getSize(r, Sizes.lg)); int span = sizeToInt(r.getSpan()); int colmd = (span > 0) ? span : sizeToInt(getSize(r, Sizes.md)); if (colmd < 0) { if ((colxs > 0) || (colsm > 0) || (collg > 0)) { colmd = (colmd > 0) ? colmd : -1; } else { colmd = (colmd > 0) ? colmd : (forceColMd ? 12 : -1); } } int offs = sizeToInt(r.getOffset()); int offsmd = (offs > 0) ? offs : sizeToInt(r.getOffsetMd()); int oxs = sizeToInt(r.getOffsetXs()); int osm = sizeToInt(r.getOffsetSm()); int olg = sizeToInt(r.getOffsetLg()); StringBuilder sb = new StringBuilder(); if (colmd > 0 || offsmd > 0) { if (colmd > 0) { sb.append("col-md-").append(colmd); } if (offsmd > 0) { if (colmd > 0) { sb.append(" "); } sb.append("col-md-offset-" + offsmd); } } else if (colmd == 0) { if (forceColMd) { sb.append("col-md-12"); sb.append(" hidden-md"); } } if (colxs > 0) { sb.append(" col-xs-").append(colxs); } if (colxs == 0) { sb.append(" hidden-xs"); } if (colsm > 0) { sb.append(" col-sm-").append(colsm); } if (colsm == 0) { sb.append(" hidden-sm"); } if (collg > 0) { sb.append(" col-lg-").append(collg); } if (collg == 0) { sb.append(" hidden-lg"); } sb.append(encodeVisibility(r, r.getVisible(), "visible")); sb.append(encodeVisibility(r, r.getHidden(), "hidden")); if (oxs > 0) { sb.append(" col-xs-offset-").append(oxs); } if (osm > 0) { sb.append(" col-sm-offset-").append(osm); } if (olg > 0) { sb.append(" col-lg-offset-").append(olg); } return " " + sb.toString().trim() + " "; } /** * Encode the visible field * @param r * @return */ private static String encodeVisibility(IResponsive r, String value, String prefix) { if(value == null) return ""; if ("true".equals(value) || "false".equals(value)) { throw new FacesException("The attributes 'visible' and 'hidden' don't accept boolean values. If you want to show or hide the element conditionally, use the attribute 'rendered' instead."); } List<String> str = wonderfulTokenizer(value, delimiters); return evaluateExpression(str, delimiters, validValues, prefix, r.getDisplay()); } /** * Decode col sizes between two way of definition * @param col * @param size * @return */ private static String getSize(IResponsiveLabel r, Sizes size) { String colSize = "-1"; switch(size) { case xs: colSize = r.getLabelColXs(); if(colSize.equals("-1")) colSize = r.getLabelTinyScreen(); break; case sm: colSize = r.getLabelColSm(); if(colSize.equals("-1")) colSize = r.getLabelSmallScreen(); break; case md: colSize = r.getLabelColMd(); if(colSize.equals("-1")) colSize = r.getLabelMediumScreen(); break; case lg: colSize = r.getLabelColLg(); if(colSize.equals("-1")) colSize = r.getLabelLargeScreen(); break; } return colSize; } private static String getSize(IResponsive r, Sizes size) { String colSize = "-1"; switch(size) { case xs: colSize = r.getColXs(); if(colSize.equals("-1")) colSize = r.getTinyScreen(); break; case sm: colSize = r.getColSm(); if(colSize.equals("-1")) colSize = r.getSmallScreen(); break; case md: colSize = r.getColMd(); if(colSize.equals("-1")) colSize = r.getMediumScreen(); break; case lg: colSize = r.getColLg(); if(colSize.equals("-1")) colSize = r.getLargeScreen(); break; } return colSize; } /** * Convert the specified size to int value * @param size * @return */ private static int sizeToInt(String size) { if (size==null) return -1; if ("full".equals(size)) return 12; if ("full-size".equals(size)) return 12; if ("fullSize".equals(size)) return 12; if ("full-width".equals(size)) return 12; if ("fullWidth".equals(size)) return 12; if ("half".equals(size)) return 6; if ("one-third".equals(size)) return 4; if ("oneThird".equals(size)) return 4; if ("two-thirds".equals(size)) return 8; if ("twoThirds".equals(size)) return 8; if ("one-fourth".equals(size)) return 3; if ("oneFourth".equals(size)) return 3; if ("three-fourths".equals(size)) return 9; if ("threeFourths".equals(size)) return 9; if (size.length()>2) { size=size.replace("columns", ""); size=size.replace("column", ""); size=size.trim(); } return new Integer(size).intValue(); } /** * Parse the expression token * * @param expressionToken * @param delimiters * @param validValues * @param visibilityLevel (visible or hidden) * @param display (block, inline or inline-block. default block) * @return */ public static String evaluateExpression( List<String> expressionToken, String[] delimiters, String[] validValues, String visibilityLevel, String display) { if ("visible".equals(visibilityLevel)) { display = (display == null || display.trim().isEmpty()) ? "" : "-" + display; } else { // hidden is not suffixed by -block, -inline or -inline-block display=""; } String finalExpr = ""; List<String> _valid = Arrays.asList(validValues); // Validate expression // expression can be: // ONE SIZE: [size] // SIZE LIST: [size],[size],...,[size] // RANGE FROM: ...[size] or [size]... to get range (only inclusive) // RANGE BETWEEN: [size]...[size] // 1. Only one size: if(expressionToken.size() == 1) { finalExpr = " " + visibilityLevel + "-" + translateSize(expressionToken.get(0), true) + display; } // 2. Expression contains comma, so is a list of sizes else if (expressionToken.contains(",")) { for(String ex: expressionToken) { if(",".equals(ex)) continue; finalExpr += " " + visibilityLevel + "-" + translateSize(ex, true) + display + " "; } } // 3. Expression is a range from else if (expressionToken.size() == 2) { if(expressionToken.get(0).equals("...")) { if(!_valid.contains(expressionToken.get(1))) throw new FacesException("Expression not valid. Valid syntax is ...[size] eg. ...sm . Valid sizes are [ xs, sm, md, lg ]."); List<String> sR = getSizeRange("<=", translateSize(expressionToken.get(1), false)); for(String s: sR) { finalExpr += " " + visibilityLevel + "-" + s + display + " "; } } else if(expressionToken.get(1).equals("...")) { if(!_valid.contains(expressionToken.get(0))) throw new FacesException("Expression not valid. Valid syntax is [size]... eg. sm... . Valid sizes are [ xs, sm, md, lg ]."); List<String> sR = getSizeRange(">=", translateSize(expressionToken.get(0), false)); for(String s: sR) { finalExpr += " " + visibilityLevel + "-" + s + display + " "; } } else { throw new FacesException("Expression not valid. Valid syntax is ...[size] or [size]... . Valid sizes are [ xs, sm, md, lg ]."); } } // 4. Expression is in range else if(expressionToken.size() == 3) { // validation: if(!_valid.contains(expressionToken.get(0)) && !"...".equals(expressionToken.get(1)) && !_valid.contains(expressionToken.get(2))) throw new FacesException("Expression not valid. Valid syntax is [size]...[size] eg. xs...md . Valid sizes are [ xs, sm, md, lg ]."); List<String> sR2 = getSizeRange(expressionToken.get(1), translateSize(expressionToken.get(0), false), translateSize(expressionToken.get(2), false)); for(String s: sR2) { finalExpr += " " + visibilityLevel + "-" + s + display + " "; } } // 5. Otherwise else { throw new FacesException("Expression not valid. See the docs for a list of possibile rules."); } return finalExpr; } /** * Translate Sizes * @param size * @return */ public static String translateSize(String size, boolean strict) { if (strict) { boolean found=false; for (String s: validValues) { if (s.equals(size)) { found=true; break; } } if (!found) { throw new FacesException("The size of b:panel must be one of the values xs, sm, md, lg, tiny-screen, small-screen, medium-screen, or large-screen"); } } if(size.equalsIgnoreCase("xs") || size.equalsIgnoreCase("tiny-screen")) return "xs"; if(size.equalsIgnoreCase("sm") || size.equalsIgnoreCase("small-screen")) return "sm"; if(size.equalsIgnoreCase("md") || size.equalsIgnoreCase("medium-screen")) return "md"; if(size.equalsIgnoreCase("lg") || size.equalsIgnoreCase("large-screen")) return "lg"; return size; } /** * Get the size ranges * @param operation * @param size * @return */ private static List<String> getSizeRange(String operation, String size) { return getSizeRange(operation, size, null); } private static List<String> getSizeRange(String operation, String size1, String size2) { String[] orderSizes = { "xs", "sm", "md", "lg" }; List<String> sizeRange = new ArrayList<String>(); int itemIdx = Arrays.asList(orderSizes).indexOf(size1); if(operation.equals(">")) { for(int i = itemIdx + 1; i < orderSizes.length; i++) { sizeRange.add(orderSizes[i]); } } else if(operation.equals(">=")) { for(int i = itemIdx; i < orderSizes.length; i++) { sizeRange.add(orderSizes[i]); } } else if(operation.equals("<")) { for(int i = 0; i < itemIdx; i++) { sizeRange.add(orderSizes[i]); } } else if(operation.equals("<=")) { for(int i = 0; i <= itemIdx; i++) { sizeRange.add(orderSizes[i]); } } else if(operation.equals("...") && size2 != null) { int secondIdx = Arrays.asList(orderSizes).indexOf(size2); if(secondIdx < itemIdx) { int temp = secondIdx; secondIdx = itemIdx; itemIdx = temp; } for(int i = itemIdx; i <= secondIdx; i++) { sizeRange.add(orderSizes[i]); } } else { throw new FacesException("Operation not valid"); } return sizeRange; } /** * Tokenize string based on rules * * @param tokenString * @param delimiters * @return */ public static List<String> wonderfulTokenizer(String tokenString, String[] delimiters) { List<String> tokens = new ArrayList<String>(); String currentToken = ""; for(int i = 0; i < tokenString.length(); i++) { String _currItem = String.valueOf(tokenString.charAt(i)); if(_currItem.trim().isEmpty()) continue; String delimiterFound = ""; for(String d: delimiters) { if(d.startsWith(_currItem)) { if(d.length() > 1) { if(d.equals(tokenString.substring(i, i + d.length()))) { delimiterFound = d; i = i + (d.length() - 1); } } else delimiterFound = d; } if(!delimiterFound.isEmpty()) break; } if(!delimiterFound.isEmpty()) { if(!currentToken.isEmpty()) { tokens.add(currentToken); currentToken = ""; } tokens.add(delimiterFound); } else currentToken += _currItem; } if(!currentToken.isEmpty()) tokens.add(currentToken); return tokens; } /** * Create the responsive class combination * @param r the component bearing the responsiveness attributes * @return null, if there's no label-col-xx attribute */ public static String getResponsiveLabelClass(IResponsiveLabel r) { if(!shouldRenderResponsiveClasses(r)) { return ""; } int colxs = sizeToInt(getSize(r, Sizes.xs)); int colsm = sizeToInt(getSize(r, Sizes.sm)); int colmd = sizeToInt(getSize(r, Sizes.md)); int collg = sizeToInt(getSize(r, Sizes.lg)); StringBuilder sb = new StringBuilder(); if (colmd > 0) { sb.append("col-md-"); sb.append(colmd); sb.append(' '); } if (colxs > 0) { sb.append("col-xs-"); sb.append(colxs); sb.append(' '); } if (colsm > 0) { sb.append("col-sm-"); sb.append(colsm); sb.append(' '); } if (collg > 0) { sb.append("col-lg-"); sb.append(collg); sb.append(' '); } if (sb.length() > 0) { return sb.substring(0, sb.length() - 1); } return null; } /** * Temporal and ugly hack to prevent responsive classes to be applied to inputs inside inline forms. * * This should be removed and the logic placed somewhere else. * * @return whether the component should render responsive classes */ private static boolean shouldRenderResponsiveClasses(Object r) { // This method only checks inputs. if(r instanceof UIComponent && r instanceof IResponsiveLabel) { UIForm form = AJAXRenderer.getSurroundingForm((UIComponent) r, true); if(form instanceof Form) { if(((Form)form).isInline()) { // If the form is inline, no responsive classes should be applied return false; } } } return true; } // TEST METHOD public static void main(String[] args) { List<String> str = wonderfulTokenizer("sm...md", delimiters); String finalExpr = evaluateExpression(str, delimiters, validValues, "hidden", "block"); for(String s: str) System.out.println(s); System.out.println(finalExpr); System.out.println("*******"); str = wonderfulTokenizer("sm...medium-screen", delimiters); finalExpr = evaluateExpression(str, delimiters, validValues, "hidden", "block"); for(String s: str) System.out.println(s); System.out.println(finalExpr); System.out.println("*******"); str = wonderfulTokenizer("...md", delimiters); finalExpr = evaluateExpression(str, delimiters, validValues, "hidden", "block"); for(String s: str) System.out.println(s); System.out.println(finalExpr); System.out.println("*******"); str = wonderfulTokenizer("xs,lg", delimiters); finalExpr = evaluateExpression(str, delimiters, validValues, "hidden", "block"); for(String s: str) System.out.println(s); System.out.println(finalExpr); System.out.println("*******"); str = wonderfulTokenizer("md...", delimiters); finalExpr = evaluateExpression(str, delimiters, validValues, "hidden", "block"); for(String s: str) System.out.println(s); System.out.println(finalExpr); } }
package net.darkhax.tesla.lib; import java.util.ArrayList; import java.util.List; import net.darkhax.tesla.api.ITeslaHandler; import net.darkhax.tesla.capability.TeslaStorage; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.translation.I18n; import net.minecraft.world.World; public class TeslaUtils { /** * The smallest unit of power measurement. */ public static final int TESLA = 1; /** * The amount of Tesla in a KiloTesla. One thousand. */ public static final int KILOTESLA = 1000; /** * The amount of Telsa in a MegaTesla. One Million. */ public static final int MEGATESLA = 1000000; /** * The amount of Tesla in a GigaTesla. One Billion. */ public static final int GIGATESLA = 1000000000; /** * The amount of Telsa in a TeraTesla. One Trillion. */ public static final long TERATESLA = 1000000000000L; /** * The amount of Tesla in a PentaTesla. One Quadrilli.on */ public static final long PENTATESLA = 1000000000000000L; /** * The amount of Tesla in a ExaTesla. One Quintilian. * * The ExaTesla should not be treated as the largest unit of Tesla. The naming scheme can * go on indefinitely. The next unit would be a ZettaTesla, followed by YottaTesla, * BronoTesla, GeopTesla and so on. While it is possible to define these measurements, * there really isn't a point. */ public static final long EXATESLA = 1000000000000000000L; /** * Converts an amount of Tesla units into a human readable String. The string amount is * only rounded to one decimal place. * * @param tesla The amount of Tesla units to display. * @return A human readable display of the Tesla units. */ public static String getDisplayableTeslaCount (long tesla) { if (tesla < 1000) return tesla + " T"; final int exp = (int) (Math.log(tesla) / Math.log(1000)); final char unitType = "KMGTPE".charAt(exp - 1); return String.format("%.1f %sT", tesla / Math.pow(1000, exp), unitType); } /** * Gets the abbreviated name of the best unit to describe the provided power. For example, * anything less than 1000 will return t for tesla, while anything between 999 and one * million will return kt for kilo tesla. This method has support for up to Exatesla. * * @param tesla The amount of Tesla to get the unit for. * @return The abbreviated name for the unit used to describe the provided power amount. */ public static String getUnitType (long tesla) { if (tesla < 1000) return tesla + "t"; final int exp = (int) (Math.log(tesla) / Math.log(1000)); return "kmgtpe".charAt(exp - 1) + "t"; } /** * Gets the name of the the power unit that best represents the amount of provided power. * The name will be translated to the local language, or english if that language is not * yet supported. * * @param tesla The amount of Tesla to get the unit name for. * @return The name of the power unit that best represents the amount of power provided. */ public static String getLocalizedUnitType (long tesla) { return I18n.translateToLocal("unit.tesla." + getUnitType(tesla)); } /** * Gets a List of all the ITeslaHandlers for the blocks that are touching the passed * position. For a valid ITeslaHandler to be detected, it must be attached to a valid * TileEntity that is directly touching the passed position. * * @param world The world to run the check in. * @param pos The position to search around. * @return A List of all valid ITeslaHandlers that are around the passed position. */ public static List<ITeslaHandler> getConnectedTeslaHandlers (World world, BlockPos pos) { List<ITeslaHandler> teslaHandlers = new ArrayList<ITeslaHandler>(); for (EnumFacing facing : EnumFacing.values()) { final TileEntity tile = world.getTileEntity(pos.offset(facing)); if (tile != null && !tile.isInvalid() && tile.hasCapability(TeslaStorage.TESLA_HANDLER_CAPABILITY, facing)) teslaHandlers.add(tile.getCapability(TeslaStorage.TESLA_HANDLER_CAPABILITY, facing)); } return teslaHandlers; } /** * Attempts to distribute power to all blocks that are directly touching the passed * possession. This will check to make sure that each tile is a valid tasla handler and * that the direction is a valid input side. * * @param world The world to distribute power within. * @param pos The position to distribute power around. * @param amount The amount of power to distribute to each individual tile. * @param simulated Whether or not this is being called as part of a simulation. * @return The amount of power that was accepted by the handlers. */ public static long distributePowerEqually (World world, BlockPos pos, long amount, boolean simulated) { long consumedPower = 0L; for (EnumFacing facing : EnumFacing.values()) { final TileEntity tile = world.getTileEntity(pos.offset(facing)); if (tile != null && !tile.isInvalid() && tile.hasCapability(TeslaStorage.TESLA_HANDLER_CAPABILITY, facing)) { final ITeslaHandler teslaHandler = tile.getCapability(TeslaStorage.TESLA_HANDLER_CAPABILITY, facing); if (teslaHandler.isInputSide(facing)) consumedPower += teslaHandler.givePower(amount, facing, simulated); } } return consumedPower; } }
package net.sf.jabref.gui; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import net.sf.jabref.*; import net.sf.jabref.groups.*; import net.sf.jabref.groups.structure.AbstractGroup; import net.sf.jabref.groups.structure.AllEntriesGroup; import net.sf.jabref.gui.actions.Actions; import net.sf.jabref.gui.worker.MarkEntriesAction; import net.sf.jabref.logic.l10n.Localization; import net.sf.jabref.model.entry.BibtexEntry; import net.sf.jabref.model.entry.BibtexEntryType; import net.sf.jabref.specialfields.Printed; import net.sf.jabref.specialfields.Priority; import net.sf.jabref.specialfields.Quality; import net.sf.jabref.specialfields.Rank; import net.sf.jabref.specialfields.ReadStatus; import net.sf.jabref.specialfields.Relevance; import net.sf.jabref.specialfields.SpecialField; import net.sf.jabref.specialfields.SpecialFieldValue; import net.sf.jabref.specialfields.SpecialFieldsUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class RightClickMenu extends JPopupMenu implements PopupMenuListener { private static final Log LOGGER = LogFactory.getLog(RightClickMenu.class); private final BasePanel panel; private final MetaData metaData; private final JMenu groupAddMenu = new JMenu(Localization.lang("Add to group")); private final JMenu groupRemoveMenu = new JMenu(Localization.lang("Remove from group")); private final JMenu groupMoveMenu = new JMenu(Localization.lang("Assign exclusively to group")); // JZTODO lyrics private final JMenu typeMenu = new JMenu(Localization.lang("Change entry type")); private final JMenuItem groupAdd; private final JMenuItem groupRemove; private final JCheckBoxMenuItem floatMarked = new JCheckBoxMenuItem(Localization.lang("Float marked entries"), Globals.prefs.getBoolean(JabRefPreferences.FLOAT_MARKED_ENTRIES)); public RightClickMenu(BasePanel panel_, MetaData metaData_) { panel = panel_; metaData = metaData_; // Are multiple entries selected? boolean multiple = panel.mainTable.getSelectedRowCount() > 1; // If only one entry is selected, get a reference to it for adapting the menu. BibtexEntry be = null; if (panel.mainTable.getSelectedRowCount() == 1) { be = panel.mainTable.getSelected().get(0); } addPopupMenuListener(this); add(new AbstractAction(Localization.lang("Copy"), IconTheme.JabRefIcon.COPY.getSmallIcon()) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.COPY); } catch (Throwable ex) { LOGGER.warn("Could not execute copy", ex); } } }); add(new AbstractAction(Localization.lang("Paste"), IconTheme.JabRefIcon.PASTE.getSmallIcon()) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.PASTE); } catch (Throwable ex) { LOGGER.warn("Could not execute paste", ex); } } }); add(new AbstractAction(Localization.lang("Cut"), IconTheme.JabRefIcon.CUT.getSmallIcon()) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.CUT); } catch (Throwable ex) { LOGGER.warn("Could not execute cut", ex); } } }); add(new AbstractAction(Localization.lang("Delete"), IconTheme.JabRefIcon.DELETE.getSmallIcon()) { @Override public void actionPerformed(ActionEvent e) { /*SwingUtilities.invokeLater(new Runnable () { public void run() {*/ try { panel.runCommand(Actions.DELETE); } catch (Throwable ex) { LOGGER.warn("Could not execute delete", ex); } } }); addSeparator(); add(new AbstractAction(Localization.lang("Export to clipboard"), IconTheme.JabRefIcon.EXPORT_TO_CLIPBOARD.getSmallIcon()) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.EXPORT_TO_CLIPBOARD); } catch (Throwable ex) { LOGGER.warn("Could not execute exportToClipboard", ex); } } }); add(new AbstractAction(Localization.lang("Send as email"), IconTheme.JabRefIcon.EMAIL.getSmallIcon()) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.SEND_AS_EMAIL); } catch (Throwable ex) { LOGGER.warn("Could not execute sendAsEmail", ex); } } }); addSeparator(); JMenu markSpecific = JabRefFrame.subMenu("Mark specific color"); JabRefFrame frame = panel.frame; for (int i = 0; i < EntryMarker.MAX_MARKING_LEVEL; i++) { markSpecific.add(new MarkEntriesAction(frame, i).getMenuItem()); } if (multiple) { add(new AbstractAction(Localization.lang("Mark entries"), IconTheme.JabRefIcon.MARK_ENTRIES.getSmallIcon()) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.MARK_ENTRIES); } catch (Throwable ex) { LOGGER.warn("Could not execute markEntries", ex); } } }); add(markSpecific); add(new AbstractAction(Localization.lang("Unmark entries"), IconTheme.JabRefIcon.UNMARK_ENTRIES.getSmallIcon()) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.UNMARK_ENTRIES); } catch (Throwable ex) { LOGGER.warn("Could not execute unmarkEntries", ex); } } }); addSeparator(); } else if (be != null) { String marked = be.getField(BibtexFields.MARKED); // We have to check for "" too as the marked field may be empty if (marked == null || marked.isEmpty()) { add(new AbstractAction(Localization.lang("Mark entry"), IconTheme.JabRefIcon.MARK_ENTRIES.getSmallIcon()) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.MARK_ENTRIES); } catch (Throwable ex) { LOGGER.warn("Could not execute markEntries", ex); } } }); add(markSpecific); } else { add(markSpecific); add(new AbstractAction(Localization.lang("Unmark entry"), IconTheme.JabRefIcon.UNMARK_ENTRIES.getSmallIcon()) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.UNMARK_ENTRIES); } catch (Throwable ex) { LOGGER.warn("Could not execute unmarkEntries", ex); } } }); } addSeparator(); } if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SPECIALFIELDSENABLED)) { if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_RANKING)) { JMenu rankingMenu = new JMenu(); RightClickMenu.populateSpecialFieldMenu(rankingMenu, Rank.getInstance(), panel.frame); add(rankingMenu); } // TODO: multiple handling for relevance and quality-assurance // if multiple values are selected ("if (multiple)"), two options (set / clear) should be offered // if one value is selected either set or clear should be offered if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_RELEVANCE)) { add(Relevance.getInstance().getValues().get(0).getMenuAction(panel.frame)); } if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_QUALITY)) { add(Quality.getInstance().getValues().get(0).getMenuAction(panel.frame)); } if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_PRINTED)) { add(Printed.getInstance().getValues().get(0).getMenuAction(panel.frame)); } if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_PRIORITY)) { JMenu priorityMenu = new JMenu(); RightClickMenu.populateSpecialFieldMenu(priorityMenu, Priority.getInstance(), panel.frame); add(priorityMenu); } if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_READ)) { JMenu readStatusMenu = new JMenu(); RightClickMenu.populateSpecialFieldMenu(readStatusMenu, ReadStatus.getInstance(), panel.frame); add(readStatusMenu); } addSeparator(); } add(new AbstractAction(Localization.lang("Open folder")) { { if (!isFieldSetForSelectedEntry("file")) { this.setEnabled(false); } } @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.OPEN_FOLDER); } catch (Throwable ex) { LOGGER.warn("Could not open folder", ex); } } }); add(new AbstractAction(Localization.lang("Open file"), getFileIconForSelectedEntry()) { { if(!isFieldSetForSelectedEntry("file")) { this.setEnabled(false); } } @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.OPEN_EXTERNAL_FILE); } catch (Throwable ex) { LOGGER.warn("Could not open external file", ex); } } }); add(new AbstractAction(Localization.lang("Attach file"), IconTheme.JabRefIcon.ATTACH_FILE.getSmallIcon()) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.ADD_FILE_LINK); } catch (Throwable ex) { LOGGER.warn("Could not attach file", ex); } } }); /*add(new AbstractAction(Globals.lang("Open PDF or PS"), GUIGlobals.getImage("openFile")) { public void actionPerformed(ActionEvent e) { try { panel.runCommand("openFile"); } catch (Throwable ex) {} } });*/ add(new AbstractAction(Localization.lang("Open URL or DOI"), IconTheme.JabRefIcon.WWW.getSmallIcon()) { { if(!(isFieldSetForSelectedEntry("url") || isFieldSetForSelectedEntry("doi"))) { this.setEnabled(false); } } @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.OPEN_URL); } catch (Throwable ex) { LOGGER.warn("Could not execute open URL", ex); } } }); add(new AbstractAction(Localization.lang("Get BibTeX data from DOI")) { { if(!(isFieldSetForSelectedEntry("doi"))) { this.setEnabled(false); } } @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.MERGE_DOI); } catch (Throwable ex) { LOGGER.warn("Could not merge with DOI data", ex); } } }); add(new AbstractAction(Localization.lang("Copy BibTeX key")) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.COPY_KEY); } catch (Throwable ex) { LOGGER.warn("Could not copy BibTex key", ex); } } }); add(new AbstractAction(Localization.lang("Copy") + " \\cite{" + Localization.lang("BibTeX key") + '}') { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.COPY_CITE_KEY); } catch (Throwable ex) { LOGGER.warn("Could not copy cite key", ex); } } }); addSeparator(); populateTypeMenu(); add(typeMenu); add(new AbstractAction(Localization.lang("Plain text import")) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.PLAIN_TEXT_IMPORT); } catch (Throwable ex) { LOGGER.debug("Could not import plain text", ex); } } }); add(JabRef.jrf.massSetField); add(JabRef.jrf.manageKeywords); addSeparator(); // for "add/move/remove to/from group" entries (appended here) groupAdd = new JMenuItem(new AbstractAction(Localization.lang("Add to group")) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.ADD_TO_GROUP); //BibtexEntry[] bes = panel.getSelectedEntries(); //JMenu groupMenu = buildGroupMenu(bes, true, false); } catch (Throwable ex) { LOGGER.debug("Could not add to group", ex); } } }); add(groupAdd); groupRemove = new JMenuItem(new AbstractAction(Localization.lang("Remove from group")) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.REMOVE_FROM_GROUP); } catch (Throwable ex) { LOGGER.debug("Could not remove from group", ex); } } }); add(groupRemove); JMenuItem groupMoveTo = add(new AbstractAction(Localization.lang("Move to group")) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.MOVE_TO_GROUP); } catch (Throwable ex) { LOGGER.debug("Could not execute move to group", ex); } } }); add(groupMoveTo); floatMarked.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Globals.prefs.putBoolean(JabRefPreferences.FLOAT_MARKED_ENTRIES, floatMarked.isSelected()); panel.mainTable.refreshSorting(); // Bad remote access } }); // create disabledIcons for all menu entries frame.createDisabledIconsForMenuEntries(this); } /** * Remove all types from the menu. Then cycle through all available * types, and add them. */ private void populateTypeMenu() { typeMenu.removeAll(); for (String key : BibtexEntryType.getAllTypes()) { typeMenu.add(new ChangeTypeAction(BibtexEntryType.getType(key), panel)); } } /** * Remove all types from the menu. * Then cycle through all available values, and add them. */ public static void populateSpecialFieldMenu(JMenu menu, SpecialField field, JabRefFrame frame) { //menu.removeAll(); menu.setText(field.getMenuString()); menu.setIcon(((IconTheme.FontBasedIcon) field.getRepresentingIcon()).createSmallIcon()); for (SpecialFieldValue val : field.getValues()) { menu.add(val.getMenuAction(frame)); } } /** * Set the dynamic contents of "Add to group ..." submenu. */ @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { BibtexEntry[] bes = panel.getSelectedEntries(); panel.storeCurrentEdit(); GroupTreeNode groups = panel.metaData().getGroups(); if (groups == null) { groupAdd.setEnabled(false); groupRemove.setEnabled(false); } else { groupAdd.setEnabled(true); groupRemove.setEnabled(true); } addSeparator(); floatMarked.setSelected(Globals.prefs.getBoolean(JabRefPreferences.FLOAT_MARKED_ENTRIES)); add(floatMarked); } private JMenu buildGroupMenu(BibtexEntry[] bes, boolean add, boolean move) { if (bes == null) { return null; } JMenu groupMenu = new JMenu(); GroupTreeNode groups = metaData.getGroups(); if (groups == null) { groupAddMenu.setEnabled(false); groupMoveMenu.setEnabled(false); groupRemoveMenu.setEnabled(false); return null; } /*groupAddMenu.setEnabled(true); groupMoveMenu.setEnabled(true); groupRemoveMenu.setEnabled(true); groupAddMenu.removeAll(); groupMoveMenu.removeAll(); groupRemoveMenu.removeAll(); add(groupAddMenu); add(groupMoveMenu); add(groupRemoveMenu); groupAddMenu.setEnabled(false); groupMoveMenu.setEnabled(false); groupRemoveMenu.setEnabled(false);*/ /*insertNodes(groupAddMenu,metaData.getGroups(),bes,true,false); insertNodes(groupMoveMenu,metaData.getGroups(),bes,true,true); insertNodes(groupRemoveMenu,metaData.getGroups(),bes,false,false);*/ insertNodes(groupMenu, metaData.getGroups(), bes, add, move); return groupMenu; } /** * @param move For add: if true, remove from previous groups */ private void insertNodes(JMenu menu, GroupTreeNode node, BibtexEntry[] selection, boolean add, boolean move) { final AbstractAction action = getAction(node, selection, add, move); if (node.getChildCount() == 0) { JMenuItem menuItem = new JMenuItem(action); setGroupFontAndIcon(menuItem, node.getGroup()); menu.add(menuItem); if (action.isEnabled()) { menu.setEnabled(true); } return; } JMenu submenu; if (node.getGroup() instanceof AllEntriesGroup) { for (int i = 0; i < node.getChildCount(); ++i) { insertNodes(menu, (GroupTreeNode) node.getChildAt(i), selection, add, move); } } else { submenu = new JMenu('[' + node.getGroup().getName() + ']'); setGroupFontAndIcon(submenu, node.getGroup()); // setEnabled(true) is done above/below if at least one menu // entry (item or submenu) is enabled submenu.setEnabled(action.isEnabled()); JMenuItem menuItem = new JMenuItem(action); setGroupFontAndIcon(menuItem, node.getGroup()); submenu.add(menuItem); submenu.add(new Separator()); for (int i = 0; i < node.getChildCount(); ++i) { insertNodes(submenu, (GroupTreeNode) node.getChildAt(i), selection, add, move); } menu.add(submenu); if (submenu.isEnabled()) { menu.setEnabled(true); } } } /** Sets the font and icon to be used, depending on the group */ private void setGroupFontAndIcon(JMenuItem menuItem, AbstractGroup group) { if (Globals.prefs.getBoolean(JabRefPreferences.GROUP_SHOW_DYNAMIC)) { menuItem.setFont(menuItem.getFont().deriveFont(group.isDynamic() ? Font.ITALIC : Font.PLAIN)); } if (Globals.prefs.getBoolean(JabRefPreferences.GROUP_SHOW_ICONS)) { switch (group.getHierarchicalContext()) { case INCLUDING: menuItem.setIcon(IconTheme.JabRefIcon.GROUP_INCLUDING.getSmallIcon()); break; case REFINING: menuItem.setIcon(IconTheme.JabRefIcon.GROUP_REFINING.getSmallIcon()); break; default: menuItem.setIcon(IconTheme.JabRefIcon.GROUP_REGULAR.getSmallIcon()); break; } } } /** * @param move For add: if true, remove from all previous groups */ private AbstractAction getAction(GroupTreeNode node, BibtexEntry[] selection, boolean add, boolean move) { AbstractAction action = add ? new AddToGroupAction(node, move, panel) : new RemoveFromGroupAction(node, panel); AbstractGroup group = node.getGroup(); if (!move) { action.setEnabled(add ? group.supportsAdd() && !group.containsAll(selection) : group.supportsRemove() && group.containsAny(selection)); } else { action.setEnabled(group.supportsAdd()); } return action; } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { remove(groupAddMenu); remove(groupMoveMenu); remove(groupRemoveMenu); } @Override public void popupMenuCanceled(PopupMenuEvent e) { // nothing to do } private boolean isFieldSetForSelectedEntry(String fieldname) { if (panel.mainTable.getSelectedRowCount() == 1) { BibtexEntry entry = panel.mainTable.getSelected().get(0); if (entry.getAllFields().contains(fieldname)) { return true; } else { return false; } } else { return false; } } private Icon getFileIconForSelectedEntry() { if (panel.mainTable.getSelectedRowCount() == 1) { BibtexEntry entry = panel.mainTable.getSelected().get(0); String file = entry.getField(Globals.FILE_FIELD); if(file!=null) { return FileListTableModel.getFirstLabel(file).getIcon(); } } return IconTheme.JabRefIcon.FILE.getSmallIcon(); } static class ChangeTypeAction extends AbstractAction { final BibtexEntryType type; final BasePanel panel; public ChangeTypeAction(BibtexEntryType type, BasePanel bp) { super(type.getName()); this.type = type; panel = bp; } @Override public void actionPerformed(ActionEvent evt) { panel.changeType(type); } } }
package org.basex.http.restxq; import static org.basex.http.restxq.RestXqText.*; import static org.basex.query.QueryText.*; import static org.basex.util.Token.*; import java.util.*; import java.util.regex.*; import org.basex.http.*; import org.basex.query.util.inspect.*; import org.basex.query.value.item.*; import org.basex.query.value.node.*; import org.basex.query.var.*; import org.basex.util.hash.*; import org.basex.util.list.*; final class RestXqWadl { /** HTTP context. */ private HTTPContext http; /** * Constructor. * @param hc HTTP context */ RestXqWadl(final HTTPContext hc) { http = hc; } /** * Returns a WADL description for all available URIs. * @param modules available modules * @return WADL description */ synchronized FElem create(final HashMap<String, RestXqModule> modules) { // create root nodes final FElem application = new FElem(WADL + "application", WADL_URI).declareNS(); final String base = http.req.getRequestURL().toString(); final FElem resources = elem("resources", application).add("base", base); // create children final TreeMap<String, FElem> map = new TreeMap<String, FElem>(); for(final RestXqModule mod : modules.values()) { for(final RestXqFunction func : mod.functions()) { final TokenObjMap<TokenList> xqdoc = func.function.doc(); final String path = func.path.toString(); final String methods = func.methods.toString().replaceAll("[^A-Z ]", ""); // create resource final FElem resource = new FElem(WADL + "resource", WADL_URI).add("path", path); map.put(path + "?" + methods, resource); // add documentation for path variables final Matcher var = Pattern.compile("\\$[^}]*").matcher(path); while(var.find()) { addParam(var.group().substring(1), "template", resource, xqdoc, func); } // create method, add function documentation final FElem method = elem("method", resource).add("name", methods); final TokenList descs = xqdoc != null ? xqdoc.get(DOC_DESCRIPTION) : null; if(descs != null) for(final byte[] desc : descs) addDoc(desc, method); // create request final FElem request = elem("request", method); for(final RestXqParam rxp : func.queryParams) addParam(rxp.key, "query", request, xqdoc, func); for(final RestXqParam rxp : func.formParams) addParam(rxp.key, "query", request, xqdoc, func); for(final RestXqParam rxp : func.headerParams) addParam(rxp.key, "header", request, xqdoc, func); // create response final FElem response = elem("response", method); final FElem representation = elem("representation", response); representation.add("mediaType", HTTPContext.mediaType(func.output)); } } // add resources in sorted order for(final FElem elem : map.values()) resources.add(elem); return application; } /** * Adds a parameter and its documentation to the specified element. * @param name name of parameter * @param style style * @param root root element * @param xqdoc documentation * @param func function */ private void addParam(final String name, final String style, final FElem root, final TokenObjMap<TokenList> xqdoc, final RestXqFunction func) { final FElem param = elem("param", root); param.add("name", name).add("style", style); final QNm qn = new QNm(name); for(final Var var : func.function.args) { if(var.name.eq(qn) && var.declType != null) { param.add("type", var.declType.toString()); } } addDoc(Inspect.doc(xqdoc, token(name)), param); } /** * Creates an element. * @param name name of element * @param parent parent node * @return element node */ private FElem elem(final String name, final FElem parent) { final FElem elem = new FElem(WADL + name, WADL_URI); if(parent != null) parent.add(elem); return elem; } /** * Adds a documentation element to the specified element. * @param xqdoc documentation (may be {@code null}) * @param parent parent node */ private void addDoc(final byte[] xqdoc, final FElem parent) { if(xqdoc == null) return; final FElem doc = elem("doc", parent); doc.namespaces().add(EMPTY, token(XHTML_URL)); Inspect.add(xqdoc, http.context(), doc); } }
package org.cobbzilla.util.http; import lombok.Cleanup; import lombok.extern.slf4j.Slf4j; import org.apache.commons.exec.CommandLine; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.*; import org.apache.http.entity.ContentType; import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.apache.http.util.EntityUtils; import org.cobbzilla.util.collection.NameAndValue; import org.cobbzilla.util.string.StringUtil; import org.cobbzilla.util.system.CommandResult; import org.cobbzilla.util.system.CommandShell; import org.cobbzilla.util.system.Sleep; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.Charset; import java.util.LinkedHashMap; import java.util.Map; import static com.google.common.net.HttpHeaders.CONTENT_DISPOSITION; import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; import static org.apache.http.HttpHeaders.*; import static org.cobbzilla.util.daemon.ZillaRuntime.*; import static org.cobbzilla.util.http.HttpContentTypes.MULTIPART_FORM_DATA; import static org.cobbzilla.util.http.HttpContentTypes.contentType; import static org.cobbzilla.util.http.HttpMethods.*; import static org.cobbzilla.util.http.HttpStatusCodes.NO_CONTENT; import static org.cobbzilla.util.http.URIUtil.getFileExt; import static org.cobbzilla.util.io.FileUtil.getDefaultTempDir; import static org.cobbzilla.util.json.JsonUtil.COMPACT_MAPPER; import static org.cobbzilla.util.json.JsonUtil.json; import static org.cobbzilla.util.security.CryptStream.BUFFER_SIZE; import static org.cobbzilla.util.string.StringUtil.CRLF; import static org.cobbzilla.util.string.StringUtil.urlEncode; import static org.cobbzilla.util.system.Sleep.sleep; import static org.cobbzilla.util.time.TimeUtil.DATE_FORMAT_LAST_MODIFIED; @Slf4j public class HttpUtil { public static final String CHUNKED_ENCODING = "chunked"; public static final String USER_AGENT_CURL = "curl/7.64.1"; public static Map<String, String> queryParams(URL url) throws UnsupportedEncodingException { return queryParams(url, StringUtil.UTF8); } public static Map<String, String> queryParams(URL url, String encoding) throws UnsupportedEncodingException { final Map<String, String> query_pairs = new LinkedHashMap<>(); final String query = url.getQuery(); final String[] pairs = query.split("&"); for (String pair : pairs) { final int idx = pair.indexOf("="); query_pairs.put(URLDecoder.decode(pair.substring(0, idx), encoding), URLDecoder.decode(pair.substring(idx + 1), encoding)); } return query_pairs; } public static InputStream getUrlInputStream(String url) throws IOException { return get(url); } public static InputStream get (String urlString) throws IOException { return get(urlString, null); } public static InputStream get (String urlString, long connectTimeout) throws IOException { return get(urlString, null, null, connectTimeout); } public static InputStream get (String urlString, Map<String, String> headers) throws IOException { return get(urlString, headers, null); } public static InputStream get (String urlString, Map<String, String> headers, Map<String, String> headers2) throws IOException { return get(urlString, headers, headers2, null); } public static InputStream get (String urlString, Map<String, String> headers, Map<String, String> headers2, Long connectTimeout) throws IOException { final URL url = new URL(urlString); final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); if (connectTimeout != null) urlConnection.setConnectTimeout(connectTimeout.intValue()); if (headers != null) addHeaders(urlConnection, headers); if (headers2 != null) addHeaders(urlConnection, headers2); return urlConnection.getInputStream(); } public static InputStream post (String urlString, InputStream data, String multipartFileName, Map<String, String> headers, Map<String, String> headers2) throws IOException { return upload(urlString, POST, multipartFileName, data, headers, headers2); } public static InputStream put (String urlString, InputStream data, String multipartFileName, Map<String, String> headers, Map<String, String> headers2) throws IOException { return upload(urlString, PUT, multipartFileName, data, headers, headers2); } public static InputStream upload (String urlString, String method, String multipartFileName, InputStream data, Map<String, String> headers, Map<String, String> headers2) throws IOException { final URL url = new URL(urlString); final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod(method); if (headers != null) addHeaders(urlConnection, headers); if (headers2 != null) addHeaders(urlConnection, headers2); if (data != null) { urlConnection.setDoOutput(true); OutputStream upload = null; try { if (multipartFileName != null) { final String boundary = randomAlphanumeric(10)+"_"+now(); urlConnection.setRequestProperty(CONTENT_TYPE, MULTIPART_FORM_DATA+"; boundary="+boundary); urlConnection.setRequestProperty(TRANSFER_ENCODING, CHUNKED_ENCODING); urlConnection.setChunkedStreamingMode(4096); final HttpEntity entity = MultipartEntityBuilder.create() .setBoundary(boundary) .setLaxMode() .addBinaryBody(multipartFileName, data, ContentType.APPLICATION_OCTET_STREAM, multipartFileName) .build(); upload = urlConnection.getOutputStream(); entity.writeTo(upload); } else { upload = urlConnection.getOutputStream(); IOUtils.copyLarge(data, upload); } } finally { if (upload != null) upload.close(); } } return urlConnection.getInputStream(); } public static void addHeaders(HttpURLConnection urlConnection, Map<String, String> headers) { for (Map.Entry<String, String> h : headers.entrySet()) { urlConnection.setRequestProperty(h.getKey(), h.getValue()); } } public static HttpResponseBean upload (String url, File file, Map<String, String> headers) throws IOException { @Cleanup final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost method = new HttpPost(url); final FileBody fileBody = new FileBody(file); MultipartEntityBuilder builder = MultipartEntityBuilder.create().addPart("file", fileBody); method.setEntity(builder.build()); if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { method.addHeader(new BasicHeader(header.getKey(), header.getValue())); } } @Cleanup final CloseableHttpResponse response = client.execute(method); final HttpResponseBean responseBean = new HttpResponseBean() .setEntityBytes(EntityUtils.toByteArray(response.getEntity())) .setHttpHeaders(response.getAllHeaders()) .setStatus(response.getStatusLine().getStatusCode()); return responseBean; } public static final int DEFAULT_RETRIES = 3; public static File url2file (String url) throws IOException { return url2file(url, null, DEFAULT_RETRIES); } public static File url2file (String url, String file) throws IOException { return url2file(url, file == null ? null : new File(file), DEFAULT_RETRIES); } public static File url2file (String url, File file) throws IOException { return url2file(url, file, DEFAULT_RETRIES); } public static File url2file (String url, File file, int retries) throws IOException { if (file == null) file = File.createTempFile("url2file-", getFileExt((url)), getDefaultTempDir()); IOException lastException = null; long sleep = 100; for (int i=0; i<retries; i++) { try { @Cleanup final InputStream in = get(url); @Cleanup final OutputStream out = new FileOutputStream(file); IOUtils.copy(in, out); lastException = null; break; } catch (IOException e) { lastException = e; sleep(sleep, "waiting to possibly retry after IOException: "+lastException); sleep *= 5; } } if (lastException != null) throw lastException; return file; } public static String url2string (String url) throws IOException { @Cleanup final InputStream in = get(url); final ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); return out.toString(); } public static String url2string (String url, long connectTimeout) throws IOException { @Cleanup final InputStream in = get(url, connectTimeout); final ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); return out.toString(); } public static HttpResponseBean getResponse(HttpRequestBean requestBean) throws IOException { final HttpClientBuilder clientBuilder = requestBean.initClientBuilder(HttpClients.custom()); @Cleanup final CloseableHttpClient client = clientBuilder.build(); return getResponse(requestBean, client); } public static HttpResponseBean getResponse(HttpRequestBean requestBean, HttpClient client) throws IOException { if (requestBean.hasStream()) return getStreamResponse(requestBean); final HttpResponseBean bean = new HttpResponseBean(); final HttpUriRequest request = initHttpRequest(requestBean); if (requestBean.hasHeaders()) { for (NameAndValue header : requestBean.getHeaders()) { request.setHeader(header.getName(), header.getValue()); } } final HttpResponse response = client.execute(request); for (Header header : response.getAllHeaders()) { bean.addHeader(header.getName(), header.getValue()); } bean.setStatus(response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != NO_CONTENT && response.getEntity() != null) { bean.setContentLength(response.getEntity().getContentLength()); final Header contentType = response.getEntity().getContentType(); if (contentType != null) { bean.setContentType(contentType.getValue()); } @Cleanup final InputStream content = response.getEntity().getContent(); bean.setEntity(content); } return bean; } public static HttpResponseBean getStreamResponse(HttpRequestBean request) { if (!request.hasStream()) return die("getStreamResponse: request stream was not set"); try { final String boundary = hexnow(); request.withHeader(CONTENT_TYPE, "multipart/form-data; boundary=" + boundary); @Cleanup("disconnect") final HttpURLConnection connection = (HttpURLConnection) new URL(request.getUri()).openConnection(); connection.setDoOutput(true); connection.setRequestMethod(request.getMethod()); if (!request.hasContentLength() || (request.hasContentLength() && request.getContentLength() > BUFFER_SIZE)) { connection.setChunkedStreamingMode(BUFFER_SIZE); } for (NameAndValue header : request.getHeaders()) { connection.setRequestProperty(header.getName(), header.getValue()); } @Cleanup final OutputStream output = connection.getOutputStream(); @Cleanup final PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, Charset.defaultCharset()), true); writer.append("--").append(boundary).append(CRLF); final String filename = request.getEntity(); addStreamHeader(writer, CONTENT_DISPOSITION, "form-data; name=\"file\"; filename=\""+ filename +"\""); addStreamHeader(writer, CONTENT_TYPE, contentType(filename)); writer.append(CRLF).flush(); IOUtils.copy(request.getEntityInputStream(), output); output.flush(); writer.append(CRLF); writer.append("--").append(boundary).append("--").append(CRLF).flush(); final HttpResponseBean response = new HttpResponseBean() .setStatus(connection.getResponseCode()) .setHttpHeaders(connection.getHeaderFields()); if (!request.discardResponseEntity()) { try { response.setEntity(connection.getInputStream()); } catch (IOException ioe) { response.setEntity(connection.getErrorStream()); } } return response; } catch (Exception e) { return die("getStreamResponse: "+e, e); } } private static PrintWriter addStreamHeader(PrintWriter writer, String name, String value) { writer.append(name).append(": ").append(value).append(CRLF); return writer; } public static HttpResponseBean getResponse(String urlString) throws IOException { final HttpResponseBean bean = new HttpResponseBean(); @Cleanup final CloseableHttpClient client = HttpClients.createDefault(); final HttpResponse response = client.execute(new HttpGet(urlString.trim())); for (Header header : response.getAllHeaders()) { bean.addHeader(header.getName(), header.getValue()); } bean.setStatus(response.getStatusLine().getStatusCode()); if (response.getEntity() != null) { final Header contentType = response.getEntity().getContentType(); if (contentType != null) bean.setContentType(contentType.getValue()); bean.setContentLength(response.getEntity().getContentLength()); bean.setEntity(response.getEntity().getContent()); } return bean; } public static HttpUriRequest initHttpRequest(HttpRequestBean requestBean) { try { final HttpUriRequest request; switch (requestBean.getMethod()) { case HEAD: request = new HttpHead(requestBean.getUri()); break; case GET: request = new HttpGet(requestBean.getUri()); break; case POST: request = new HttpPost(requestBean.getUri()); break; case PUT: request = new HttpPut(requestBean.getUri()); break; case PATCH: request = new HttpPatch(requestBean.getUri()); break; case DELETE: request = new HttpDelete(requestBean.getUri()); break; default: return die("Invalid request method: " + requestBean.getMethod()); } if (requestBean.hasData() && request instanceof HttpEntityEnclosingRequestBase) { setData(requestBean.getEntity(), (HttpEntityEnclosingRequestBase) request); } return request; } catch (UnsupportedEncodingException e) { return die("initHttpRequest: " + e, e); } } private static void setData(Object data, HttpEntityEnclosingRequestBase request) throws UnsupportedEncodingException { if (data == null) return; if (data instanceof String) { request.setEntity(new StringEntity((String) data)); } else if (data instanceof InputStream) { request.setEntity(new InputStreamEntity((InputStream) data)); } else { throw new IllegalArgumentException("Unsupported request entity type: "+data.getClass().getName()); } } public static String getContentType(HttpResponse response) { final Header contentTypeHeader = response.getFirstHeader(CONTENT_TYPE); return (contentTypeHeader == null) ? null : contentTypeHeader.getValue(); } public static boolean isOk(String url) { return isOk(url, URIUtil.getHost(url)); } public static boolean isOk(String url, String host) { final CommandLine command = new CommandLine("curl") .addArgument("--insecure") // since we are requested via the IP address, the cert will not match .addArgument("--header").addArgument("Host: " + host) // pass FQDN via Host header .addArgument("--silent") .addArgument("--location") // follow redirects .addArgument("--write-out").addArgument("%{http_code}") // just print status code .addArgument("--output").addArgument("/dev/null") // and ignore data .addArgument(url); try { final CommandResult result = CommandShell.exec(command); final String statusCode = result.getStdout(); return result.isZeroExitStatus() && statusCode != null && statusCode.trim().startsWith("2"); } catch (IOException e) { log.warn("isOk: Error fetching " + url + " with Host header=" + host + ": " + e); return false; } } public static boolean isOk(String url, String host, int maxTries, long sleepUnit) { long sleep = sleepUnit; for (int i = 0; i < maxTries; i++) { if (i > 0) { Sleep.sleep(sleep); sleep *= 2; } if (isOk(url, host)) return true; } return false; } public static HttpMeta getHeadMetadata(HttpRequestBean request) throws IOException { final HttpResponseBean headResponse = HttpUtil.getResponse(new HttpRequestBean(request).setMethod(HEAD)); if (!headResponse.isOk()) return die("HTTP HEAD response was not 200: "+headResponse); final HttpMeta meta = new HttpMeta(request.getUri()); final String lastModString = headResponse.getFirstHeaderValue(LAST_MODIFIED); if (lastModString != null) meta.setLastModified(DATE_FORMAT_LAST_MODIFIED.parseMillis(lastModString)); final String etag = headResponse.getFirstHeaderValue(ETAG); if (etag != null) meta.setEtag(etag); return meta; } public static final byte[] CHUNK_SEP = "\r\n".getBytes(); public static final int CHUNK_EXTRA_BYTES = 2 * CHUNK_SEP.length; public static final byte[] CHUNK_END = "0\r\n".getBytes(); public static byte[] makeHttpChunk(byte[] buffer, int bytesRead) { final byte[] httpChunkLengthBytes = Integer.toHexString(bytesRead).getBytes(); final byte[] httpChunk = new byte[bytesRead + httpChunkLengthBytes.length + CHUNK_EXTRA_BYTES]; System.arraycopy(httpChunkLengthBytes, 0, httpChunk, 0, httpChunkLengthBytes.length); System.arraycopy(buffer, 0, httpChunk, httpChunkLengthBytes.length, bytesRead); System.arraycopy(CHUNK_SEP, 0, httpChunk, httpChunkLengthBytes.length+bytesRead, CHUNK_SEP.length); return httpChunk; } public static boolean isBrowser (String ua) { final boolean browser = !empty(ua) && !ua.equals("NONE") && !ua.equals("UNKNOWN") && ( ua.startsWith("Mozilla/") // Older versions of Opera || ua.startsWith("Opera/") // Down the rabbit hole... || ua.startsWith("Lynx/") || ua.startsWith("Links ") || ua.startsWith("Elinks ") || ua.startsWith("ELinks ") || ua.startsWith("ELinks/") || ua.startsWith("Midori/") || ua.startsWith("w3m/") || ua.startsWith("Webkit/") || ua.startsWith("Vimprobable/") || ua.startsWith("Dooble/") || ua.startsWith("Dillo/") || ua.startsWith("Surf/") || ua.startsWith("NetSurf/") || ua.startsWith("Galaxy/") || ua.startsWith("Cyberdog/") || ua.startsWith("iCab/") || ua.startsWith("IBrowse/") || ua.startsWith("IBM WebExplorer /") || ua.startsWith("AmigaVoyager/") || ua.startsWith("HotJava/") || ua.startsWith("retawq/") || ua.startsWith("uzbl ") || ua.startsWith("Uzbl ") || ua.startsWith("NCSA Mosaic/") || ua.startsWith("NCSA_Mosaic/") // And, finally, we test to see if they"re using *the first browser ever*. || ua.equals("WorldWideweb (NEXT)") ); if (log.isDebugEnabled()) log.debug("isBrowser("+ua+") returning "+browser); return browser; } public static String chaseRedirects(String url) { return chaseRedirects(url, 5); } public static String chaseRedirects(String url, int maxDepth) { log.info("chaseRedirects("+url+") starting..."); // strip tracking params url = cleanParams(url); String lastHost; try { lastHost = URIUtil.getScheme(url) + "://" + URIUtil.getHost(url); HttpRequestBean requestBean = curlHead(url); final HttpClientBuilder clientBuilder = requestBean.initClientBuilder(HttpClients.custom().disableRedirectHandling()); @Cleanup final CloseableHttpClient client = clientBuilder.build(); HttpResponseBean responseBean = HttpUtil.getResponse(requestBean, client); if (log.isDebugEnabled()) log.debug("follow("+url+"): HEAD "+url+" returned "+json(responseBean, COMPACT_MAPPER)); if (responseBean.isOk()) return url; // standard redirect chasing... int depth = 0; String nextUrl; while (depth < maxDepth && responseBean.is3xx() && responseBean.hasHeader(HttpHeaders.LOCATION)) { depth++; nextUrl = cleanParams(responseBean.getFirstHeaderValue(HttpHeaders.LOCATION)); if (log.isDebugEnabled()) log.debug("follow("+url+"): found nextUrl="+nextUrl); if (nextUrl == null) break; if (nextUrl.startsWith("/")) { nextUrl = lastHost + nextUrl; } else { lastHost = URIUtil.getScheme(nextUrl) + "://" + URIUtil.getHost(nextUrl); } url = nextUrl; requestBean = curlHead(url); responseBean = HttpUtil.getResponse(requestBean, client); } } catch (Exception e) { if (log.isErrorEnabled()) log.error("follow("+url+"): error following: "+shortError(e)); } return url; } public static String cleanParams(String url) { final int qPos = url.indexOf("?"); if (qPos != -1) { final Map<String, String> params = URIUtil.queryParams(url); if (!params.isEmpty()) { final StringBuilder b = new StringBuilder(); for (Map.Entry<String, String> param : params.entrySet()) { if (!isBlockedParam(param.getKey())) { if (b.length() > 0) b.append("&"); b.append(param.getKey()).append("=").append(urlEncode(param.getValue())); } } url = url.substring(0, qPos+1) + b.toString(); } } return url; } public static final String[] BLOCKED_PARAMS = {"dfaid", "cmp", "cid", "dclid"}; private static boolean isBlockedParam(String key) { return key.startsWith("utm_") || ArrayUtils.contains(BLOCKED_PARAMS, key); } public static HttpRequestBean curlHead(String url) { return new HttpRequestBean(HttpMethods.HEAD, url) .setHeader(ACCEPT, "*/*") .setHeader(USER_AGENT, USER_AGENT_CURL); } public static void main (String[] args) { String dest = chaseRedirects("http://example.com/?", 10); System.out.println("dest = "+dest); } }
package org.embulk.output; import java.io.File; import java.io.IOException; import java.io.FileInputStream; import com.google.api.client.http.FileContent; import com.google.api.client.http.InputStreamContent; import java.util.ArrayList; import java.util.List; import java.util.Iterator; import java.util.HashMap; import java.util.IllegalFormatException; import java.util.concurrent.Callable; import java.util.concurrent.TimeoutException; import org.apache.commons.lang3.StringUtils; import com.google.common.base.Optional; import com.google.common.collect.ImmutableSet; import java.security.GeneralSecurityException; import org.embulk.spi.Exec; import org.slf4j.Logger; import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.BigqueryScopes; import com.google.api.services.bigquery.Bigquery.Datasets; import com.google.api.services.bigquery.Bigquery.Jobs.Insert; import com.google.api.services.bigquery.Bigquery.Jobs.GetQueryResults; import com.google.api.services.bigquery.model.Job; import com.google.api.services.bigquery.model.JobConfiguration; import com.google.api.services.bigquery.model.JobConfigurationLoad; import com.google.api.services.bigquery.model.JobStatus; import com.google.api.services.bigquery.model.JobStatistics; import com.google.api.services.bigquery.model.JobReference; import com.google.api.services.bigquery.model.DatasetList; import com.google.api.services.bigquery.model.TableSchema; import com.google.api.services.bigquery.model.TableReference; import com.google.api.services.bigquery.model.TableFieldSchema; import com.google.api.services.bigquery.model.TableCell; import com.google.api.services.bigquery.model.TableRow; import com.google.api.services.bigquery.model.ErrorProto; public class BigqueryWriter { private final Logger log = Exec.getLogger(BigqueryWriter.class); private final String project; private final String dataset; private final String table; private final boolean autoCreateTable; private final Optional<String> schemaPath; private final String sourceFormat; private final String fieldDelimiter; private final int maxBadrecords; private final long jobStatusMaxPollingTime; private final long jobStatusPollingInterval; private final boolean isSkipJobResultCheck; private final Bigquery bigQueryClient; public BigqueryWriter(Builder builder) throws IOException, GeneralSecurityException { this.project = builder.project; this.dataset = builder.dataset; this.table = builder.table; this.autoCreateTable = builder.autoCreateTable; this.schemaPath = builder.schemaPath; this.sourceFormat = builder.sourceFormat.toUpperCase(); this.fieldDelimiter = builder.fieldDelimiter; this.maxBadrecords = builder.maxBadrecords; this.jobStatusMaxPollingTime = builder.jobStatusMaxPollingTime; this.jobStatusPollingInterval = builder.jobStatusPollingInterval; this.isSkipJobResultCheck = builder.isSkipJobResultCheck; BigqueryAuthentication auth = new BigqueryAuthentication(builder.serviceAccountEmail, builder.p12KeyFilePath, builder.applicationName); this.bigQueryClient = auth.getBigqueryClient(); } private String getJobStatus(JobReference jobRef) throws JobFailedException { try { Job job = bigQueryClient.jobs().get(project, jobRef.getJobId()).execute(); ErrorProto fatalError = job.getStatus().getErrorResult(); if (fatalError != null) { throw new JobFailedException(String.format("Job failed. job id:[%s] reason:[%s][%s] status:[FAILED]", jobRef.getJobId(), fatalError.getReason(), fatalError.getMessage())); } List<ErrorProto> errors = job.getStatus().getErrors(); if (errors != null) { for (ErrorProto error : errors) { log.warn(String.format("Error: job id:[%s] reason[%s][%s] location:[%s]", jobRef.getJobId(), error.getReason(), error.getMessage(), error.getLocation())); } } String jobStatus = job.getStatus().getState(); if (jobStatus.equals("DONE")) { JobStatistics statistics = job.getStatistics(); //log.info(String.format("Job end. create:[%s] end:[%s]", statistics.getCreationTime(), statistics.getEndTime())); log.info(String.format("Job statistics [%s]", statistics.getLoad())); } return jobStatus; } catch (IOException ex) { log.warn(ex.getMessage()); return "UNKNOWN"; } } private void getJobStatusUntilDone(JobReference jobRef) throws TimeoutException, JobFailedException { long startTime = System.currentTimeMillis(); long elapsedTime; try { while (true) { String jobStatus = getJobStatus(jobRef); elapsedTime = System.currentTimeMillis() - startTime; if (jobStatus.equals("DONE")) { log.info(String.format("Job completed successfully. job id:[%s] elapsed_time:%dms status:[%s]", jobRef.getJobId(), elapsedTime, "SUCCESS")); break; } else if (elapsedTime > jobStatusMaxPollingTime * 1000) { throw new TimeoutException(String.format("Checking job status...Timeout. job id:[%s] elapsed_time:%dms status:[%s]", jobRef.getJobId(), elapsedTime, "TIMEOUT")); } else { log.info(String.format("Checking job status... job id:[%s] elapsed_time:%dms status:[%s]", jobRef.getJobId(), elapsedTime, jobStatus)); } Thread.sleep(jobStatusPollingInterval * 1000); } } catch (InterruptedException ex) { log.warn(ex.getMessage()); } } public void executeLoad(String localFilePath) throws IOException, TimeoutException, JobFailedException { log.info(String.format("Job preparing... project:%s dataset:%s table:%s", project, dataset, table)); Job job = new Job(); JobConfiguration jobConfig = new JobConfiguration(); JobConfigurationLoad loadConfig = new JobConfigurationLoad(); jobConfig.setLoad(loadConfig); job.setConfiguration(jobConfig); loadConfig.setAllowQuotedNewlines(false); if (sourceFormat.equals("NEWLINE_DELIMITED_JSON")) { loadConfig.setSourceFormat("NEWLINE_DELIMITED_JSON"); } else { loadConfig.setFieldDelimiter(fieldDelimiter); } if (autoCreateTable) { loadConfig.setSchema(getTableSchema()); loadConfig.setWriteDisposition("WRITE_EMPTY"); loadConfig.setCreateDisposition("CREATE_IF_NEEDED"); log.info(String.format("table:[%s] will be create.", table)); } else { loadConfig.setWriteDisposition("WRITE_APPEND"); loadConfig.setCreateDisposition("CREATE_NEVER"); } loadConfig.setMaxBadRecords(maxBadrecords); loadConfig.setDestinationTable(getTableReference()); log.info(String.format("Uploading file [%s]", localFilePath)); File file = new File(localFilePath); FileContent mediaContent = new FileContent("application/octet-stream", file); Insert insert = bigQueryClient.jobs().insert(project, job, mediaContent); insert.setDisableGZipContent(true); insert.setProjectId(project); JobReference jobRef = insert.execute().getJobReference(); log.info(String.format("Job executed. job id:[%s]", jobRef.getJobId())); if (isSkipJobResultCheck) { log.info(String.format("Skip job status check. job id:[%s]", jobRef.getJobId())); } else { getJobStatusUntilDone(jobRef); } } private TableReference getTableReference() { return new TableReference() .setProjectId(project) .setDatasetId(dataset) .setTableId(table); } private TableSchema getTableSchema() { TableSchema tableSchema = new TableSchema(); List<TableFieldSchema> fields = new ArrayList<TableFieldSchema>(); TableFieldSchema tableField; // TODO import from json file /* for () { tableField = new TableFieldSchema() .setName(name) .setType(type); fields.add(tableField); } */ tableSchema.setFields(fields); return tableSchema; } public static class Builder { private final String serviceAccountEmail; private String p12KeyFilePath; private String applicationName; private String project; private String dataset; private String table; private boolean autoCreateTable; private Optional<String> schemaPath; private String sourceFormat; private String fieldDelimiter; private int maxBadrecords; private int jobStatusMaxPollingTime; private int jobStatusPollingInterval; private boolean isSkipJobResultCheck; public Builder(String serviceAccountEmail) { this.serviceAccountEmail = serviceAccountEmail; } public Builder setP12KeyFilePath(String p12KeyFilePath) { this.p12KeyFilePath = p12KeyFilePath; return this; } public Builder setApplicationName(String applicationName) { this.applicationName = applicationName; return this; } public Builder setProject(String project) { this.project = project; return this; } public Builder setDataset(String dataset) { this.dataset = dataset; return this; } public Builder setTable(String table) { this.table = table; return this; } public Builder setAutoCreateTable(boolean autoCreateTable) { this.autoCreateTable = autoCreateTable; return this; } public Builder setSchemaPath(Optional<String> schemaPath) { this.schemaPath = schemaPath; return this; } public Builder setSourceFormat(String sourceFormat) { this.sourceFormat = sourceFormat; return this; } public Builder setFieldDelimiter(String fieldDelimiter) { this.fieldDelimiter = fieldDelimiter; return this; } public Builder setMaxBadrecords(int maxBadrecords) { this.maxBadrecords = maxBadrecords; return this; } public Builder setJobStatusMaxPollingTime(int jobStatusMaxPollingTime) { this.jobStatusMaxPollingTime = jobStatusMaxPollingTime; return this; } public Builder setJobStatusPollingInterval(int jobStatusPollingInterval) { this.jobStatusPollingInterval = jobStatusPollingInterval; return this; } public Builder setIsSkipJobResultCheck(boolean isSkipJobResultCheck) { this.isSkipJobResultCheck = isSkipJobResultCheck; return this; } public BigqueryWriter build() throws IOException, GeneralSecurityException { return new BigqueryWriter(this); } } public class JobFailedException extends Exception { public JobFailedException(String message) { super(message); } } }
package org.jtrfp.trcl.core; import java.util.concurrent.Callable; import com.jogamp.opengl.GLAutoDrawable; import com.jogamp.opengl.GLContext; import com.jogamp.opengl.GLRunnable; import com.jogamp.opengl.awt.GLCanvas; public class GLFutureTask<V> extends TRFutureTask<V> implements GLRunnable { private final GLCanvas canvas; public GLFutureTask(GLCanvas canvas, Callable<V> callable) { super(callable); this.canvas=canvas; } @Override public void run(){ super.run();} public boolean enqueue(){ return canvas.invoke(false, this); } @Override public boolean run(GLAutoDrawable drawable) { super.run(); return true; }//end run(GL) @Override public V get(){ final GLContext context = canvas.getContext(); if(!super.isDone()) if( context != null ) { if(context.isCurrent()) run(); } else throw new IllegalStateException("GL Context is closed."); return super.get(); } }//end GLFutureTask
package org.jtrfp.trcl.mem; import java.io.IOException; import java.nio.ByteBuffer; import org.jtrfp.trcl.core.IndexPool; import org.jtrfp.trcl.core.IndexPool.GrowthBehavior; import org.jtrfp.trcl.gpu.GLProgram; import org.jtrfp.trcl.gpu.GLUniform; import org.jtrfp.trcl.gpu.GPU; import org.jtrfp.trcl.gpu.MemoryUsageHint; import org.jtrfp.trcl.gpu.ReallocatableGLTextureBuffer; public final class MemoryManager { private final IndexPool pageIndexPool = new IndexPool(); private final ByteBuffer [] physicalMemory = new ByteBuffer[1]; private final ReallocatableGLTextureBuffer glPhysicalMemory; private final GPU gpu; public MemoryManager(GPU gpu){ this.gpu=gpu; glPhysicalMemory=new ReallocatableGLTextureBuffer(gpu); glPhysicalMemory.reallocate(PagedByteBuffer.PAGE_SIZE_BYTES); physicalMemory[0] = glPhysicalMemory.map(); glPhysicalMemory.setUsageHint(MemoryUsageHint.DymamicDraw); pageIndexPool.setGrowthBehavior(new GrowthBehavior(){ @Override public int grow(int previousMaxCapacity) { glPhysicalMemory.reallocate(previousMaxCapacity*PagedByteBuffer.PAGE_SIZE_BYTES*2); physicalMemory[0] = glPhysicalMemory.map(); return previousMaxCapacity*2; }//end grow(...) }); }//end constructor public int getMaxCapacityInBytes(){ return PagedByteBuffer.PAGE_SIZE_BYTES*pageIndexPool.getMaxCapacity(); } public void map(){ if((physicalMemory[0] = glPhysicalMemory.map())==null)throw new NullPointerException("Failed to map GPU memory. (returned null)"); } public void unmap(){ physicalMemory[0]=null;//Make sure we don't start reading/writing somewhere bad. glPhysicalMemory.unmap(); } public PagedByteBuffer createPagedByteBuffer(int initialSizeInBytes, String debugName){ return new PagedByteBuffer(physicalMemory, pageIndexPool, initialSizeInBytes, debugName); } public void bindToUniform(int textureUnit, GLProgram shaderProgram, GLUniform uniform) { glPhysicalMemory.bindToUniform(textureUnit, shaderProgram, uniform); } public void dumpAllGPUMemTo(ByteBuffer dest) throws IOException{ map(); physicalMemory[0].clear(); dest.clear(); physicalMemory[0].limit(dest.limit());//Avoid overflow dest.put(physicalMemory[0]); physicalMemory[0].clear(); dest.clear(); } }//end MemmoryManager
package org.jtrfp.trcl.obj; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.jtrfp.trcl.Controller; import org.jtrfp.trcl.RenderMode; import org.jtrfp.trcl.Triangle; import org.jtrfp.trcl.beh.Behavior; import org.jtrfp.trcl.beh.CollisionBehavior; import org.jtrfp.trcl.core.TR; import org.jtrfp.trcl.core.TextureDescription; import org.jtrfp.trcl.file.TNLFile.Segment; import org.jtrfp.trcl.file.TNLFile.Segment.FlickerLightType; import org.jtrfp.trcl.gpu.Model; import org.jtrfp.trcl.math.IntRandomTransferFunction; public class TunnelSegment extends WorldObject { public static final int TUNNEL_DIA_SCALAR = 128; public static final int TUNNEL_SEG_LEN = 65535; Segment segment; private final double segmentLength; private final double endX, endY; public TunnelSegment(TR tr, Segment s, TextureDescription[] tunnelTexturePalette, double segLen, double endX, double endY) { super(tr, createModel(s, segLen, tunnelTexturePalette, endX, endY, tr)); segmentLength = segLen; this.endX = endX; this.endY = endY; this.segment = s; addBehavior(new TunnelSegmentBehavior()); } @Override public boolean supportsLoop(){ return false; } private static class TunnelSegmentBehavior extends Behavior implements CollisionBehavior { @Override public void proposeCollision(WorldObject other) {//DUMMY } } public static double getStartWidth(Segment s) { return TR.legacy2Modern(s.getStartWidth() * TUNNEL_DIA_SCALAR * 3); } public static double getEndWidth(Segment s) { return TR.legacy2Modern(s.getEndWidth() * TUNNEL_DIA_SCALAR * 3); } public static double getStartHeight(Segment s) { return TR.legacy2Modern(s.getStartHeight() * TUNNEL_DIA_SCALAR * 3); } public static double getEndHeight(Segment s) { return TR.legacy2Modern(s.getEndHeight() * TUNNEL_DIA_SCALAR * 3); } private static final IntRandomTransferFunction flickerRandom = new IntRandomTransferFunction(); private static Model createModel(Segment s, double segLen, TextureDescription[] tunnelTexturePalette, double endX, double endY, final TR tr) { Model mainModel = new Model(true, tr); mainModel.setDebugName("tunnelSegment main."); final int numPolys = s.getNumPolygons(); double startWidth = getStartWidth(s); double startHeight = getStartHeight(s); double endWidth = getEndWidth(s); double endHeight = getEndHeight(s); final FlickerLightType lightType = s.getFlickerLightType(); // TODO: Cleanup. final double startAngle1 = ((double) s.getStartAngle1() / 65535.) * 2. * Math.PI; final double startAngle2 = ((double) s.getStartAngle2() / 65535.) * 2. * Math.PI; final double startAngle = startAngle1; final double endAngle1 = ((double) s.getEndAngle1() / 65535.) * 2. * Math.PI; final double endAngle2 = ((double) s.getEndAngle2() / 65535.) * 2. * Math.PI; double endAngle = endAngle1; final double dAngleStart = (startAngle2 - startAngle1) / (double) numPolys; final double dAngleEnd = (endAngle2 - endAngle1) / (double) numPolys; final double startX = 0; final double startY = 0; final double zStart = 0; final double zEnd = segLen; final int numPolygonsMinusOne = s.getNumPolygons() - 1; final int lightPoly = s.getLightPolygon(); final boolean hasLight = lightPoly!=-1; if(hasLight){ mainModel.setAnimateUV(true); mainModel.setSmoothAnimation(false); if(lightType==FlickerLightType.noLight){ //Do nothing. }else if(lightType==FlickerLightType.off1p5Sec){ mainModel.setController(new Controller(){ private final int off = (int)(Math.random()*2000); @Override public double getCurrentFrame() { return (off+System.currentTimeMillis()%2000)>1500?1:0; } @Override public void setDebugMode(boolean b) { //Not implemented. }}); }else if(lightType==FlickerLightType.on1p5Sec){ mainModel.setController(new Controller(){ private final int off = (int)(Math.random()*2000); @Override public double getCurrentFrame() { return (off+System.currentTimeMillis()%2000)<1500?1:0; } @Override public void setDebugMode(boolean b) { //Not implemented. }}); }else if(lightType==FlickerLightType.on1Sec){ mainModel.setController(new Controller(){ private final int off = (int)(Math.random()*2000); @Override public double getCurrentFrame() { return (off+System.currentTimeMillis()%2000)>1000?1:0; } @Override public void setDebugMode(boolean b) { //Not implemented. }}); } }//end (has light) final double[] noLightU=new double[] { 1, 1, 0, 0 }; final double[] noLightV=new double[] { 0, 1, 1, 0 }; final double[] lightOffU=new double[] { 1, 1, .5, .5 }; final double[] lightOffV=new double[] { .5, 1, 1, .5 }; final double[] lightOnU=new double[] { .5, .5, 0, 0 }; final double[] lightOnV=new double[] { .5, 1, 1, .5 }; double rotPeriod = (1000.*32768.)/(double)s.getRotationSpeed(); final boolean reverseDirection = rotPeriod<0; if(reverseDirection)rotPeriod*=-1; final int numFramesIfRotating=30; final int numFramesIfStatic=2; final boolean isRotating = !Double.isInfinite(rotPeriod); int numAnimFrames = isRotating?numFramesIfRotating:numFramesIfStatic; if(isRotating) mainModel.setFrameDelayInMillis((int)(rotPeriod/(numAnimFrames))); final double animationDeltaRadians = isRotating? ((reverseDirection?1:-1)*(2 * Math.PI) / (double)numAnimFrames) :0; //FRAME LOOP for(int frameIndex=0; frameIndex<numAnimFrames; frameIndex++){ final Model m = new Model(false,tr); m.setDebugName("TunnelSegment frame "+frameIndex+" of "+numAnimFrames); final double frameAngleDeltaRadians = animationDeltaRadians * (double)frameIndex; double frameStartAngle = startAngle + frameAngleDeltaRadians; double frameEndAngle = endAngle + frameAngleDeltaRadians; final double frameStartAngle1 = startAngle1 + frameAngleDeltaRadians; final double frameStartAngle2 = startAngle2 + frameAngleDeltaRadians; final double frameEndAngle1 = endAngle + frameAngleDeltaRadians; double []thisU=noLightU,thisV=noLightV;//Changeable u/v references, default to noLight // Poly quads for (int pi = 0; pi < numPolygonsMinusOne; pi++) { Vector3D p0 = segPoint(frameStartAngle, zStart, startWidth, startHeight, startX, startY); Vector3D p1 = segPoint(frameEndAngle, zEnd, endWidth, endHeight, endX, endY); Vector3D p2 = segPoint(frameEndAngle + dAngleEnd, zEnd, endWidth, endHeight, endX, endY); Vector3D p3 = segPoint(frameStartAngle + dAngleStart, zStart, startWidth, startHeight, startX, startY); TextureDescription tex = tunnelTexturePalette [s.getPolyTextureIndices().get(pi)]; if (pi == lightPoly && lightType != FlickerLightType.noLight) { if(frameIndex==0){thisU=lightOnU; thisV=lightOnV;} else {thisU=lightOffU;thisV=lightOffV;} /*try { final int flickerThresh = flt == FlickerLightType.off1p5Sec ? (int) (-.3 * (double) Integer.MAX_VALUE) : flt == FlickerLightType.on1p5Sec ? (int) (.4 * (double) Integer.MAX_VALUE) : flt == FlickerLightType.on1Sec ? (int) (.25 * (double) Integer.MAX_VALUE) : Integer.MAX_VALUE; m.addTickableAnimator(new Tickable() { @Override public void tick() { if (flickerRandom.transfer(Math.abs((int) System .currentTimeMillis())) > flickerThresh) st.setFrame(1); else st.setFrame(0); } }); } catch (Exception e) { e.printStackTrace(); }*/ } else {thisU=noLightU; thisV=noLightV; }// No light m.addTriangles(Triangle.quad2Triangles( new double[] { p3.getX(), p2.getX(), p1.getX(), p0.getX() }, new double[] { p3.getY(), p2.getY(), p1.getY(), p0.getY() }, new double[] { p3.getZ(), p2.getZ(), p1.getZ(), p0.getZ() }, thisU, thisV, tex, RenderMode.DYNAMIC, new Vector3D[] { new Vector3D(Math.cos(frameStartAngle + dAngleStart), -Math.sin(frameStartAngle + dAngleStart), 0), new Vector3D(Math.cos(frameEndAngle + dAngleEnd), -Math .sin(frameEndAngle + dAngleEnd), 0), new Vector3D(Math.cos(frameEndAngle), -Math .sin(frameEndAngle), 0), new Vector3D(Math.cos(frameStartAngle), -Math .sin(frameStartAngle), 0) }, 0)); frameStartAngle += dAngleStart; frameEndAngle += dAngleEnd; }// for(polygons) if(s.isCutout()){ // The slice quad // INWARD Vector3D p0 = segPoint(frameStartAngle, zStart, startWidth, startHeight, startX, startY); Vector3D p1 = segPoint(frameEndAngle, zEnd, endWidth, endHeight, endX, endY); Vector3D p2 = segPoint(frameEndAngle1, zEnd, 0, 0, endX, endY); Vector3D p3 = segPoint(frameStartAngle1, zStart, 0, 0, startX, startY); m.addTriangles(Triangle.quad2Triangles( new double[] { p3.getX(), p2.getX(), p1.getX(), p0.getX() }, new double[] { p3.getY(), p2.getY(), p1.getY(), p0.getY() }, new double[] { p3.getZ(), p2.getZ(), p1.getZ(), p0.getZ() }, new double[] { 1, 1, 0, 0 }, new double[] { 0, 1, 1, 0 }, tunnelTexturePalette[s.getPolyTextureIndices().get( numPolygonsMinusOne)], RenderMode.DYNAMIC, new Vector3D[] { new Vector3D(Math.cos(frameStartAngle + dAngleStart), -Math.sin(frameStartAngle + dAngleStart), 0), new Vector3D(Math.cos(frameEndAngle + dAngleEnd), -Math .sin(frameEndAngle + dAngleEnd), 0), new Vector3D(Math.cos(frameEndAngle), -Math .sin(frameEndAngle), 0), new Vector3D(Math.cos(frameStartAngle), -Math .sin(frameStartAngle), 0)}, 0)); // OUTWARD p3 = segPoint(frameStartAngle1, zStart, startWidth, startHeight, startX, startY); p2 = segPoint(frameEndAngle1, zEnd, endWidth, endHeight, endX, endY); p1 = segPoint(frameEndAngle1, zEnd, 0, 0, endX, endY); p0 = segPoint(frameStartAngle1, zStart, 0, 0, startX, startY); m.addTriangles(Triangle.quad2Triangles( new double[] { p3.getX(), p2.getX(), p1.getX(), p0.getX() }, new double[] { p3.getY(), p2.getY(), p1.getY(), p0.getY() }, new double[] { p3.getZ(), p2.getZ(), p1.getZ(), p0.getZ() }, new double[] { 1, 1, 0, 0 }, new double[] { 0, 1, 1, 0 }, tunnelTexturePalette[s.getPolyTextureIndices().get( numPolygonsMinusOne)], RenderMode.DYNAMIC, new Vector3D[] { new Vector3D(Math.cos(frameStartAngle + dAngleStart), -Math.sin(frameStartAngle + dAngleStart), 0), new Vector3D(Math.cos(frameEndAngle + dAngleEnd), -Math .sin(frameEndAngle + dAngleEnd), 0), new Vector3D(Math.cos(frameEndAngle), -Math .sin(frameEndAngle), 0), new Vector3D(Math.cos(frameStartAngle), -Math .sin(frameStartAngle), 0) }, 0)); }else{ // The slice quad Vector3D p0 = segPoint(frameStartAngle, zStart, startWidth, startHeight, startX, startY); Vector3D p1 = segPoint(frameEndAngle, zEnd, endWidth, endHeight, endX, endY); Vector3D p2 = segPoint(frameEndAngle1, zEnd, endWidth, endHeight, endX, endY); Vector3D p3 = segPoint(frameStartAngle1, zStart, startWidth, startHeight, startX, startY); m.addTriangles(Triangle.quad2Triangles( new double[] { p3.getX(), p2.getX(), p1.getX(), p0.getX() }, new double[] { p3.getY(), p2.getY(), p1.getY(), p0.getY() }, new double[] { p3.getZ(), p2.getZ(), p1.getZ(), p0.getZ() }, new double[] { 1, 1, 0, 0 }, new double[] { 0, 1, 1, 0 }, tunnelTexturePalette[s.getPolyTextureIndices().get( numPolygonsMinusOne)], RenderMode.DYNAMIC, new Vector3D[] { new Vector3D(Math.cos(frameStartAngle + dAngleStart), -Math.sin(frameStartAngle + dAngleStart), 0), new Vector3D(Math.cos(frameEndAngle + dAngleEnd), -Math .sin(frameEndAngle + dAngleEnd), 0), new Vector3D(Math.cos(frameEndAngle), -Math .sin(frameEndAngle), 0), new Vector3D(Math.cos(frameStartAngle), -Math .sin(frameStartAngle), 0) }, 0)); }//end !cutout //if(numAnimFrames!=1)//Push frame if animated. mainModel.addFrame(m); }//end for(frames) return mainModel; }//end createModel() private static Vector3D segPoint(double angle, double z, double w, double h, double x, double y) { return new Vector3D(-Math.cos(angle) * w + x, Math.sin(angle) * h + y, z); } public Segment getSegmentData() { return segment; } public double getSegmentLength() { return segmentLength; } public double getEndX() { return endX; } public double getEndY() { return endY; } }// end TunnelSegment
package org.lantern; import java.io.IOException; import org.lantern.state.StaticSettings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.Singleton; @Singleton public class ChromeBrowserService implements BrowserService { private final Logger log = LoggerFactory.getLogger(getClass()); private static final int SCREEN_WIDTH = 970; private static final int SCREEN_HEIGHT = 630; private final ChromeRunner chrome = new ChromeRunner(SCREEN_WIDTH, SCREEN_HEIGHT); private final MessageService messageService; @Inject public ChromeBrowserService(final MessageService messageService) { this.messageService = messageService; } /** * Opens the browser. */ @Override public void openBrowser() { final Thread t = new Thread(new Runnable() { @Override public void run() { //buildBrowser(); launchChrome(StaticSettings.getApiPort(), StaticSettings.getPrefix()); } }, "Chrome-Browser-Launch-Thread"); t.setDaemon(true); t.start(); } /** * Opens the browser. * @param port */ @Override public void openBrowser(final int port, final String prefix) { final Thread t = new Thread(new Runnable() { @Override public void run() { //buildBrowser(); launchChrome(port, prefix); } }, "Chrome-Browser-Launch-Thread"); t.setDaemon(true); t.start(); } private void launchChrome(final int port, final String prefix) { log.info("Launching chrome..."); try { this.chrome.open(port, prefix); } catch (final IOException e) { log.error("Could not open chrome?", e); } catch (final UnsupportedOperationException e) { this.messageService.showMessage("Chrome Required", "We're sorry, but Lantern requires you to have Google Chrome " + "to run successfully. You can download Google Chrome from " + "https: "please restart Lantern."); System.exit(2); } } @Override public void openBrowserWhenPortReady() { final int port = StaticSettings.getApiPort(); final String prefix = StaticSettings.getPrefix(); log.info("Waiting on port: "+port); openBrowserWhenPortReady(port, prefix); } @Override public void openBrowserWhenPortReady(final int port, final String prefix) { log.debug("Waiting for server..."); final long start = System.currentTimeMillis(); LanternUtils.waitForServer(port); log.debug("Server is running. Opening browser on port: {} WAITED FOR " + "SERVER FOR {} ms", port, System.currentTimeMillis() - start); log.debug("OPENING BROWSER AFTER {} OF TOTAL START TIME...", System.currentTimeMillis() - Launcher.START_TIME); openBrowser(port, prefix); } @Override public void start() { } @Override public void stop() { if (this.chrome != null) { this.chrome.close(); } } @Override public void reopenBrowser() { stop(); openBrowser(); } }
package org.lightmare.deploy; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.ejb.Local; import javax.ejb.Remote; import javax.ejb.Stateless; import org.apache.log4j.Logger; import org.lightmare.cache.ArchiveData; import org.lightmare.cache.DeployData; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.cache.MetaContainer; import org.lightmare.cache.RestContainer; import org.lightmare.cache.TmpResources; import org.lightmare.config.ConfigKeys; import org.lightmare.config.Configuration; import org.lightmare.deploy.fs.Watcher; import org.lightmare.jpa.datasource.Initializer; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.libraries.LibraryLoader; import org.lightmare.remote.rpc.RPCall; import org.lightmare.remote.rpc.RpcListener; import org.lightmare.rest.providers.RestProvider; import org.lightmare.scannotation.AnnotationDB; import org.lightmare.utils.AbstractIOUtils; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.LogUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.fs.FileUtils; import org.lightmare.utils.fs.WatchUtils; import org.lightmare.utils.shutdown.ShutDown; /** * Determines and saves in cache EJB beans {@link org.lightmare.cache.MetaData} * on startup * * @author Levan * */ public class MetaCreator { private static AnnotationDB annotationDB; // Cached temporal resources for clean after deployment private TmpResources tmpResources; private boolean await; // Blocker for deployments connections or beans private CountDownLatch blocker; // Data for cache at deploy time private Map<String, AbstractIOUtils> aggregateds = new HashMap<String, AbstractIOUtils>(); private Map<URL, ArchiveData> archivesURLs; private Map<String, URL> classOwnersURL; private Map<URL, DeployData> realURL; private ClassLoader current; // Configuration for appropriate archives URLs private Configuration configuration; // Lock for deployment and directory scanning private final Lock scannerLock = new ReentrantLock(); // Lock for MetaCreator initialization private static final Lock LOCK = new ReentrantLock(); private static final Logger LOG = Logger.getLogger(MetaCreator.class); private MetaCreator() { tmpResources = new TmpResources(); ShutDown.setHook(tmpResources); } private static MetaCreator get() { MetaCreator creator = MetaContainer.getCreator(); if (creator == null) { LOCK.lock(); try { if (creator == null) { creator = new MetaCreator(); MetaContainer.setCreator(creator); } } finally { LOCK.unlock(); } } return creator; } private void configure(URL[] archives) { if (configuration == null && CollectionUtils.available(archives)) { configuration = MetaContainer.getConfig(archives); } } public AnnotationDB getAnnotationDB() { return annotationDB; } public Map<String, AbstractIOUtils> getAggregateds() { return aggregateds; } /** * Caches each archive by it's {@link URL} for deployment * * @param ejbURLs * @param archiveData */ private void fillArchiveURLs(Collection<URL> ejbURLs, ArchiveData archiveData, DeployData deployData) { for (URL ejbURL : ejbURLs) { archivesURLs.put(ejbURL, archiveData); realURL.put(ejbURL, deployData); } } /** * Caches each archive by it's {@link URL} for deployment and creates fill * {@link URL} array for scanning and finding {@link javax.ejb.Stateless} * annotated classes * * @param archive * @param modifiedArchives * @throws IOException */ private void fillArchiveURLs(URL archive, List<URL> modifiedArchives) throws IOException { AbstractIOUtils ioUtils = AbstractIOUtils.getAppropriatedType(archive); if (ObjectUtils.notNull(ioUtils)) { ioUtils.scan(configuration.isPersXmlFromJar()); List<URL> ejbURLs = ioUtils.getEjbURLs(); modifiedArchives.addAll(ejbURLs); ArchiveData archiveData = new ArchiveData(); archiveData.setIoUtils(ioUtils); DeployData deployData = new DeployData(); deployData.setType(ioUtils.getType()); deployData.setUrl(archive); if (ejbURLs.isEmpty()) { archivesURLs.put(archive, archiveData); realURL.put(archive, deployData); } else { fillArchiveURLs(ejbURLs, archiveData, deployData); } } } /** * Gets {@link URL} array for all classes and jar libraries within archive * file for class loading policy * * @param archives * @return {@link URL}[] * @throws IOException */ private URL[] getFullArchives(URL[] archives) throws IOException { List<URL> modifiedArchives = new ArrayList<URL>(); for (URL archive : archives) { fillArchiveURLs(archive, modifiedArchives); } return CollectionUtils.toArray(modifiedArchives, URL.class); } /** * Awaits for {@link Future} tasks if it set so by configuration * * @param future */ private void awaitDeployment(Future<String> future) { if (await) { try { String nameFromFuture = future.get(); LogUtils.info(LOG, "Deploy processing of %s finished", nameFromFuture); } catch (InterruptedException ex) { LOG.error(ex.getMessage(), ex); } catch (ExecutionException ex) { LOG.error(ex.getMessage(), ex); } } } /** * Awaits for {@link CountDownLatch} of deployments */ private void awaitDeployments() { try { blocker.await(); } catch (InterruptedException ex) { LOG.error(ex); } } /** * Starts bean deployment process for bean name * * @param beanName * @throws IOException */ private void deployBean(String beanName) throws IOException { URL currentURL = classOwnersURL.get(beanName); ArchiveData archiveData = archivesURLs.get(currentURL); if (archiveData == null) { archiveData = new ArchiveData(); } AbstractIOUtils ioUtils = archiveData.getIoUtils(); if (ioUtils == null) { ioUtils = AbstractIOUtils.getAppropriatedType(currentURL); archiveData.setIoUtils(ioUtils); } ClassLoader loader = archiveData.getLoader(); // Finds appropriated ClassLoader if needed and or creates new one List<File> tmpFiles = null; if (ObjectUtils.notNull(ioUtils)) { if (loader == null) { if (ioUtils.notExecuted()) { ioUtils.scan(configuration.isPersXmlFromJar()); } URL[] libURLs = ioUtils.getURLs(); loader = LibraryLoader.initializeLoader(libURLs); archiveData.setLoader(loader); } tmpFiles = ioUtils.getTmpFiles(); aggregateds.put(beanName, ioUtils); } // Archive file url which contains this bean DeployData deployData; if (CollectionUtils.available(realURL)) { deployData = realURL.get(currentURL); } else { deployData = null; } // Initializes and fills BeanLoader.BeanParameters class to deploy // stateless EJB bean BeanLoader.BeanParameters parameters = new BeanLoader.BeanParameters(); parameters.creator = this; parameters.className = beanName; parameters.loader = loader; parameters.tmpFiles = tmpFiles; parameters.blocker = blocker; parameters.deployData = deployData; parameters.configuration = configuration; Future<String> future = BeanLoader.loadBean(parameters); awaitDeployment(future); if (CollectionUtils.available(tmpFiles)) { tmpResources.addFile(tmpFiles); } } /** * Deploys single bean by class name * * @param beanNames */ private void deployBeans(Set<String> beanNames) { blocker = new CountDownLatch(beanNames.size()); for (String beanName : beanNames) { LogUtils.info(LOG, "Deploing bean %s", beanName); try { deployBean(beanName); } catch (IOException ex) { LogUtils.error(LOG, ex, "Could not deploy bean %s cause", beanName, ex.getMessage()); } } awaitDeployments(); if (RestContainer.hasRest()) { RestProvider.reload(); } boolean hotDeployment = configuration.isHotDeployment(); boolean watchStatus = configuration.isWatchStatus(); if (hotDeployment && ObjectUtils.notTrue(watchStatus)) { Watcher.startWatch(); watchStatus = Boolean.TRUE; } } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @param archives * @throws IOException * @throws ClassNotFoundException */ public void scanForBeans(URL[] archives) throws IOException { scannerLock.lock(); try { configure(archives); // starts RPC server if configured as remote and server if (configuration.isRemote() && Configuration.isServer()) { RpcListener.startServer(configuration); } else if (configuration.isRemote()) { RPCall.configure(configuration); } String[] libraryPaths = configuration.getLibraryPaths(); // Loads libraries from specified path if (ObjectUtils.notNull(libraryPaths)) { LibraryLoader.loadLibraries(libraryPaths); } // Gets and caches class loader current = LibraryLoader.getContextClassLoader(); archivesURLs = new HashMap<URL, ArchiveData>(); if (CollectionUtils.available(archives)) { realURL = new HashMap<URL, DeployData>(); } URL[] fullArchives = getFullArchives(archives); annotationDB = new AnnotationDB(); annotationDB.setScanFieldAnnotations(Boolean.FALSE); annotationDB.setScanParameterAnnotations(Boolean.FALSE); annotationDB.setScanMethodAnnotations(Boolean.FALSE); annotationDB.scanArchives(fullArchives); Set<String> beanNames = annotationDB.getAnnotationIndex().get( Stateless.class.getName()); classOwnersURL = annotationDB.getClassOwnersURLs(); Initializer.initializeDataSources(configuration); if (CollectionUtils.available(beanNames)) { deployBeans(beanNames); } } finally { // Caches configuration MetaContainer.putConfig(archives, configuration); // clears cached resources clear(); // gets rid from all created temporary files tmpResources.removeTempFiles(); scannerLock.unlock(); } } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @throws ClassNotFoundException * @throws IOException */ public void scanForBeans(File[] jars) throws IOException { List<URL> urlList = new ArrayList<URL>(); URL url; for (File file : jars) { url = file.toURI().toURL(); urlList.add(url); } URL[] archives = CollectionUtils.toArray(urlList, URL.class); scanForBeans(archives); } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @throws ClassNotFoundException * @throws IOException */ public void scanForBeans(String... paths) throws IOException { if (CollectionUtils.notAvailable(paths) && CollectionUtils.available(configuration.getDeploymentPath())) { Set<DeploymentDirectory> deployments = configuration .getDeploymentPath(); List<String> pathList = new ArrayList<String>(); File deployFile; for (DeploymentDirectory deployment : deployments) { deployFile = new File(deployment.getPath()); if (deployment.isScan()) { String[] subDeployments = deployFile.list(); if (CollectionUtils.available(subDeployments)) { pathList.addAll(Arrays.asList(subDeployments)); } } } paths = CollectionUtils.toArray(pathList, String.class); } List<URL> urlList = new ArrayList<URL>(); List<URL> archive; for (String path : paths) { archive = FileUtils.toURLWithClasspath(path); urlList.addAll(archive); } URL[] archives = CollectionUtils.toArray(urlList, URL.class); scanForBeans(archives); } public ClassLoader getCurrent() { return current; } /** * Clears all locally cached data */ public void clear() { boolean locked = scannerLock.tryLock(); while (ObjectUtils.notTrue(locked)) { locked = scannerLock.tryLock(); } if (locked) { try { if (ObjectUtils.available(realURL)) { realURL.clear(); realURL = null; } if (ObjectUtils.available(aggregateds)) { aggregateds.clear(); } if (ObjectUtils.available(archivesURLs)) { archivesURLs.clear(); archivesURLs = null; } if (ObjectUtils.available(classOwnersURL)) { classOwnersURL.clear(); classOwnersURL = null; } configuration = null; } finally { scannerLock.unlock(); } } } /** * Closes all connections clears all caches * * @throws IOException */ public static void close() throws IOException { ShutDown.clearAll(); } /** * Builder class to provide properties for lightmare application and * initialize {@link MetaCreator} instance * * @author levan * */ public static class Builder { private MetaCreator creator; public Builder(boolean cloneConfiguration) throws IOException { creator = MetaCreator.get(); Configuration config = creator.configuration; if (cloneConfiguration && ObjectUtils.notNull(config)) { try { creator.configuration = (Configuration) config.clone(); } catch (CloneNotSupportedException ex) { throw new IOException(ex); } } else { creator.configuration = new Configuration(); } } public Builder() throws IOException { this(Boolean.FALSE); } public Builder(Map<Object, Object> configuration) throws IOException { this(); creator.configuration.configure(configuration); } public Builder(String path) throws IOException { this(); creator.configuration.configure(path); } private Map<Object, Object> initPersistenceProperties() { Map<Object, Object> persistenceProperties = creator.configuration .getPersistenceProperties(); if (persistenceProperties == null) { persistenceProperties = new HashMap<Object, Object>(); creator.configuration .setPersistenceProperties(persistenceProperties); } return persistenceProperties; } /** * Sets additional persistence properties * * @param properties * @return {@link Builder} */ public Builder setPersistenceProperties(Map<String, String> properties) { if (ObjectUtils.available(properties)) { Map<Object, Object> persistenceProperties = initPersistenceProperties(); persistenceProperties.putAll(properties); } return this; } /** * Adds instant persistence property * * @param key * @param property * @return {@link Builder} */ public Builder addPersistenceProperty(String key, String property) { Map<Object, Object> persistenceProperties = initPersistenceProperties(); persistenceProperties.put(key, property); return this; } /** * Adds property to scan for {@link javax.persistence.Entity} annotated * classes from deployed archives * * @param scanForEnt * @return {@link Builder} */ public Builder setScanForEntities(boolean scanForEnt) { creator.configuration.setScanForEntities(scanForEnt); return this; } /** * Adds property to use only {@link org.lightmare.annotations.UnitName} * annotated entities for which * {@link org.lightmare.annotations.UnitName#value()} matches passed * unit name * * @param unitName * @return {@link Builder} */ public Builder setUnitName(String unitName) { creator.configuration.setAnnotatedUnitName(unitName); return this; } /** * Sets path for persistence.xml file * * @param path * @return {@link Builder} */ public Builder setPersXmlPath(String path) { creator.configuration.setPersXmlPath(path); creator.configuration.setScanArchives(Boolean.FALSE); return this; } /** * Adds path for additional libraries to load at start time * * @param libPaths * @return {@link Builder} */ public Builder setLibraryPath(String... libPaths) { creator.configuration.setLibraryPaths(libPaths); return this; } /** * Sets boolean checker to scan persistence.xml files from appropriated * jar files * * @param xmlFromJar * @return {@link Builder} */ public Builder setXmlFromJar(boolean xmlFromJar) { creator.configuration.setPersXmlFromJar(xmlFromJar); return this; } /** * Sets boolean checker to swap jta data source value with non jta data * source value * * @param swapDataSource * @return {@link Builder} */ public Builder setSwapDataSource(boolean swapDataSource) { creator.configuration.setSwapDataSource(swapDataSource); return this; } /** * Adds path for data source file * * @param dataSourcePath * @return {@link Builder} */ public Builder addDataSourcePath(String dataSourcePath) { creator.configuration.addDataSourcePath(dataSourcePath); return this; } /** * This method is deprecated should use * {@link MetaCreator.Builder#addDataSourcePath(String)} instead * * @param dataSourcePath * @return {@link MetaCreator.Builder} */ @Deprecated public Builder setDataSourcePath(String dataSourcePath) { creator.configuration.addDataSourcePath(dataSourcePath); return this; } /** * Sets boolean checker to scan {@link javax.persistence.Entity} * annotated classes from appropriated deployed archive files * * @param scanArchives * @return {@link Builder} */ public Builder setScanArchives(boolean scanArchives) { creator.configuration.setScanArchives(scanArchives); return this; } /** * Sets boolean checker to block deployment processes * * @param await * @return {@link Builder} */ public Builder setAwaitDeploiment(boolean await) { creator.await = await; return this; } /** * Sets property is server or not in embedded mode * * @param remote * @return {@link Builder} */ public Builder setRemote(boolean remote) { creator.configuration.setRemote(remote); return this; } /** * Sets property is application server or just client for other remote * server * * @param server * @return {@link Builder} */ public Builder setServer(boolean server) { Configuration.setServer(server); creator.configuration.setClient(ObjectUtils.notTrue(server)); return this; } /** * Sets boolean check is application in just client mode or not * * @param client * @return {@link Builder} */ public Builder setClient(boolean client) { creator.configuration.setClient(client); Configuration.setServer(ObjectUtils.notTrue(client)); return this; } /** * To add any additional property * * @param key * @param property * @return {@link Builder} */ public Builder setProperty(String key, String property) { creator.configuration.putValue(key, property); return this; } /** * File path for administrator user name and password * * @param property * @return {@link Builder} */ public Builder setAdminUsersPth(String property) { Configuration.setAdminUsersPath(property); return this; } /** * Sets specific IP address in case when application is in remote server * mode * * @param property * @return {@link Builder} */ public Builder setIpAddress(String property) { creator.configuration.putValue(ConfigKeys.IP_ADDRESS.key, property); return this; } /** * Sets specific port in case when application is in remote server mode * * @param property * @return {@link Builder} */ public Builder setPort(String property) { creator.configuration.putValue(ConfigKeys.PORT.key, property); return this; } /** * Sets amount for network master threads in case when application is in * remote server mode * * @param property * @return {@link Builder} */ public Builder setMasterThreads(String property) { creator.configuration.putValue(ConfigKeys.BOSS_POOL.key, property); return this; } /** * Sets amount of worker threads in case when application is in remote * server mode * * @param property * @return {@link Builder} */ public Builder setWorkerThreads(String property) { creator.configuration .putValue(ConfigKeys.WORKER_POOL.key, property); return this; } /** * Adds deploy file path to application with boolean checker if file is * directory to scan this directory for deployment files list * * @param deploymentPath * @param scan * @return {@link Builder} */ public Builder addDeploymentPath(String deploymentPath, boolean scan) { String clearPath = WatchUtils.clearPath(deploymentPath); creator.configuration.addDeploymentPath(clearPath, scan); return this; } /** * Adds deploy file path to application * * @param deploymentPath * @return {@link Builder} */ public Builder addDeploymentPath(String deploymentPath) { addDeploymentPath(deploymentPath, Boolean.FALSE); return this; } /** * Adds timeout for connection in case when application is in remote * server or client mode * * @param property * @return {@link Builder} */ public Builder setTimeout(String property) { creator.configuration.putValue(ConfigKeys.CONNECTION_TIMEOUT.key, property); return this; } /** * Adds boolean check if application is using pooled data source * * @param dsPooledType * @return {@link Builder} */ public Builder setDataSourcePooledType(boolean dsPooledType) { creator.configuration.setDataSourcePooledType(dsPooledType); return this; } /** * Sets which data source pool provider should use application by * {@link PoolProviderType} parameter * * @param poolProviderType * @return {@link Builder} */ public Builder setPoolProviderType(PoolProviderType poolProviderType) { creator.configuration.setPoolProviderType(poolProviderType); return this; } /** * Sets path for data source pool additional properties * * @param path * @return {@link Builder} */ public Builder setPoolPropertiesPath(String path) { creator.configuration.setPoolPropertiesPath(path); return this; } /** * Sets data source pool additional properties * * @param properties * @return {@link Builder} */ public Builder setPoolProperties( Map<? extends Object, ? extends Object> properties) { creator.configuration.setPoolProperties(properties); return this; } /** * Adds instance property for pooled data source * * @param key * @param value * @return {@link Builder} */ public Builder addPoolProperty(Object key, Object value) { creator.configuration.addPoolProperty(key, value); return this; } /** * Sets boolean check is application in hot deployment (with watch * service on deployment directories) or not * * @param hotDeployment * @return {@link Builder} */ public Builder setHotDeployment(boolean hotDeployment) { creator.configuration.setHotDeployment(hotDeployment); return this; } /** * Adds additional parameters from passed {@link Map} to existing * configuration * * @param configuration * @return */ public Builder addConfiguration(Map<Object, Object> configuration) { creator.configuration.configure(configuration); return this; } public MetaCreator build() throws IOException { creator.configuration.configure(); LOG.info("Lightmare application starts working"); return creator; } } }
package org.ndexbio.model.object; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonSubTypes.Type; import com.fasterxml.jackson.annotation.JsonTypeInfo; @JsonIgnoreProperties(ignoreUnknown = true) @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "accountType") @JsonSubTypes(value = { @Type(value = Group.class, name = "Group"), @Type(value = User.class, name = "User") }) public abstract class Account extends NdexExternalObject implements PropertiedObject { private String _imageURL; private String _description; private String _website; private String _accountName; private String _password; public Account() { super(); } public String getImage() { return _imageURL; } public void setImage(String imageURL) { _imageURL = imageURL; } public String getDescription() { return _description; } public void setDescription(String description) { _description = description; } public String getWebsite() { return _website; } public void setWebsite(String website) { _website = website; } private List<NdexProperty> _properties; private List<NdexProperty> _presentationProperties; public List<NdexProperty> getProperties() { return _properties; } public List<NdexProperty> getPresentationProperties() { return _presentationProperties; } public void setProperties(List<NdexProperty> properties) { _properties = properties; } public void setPresentationProperties(List<NdexProperty> properties) { _presentationProperties = properties; } public String getAccountName() { return _accountName; } public void setAccountName(String _accountName) { this._accountName = _accountName; } public String getPassword() { return _password; } public void setPassword(String _password) { this._password = _password; } }
package org.scijava.console; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import org.scijava.command.CommandInfo; import org.scijava.log.LogService; import org.scijava.module.ModuleInfo; import org.scijava.module.ModuleItem; /** * Helper class for {@link ConsoleArgument}s. * * @author Mark Hiner hinerm at gmail.com */ public final class ConsoleUtils { /** * @see #parseParameterString(String, ModuleInfo, LogService) */ public static Map<String, Object> parseParameterString(final String parameterString) { return parseParameterString(parameterString, (CommandInfo)null); } /** * @see #parseParameterString(String, ModuleInfo, LogService) */ public static Map<String, Object> parseParameterString(final String parameterString, final ModuleInfo info) { return parseParameterString(parameterString, info, null); } /** * @see #parseParameterString(String, ModuleInfo, LogService) */ public static Map<String, Object> parseParameterString(final String parameterString, final LogService logService) { return parseParameterString(parameterString, null, logService); } /** * Helper method for turning a parameter string into a {@code Map} of * key:value pairs. If a {@link ModuleInfo} is provided, the parameter * string is assumed to be a comma-separated list of values, ordered * according to the {@code ModuleInfo's} inputs. Otherwise, the parameter * string is assumed to be a comma-separated list of "key=value" pairs. * * TODO reconcile with attribute parsing of {@link ScriptInfo} */ public static Map<String, Object> parseParameterString(final String parameterString, final ModuleInfo info, final LogService logService) { final Map<String, Object> inputMap = new HashMap<String, Object>(); if (!parameterString.isEmpty()) { Iterator<ModuleItem<?>> inputs = null; if (info != null) { inputs = info.inputs().iterator(); } final String[] pairs = parameterString.split(","); for (final String pair : pairs) { final String[] split = pair.split("="); if (split.length == 2) inputMap.put(split[0], split[1]); else if (inputs != null && inputs.hasNext() && split.length == 1) { inputMap.put(inputs.next().getName(), split[0]); } else if (logService != null) logService.error("Parameters must be formatted as a comma-separated list of key=value pairs"); } } return inputMap; } /** * Test if the next argument is an appropriate parameter to a * {@link ConsoleArgument}. * * @return {@code true} if the first argument of the given list does not * start with a {@code '-'} character. */ public static boolean hasParam(final LinkedList<String> args) { return !(args.isEmpty() || args.getFirst().startsWith("-")); } }
package org.spongepowered.mod; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.ChatComponentText; import net.minecraft.world.WorldServer; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.fml.common.FMLCommonHandler; import org.spongepowered.api.Game; import org.spongepowered.api.GameRegistry; import org.spongepowered.api.Platform; import org.spongepowered.api.entity.player.Player; import org.spongepowered.api.plugin.PluginManager; import org.spongepowered.api.service.ServiceManager; import org.spongepowered.api.service.command.CommandService; import org.spongepowered.api.service.event.EventManager; import org.spongepowered.api.service.scheduler.Scheduler; import org.spongepowered.api.text.message.Message; import org.spongepowered.api.util.annotation.NonnullByDefault; import org.spongepowered.api.world.World; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.UUID; import javax.annotation.Nullable; import javax.inject.Inject; @NonnullByDefault public final class SpongeGame implements Game { @Nullable private static final String apiVersion = Game.class.getPackage().getImplementationVersion(); @Nullable private static final String implementationVersion = SpongeGame.class.getPackage().getImplementationVersion(); private final PluginManager pluginManager; private final EventManager eventManager; private final GameRegistry gameRegistry; @Inject public SpongeGame(PluginManager plugin, EventManager event, GameRegistry registry) { pluginManager = plugin; eventManager = event; gameRegistry = registry; } @Override public Platform getPlatform() { switch (FMLCommonHandler.instance().getEffectiveSide()) { case CLIENT: return Platform.CLIENT; default: return Platform.SERVER; } } @Override public PluginManager getPluginManager() { return pluginManager; } @Override public EventManager getEventManager() { return eventManager; } @Override public Collection<World> getWorlds() { List<World> worlds = new ArrayList<World>(); for (WorldServer worldServer : DimensionManager.getWorlds()) { worlds.add((World) worldServer); } return worlds; } @Override public World getWorld(UUID uniqueId) { // TODO: This needs to map to world id's somehow throw new UnsupportedOperationException(); } @Override public World getWorld(String worldName) { for (World world : getWorlds()) { if (world.getName().equals(worldName)) { return world; } } return null; } @Override public void broadcastMessage(Message<?> message) { @Nullable MinecraftServer server = getServer(); if (server != null) { // TODO: Revisit this when text API is actually implemented. server.getConfigurationManager().sendChatMsg(new ChatComponentText((String) message.getContent())); } } @Override public String getAPIVersion() { return apiVersion != null ? apiVersion : "UNKNOWN"; } @Override public String getImplementationVersion() { return implementationVersion != null ? implementationVersion : "UNKNOWN"; } @Override public GameRegistry getRegistry() { return gameRegistry; } @Override public ServiceManager getServiceManager() { throw new UnsupportedOperationException(); } @Override public Scheduler getScheduler() { throw new UnsupportedOperationException(); } @Override public CommandService getCommandDispatcher() { throw new UnsupportedOperationException(); } @Override @SuppressWarnings("unchecked") public Collection<Player> getOnlinePlayers() { @Nullable MinecraftServer server = getServer(); if (server != null) { return ImmutableList.copyOf((List<Player>)server.getConfigurationManager().playerEntityList); } else { throw new IllegalStateException("There is no running server."); } } @Override public int getMaxPlayers() { @Nullable MinecraftServer server = getServer(); if (server != null) { return server.getMaxPlayers(); } else { throw new IllegalStateException("There is no running server."); } } @Override public Optional<Player> getPlayer(UUID uniqueId) { @Nullable MinecraftServer server = getServer(); if (server != null) { return Optional.fromNullable((Player) server.getConfigurationManager().func_177451_a(uniqueId)); } else { return Optional.absent(); } } @Override public Optional<Player> getPlayer(String name) { @Nullable MinecraftServer server = getServer(); if (server != null) { return Optional.fromNullable((Player) server.getConfigurationManager().getPlayerByUsername(name)); } else { return Optional.absent(); } } @Nullable public MinecraftServer getServer() { return FMLCommonHandler.instance().getMinecraftServerInstance(); } }
package pl.koziolekweb.sqrlaw.utils; import java.util.ArrayList; import java.util.Collection; import java.util.Random; import java.util.stream.Collectors; /** * TODO write JAVADOC!!! * User: koziolek */ public interface Dice { public static final Dice K4 = () -> 4; public static final Dice K6 = () -> 6; public static final Dice K8 = () -> 8; public static final Dice K10 = () -> 10; public static final Dice K12 = () -> 12; public static final Dice K20 = () -> 20; static final Random RANDOM = new Random(); int maxDots(); default Integer throwDice() { return RANDOM.nextInt(maxDots()); } default Collection<Integer> throwDice(long nb) { return RANDOM.ints(nb, 1, maxDots() + 1).boxed().collect(Collectors.toCollection(ArrayList::new)); } }
package redis.clients.jedis; import static redis.clients.jedis.Protocol.toByteArray; import static redis.clients.jedis.Protocol.Command.*; import static redis.clients.jedis.Protocol.Keyword.LIMIT; import static redis.clients.jedis.Protocol.Keyword.NO; import static redis.clients.jedis.Protocol.Keyword.ONE; import static redis.clients.jedis.Protocol.Keyword.STORE; import static redis.clients.jedis.Protocol.Keyword.WITHSCORES; import java.util.ArrayList; import java.util.List; import java.util.Map; import redis.clients.jedis.Protocol.Command; import redis.clients.jedis.Protocol.Keyword; import redis.clients.util.SafeEncoder; public class BinaryClient extends Connection { public enum LIST_POSITION { BEFORE, AFTER; public final byte[] raw; private LIST_POSITION() { raw = SafeEncoder.encode(name()); } } private boolean isInMulti; private String password; private long db; public boolean isInMulti() { return isInMulti; } public BinaryClient(final String host) { super(host); } public BinaryClient(final String host, final int port) { super(host, port); } public void setPassword(final String password) { this.password = password; } @Override public void connect() { if (!isConnected()) { super.connect(); if (password != null) { auth(password); getStatusCodeReply(); } if (db > 0) { select(Long.valueOf(db).intValue()); getStatusCodeReply(); } } } public void ping() { sendCommand(PING); } public void set(final byte[] key, final byte[] value) { sendCommand(Command.SET, key, value); } public void get(final byte[] key) { sendCommand(Command.GET, key); } public void quit() { db = 0; sendCommand(QUIT); } public void exists(final byte[] key) { sendCommand(EXISTS, key); } public void del(final byte[]... keys) { sendCommand(DEL, keys); } public void type(final byte[] key) { sendCommand(TYPE, key); } public void flushDB() { sendCommand(FLUSHDB); } public void keys(final byte[] pattern) { sendCommand(KEYS, pattern); } public void randomKey() { sendCommand(RANDOMKEY); } public void rename(final byte[] oldkey, final byte[] newkey) { sendCommand(RENAME, oldkey, newkey); } public void renamenx(final byte[] oldkey, final byte[] newkey) { sendCommand(RENAMENX, oldkey, newkey); } public void dbSize() { sendCommand(DBSIZE); } public void expire(final byte[] key, final int seconds) { sendCommand(EXPIRE, key, toByteArray(seconds)); } public void expireAt(final byte[] key, final long unixTime) { sendCommand(EXPIREAT, key, toByteArray(unixTime)); } public void ttl(final byte[] key) { sendCommand(TTL, key); } public void select(final int index) { db = index; sendCommand(SELECT, toByteArray(index)); } public void move(final byte[] key, final int dbIndex) { sendCommand(MOVE, key, toByteArray(dbIndex)); } public void flushAll() { sendCommand(FLUSHALL); } public void getSet(final byte[] key, final byte[] value) { sendCommand(GETSET, key, value); } public void mget(final byte[]... keys) { sendCommand(MGET, keys); } public void setnx(final byte[] key, final byte[] value) { sendCommand(SETNX, key, value); } public void setex(final byte[] key, final int seconds, final byte[] value) { sendCommand(SETEX, key, toByteArray(seconds), value); } public void mset(final byte[]... keysvalues) { sendCommand(MSET, keysvalues); } public void msetnx(final byte[]... keysvalues) { sendCommand(MSETNX, keysvalues); } public void decrBy(final byte[] key, final long integer) { sendCommand(DECRBY, key, toByteArray(integer)); } public void decr(final byte[] key) { sendCommand(DECR, key); } public void incrBy(final byte[] key, final long integer) { sendCommand(INCRBY, key, toByteArray(integer)); } public void incr(final byte[] key) { sendCommand(INCR, key); } public void append(final byte[] key, final byte[] value) { sendCommand(APPEND, key, value); } public void substr(final byte[] key, final int start, final int end) { sendCommand(SUBSTR, key, toByteArray(start), toByteArray(end)); } public void hset(final byte[] key, final byte[] field, final byte[] value) { sendCommand(HSET, key, field, value); } public void hget(final byte[] key, final byte[] field) { sendCommand(HGET, key, field); } public void hsetnx(final byte[] key, final byte[] field, final byte[] value) { sendCommand(HSETNX, key, field, value); } public void hmset(final byte[] key, final Map<byte[], byte[]> hash) { final List<byte[]> params = new ArrayList<byte[]>(); params.add(key); for (final byte[] field : hash.keySet()) { params.add(field); params.add(hash.get(field)); } sendCommand(HMSET, params.toArray(new byte[params.size()][])); } public void hmget(final byte[] key, final byte[]... fields) { final byte[][] params = new byte[fields.length + 1][]; params[0] = key; System.arraycopy(fields, 0, params, 1, fields.length); sendCommand(HMGET, params); } public void hincrBy(final byte[] key, final byte[] field, final long value) { sendCommand(HINCRBY, key, field, toByteArray(value)); } public void hexists(final byte[] key, final byte[] field) { sendCommand(HEXISTS, key, field); } public void hdel(final byte[] key, final byte[] field) { sendCommand(HDEL, key, field); } public void hlen(final byte[] key) { sendCommand(HLEN, key); } public void hkeys(final byte[] key) { sendCommand(HKEYS, key); } public void hvals(final byte[] key) { sendCommand(HVALS, key); } public void hgetAll(final byte[] key) { sendCommand(HGETALL, key); } public void rpush(final byte[] key, final byte[] string) { sendCommand(RPUSH, key, string); } public void lpush(final byte[] key, final byte[] string) { sendCommand(LPUSH, key, string); } public void llen(final byte[] key) { sendCommand(LLEN, key); } public void lrange(final byte[] key, final long start, final long end) { sendCommand(LRANGE, key, toByteArray(start), toByteArray(end)); } public void ltrim(final byte[] key, final long start, final long end) { sendCommand(LTRIM, key, toByteArray(start), toByteArray(end)); } public void lindex(final byte[] key, final long index) { sendCommand(LINDEX, key, toByteArray(index)); } public void lset(final byte[] key, final long index, final byte[] value) { sendCommand(LSET, key, toByteArray(index), value); } public void lrem(final byte[] key, long count, final byte[] value) { sendCommand(LREM, key, toByteArray(count), value); } public void lpop(final byte[] key) { sendCommand(LPOP, key); } public void rpop(final byte[] key) { sendCommand(RPOP, key); } public void rpoplpush(final byte[] srckey, final byte[] dstkey) { sendCommand(RPOPLPUSH, srckey, dstkey); } public void sadd(final byte[] key, final byte[] member) { sendCommand(SADD, key, member); } public void smembers(final byte[] key) { sendCommand(SMEMBERS, key); } public void srem(final byte[] key, final byte[] member) { sendCommand(SREM, key, member); } public void spop(final byte[] key) { sendCommand(SPOP, key); } public void smove(final byte[] srckey, final byte[] dstkey, final byte[] member) { sendCommand(SMOVE, srckey, dstkey, member); } public void scard(final byte[] key) { sendCommand(SCARD, key); } public void sismember(final byte[] key, final byte[] member) { sendCommand(SISMEMBER, key, member); } public void sinter(final byte[]... keys) { sendCommand(SINTER, keys); } public void sinterstore(final byte[] dstkey, final byte[]... keys) { final byte[][] params = new byte[keys.length + 1][]; params[0] = dstkey; System.arraycopy(keys, 0, params, 1, keys.length); sendCommand(SINTERSTORE, params); } public void sunion(final byte[]... keys) { sendCommand(SUNION, keys); } public void sunionstore(final byte[] dstkey, final byte[]... keys) { byte[][] params = new byte[keys.length + 1][]; params[0] = dstkey; System.arraycopy(keys, 0, params, 1, keys.length); sendCommand(SUNIONSTORE, params); } public void sdiff(final byte[]... keys) { sendCommand(SDIFF, keys); } public void sdiffstore(final byte[] dstkey, final byte[]... keys) { byte[][] params = new byte[keys.length + 1][]; params[0] = dstkey; System.arraycopy(keys, 0, params, 1, keys.length); sendCommand(SDIFFSTORE, params); } public void srandmember(final byte[] key) { sendCommand(SRANDMEMBER, key); } public void zadd(final byte[] key, final double score, final byte[] member) { sendCommand(ZADD, key, toByteArray(score), member); } public void zrange(final byte[] key, final int start, final int end) { sendCommand(ZRANGE, key, toByteArray(start), toByteArray(end)); } public void zrem(final byte[] key, final byte[] member) { sendCommand(ZREM, key, member); } public void zincrby(final byte[] key, final double score, final byte[] member) { sendCommand(ZINCRBY, key, toByteArray(score), member); } public void zrank(final byte[] key, final byte[] member) { sendCommand(ZRANK, key, member); } public void zrevrank(final byte[] key, final byte[] member) { sendCommand(ZREVRANK, key, member); } public void zrevrange(final byte[] key, final int start, final int end) { sendCommand(ZREVRANGE, key, toByteArray(start), toByteArray(end)); } public void zrangeWithScores(final byte[] key, final int start, final int end) { sendCommand(ZRANGE, key, toByteArray(start), toByteArray(end), WITHSCORES.raw); } public void zrevrangeWithScores(final byte[] key, final int start, final int end) { sendCommand(ZREVRANGE, key, toByteArray(start), toByteArray(end), WITHSCORES.raw); } public void zcard(final byte[] key) { sendCommand(ZCARD, key); } public void zscore(final byte[] key, final byte[] member) { sendCommand(ZSCORE, key, member); } public void multi() { sendCommand(MULTI); isInMulti = true; } public void discard() { sendCommand(DISCARD); isInMulti = false; } public void exec() { sendCommand(EXEC); isInMulti = false; } public void watch(final byte[]... keys) { sendCommand(WATCH, keys); } public void unwatch() { sendCommand(UNWATCH); } public void sort(final byte[] key) { sendCommand(SORT, key); } public void sort(final byte[] key, final SortingParams sortingParameters) { final List<byte[]> args = new ArrayList<byte[]>(); args.add(key); args.addAll(sortingParameters.getParams()); sendCommand(SORT, args.toArray(new byte[args.size()][])); } public void blpop(final byte[][] args) { sendCommand(BLPOP, args); } public void sort(final byte[] key, final SortingParams sortingParameters, final byte[] dstkey) { final List<byte[]> args = new ArrayList<byte[]>(); args.add(key); args.addAll(sortingParameters.getParams()); args.add(STORE.raw); args.add(dstkey); sendCommand(SORT, args.toArray(new byte[args.size()][])); } public void sort(final byte[] key, final byte[] dstkey) { sendCommand(SORT, key, STORE.raw, dstkey); } public void brpop(final byte[][] args) { sendCommand(BRPOP, args); } public void auth(final String password) { setPassword(password); sendCommand(AUTH, password); } public void subscribe(final byte[]... channels) { sendCommand(SUBSCRIBE, channels); } public void publish(final byte[] channel, final byte[] message) { sendCommand(PUBLISH, channel, message); } public void unsubscribe() { sendCommand(UNSUBSCRIBE); } public void unsubscribe(final byte[]... channels) { sendCommand(UNSUBSCRIBE, channels); } public void psubscribe(final byte[]... patterns) { sendCommand(PSUBSCRIBE, patterns); } public void punsubscribe() { sendCommand(PUNSUBSCRIBE); } public void punsubscribe(final byte[]... patterns) { sendCommand(PUNSUBSCRIBE, patterns); } public void zcount(final byte[] key, final double min, final double max) { byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); sendCommand(ZCOUNT, key, byteArrayMin, byteArrayMax); } public void zcount(final byte[] key, final byte min[], final byte max[]) { sendCommand(ZCOUNT, key, min, max); } public void zcount(final byte[] key, final String min, final String max) { sendCommand(ZCOUNT, key, min.getBytes(), max.getBytes()); } public void zrangeByScore(final byte[] key, final double min, final double max) { byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); sendCommand(ZRANGEBYSCORE, key, byteArrayMin, byteArrayMax); } public void zrangeByScore(final byte[] key, final byte[] min, final byte[] max) { sendCommand(ZRANGEBYSCORE, key, min, max); } public void zrangeByScore(final byte[] key, final String min, final String max) { sendCommand(ZRANGEBYSCORE, key, min.getBytes(), max.getBytes()); } public void zrevrangeByScore(final byte[] key, final double max, final double min) { byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); sendCommand(ZREVRANGEBYSCORE, key, byteArrayMax, byteArrayMin); } public void zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min) { sendCommand(ZREVRANGEBYSCORE, key, max, min); } public void zrevrangeByScore(final byte[] key, final String max, final String min) { sendCommand(ZREVRANGEBYSCORE, key, max.getBytes(), min.getBytes()); } public void zrangeByScore(final byte[] key, final double min, final double max, final int offset, int count) { byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); sendCommand(ZRANGEBYSCORE, key, byteArrayMin, byteArrayMax, LIMIT.raw, toByteArray(offset), toByteArray(count)); } public void zrangeByScore(final byte[] key, final byte min[], final byte max[], final int offset, int count) { sendCommand(ZRANGEBYSCORE, key, min, max, LIMIT.raw, toByteArray(offset), toByteArray(count)); } public void zrangeByScore(final byte[] key, final String min, final String max, final int offset, int count) { sendCommand(ZRANGEBYSCORE, key, min.getBytes(), max.getBytes(), LIMIT.raw, toByteArray(offset), toByteArray(count)); } public void zrevrangeByScore(final byte[] key, final double max, final double min, final int offset, int count) { byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); sendCommand(ZREVRANGEBYSCORE, key, byteArrayMax, byteArrayMin, LIMIT.raw, toByteArray(offset), toByteArray(count)); } public void zrevrangeByScore(final byte[] key, final byte max[], final byte min[], final int offset, int count) { sendCommand(ZREVRANGEBYSCORE, key, max, min, LIMIT.raw, toByteArray(offset), toByteArray(count)); } public void zrevrangeByScore(final byte[] key, final String max, final String min, final int offset, int count) { sendCommand(ZREVRANGEBYSCORE, key, max.getBytes(), min.getBytes(), LIMIT.raw, toByteArray(offset), toByteArray(count)); } public void zrangeByScoreWithScores(final byte[] key, final double min, final double max) { byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); sendCommand(ZRANGEBYSCORE, key, byteArrayMin, byteArrayMax, WITHSCORES.raw); } public void zrangeByScoreWithScores(final byte[] key, final byte min[], final byte max[]) { sendCommand(ZRANGEBYSCORE, key, min, max, WITHSCORES.raw); } public void zrangeByScoreWithScores(final byte[] key, final String min, final String max) { sendCommand(ZRANGEBYSCORE, key, min.getBytes(), max.getBytes(), WITHSCORES.raw); } public void zrevrangeByScoreWithScores(final byte[] key, final double max, final double min) { byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); sendCommand(ZREVRANGEBYSCORE, key, byteArrayMax, byteArrayMin, WITHSCORES.raw); } public void zrevrangeByScoreWithScores(final byte[] key, final byte max[], final byte min[]) { sendCommand(ZREVRANGEBYSCORE, key, max, min, WITHSCORES.raw); } public void zrevrangeByScoreWithScores(final byte[] key, final String max, final String min) { sendCommand(ZREVRANGEBYSCORE, key, max.getBytes(), min.getBytes(), WITHSCORES.raw); } public void zrangeByScoreWithScores(final byte[] key, final double min, final double max, final int offset, final int count) { byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); sendCommand(ZRANGEBYSCORE, key, byteArrayMin, byteArrayMax, LIMIT.raw, toByteArray(offset), toByteArray(count), WITHSCORES.raw); } public void zrangeByScoreWithScores(final byte[] key, final byte min[], final byte max[], final int offset, final int count) { sendCommand(ZRANGEBYSCORE, key, min, max, LIMIT.raw, toByteArray(offset), toByteArray(count), WITHSCORES.raw); } public void zrangeByScoreWithScores(final byte[] key, final String min, final String max, final int offset, final int count) { sendCommand(ZRANGEBYSCORE, key, min.getBytes(), max.getBytes(), LIMIT.raw, toByteArray(offset), toByteArray(count), WITHSCORES.raw); } public void zrevrangeByScoreWithScores(final byte[] key, final double max, final double min, final int offset, final int count) { byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); sendCommand(ZREVRANGEBYSCORE, key, byteArrayMax, byteArrayMin, LIMIT.raw, toByteArray(offset), toByteArray(count), WITHSCORES.raw); } public void zrevrangeByScoreWithScores(final byte[] key, final byte max[], final byte min[], final int offset, final int count) { sendCommand(ZREVRANGEBYSCORE, key, max, min, LIMIT.raw, toByteArray(offset), toByteArray(count), WITHSCORES.raw); } public void zrevrangeByScoreWithScores(final byte[] key, final String max, final String min, final int offset, final int count) { sendCommand(ZREVRANGEBYSCORE, key, max.getBytes(), min.getBytes(), LIMIT.raw, toByteArray(offset), toByteArray(count), WITHSCORES.raw); } public void zremrangeByRank(final byte[] key, final int start, final int end) { sendCommand(ZREMRANGEBYRANK, key, toByteArray(start), toByteArray(end)); } public void zremrangeByScore(final byte[] key, final double start, final double end) { sendCommand(ZREMRANGEBYSCORE, key, toByteArray(start), toByteArray(end)); } public void zremrangeByScore(final byte[] key, final byte start[], final byte end[]) { sendCommand(ZREMRANGEBYSCORE, key, start, end); } public void zremrangeByScore(final byte[] key, final String start, final String end) { sendCommand(ZREMRANGEBYSCORE, key, start.getBytes(), end.getBytes()); } public void zunionstore(final byte[] dstkey, final byte[]... sets) { final byte[][] params = new byte[sets.length + 2][]; params[0] = dstkey; params[1] = toByteArray(sets.length); System.arraycopy(sets, 0, params, 2, sets.length); sendCommand(ZUNIONSTORE, params); } public void zunionstore(final byte[] dstkey, final ZParams params, final byte[]... sets) { final List<byte[]> args = new ArrayList<byte[]>(); args.add(dstkey); args.add(Protocol.toByteArray(sets.length)); for (final byte[] set : sets) { args.add(set); } args.addAll(params.getParams()); sendCommand(ZUNIONSTORE, args.toArray(new byte[args.size()][])); } public void zinterstore(final byte[] dstkey, final byte[]... sets) { final byte[][] params = new byte[sets.length + 2][]; params[0] = dstkey; params[1] = Protocol.toByteArray(sets.length); System.arraycopy(sets, 0, params, 2, sets.length); sendCommand(ZINTERSTORE, params); } public void zinterstore(final byte[] dstkey, final ZParams params, final byte[]... sets) { final List<byte[]> args = new ArrayList<byte[]>(); args.add(dstkey); args.add(Protocol.toByteArray(sets.length)); for (final byte[] set : sets) { args.add(set); } args.addAll(params.getParams()); sendCommand(ZINTERSTORE, args.toArray(new byte[args.size()][])); } public void save() { sendCommand(SAVE); } public void bgsave() { sendCommand(BGSAVE); } public void bgrewriteaof() { sendCommand(BGREWRITEAOF); } public void lastsave() { sendCommand(LASTSAVE); } public void shutdown() { sendCommand(SHUTDOWN); } public void info() { sendCommand(INFO); } public void monitor() { sendCommand(MONITOR); } public void slaveof(final String host, final int port) { sendCommand(SLAVEOF, host, String.valueOf(port)); } public void slaveofNoOne() { sendCommand(SLAVEOF, NO.raw, ONE.raw); } public void configGet(final String pattern) { sendCommand(CONFIG, Keyword.GET.name(), pattern); } public void configSet(final String parameter, final String value) { sendCommand(CONFIG, Keyword.SET.name(), parameter, value); } public void strlen(final byte[] key) { sendCommand(STRLEN, key); } public void sync() { sendCommand(SYNC); } public void lpushx(final byte[] key, final byte[] string) { sendCommand(LPUSHX, key, string); } public void persist(final byte[] key) { sendCommand(PERSIST, key); } public void rpushx(final byte[] key, final byte[] string) { sendCommand(RPUSHX, key, string); } public void echo(final byte[] string) { sendCommand(ECHO, string); } public void linsert(final byte[] key, final LIST_POSITION where, final byte[] pivot, final byte[] value) { sendCommand(LINSERT, key, where.raw, pivot, value); } public void debug(final DebugParams params) { sendCommand(DEBUG, params.getCommand()); } public void brpoplpush(final byte[] source, final byte[] destination, final int timeout) { sendCommand(BRPOPLPUSH, source, destination, toByteArray(timeout)); } public void configResetStat() { sendCommand(CONFIG, Keyword.RESETSTAT.name()); } public void setbit(byte[] key, long offset, byte[] value) { sendCommand(SETBIT, key, toByteArray(offset), value); } public void getbit(byte[] key, long offset) { sendCommand(GETBIT, key, toByteArray(offset)); } public void setrange(byte[] key, long offset, byte[] value) { sendCommand(SETRANGE, key, toByteArray(offset), value); } public void getrange(byte[] key, long startOffset, long endOffset) { sendCommand(GETRANGE, key, toByteArray(startOffset), toByteArray(endOffset)); } public Long getDB() { return db; } public void disconnect() { db = 0; super.disconnect(); } }
package seedu.address.model; import java.util.ArrayList; import java.util.Comparator; import java.util.Optional; import java.util.function.Predicate; import java.util.logging.Logger; import javafx.collections.ObservableList; import seedu.address.commons.core.ComponentManager; import seedu.address.commons.core.LogsCenter; import seedu.address.commons.events.model.TaskBookChangedEvent; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.model.config.Config; import seedu.address.model.config.ReadOnlyConfig; import seedu.address.model.task.DeadlineTask; import seedu.address.model.task.EventTask; import seedu.address.model.task.FloatingTask; /** * Represents the in-memory model of the address book data. * All changes to any model should be synchronized. */ public class ModelManager extends ComponentManager implements Model { private static final Logger logger = LogsCenter.getLogger(ModelManager.class); private final Config config; private final WorkingTaskBook workingTaskBook; //for undo private ArrayList<Commit> commits = new ArrayList<Commit>(); private int head = -1; //head points to a the current commit which holds the TaskBook displayed by the UI /** * Initializes a ModelManager with the given config and TaskBook * TaskBook and its variables should not be null */ public ModelManager(ReadOnlyConfig config, ReadOnlyTaskBook taskBook) { super(); assert taskBook != null; logger.fine("Initializing with config: " + config + " and task book: " + taskBook); this.config = new Config(config); this.workingTaskBook = new WorkingTaskBook(taskBook); recordState("initial commit"); } public ModelManager() { this(new Config(), new TaskBook()); } //// Config @Override public ReadOnlyConfig getConfig() { return config; } @Override public String getTaskBookFilePath() { return config.getTaskBookFilePath(); } @Override public void setTaskBookFilePath(String filePath) { config.setTaskBookFilePath(filePath); } //// Task Book @Override public void resetTaskBook(ReadOnlyTaskBook newData) { workingTaskBook.resetData(newData); indicateTaskBookChanged(); } @Override public ReadOnlyTaskBook getTaskBook() { return workingTaskBook.getTaskBook(); } /** Raises an event to indicate the model has changed */ private void indicateTaskBookChanged() { raise(new TaskBookChangedEvent(workingTaskBook.getTaskBook())); } //// Floating tasks @Override public synchronized int addFloatingTask(FloatingTask floatingTask) { final int workingIndex = workingTaskBook.addFloatingTask(floatingTask); indicateTaskBookChanged(); return workingIndex; } @Override public synchronized FloatingTask getFloatingTask(int workingIndex) throws IllegalValueException { return workingTaskBook.getFloatingTask(workingIndex); } @Override public synchronized FloatingTask removeFloatingTask(int workingIndex) throws IllegalValueException { final FloatingTask removedFloating = workingTaskBook.removeFloatingTask(workingIndex); indicateTaskBookChanged(); return removedFloating; } @Override public synchronized void setFloatingTask(int workingIndex, FloatingTask newFloatingTask) throws IllegalValueException { workingTaskBook.setFloatingTask(workingIndex, newFloatingTask); indicateTaskBookChanged(); } @Override public ObservableList<IndexedItem<FloatingTask>> getFloatingTaskList() { return workingTaskBook.getFloatingTaskList(); } @Override public void setFloatingTaskPredicate(Predicate<? super FloatingTask> predicate) { workingTaskBook.setFloatingTaskPredicate(predicate); } @Override public Comparator<? super FloatingTask> getFloatingTaskComparator() { return workingTaskBook.getFloatingTaskComparator(); } @Override public void setFloatingTaskComparator(Comparator<? super FloatingTask> comparator) { workingTaskBook.setFloatingTaskComparator(comparator); } //// Deadline tasks @Override public synchronized int addDeadlineTask(DeadlineTask deadlineTask) { assert deadlineTask.isFinished() == false; final int workingIndex = workingTaskBook.addDeadlineTask(deadlineTask); indicateTaskBookChanged(); return workingIndex; } @Override public synchronized DeadlineTask getDeadlineTask(int workingIndex) throws IllegalValueException { return workingTaskBook.getDeadlineTask(workingIndex); } @Override public synchronized DeadlineTask removeDeadlineTask(int workingIndex) throws IllegalValueException { final DeadlineTask removedDeadline = workingTaskBook.removeDeadlineTask(workingIndex); indicateTaskBookChanged(); return removedDeadline; } @Override public synchronized void setDeadlineTask(int workingIndex, DeadlineTask newDeadlineTask) throws IllegalValueException { workingTaskBook.setDeadlineTask(workingIndex, newDeadlineTask); indicateTaskBookChanged(); } @Override public ObservableList<IndexedItem<DeadlineTask>> getDeadlineTaskList() { return workingTaskBook.getDeadlineTaskList(); } @Override public void setDeadlineTaskPredicate(Predicate<? super DeadlineTask> predicate) { workingTaskBook.setDeadlineTaskPredicate(predicate); } @Override public Comparator<? super DeadlineTask> getDeadlineTaskComparator() { return workingTaskBook.getDeadlineTaskComparator(); } @Override public void setDeadlineTaskComparator(Comparator<? super DeadlineTask> comparator) { workingTaskBook.setDeadlineTaskComparator(comparator); } //// Event tasks @Override public synchronized int addEventTask(EventTask eventTask) { final int workingIndex = workingTaskBook.addEventTask(eventTask); indicateTaskBookChanged(); return workingIndex; } @Override public synchronized EventTask getEventTask(int workingIndex) throws IllegalValueException { return workingTaskBook.getEventTask(workingIndex); } @Override public synchronized EventTask removeEventTask(int workingIndex) throws IllegalValueException { final EventTask removedEvent = workingTaskBook.removeEventTask(workingIndex); indicateTaskBookChanged(); return removedEvent; } @Override public synchronized void setEventTask(int workingIndex, EventTask newEventTask) throws IllegalValueException { workingTaskBook.setEventTask(workingIndex, newEventTask); indicateTaskBookChanged(); } @Override public ObservableList<IndexedItem<EventTask>> getEventTaskList() { return workingTaskBook.getEventTaskList(); } @Override public void setEventTaskPredicate(Predicate<? super EventTask> predicate) { workingTaskBook.setEventTaskPredicate(predicate); } @Override public Comparator<? super EventTask> getEventTaskComparator() { return workingTaskBook.getEventTaskComparator(); } @Override public void setEventTaskComparator(Comparator<? super EventTask> comparator) { workingTaskBook.setEventTaskComparator(comparator); } ////undo redo @Override public Commit undo() throws HeadAtBoundaryException { if (head <= 0) { throw new HeadAtBoundaryException(); } final Commit undoneCommit = commits.get(head); head Commit commit = commits.get(head); workingTaskBook.resetData(commit.workingTaskBook); return undoneCommit; } @Override public Commit recordState(String name) { assert name != null; //clear redoable, which are the commits above head commits.subList(head + 1, commits.size()).clear(); final Commit newCommit = new Commit(name, workingTaskBook); commits.add(newCommit); head = commits.size() - 1; return newCommit; } @Override public Commit redo() throws HeadAtBoundaryException { if (head >= commits.size() - 1) { throw new HeadAtBoundaryException(); } head++; Commit commit = commits.get(head); workingTaskBook.resetData(commit.workingTaskBook); return commit; } /** * check if taskBook has changed. * @return true if TaskBook changed */ @Override public boolean hasUncommittedChanges() { return !(getTaskBook().equals(commits.get(head).getTaskBook())); } private class Commit implements Model.Commit { private String name; private final WorkingTaskBook workingTaskBook; private Commit(String name, WorkingTaskBook workingTaskBook) { this.name = name; this.workingTaskBook = new WorkingTaskBook(workingTaskBook); } @Override public String getName() { return name; } private ReadOnlyTaskBook getTaskBook() { return workingTaskBook.getTaskBook(); } @Override public boolean equals(Object other) { return other == this || (other instanceof Commit && name.equals(((Commit)other).name) && workingTaskBook.equals(((Commit)other).workingTaskBook) ); } } public class HeadAtBoundaryException extends Exception { public HeadAtBoundaryException() { super(); } } }
package seedu.geekeep.ui; import java.util.Date; import java.util.logging.Logger; import org.controlsfx.control.StatusBar; import com.google.common.eventbus.Subscribe; import javafx.fxml.FXML; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Region; import seedu.geekeep.commons.core.LogsCenter; import seedu.geekeep.commons.events.model.GeeKeepChangedEvent; import seedu.geekeep.commons.events.model.GeekeepFilePathChangedEvent; import seedu.geekeep.commons.util.FxViewUtil; /** * A ui for the status bar that is displayed at the footer of the application. */ public class StatusBarFooter extends UiPart<Region> { private static final Logger logger = LogsCenter.getLogger(StatusBarFooter.class); @FXML private StatusBar syncStatus; @FXML private StatusBar saveLocationStatus; private static final String FXML = "StatusBarFooter.fxml"; public StatusBarFooter(AnchorPane placeHolder, String saveLocation) { super(FXML); addToPlaceholder(placeHolder); setSyncStatus("Not updated yet in this session"); setSaveLocation(saveLocation); registerAsAnEventHandler(this); } private void addToPlaceholder(AnchorPane placeHolder) { FxViewUtil.applyAnchorBoundaryParameters(getRoot(), 0.0, 0.0, 0.0, 0.0); placeHolder.getChildren().add(getRoot()); } private void setSaveLocation(String location) { this.saveLocationStatus.setText(location); } private void setSyncStatus(String status) { this.syncStatus.setText(status); } @Subscribe public void handleGeeKeepChangedEvent(GeeKeepChangedEvent abce) { String lastUpdated = (new Date()).toString(); logger.info(LogsCenter.getEventHandlingLogMessage(abce, "Setting last updated status to " + lastUpdated)); setSyncStatus("Last Updated: " + lastUpdated); } @Subscribe private void handleGeekeepFilePathChangedEvent(GeekeepFilePathChangedEvent event) { setSaveLocation(event.config.getGeekeepFilePath()); String lastUpdated = (new Date()).toString(); setSyncStatus("Last Updated: " + lastUpdated); } }
package stsc.storage; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.Set; import java.util.TimeZone; import com.google.common.collect.Sets; import stsc.common.stocks.UnitedFormatStock; import stsc.common.storage.StockStorage; /** * StockStorageFactory is a factory for {@link ThreadSafeStockStorage}. <br/> * Main idea is to provide possibility to load only predefined set of stock (by * names).<br/> * Has methods to load {@link StockStorage} stock defined by name and to load * set of stocks defined by names. */ public final class StockStorageFactory { static { TimeZone.setDefault(TimeZone.getTimeZone("UTC")); } public StockStorageFactory() { // use static method to create StockStorage } public StockStorage createStockStorage(final String stockName, final String filterDataFolderPath) throws ClassNotFoundException, IOException, InterruptedException { return createStockStorage(Sets.newHashSet(new String[] { stockName }), filterDataFolderPath); } public StockStorage createStockStorage(final Set<String> stockNames, final String filterDataFolderPath) throws ClassNotFoundException, IOException, InterruptedException { return createStockStorage(stockNames, FileSystems.getDefault().getPath(filterDataFolderPath)); } public StockStorage createStockStorage(final Set<String> stockNames, final Path filterDataPath) throws ClassNotFoundException, IOException, InterruptedException { final StockStorage stockStorage = new ThreadSafeStockStorage(); for (String name : stockNames) { final String path = filterDataPath.resolve(name + UnitedFormatStock.EXTENSION).toString(); stockStorage.updateStock(UnitedFormatStock.readFromUniteFormatFile(path)); } return stockStorage; } }
package teetime.framework; import java.util.Collection; import java.util.List; import teetime.framework.signal.ISignal; import teetime.framework.validation.InvalidPortConnection; /** * Represents a minimal stage that composes several other stages. * * @since 1.1 * @author Christian Wulf * */ @SuppressWarnings("PMD.AbstractNaming") public abstract class CompositeStage extends Stage { protected abstract Stage getFirstStage(); protected abstract Collection<? extends Stage> getLastStages(); @Override protected final void executeWithPorts() { getFirstStage().executeWithPorts(); } @Override protected void onSignal(final ISignal signal, final InputPort<?> inputPort) { getFirstStage().onSignal(signal, inputPort); } @Override protected TerminationStrategy getTerminationStrategy() { return getFirstStage().getTerminationStrategy(); } @Override protected void terminate() { getFirstStage().terminate(); } @Override protected boolean shouldBeTerminated() { return getFirstStage().shouldBeTerminated(); } @Override protected InputPort<?>[] getInputPorts() { return getFirstStage().getInputPorts(); } @Override public void validateOutputPorts(final List<InvalidPortConnection> invalidPortConnections) { for (final Stage s : getLastStages()) { s.validateOutputPorts(invalidPortConnections); } } @Override protected boolean isStarted() { boolean isStarted = true; for (final Stage s : getLastStages()) { isStarted = isStarted && s.isStarted(); } return isStarted; } }
package tigase.conf; import tigase.db.AuthRepository; import tigase.db.AuthRepositoryMDImpl; import tigase.db.DBInitException; import tigase.db.RepositoryFactory; import tigase.db.TigaseDBException; import tigase.db.UserRepository; import tigase.db.UserRepositoryMDImpl; import tigase.db.comp.ComponentRepository; import tigase.io.TLSUtil; import tigase.server.AbstractComponentRegistrator; import tigase.server.ServerComponent; import tigase.xmpp.BareJID; import static tigase.io.SSLContextContainerIfc.*; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; import javax.script.Bindings; /** * Created: Dec 7, 2009 4:15:31 PM * * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @version $Rev$ */ public abstract class ConfiguratorAbstract extends AbstractComponentRegistrator<Configurable> { /** Field description */ public static final String CONFIG_REPO_CLASS_INIT_KEY = "--tigase-config-repo-class"; /** Field description */ public static final String CONFIG_REPO_CLASS_PROP_KEY = "tigase-config-repo-class"; /** Field description */ public static final String USER_DOMAIN_POOL_CLASS_PROP_KEY = "user-domain-repo-pool"; /** Field description */ public static final String USER_DOMAIN_POOL_CLASS_PROP_VAL = "tigase.db.UserRepositoryMDImpl"; /** Field description */ public static final String AUTH_DOMAIN_POOL_CLASS_PROP_KEY = "auth-domain-repo-pool"; /** Field description */ public static final String AUTH_DOMAIN_POOL_CLASS_PROP_VAL = "tigase.db.AuthRepositoryMDImpl"; private static final String LOGGING_KEY = "logging/"; /** Field description */ public static final String PROPERTY_FILENAME_PROP_KEY = "--property-file"; private static final Logger log = Logger.getLogger(ConfiguratorAbstract.class.getName()); /** Field description */ public static String logManagerConfiguration = null; private static MonitoringSetupIfc monitoring = null; private AuthRepositoryMDImpl auth_repo_impl = null; private Map<String, String> auth_repo_params = null; private AuthRepository auth_repository = null; // Default user auth repository instance which can be shared among components private ConfigRepositoryIfc configRepo = new ConfigurationCache(); private UserRepositoryMDImpl user_repo_impl = null; private Map<String, String> user_repo_params = null; // Default user repository instance which can be shared among components private UserRepository user_repository = null; private boolean setup_in_progress = false; /** * Configuration settings read from the init.properties file or any other source * which provides startup configuration. */ private List<String> initSettings = new LinkedList<String>(); /** * Properties from the command line parameters and init.properties file or any * other source which are used to generate default configuration. All the settings * starting with '--' */ private Map<String, Object> initProperties = new LinkedHashMap<String, Object>(100); /** * Method description * * * @param objName * * @return */ public static Object getMXBean(String objName) { if (monitoring != null) { return monitoring.getMXBean(objName); } else { return null; } } /** * Method description * * * @param config */ public static void loadLogManagerConfig(String config) { logManagerConfiguration = config; try { final ByteArrayInputStream bis = new ByteArrayInputStream(config.getBytes()); LogManager.getLogManager().readConfiguration(bis); bis.close(); } catch (IOException e) { log.log(Level.SEVERE, "Can not configure logManager", e); } // end of try-catch } /** * Method description * * * @param objName * @param bean */ public static void putMXBean(String objName, Object bean) { if (monitoring != null) { monitoring.putMXBean(objName, bean); } } /** * Method description * * * @param component */ @Override public void componentAdded(Configurable component) { if (log.isLoggable(Level.CONFIG)) { log.log(Level.CONFIG, " component: {0}", component.getName()); } setup(component); } /** * Method description * * * @param component */ @Override public void componentRemoved(Configurable component) {} /** * Method description * * * @return */ public Map<String, Object> getDefConfigParams() { return initProperties; } /** * Returns default configuration settings in case if there is no * configuration file. * @param params * @return */ @Override public Map<String, Object> getDefaults(Map<String, Object> params) { Map<String, Object> defaults = super.getDefaults(params); if ((Boolean) params.get(GEN_TEST)) { defaults.put(LOGGING_KEY + ".level", "WARNING"); } else { defaults.put(LOGGING_KEY + ".level", "CONFIG"); } defaults.put(LOGGING_KEY + "handlers", "java.util.logging.ConsoleHandler java.util.logging.FileHandler"); defaults.put(LOGGING_KEY + "java.util.logging.ConsoleHandler.formatter", "tigase.util.LogFormatter"); defaults.put(LOGGING_KEY + "java.util.logging.ConsoleHandler.level", "WARNING"); defaults.put(LOGGING_KEY + "java.util.logging.FileHandler.append", "true"); defaults.put(LOGGING_KEY + "java.util.logging.FileHandler.count", "5"); defaults.put(LOGGING_KEY + "java.util.logging.FileHandler.formatter", "tigase.util.LogFormatter"); defaults.put(LOGGING_KEY + "java.util.logging.FileHandler.limit", "10000000"); defaults.put(LOGGING_KEY + "java.util.logging.FileHandler.pattern", "logs/tigase.log"); defaults.put(LOGGING_KEY + "tigase.useParentHandlers", "true"); defaults.put(LOGGING_KEY + "java.util.logging.FileHandler.level", "ALL"); if (params.get(GEN_DEBUG) != null) { String[] packs = ((String) params.get(GEN_DEBUG)).split(","); for (String pack : packs) { defaults.put(LOGGING_KEY + "tigase." + pack + ".level", "ALL"); } // end of for (String pack: packs) } if (params.get(GEN_DEBUG_PACKAGES) != null) { String[] packs = ((String) params.get(GEN_DEBUG_PACKAGES)).split(","); for (String pack : packs) { defaults.put(LOGGING_KEY + pack + ".level", "ALL"); } // end of for (String pack: packs) } String repo_pool = null; // Default repository pools implementations // repo_pool = (String) params.get(USER_REPO_POOL_CLASS); // if (repo_pool == null) { // repo_pool = USER_REPO_POOL_CLASS_PROP_VAL; // defaults.put(USER_REPO_POOL_CLASS_PROP_KEY, repo_pool); repo_pool = (String) params.get(USER_DOMAIN_POOL_CLASS); if (repo_pool == null) { repo_pool = USER_DOMAIN_POOL_CLASS_PROP_VAL; } defaults.put(USER_DOMAIN_POOL_CLASS_PROP_KEY, repo_pool); // repo_pool = (String) params.get(AUTH_REPO_POOL_CLASS); // if (repo_pool == null) { // repo_pool = AUTH_REPO_POOL_CLASS_PROP_VAL; // defaults.put(AUTH_REPO_POOL_CLASS_PROP_KEY, repo_pool); repo_pool = (String) params.get(AUTH_DOMAIN_POOL_CLASS); if (repo_pool == null) { repo_pool = AUTH_DOMAIN_POOL_CLASS_PROP_VAL; } defaults.put(AUTH_DOMAIN_POOL_CLASS_PROP_KEY, repo_pool); // System.out.println("Setting logging properties:\n" + defaults.toString()); // Default repository implementations String user_repo_class = DUMMY_REPO_CLASS_PROP_VAL; String user_repo_url = DERBY_REPO_URL_PROP_VAL; String auth_repo_class = DUMMY_REPO_CLASS_PROP_VAL; String auth_repo_url = DERBY_REPO_URL_PROP_VAL; if (params.get(GEN_USER_DB) != null) { user_repo_class = (String) params.get(GEN_USER_DB); //auth_repo_class = (String) params.get(GEN_USER_DB); auth_repo_class = TIGASE_CUSTOM_AUTH_REPO_CLASS_PROP_VAL; } if (params.get(GEN_USER_DB_URI) != null) { user_repo_url = (String) params.get(GEN_USER_DB_URI); auth_repo_url = user_repo_url; } if (params.get(GEN_AUTH_DB) != null) { auth_repo_class = (String) params.get(GEN_AUTH_DB); } if (params.get(GEN_AUTH_DB_URI) != null) { auth_repo_url = (String) params.get(GEN_AUTH_DB_URI); } if (params.get(USER_REPO_POOL_SIZE) != null) { defaults.put(USER_REPO_POOL_SIZE_PROP_KEY, params.get(USER_REPO_POOL_SIZE)); } else { defaults.put(USER_REPO_POOL_SIZE_PROP_KEY, "" + 1); } defaults.put(RepositoryFactory.USER_REPO_CLASS_PROP_KEY, user_repo_class); defaults.put(USER_REPO_URL_PROP_KEY, user_repo_url); // defaults.put(USER_REPO_PARAMS_NODE + "/param-1", "value-1"); defaults.put(RepositoryFactory.AUTH_REPO_CLASS_PROP_KEY, auth_repo_class); defaults.put(AUTH_REPO_URL_PROP_KEY, auth_repo_url); // defaults.put(AUTH_REPO_PARAMS_NODE + "/param-1", "value-1"); List<String> user_repo_domains = new ArrayList<String>(10); List<String> auth_repo_domains = new ArrayList<String>(10); for (Map.Entry<String, Object> entry : params.entrySet()) { if (entry.getKey().startsWith(GEN_USER_DB_URI)) { String domain = parseUserRepoParams(entry, params, user_repo_class, defaults); if (domain != null) { user_repo_domains.add(domain); } } if (entry.getKey().startsWith(GEN_AUTH_DB_URI)) { String domain = parseAuthRepoParams(entry, params, auth_repo_class, defaults); if (domain != null) { auth_repo_domains.add(domain); } } } if (user_repo_domains.size() > 0) { defaults.put(USER_REPO_DOMAINS_PROP_KEY, user_repo_domains.toArray(new String[user_repo_domains.size()])); } if (auth_repo_domains.size() > 0) { defaults.put(AUTH_REPO_DOMAINS_PROP_KEY, auth_repo_domains.toArray(new String[auth_repo_domains.size()])); } // TLS/SSL configuration if (params.get("--" + SSL_CONTAINER_CLASS_KEY) != null) { defaults.put(SSL_CONTAINER_CLASS_KEY, (String) params.get("--" + SSL_CONTAINER_CLASS_KEY)); } else { defaults.put(SSL_CONTAINER_CLASS_KEY, SSL_CONTAINER_CLASS_VAL); } if (params.get("--" + SERVER_CERTS_LOCATION_KEY) != null) { defaults.put(SERVER_CERTS_LOCATION_KEY, (String) params.get("--" + SERVER_CERTS_LOCATION_KEY)); } else { defaults.put(SERVER_CERTS_LOCATION_KEY, SERVER_CERTS_LOCATION_VAL); } if (params.get("--" + DEFAULT_DOMAIN_CERT_KEY) != null) { defaults.put(DEFAULT_DOMAIN_CERT_KEY, (String) params.get("--" + DEFAULT_DOMAIN_CERT_KEY)); } else { defaults.put(DEFAULT_DOMAIN_CERT_KEY, DEFAULT_DOMAIN_CERT_VAL); } // Setup tracer, this is a temporarily code... // String ips = (String)params.get(TigaseTracer.TRACER_IPS_PROP_KEY); // if (ips != null) { // String[] ipsa = ips.split(","); // for (String ip : ipsa) { // TigaseTracer.addIP(ip); // String jids = (String)params.get(TigaseTracer.TRACER_JIDS_PROP_KEY); // if (jids != null) { // String[] jidsa = jids.split(","); // for (String jid : jidsa) { // TigaseTracer.addJid(jid); return defaults; } /** * Method description * * * @return */ public String getMessageRouterClassName() { return "tigase.server.MessageRouter"; } /** * Method description * * * @param nodeId * * @return * * @throws ConfigurationException */ public Map<String, Object> getProperties(String nodeId) throws ConfigurationException { return configRepo.getProperties(nodeId); } /** * Method description * * * @param args * * @throws ConfigurationException * @throws TigaseDBException */ public void init(String[] args) throws ConfigurationException, TigaseDBException { parseArgs(args); String stringprep = (String) initProperties.get(STRINGPREP_PROCESSOR); if (stringprep != null) { BareJID.useStringprepProcessor(stringprep); } String cnf_class_name = System.getProperty(CONFIG_REPO_CLASS_PROP_KEY); if (cnf_class_name != null) { initProperties.put(CONFIG_REPO_CLASS_INIT_KEY, cnf_class_name); } cnf_class_name = (String) initProperties.get(CONFIG_REPO_CLASS_INIT_KEY); if (cnf_class_name != null) { try { configRepo = (ConfigRepositoryIfc) Class.forName(cnf_class_name).newInstance(); } catch (Exception e) { log.log(Level.SEVERE, "Problem initializing configuration system: ", e); log.log(Level.SEVERE, "Please check settings, and rerun the server."); log.log(Level.SEVERE, "Server is stopping now."); System.err.println("Problem initializing configuration system: " + e); System.err.println("Please check settings, and rerun the server."); System.err.println("Server is stopping now."); System.exit(1); } } configRepo.setDefHostname(getDefHostName().getDomain()); configRepo.init(initProperties); for (String prop : initSettings) { ConfigItem item = configRepo.getItemInstance(); item.initFromPropertyString(prop); configRepo.addItem(item); } Map<String, Object> repoInitProps = configRepo.getInitProperties(); if (repoInitProps != null) { initProperties.putAll(repoInitProps); } // Not sure if this is the correct pleace to initialize monitoring // maybe it should be initialized init initializationCompleted but // Then some stuff might be missing. Let's try to do it here for now // and maybe change it later. String property_filenames = (String) initProperties.get(PROPERTY_FILENAME_PROP_KEY); if (property_filenames != null) { String[] prop_files = property_filenames.split(","); initMonitoring((String) initProperties.get(MONITORING), new File(prop_files[0]).getParent()); } } /** * Method description * * * @param binds */ @Override public void initBindings(Bindings binds) { super.initBindings(binds); binds.put(ComponentRepository.COMP_REPO_BIND, configRepo); } /** * Method description * */ @Override public void initializationCompleted() { super.initializationCompleted(); if (monitoring != null) { monitoring.initializationCompleted(); } } /** * Method description * * * @param component * * @return */ @Override public boolean isCorrectType(ServerComponent component) { return component instanceof Configurable; } /** * Method description * * * @param args */ public void parseArgs(String[] args) { initProperties.put(GEN_TEST, Boolean.FALSE); initProperties.put("config-type", GEN_CONFIG_DEF); if ((args != null) && (args.length > 0)) { for (int i = 0; i < args.length; i++) { String key = null; Object val = null; if (args[i].startsWith(GEN_CONFIG)) { key = "config-type"; val = args[i]; } if (args[i].startsWith(GEN_TEST)) { key = args[i]; val = Boolean.TRUE; } if ((key == null) && args[i].startsWith("-") &&!args[i].startsWith(GEN_CONFIG)) { key = args[i]; val = args[++i]; } if (key != null) { initProperties.put(key, val); // System.out.println("Setting defaults: " + key + "=" + val.toString()); log.config("Setting defaults: " + key + "=" + val.toString()); } // end of if (key != null) } // end of for (int i = 0; i < args.length; i++) } String property_filenames = (String) initProperties.get(PROPERTY_FILENAME_PROP_KEY); if (property_filenames != null) { String[] prop_files = property_filenames.split(","); for (String property_filename : prop_files) { log.log(Level.CONFIG, "Loading initial properties from property file: {0}", property_filename); try { Properties defProps = new Properties(); defProps.load(new FileReader(property_filename)); Set<String> prop_keys = defProps.stringPropertyNames(); for (String key : prop_keys) { String value = defProps.getProperty(key).trim(); if (key.startsWith("-") || key.equals("config-type")) { initProperties.put(key.trim(), value); // defProperties.remove(key); log.log(Level.CONFIG, "Added default config parameter: ({0}={1})", new Object[] { key, value }); } else { initSettings.add(key + "=" + value); } } } catch (FileNotFoundException e) { log.log(Level.WARNING, "Given property file was not found: {0}", property_filename); } catch (IOException e) { log.log(Level.WARNING, "Can not read property file: " + property_filename, e); } } } // Set all parameters starting with '--' as a system properties with removed // the starting '-' characters. for (Map.Entry<String, Object> entry : initProperties.entrySet()) { if (entry.getKey().startsWith(" System.setProperty(entry.getKey().substring(2), ((entry.getValue() == null) ? null : entry.getValue().toString())); } } } /** * Method description * * * @param compId * @param props * * @throws ConfigurationException */ public void putProperties(String compId, Map<String, Object> props) throws ConfigurationException { configRepo.putProperties(compId, props); } /** * Sets all configuration properties for object. * @param props */ @Override public void setProperties(Map<String, Object> props) { super.setProperties(props); setupLogManager(props); TLSUtil.configureSSLContext(props); int repo_pool_size = 1; try { repo_pool_size = Integer.parseInt((String) props.get(USER_REPO_POOL_SIZE_PROP_KEY)); } catch (Exception e) { repo_pool_size = 1; } String[] user_repo_domains = (String[]) props.get(USER_REPO_DOMAINS_PROP_KEY); String[] auth_repo_domains = (String[]) props.get(AUTH_REPO_DOMAINS_PROP_KEY); String authRepoMDImpl = (String) props.get(AUTH_DOMAIN_POOL_CLASS_PROP_KEY); String userRepoMDImpl = (String) props.get(USER_DOMAIN_POOL_CLASS_PROP_KEY); try { // Authentication multi-domain repository pool initialization Map<String, String> params = getRepoParams(props, AUTH_REPO_PARAMS_NODE, null); String conn_url = (String) props.get(AUTH_REPO_URL_PROP_KEY); auth_repo_impl = (AuthRepositoryMDImpl) Class.forName(authRepoMDImpl).newInstance(); auth_repo_impl.initRepository(conn_url, params); // User multi-domain repository pool initialization params = getRepoParams(props, USER_REPO_PARAMS_NODE, null); conn_url = (String) props.get(USER_REPO_URL_PROP_KEY); user_repo_impl = (UserRepositoryMDImpl) Class.forName(userRepoMDImpl).newInstance(); user_repo_impl.initRepository(conn_url, params); } catch (Exception ex) { log.log(Level.SEVERE, "An error initializing domain repository pool: ", ex); } user_repository = null; auth_repository = null; if (user_repo_domains != null) { for (String domain : user_repo_domains) { try { addUserRepo(props, domain, repo_pool_size); } catch (Exception e) { log.log(Level.SEVERE, "Can't initialize user repository for domain: " + domain, e); } } } if (user_repository == null) { try { addUserRepo(props, null, repo_pool_size); } catch (Exception e) { log.log(Level.SEVERE, "Can't initialize user default repository: ", e); } } if (auth_repo_domains != null) { for (String domain : auth_repo_domains) { try { addAuthRepo(props, domain, repo_pool_size); } catch (Exception e) { log.log(Level.SEVERE, "Can't initialize user repository for domain: " + domain, e); } } } if (auth_repository == null) { try { addAuthRepo(props, null, repo_pool_size); } catch (Exception e) { log.log(Level.SEVERE, "Can't initialize auth default repository: ", e); } } // user_repo_params = getRepoParams(props, USER_REPO_PARAMS_NODE, null); // auth_repo_params = getRepoParams(props, AUTH_REPO_PARAMS_NODE, null); // try { // String cls_name = (String) props.get(USER_REPO_CLASS_PROP_KEY); // String res_uri = (String) props.get(USER_REPO_URL_PROP_KEY); // repo_pool.initRepository(res_uri, user_repo_params); // for (int i = 0; i < repo_pool_size; i++) { // user_repository = RepositoryFactory.getUserRepository(getName() + "-" + (i + 1), // cls_name, res_uri, user_repo_params); // repo_pool.addRepo(user_repository); // log.config("Initialized " + cls_name + " as user repository: " + res_uri); // log.config("Initialized user repository pool: " + repo_pool_size); // } catch (Exception e) { // log.log(Level.SEVERE, "Can't initialize user repository: ", e); // } // end of try-catch // try { // String cls_name = (String) props.get(AUTH_REPO_CLASS_PROP_KEY); // String res_uri = (String) props.get(AUTH_REPO_URL_PROP_KEY); // auth_pool.initRepository(res_uri, auth_repo_params); // for (int i = 0; i < repo_pool_size; i++) { // auth_repository = RepositoryFactory.getAuthRepository(getName() + "-" + (i + 1), // cls_name, res_uri, auth_repo_params); // auth_pool.addRepo(auth_repository); // log.config("Initialized " + cls_name + " as auth repository: " + res_uri); // log.config("Initialized user auth repository pool: " + repo_pool_size); // } catch (Exception e) { // log.log(Level.SEVERE, "Can't initialize auth repository: ", e); // } // end of try-catch } /** * Method description * * * @param component */ public void setup(Configurable component) { // Try to avoid recursive execution of the method if (component == this) { if (setup_in_progress) { return; } else { setup_in_progress = true; } } String compId = component.getName(); Map<String, Object> prop = null; try { prop = configRepo.getProperties(compId); } catch (ConfigurationException ex) { log.log(Level.WARNING, "Propblem retrieving configuration properties for component: " + compId, ex); return; } // if (component == this) { // System.out.println("Properties: " + prop.toString()); Map<String, Object> defs = component.getDefaults(getDefConfigParams()); Set<Map.Entry<String, Object>> defs_entries = defs.entrySet(); boolean modified = false; for (Map.Entry<String, Object> entry : defs_entries) { if ( !prop.containsKey(entry.getKey())) { prop.put(entry.getKey(), entry.getValue()); modified = true; } // end of if () } // end of for () if (modified) { try { configRepo.putProperties(compId, prop); } catch (ConfigurationException ex) { log.log(Level.WARNING, "Propblem with saving configuration properties for component: " + compId, ex); } } // end of if (modified) prop.put(SHARED_USER_REPO_PROP_KEY, user_repo_impl); prop.put(SHARED_USER_REPO_PARAMS_PROP_KEY, user_repo_params); prop.put(SHARED_AUTH_REPO_PROP_KEY, auth_repo_impl); prop.put(SHARED_AUTH_REPO_PARAMS_PROP_KEY, auth_repo_params); // prop.put(SHARED_USER_REPO_POOL_PROP_KEY, user_repo_impl); // prop.put(SHARED_USER_AUTH_REPO_POOL_PROP_KEY, auth_repo_impl); component.setProperties(prop); if (component == this) { setup_in_progress = false; } } private void addAuthRepo(Map<String, Object> props, String domain, int pool_size) throws DBInitException, ClassNotFoundException, InstantiationException, IllegalAccessException { Map<String, String> params = getRepoParams(props, AUTH_REPO_PARAMS_NODE, domain); String cls_name = (String) props.get(RepositoryFactory.AUTH_REPO_CLASS_PROP_KEY + ((domain == null) ? "" : "/" + domain)); String conn_url = (String) props.get(AUTH_REPO_URL_PROP_KEY + ((domain == null) ? "" : "/" + domain)); // String authRepoPoolImpl = (String) props.get(AUTH_REPO_POOL_CLASS_PROP_KEY); // AuthRepositoryPool repo_pool = // (AuthRepositoryPool) Class.forName(authRepoPoolImpl).newInstance(); // repo_pool.initRepository(conn_url, params); // for (int i = 0; i < pool_size; i++) { AuthRepository repo = RepositoryFactory.getAuthRepository(cls_name, conn_url, params); // repo_pool.addRepo(repo); if ((domain == null) || domain.trim().isEmpty()) { auth_repo_impl.addRepo("", repo); auth_repo_impl.setDefault(repo); auth_repository = repo; } else { auth_repo_impl.addRepo(domain, repo); } log.log(Level.INFO, "[{0}] Initialized {1} as user auth repository pool: {2}, url: {3}", new Object[] { ((domain != null) ? domain : "DEFAULT"), cls_name, pool_size, conn_url }); } private void addUserRepo(Map<String, Object> props, String domain, int pool_size) throws DBInitException, ClassNotFoundException, InstantiationException, IllegalAccessException { Map<String, String> params = getRepoParams(props, USER_REPO_PARAMS_NODE, domain); String cls_name = (String) props.get(RepositoryFactory.USER_REPO_CLASS_PROP_KEY + ((domain == null) ? "" : "/" + domain)); String conn_url = (String) props.get(USER_REPO_URL_PROP_KEY + ((domain == null) ? "" : "/" + domain)); // String userRepoPoolImpl = (String) props.get(USER_REPO_POOL_CLASS_PROP_KEY); // UserRepositoryPool repo_pool = // (UserRepositoryPool) Class.forName(userRepoPoolImpl).newInstance(); // repo_pool.initRepository(conn_url, params); // for (int i = 0; i < pool_size; i++) { UserRepository repo = RepositoryFactory.getUserRepository(cls_name, conn_url, params); // repo_pool.addRepo(repo); if ((domain == null) || domain.trim().isEmpty()) { user_repo_impl.addRepo("", repo); user_repo_impl.setDefault(repo); user_repository = repo; } else { user_repo_impl.addRepo(domain, repo); } log.log(Level.INFO, "[{0}] Initialized {1} as user repository pool:, {2} url: {3}", new Object[] { ((domain != null) ? domain : "DEFAULT"), cls_name, pool_size, conn_url }); } private Map<String, String> getRepoParams(Map<String, Object> props, String repo_type, String domain) { Map<String, String> result = new LinkedHashMap<String, String>(10); String prop_start = repo_type + ((domain == null) ? "" : "/" + domain); for (Map.Entry<String, Object> entry : props.entrySet()) { if (entry.getKey().startsWith(prop_start)) { // Split the key to configuration nodes separated with '/' String[] nodes = entry.getKey().split("/"); // The plugin ID part may contain many IDs separated with comma ',' if (nodes.length > 1) { result.put(nodes[nodes.length - 1], entry.getValue().toString()); } } } return result; } private void initMonitoring(String settings, String configDir) { if ((monitoring == null) && (settings != null)) { try { String mon_cls = "tigase.management.MonitoringSetup"; monitoring = (MonitoringSetupIfc) Class.forName(mon_cls).newInstance(); monitoring.initMonitoring(settings, configDir); } catch (Exception e) { log.log(Level.WARNING, "Can not initialize monitoring: ", e); } } } private String parseAuthRepoParams(Entry<String, Object> entry, Map<String, Object> params, String auth_repo_class, Map<String, Object> defaults) { String key = entry.getKey(); int br_open = key.indexOf('['); int br_close = key.indexOf(']'); if ((br_open < 0) || (br_close < 0)) { // default database is configured elsewhere return null; } String repo_class = auth_repo_class; String options = key.substring(br_open + 1, br_close); String domain = options.split(":")[0]; log.log(Level.INFO, "Found DB domain: {0}", domain); String get_user_db = GEN_AUTH_DB + "[" + options + "]"; if (params.get(get_user_db) != null) { repo_class = (String) params.get(get_user_db); } defaults.put(RepositoryFactory.AUTH_REPO_CLASS_PROP_KEY + "/" + domain, repo_class); log.config("Setting defaults: " + RepositoryFactory.AUTH_REPO_CLASS_PROP_KEY + "/" + domain + "=" + repo_class); defaults.put(AUTH_REPO_URL_PROP_KEY + "/" + domain, entry.getValue()); log.config("Setting defaults: " + AUTH_REPO_URL_PROP_KEY + "/" + domain + "=" + entry.getValue()); return domain; } private String parseUserRepoParams(Entry<String, Object> entry, Map<String, Object> params, String user_repo_class, Map<String, Object> defaults) { String key = entry.getKey(); int br_open = key.indexOf('['); int br_close = key.indexOf(']'); if ((br_open < 0) || (br_close < 0)) { // default database is configured elsewhere return null; } String repo_class = user_repo_class; String options = key.substring(br_open + 1, br_close); String domain = options.split(":")[0]; log.log(Level.INFO, "Found DB domain: {0}", domain); String get_user_db = GEN_USER_DB + "[" + options + "]"; if (params.get(get_user_db) != null) { repo_class = (String) params.get(get_user_db); } defaults.put(RepositoryFactory.USER_REPO_CLASS_PROP_KEY + "/" + domain, repo_class); log.config("Setting defaults: " + RepositoryFactory.USER_REPO_CLASS_PROP_KEY + "/" + domain + "=" + repo_class); defaults.put(USER_REPO_URL_PROP_KEY + "/" + domain, entry.getValue()); log.config("Setting defaults: " + USER_REPO_URL_PROP_KEY + "/" + domain + "=" + entry.getValue()); return domain; } private void setupLogManager(Map<String, Object> properties) { Set<Map.Entry<String, Object>> entries = properties.entrySet(); StringBuilder buff = new StringBuilder(200); for (Map.Entry<String, Object> entry : entries) { if (entry.getKey().startsWith(LOGGING_KEY)) { String key = entry.getKey().substring(LOGGING_KEY.length()); buff.append(key).append("=").append(entry.getValue()).append("\n"); if (key.equals("java.util.logging.FileHandler.pattern")) { File log_path = new File(entry.getValue().toString()).getParentFile(); if ( !log_path.exists()) { log_path.mkdirs(); } } // end of if (key.equals()) } // end of if (entry.getKey().startsWith(LOGGING_KEY)) } // System.out.println("Setting logging: \n" + buff.toString()); loadLogManagerConfig(buff.toString()); log.config("DONE"); } } //~ Formatted in Sun Code Convention
package com.exedio.cope; public class EnumTest extends AbstractLibTest { static final Model MODEL = new Model(EnumItem.TYPE, EnumItem2.TYPE); EnumItem item; EnumItem2 item2; private static final EnumItem.Status status1 = EnumItem.Status.status1; private static final EnumItem2.Status state1 = EnumItem2.Status.state1; public EnumTest() { super(MODEL); } @Override protected void setUp() throws Exception { super.setUp(); deleteOnTearDown(item = new EnumItem(EnumItem.Status.status1)); deleteOnTearDown(item2 = new EnumItem2(EnumItem2.Status.state1)); } public void testIt() { assertEquals(EnumItem.Status.class, item.status.getValueClass()); assertEquals(EnumItem2.Status.class, item2.status.getValueClass()); assertEquals(status1, item.getStatus()); assertEquals(state1, item2.getStatus()); } }
package water.rapids; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import water.*; import water.fvec.Frame; import water.fvec.NFSFileVec; import water.fvec.Vec; import water.parser.ParseDataset; import water.parser.ParseSetup; import water.rapids.ast.AstRoot; import water.rapids.ast.params.AstNumList; import water.rapids.ast.params.AstStr; import water.rapids.vals.ValFrame; import water.util.ArrayUtils; import water.util.Log; import java.io.File; import java.util.Arrays; import static org.junit.Assert.*; import static water.rapids.Rapids.IllegalASTException; public class RapidsTest extends TestUtil { @BeforeClass public static void setup() { stall_till_cloudsize(1); } @Test public void bigSlice() { // check that large slices do something sane String tree = "(rows a.hex [0:2147483647])"; checkTree(tree); } @Test public void testParseString() { astStr_ok("'hello'", "hello"); astStr_ok("\"one two three\"", "one two three"); astStr_ok("\" \\\" \"", " \" "); astStr_ok("\"\\\\\"", "\\"); astStr_ok("'test\"omg'", "test\"omg"); astStr_ok("'sun\nmoon'", "sun\nmoon"); astStr_ok("'a\\nb'", "a\nb"); astStr_ok("'\\n\\r\\t\\b\\f\\'\\\"\\\\'", "\n\r\t\b\f\'\"\\"); astStr_ok("'\\x00\\xa2\\xBC\\xDe\\xFF\\xcb'", "\u0000\u00A2\u00BC\u00DE\u00FF\u00CB"); astStr_ok("\"\\uABCD\\u0000\\uffff\"", "\uABCD\u0000\uFFFF"); astStr_ok("\"\\U0001F578\"", new String(Character.toChars(0x1F578))); parse_err("\"hello"); parse_err("\"one\"two\""); parse_err("\"something\'"); parse_err("'\\+'"); parse_err("'\\0'"); parse_err("'\\xA'"); parse_err("'\\xHI"); parse_err("'\\u123 spam'"); parse_err("'\\U'"); parse_err("'\\U12345678'"); parse_err("'\\U1F578'"); parse_err("'\\U+1F578'"); parse_err("'\\u{1F578}'"); } @Test public void testParseNumList() { astNumList_ok("[]"); astNumList_ok("[1 2 3]"); astNumList_ok("[000.1 -3 17.003 2e+01 +11.1 1234567890]"); astNumList_ok("[NaN nan]"); astNumList_ok("[1 2:3 5:10:2]"); astNumList_ok("[-0.5:10:0.1]"); parse_err("[21 11"); parse_err("[1 0.00.0]"); parse_err("[0 1 true false]"); parse_err("[#1 #2 #3]"); parse_err("[0 1 'hello']"); parse_err("[1:0]"); parse_err("[0:nan:2]"); parse_err("[1:0:5]"); parse_err("[1:-20]"); parse_err("[1:20:-5]"); } @Test public void test1() { // Checking `hex + 5` String tree = "(+ a.hex 5)"; checkTree(tree); } @Test public void test2() { // Checking `hex + 5 + 10` String tree = "(+ a.hex (+ 5 10))"; checkTree(tree); } @Test public void test3() { // Checking `hex + 5 - 1 * hex + 15 * (23 / hex)` String tree = "(+ (- (+ a.hex 5) (* 1 a.hex)) (* 15 (/ 23 a.hex)))"; checkTree(tree); } @Test public void test4() { //Checking `hex == 5`, <=, >=, <, >, != String tree = "(== a.hex 5)"; checkTree(tree); tree = "(<= a.hex 5)"; checkTree(tree); tree = "(>= a.hex 1.25132)"; checkTree(tree); tree = "(< a.hex 112.341e-5)"; checkTree(tree); tree = "(> a.hex 0.0123)"; checkTree(tree); tree = "(!= a.hex 0)"; checkTree(tree); } @Test public void test4_throws() { String tree = "(== a.hex (cols a.hex [1 2]))"; checkTree(tree, "Frames must have same columns, found 4 columns and 2 columns."); } @Test public void test5() { // Checking `hex && hex`, ||, &, | String tree = "(&& a.hex a.hex)"; checkTree(tree); tree = "(|| a.hex a.hex)"; checkTree(tree); tree = "(& a.hex a.hex)"; checkTree(tree); tree = "(| a.hex a.hex)"; checkTree(tree); } @Test public void test6() { // Checking `hex[,1]` String tree = "(cols a.hex [0])"; checkTree(tree); // Checking `hex[1,5]` tree = "(rows (cols a.hex [0]) [5])"; checkTree(tree); // Checking `hex[c(1:5,7,9),6]` tree = "(cols (rows a.hex [0:4 6 7]) [0])"; checkTree(tree); // Checking `hex[c(8,1,1,7),1]` // No longer handle dup or out-of-order rows tree = "(rows a.hex [2 7 8])"; checkTree(tree); } @Test public void testRowAssign() { String tree; // Assign column 3 over column 0 tree = "(:= a.hex (cols a.hex [3]) 0 [0:150])"; checkTree(tree); // Assign 17 over column 0 tree = "(:= a.hex 17 [0] [0:150])"; checkTree(tree); // Assign 17 over column 0, row 5 tree = "(:= a.hex 17 [0] [5])"; checkTree(tree); // Append 17 tree = "(append a.hex 17 \"nnn\")"; checkTree(tree); } @Test public void testFun() { // Compute 3*3; single variable defined in function body String tree = "({var1 . (* var1 var1)} 3)"; checkTree(tree); // Unknown var2 tree = "({var1 . (* var1 var2)} 3)"; checkTree(tree, "Name lookup of 'var2' failed"); // Compute 3* a.hex[0,0] tree = "({var1 . (* var1 (rows a.hex [0]))} 3)"; checkTree(tree); // Some more horrible functions. Drop the passed function and return a 3 tree = "({fun . 3} {y . (* y y)})"; checkTree(tree); // Apply a 3 to the passed function tree = "({fun . (fun 3)} {y . (* y y)})"; checkTree(tree); // Pass the squaring function thru the ID function tree = "({fun . fun} {y . (* y y)})"; checkTree(tree); // Pass the squaring function thru the twice-apply-3 function tree = "({fun . (fun (fun 3))} {y . (* y y)})"; checkTree(tree); // Pass the squaring function thru the twice-apply-x function tree = "({fun x . (fun (fun x))} {y . (* y y)} 3)"; checkTree(tree); // Pass the squaring function thru the twice-apply function tree = " ({fun . {x . (fun (fun x))}} {y . (* y y)}) "; checkTree(tree); // Pass the squaring function thru the twice-apply function, and apply it tree = "(({fun . {x . (fun (fun x))}} {y . (* y y)}) 3)"; checkTree(tree); } @Test public void testCBind() { String tree = "(cbind 1 2)"; checkTree(tree); tree = "(cbind 1 a.hex 2)"; checkTree(tree); tree = "(cbind a.hex (cols a.hex 0) 2)"; checkTree(tree); } @Test public void testRBind() { String tree = "(rbind 1 2)"; checkTree(tree); //tree = "(rbind a.hex 1 2)"; //checkTree(tree); } @Test public void testApply() { // Sum, reduction. 1 row result String tree = "(apply a.hex 2 {x . (sum x)})"; checkTree(tree); // Return ID column results. Shared data result. tree = "(apply a.hex 2 {x . x})"; checkTree(tree); // Return column results, new data result. tree = "(apply a.hex 2 abs)"; checkTree(tree); // Return two results tree = "(apply a.hex 2 {x . (rbind (sumNA x) (sum x))})"; checkTree(tree); } @Test public void testRowApply() { String tree = "(apply a.hex 1 sum)"; checkTree(tree); tree = "(apply a.hex 1 max)"; checkTree(tree); tree = "(apply a.hex 1 {x . (sum x)})"; checkTree(tree); tree = "(apply a.hex 1 {x . (sum (* x x))})"; checkTree(tree); // require lookup of 'y' outside the scope of the applied function. // doubles all values. tree = "({y . (apply a.hex 1 {x . (sum (* x y))})} 2)"; checkTree(tree); } @Test public void testMath() { for( String s : new String[] {"abs", "cos", "sin", "acos", "ceiling", "floor", "cosh", "exp", "log", "sqrt", "tan", "tanh"} ) checkTree("("+s+" a.hex)"); } @Test public void testVariance() { // Checking variance: scalar String tree = "({x . (var x x \"everything\" FALSE)} (rows a.hex [0]))"; checkTree(tree); tree = "({x . (var x x \"everything\" FALSE)} a.hex)"; checkTree(tree); tree = "(table (trunc (cols a.hex 1)) FALSE)"; checkTree(tree); tree = "(table (cols a.hex 1) FALSE)"; checkTree(tree); tree = "(table (cols a.hex 1) (cols a.hex 2) FALSE)"; checkTree(tree); } private void checkTree(String tree) { checkTree(tree, null); } private void checkTree(String tree, String thrownMessage) { //Frame r = frame(new double[][]{{-1},{1},{2},{3},{4},{5},{6},{254}}); //Key ahex = Key.make("a.hex"); //Frame fr = new Frame(ahex, null, new Vec[]{r.remove(0)}); //r.delete(); //DKV.put(ahex, fr); Frame fr = parse_test_file(Key.make("a.hex"),"smalldata/iris/iris_wheader.csv"); fr.remove(4).remove(); try { Val val = Rapids.exec(tree); Assert.assertNull(thrownMessage); System.out.println(val.toString()); if (val instanceof ValFrame) { Frame fr2 = val.getFrame(); System.out.println(fr2.vec(0)); fr2.remove(); } } catch( IllegalArgumentException iae ) { if (thrownMessage != null) { Assert.assertEquals(thrownMessage, iae.getMessage()); Log.debug("Expected Exception suppressed", iae); } else throw iae; } finally { fr.delete(); } } @Test public void testProstate_assign_frame_scalar() { Frame fr = parse_test_file(Key.make("prostate.hex"), "smalldata/logreg/prostate.csv"); try { Val val = Rapids.exec("(tmp= py_1 (:= prostate.hex -1 1 (== (cols_py prostate.hex 1) 0)))"); if (val instanceof ValFrame ) { Frame fr2 = val.getFrame(); System.out.println(fr2.vec(0)); fr2.remove(); } } finally { fr.delete(); } } @Test public void testCombo() { Frame fr = parse_test_file(Key.make("a.hex"),"smalldata/iris/iris_wheader.csv"); String tree = "(tmp= py_2 (:= (tmp= py_1 (cbind a.hex (== (cols_py a.hex 4.0 ) \"Iris-setosa\" ) ) ) (as.factor (cols_py py_1 5.0 ) ) 5.0 [] ) )"; //String tree = "(:= (tmp= py_1 a.hex) (h2o.runif a.hex -1) 4 [])"; Val val = Rapids.exec(tree); if (val instanceof ValFrame ) { Frame fr2 = val.getFrame(); System.out.println(fr2.vec(0)); fr2.remove(); } fr.delete(); } @Test public void testMerge() { Frame l=null,r=null,f=null; try { l = ArrayUtils.frame("name" ,vec(ar("Cliff","Arno","Tomas","Spencer"),ari(0,1,2,3))); l. add("age" ,vec(ar(">dirt" ,"middle","middle","young'n"),ari(0,1,2,3))); l = new Frame(l); DKV.put(l); System.out.println(l); r = ArrayUtils.frame("name" ,vec(ar("Arno","Tomas","Michael","Cliff"),ari(0,1,2,3))); r. add("skill",vec(ar("science","linearmath","sparkling","hacker"),ari(0,1,2,3))); r = new Frame(r); DKV.put(r); System.out.println(r); String x = String.format("(merge %s %s 1 0 [] [] \"auto\")",l._key,r._key); Val res = Rapids.exec(x); f = res.getFrame(); System.out.println(f); Vec names = f.vec(0); Assert.assertEquals(names.factor(names.at8(0)),"Cliff"); Vec ages = f.vec(1); Assert.assertEquals(ages .factor(ages .at8(0)),">dirt"); Vec skilz = f.vec(2); Assert.assertEquals(skilz.factor(skilz.at8(0)),"hacker"); } finally { if( f != null ) f.delete(); if( r != null ) r.delete(); if( l != null ) l.delete(); } } @Test public void testQuantile() { Frame f = null; try { Frame fr = ArrayUtils.frame(ard(ard(1.223292e-02), ard(1.635312e-25), ard(1.601522e-11), ard(8.452298e-10), ard(2.643733e-10), ard(2.671520e-06), ard(1.165381e-06), ard(7.193265e-10), ard(3.383532e-04), ard(2.561221e-05))); double[] probs = new double[]{0.001, 0.005, .01, .02, .05, .10, .50, .8883, .90, .99}; String x = String.format("(quantile %s %s \"interpolate\" _)", fr._key, Arrays.toString(probs)); Val val = Rapids.exec(x); fr.delete(); f = val.getFrame(); Assert.assertEquals(2,f.numCols()); // Expected values computed as golden values from R's quantile call double[] exp = ard(1.4413698000016206E-13, 7.206849000001562E-13, 1.4413698000001489E-12, 2.882739600000134E-12, 7.20684900000009E-12, 1.4413698000000017E-11, 5.831131148999999E-07, 3.3669567275300000E-04, 0.00152780988 , 0.011162408988 ); for( int i=0; i<exp.length; i++ ) Assert.assertTrue( "expected "+exp[i]+" got "+f.vec(1).at(i), water.util.MathUtils.compare(exp[i],f.vec(1).at(i),1e-6,1e-6) ); } finally { if( f != null ) f.delete(); } } static void exec_str( String str, Session ses ) { Val val = Rapids.exec(str,ses); switch( val.type() ) { case Val.FRM: Frame fr = val.getFrame(); System.out.println(fr); checkSaneFrame(); break; case Val.NUM: System.out.println("num= "+val.getNum()); checkSaneFrame(); break; case Val.STR: System.out.println("str= "+val.getStr()); checkSaneFrame(); break; default: throw water.H2O.fail(); } } static void checkSaneFrame() { assert checkSaneFrame_impl(); } static boolean checkSaneFrame_impl() { for( Key k : H2O.localKeySet() ) { Value val = Value.STORE_get(k); if( val != null && val.isFrame() ) { Frame fr = val.get(); Vec vecs[] = fr.vecs(); for( int i=0; i<vecs.length; i++ ) { Vec v = vecs[i]; if( DKV.get(v._key) == null ) { System.err.println("Frame "+fr._key+" in the DKV, is missing Vec "+v._key+", name="+fr._names[i]); return false; } } } } return true; } @Test public void testRowSlice() { Session ses = new Session(); Frame fr = null; try { fr = parse_test_file(Key.make("a.hex"),"smalldata/airlines/AirlinesTrainMM.csv.zip"); System.out.printf(fr.toString()); Rapids.exec("(h2o.runif a.hex -1)->flow_1",ses); Rapids.exec("(tmp= f.25 (rows a.hex (< flow_1 0.25) ) )",ses); Rapids.exec("(rows a.hex (>= flow_1 0.25) )->f.75",ses); Rapids.exec("(h2o.runif a.hex -1)->flow_2",ses); ses.end(null); } catch( Throwable ex ) { throw ses.endQuietly(ex); } finally { if (fr != null) fr.delete(); } } @Test public void testChicago() { String oldtz = Rapids.exec("(getTimeZone)").getStr(); Session ses = new Session(); try { parse_test_file(Key.make("weather.hex"),"smalldata/chicago/chicagoAllWeather.csv"); parse_test_file(Key.make( "crimes.hex"),"smalldata/chicago/chicagoCrimes10k.csv.zip"); String fname = "smalldata/chicago/chicagoCensus.csv"; File f = find_test_file(fname); assert f != null && f.exists():" file not found: " + fname; NFSFileVec nfs = NFSFileVec.make(f); ParseSetup ps = ParseSetup.guessSetup(new Key[]{nfs._key}, false, 1); ps.getColumnTypes()[1] = Vec.T_CAT; ParseDataset.parse(Key.make( "census.hex"), new Key[]{nfs._key}, true, ps); exec_str("(assign census.hex (colnames= census.hex\t[0 1 2 3 4 5 6 7 8] \n" + "['Community.Area.Number' 'COMMUNITY.AREA.NAME' \"PERCENT.OF.HOUSING.CROWDED\" \r\n" + " \"PERCENT.HOUSEHOLDS.BELOW.POVERTY\" \"PERCENT.AGED.16..UNEMPLOYED\" " + " \"PERCENT.AGED.25..WITHOUT.HIGH.SCHOOL.DIPLOMA\" \"PERCENT.AGED.UNDER.18.OR.OVER.64\" " + " \"PER.CAPITA.INCOME.\" \"HARDSHIP.INDEX\"]))", ses); exec_str("(assign crimes.hex (colnames= crimes.hex [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21] [\"ID\" \"Case.Number\" \"Date\" \"Block\" \"IUCR\" \"Primary.Type\" \"Description\" \"Location.Description\" \"Arrest\" \"Domestic\" \"Beat\" \"District\" \"Ward\" \"Community.Area\" \"FBI.Code\" \"X.Coordinate\" \"Y.Coordinate\" \"Year\" \"Updated.On\" \"Latitude\" \"Longitude\" \"Location\"]))", ses); exec_str("(setTimeZone \"Etc/UTC\")", ses); exec_str("(assign crimes.hex (append crimes.hex (tmp= unary_op_6 (day (tmp= nary_op_5 (cols crimes.hex [2])))) \"Day\"))", ses); checkSaneFrame(); exec_str("(assign crimes.hex (append crimes.hex (tmp= binary_op_31 (+ (tmp= unary_op_7 (month nary_op_5)) 1)) \"Month\"))", ses); exec_str("(rm nary_op_30)",ses); exec_str("(assign crimes.hex (append crimes.hex (tmp= binary_op_32 (+ (tmp= binary_op_9 (- (tmp= unary_op_8 (year nary_op_5)) 1900)) 1900)) \"Year\"))", ses); exec_str("(assign crimes.hex (append crimes.hex (tmp= unary_op_10 (week nary_op_5)) \"WeekNum\"))", ses); exec_str("(rm binary_op_32)",ses); exec_str("(rm binary_op_31)",ses); exec_str("(rm unary_op_8)",ses); checkSaneFrame(); exec_str("(assign crimes.hex (append crimes.hex (tmp= unary_op_11 (dayOfWeek nary_op_5)) \"WeekDay\"))", ses); exec_str("(rm 'nfs:\\\\C:\\\\Users\\\\cliffc\\\\Desktop\\\\h2o-3\\\\smalldata\\\\chicago\\\\chicagoCrimes10k.csv.zip')", ses); exec_str("(assign crimes.hex (append crimes.hex (tmp= unary_op_12 (hour nary_op_5)) \"HourOfDay\"))", ses); exec_str("(assign crimes.hex (append crimes.hex (tmp= nary_op_16 (ifelse (tmp= binary_op_15 (| (tmp= binary_op_13 (== unary_op_11 \"Sun\")) (tmp= binary_op_14 (== unary_op_11 \"Sat\")))) 1 0)) \"Weekend\"))", ses); // Season is incorrectly assigned in the original chicago demo; picks up the Weekend flag exec_str("(assign crimes.hex (append crimes.hex nary_op_16 \"Season\"))", ses); // Standard "head of 10 rows" pattern for printing exec_str("(tmp= subset_33 (rows crimes.hex [0:10]))", ses); exec_str("(rm subset_33)",ses); exec_str("(rm subset_33)",ses); exec_str("(rm unary_op_29)",ses); exec_str("(rm nary_op_28)",ses); exec_str("(rm nary_op_27)",ses); exec_str("(rm nary_op_26)",ses); exec_str("(rm binary_op_25)",ses); exec_str("(rm binary_op_24)",ses); exec_str("(rm binary_op_23)",ses); exec_str("(rm binary_op_22)",ses); exec_str("(rm binary_op_21)",ses); exec_str("(rm binary_op_20)",ses); exec_str("(rm binary_op_19)",ses); exec_str("(rm binary_op_18)",ses); exec_str("(rm binary_op_17)",ses); exec_str("(rm nary_op_16)",ses); exec_str("(rm binary_op_15)",ses); exec_str("(rm binary_op_14)",ses); exec_str("(rm binary_op_13)",ses); exec_str("(rm unary_op_12)",ses); exec_str("(rm unary_op_11)",ses); exec_str("(rm unary_op_10)",ses); exec_str("(rm binary_op_9)",ses); exec_str("(rm unary_op_8)",ses); exec_str("(rm unary_op_7)",ses); exec_str("(rm unary_op_6)",ses); exec_str("(rm nary_op_5)",ses); checkSaneFrame(); // Standard "head of 10 rows" pattern for printing exec_str("(tmp= subset_34 (rows crimes.hex [0:10]))", ses); exec_str("(rm subset_34)",ses); exec_str("(assign census.hex (colnames= census.hex [0 1 2 3 4 5 6 7 8] [\"Community.Area\" \"COMMUNITY.AREA.NAME\" \"PERCENT.OF.HOUSING.CROWDED\" \"PERCENT.HOUSEHOLDS.BELOW.POVERTY\" \"PERCENT.AGED.16..UNEMPLOYED\" \"PERCENT.AGED.25..WITHOUT.HIGH.SCHOOL.DIPLOMA\" \"PERCENT.AGED.UNDER.18.OR.OVER.64\" \"PER.CAPITA.INCOME.\" \"HARDSHIP.INDEX\"]))", ses); exec_str("(rm subset_34)",ses); exec_str("(tmp= subset_35 (cols crimes.hex [-3]))", ses); exec_str("(tmp= subset_36 (cols weather.hex [-1]))", ses); exec_str("(tmp= subset_36_2 (colnames= subset_36 [0 1 2 3 4 5] [\"Month\" \"Day\" \"Year\" \"maxTemp\" \"meanTemp\" \"minTemp\"]))", ses); exec_str("(rm crimes.hex)",ses); exec_str("(rm weather.hex)",ses); // nary_op_37 = merge( X Y ); Vecs in X & nary_op_37 shared exec_str("(tmp= nary_op_37 (merge subset_35 census.hex TRUE FALSE [] [] \"auto\"))", ses); // nary_op_38 = merge( nary_op_37 subset_36_2); Vecs in nary_op_38 and nary_pop_37 and X shared exec_str("(tmp= subset_41 (rows (tmp= nary_op_38 (merge nary_op_37 subset_36_2 TRUE FALSE [] [] \"auto\")) (tmp= binary_op_40 (<= (tmp= nary_op_39 (h2o.runif nary_op_38 30792152736.5179)) 0.8))))", ses); // Standard "head of 10 rows" pattern for printing exec_str("(tmp= subset_44 (rows subset_41 [0:10]))", ses); exec_str("(rm subset_44)",ses); exec_str("(rm subset_44)",ses); exec_str("(rm binary_op_40)",ses); exec_str("(rm nary_op_37)",ses); exec_str("(tmp= subset_43 (rows nary_op_38 (tmp= binary_op_42 (> nary_op_39 0.8))))", ses); // Chicago demo continues on past, but this is all I've captured for now checkSaneFrame(); ses.end(null); } catch( Throwable ex ) { throw ses.endQuietly(ex); } finally { Rapids.exec("(setTimeZone \""+oldtz+"\")"); // Restore time zone (which is global, and will affect following tests) for( String s : new String[]{"weather.hex","crimes.hex","census.hex", "nary_op_5", "unary_op_6", "unary_op_7", "unary_op_8", "binary_op_9", "unary_op_10", "unary_op_11", "unary_op_12", "binary_op_13", "binary_op_14", "binary_op_15", "nary_op_16", "binary_op_17", "binary_op_18", "binary_op_19", "binary_op_20", "binary_op_21", "binary_op_22", "binary_op_23", "binary_op_24", "binary_op_25", "nary_op_26", "nary_op_27", "nary_op_28", "unary_op_29", "binary_op_30", "binary_op_31", "binary_op_32", "subset_33", "subset_34", "subset_35", "subset_36", "subset_36_2", "nary_op_37", "nary_op_38", "nary_op_39", "binary_op_40", "subset_41", "binary_op_42", "subset_43", "subset_44", } ) Keyed.remove(Key.make(s)); } } @Test public void testCumu() { Frame fr = null,fr2=null; String x = null; try { fr = ArrayUtils.frame("c1",vec(ari(1,1))); fr. add("c2" ,vec(ari(2,2))); fr. add("c3" ,vec(ari(3,3))); fr. add("c4" ,vec(ari(4,4))); fr = new Frame(fr); DKV.put(fr); x = String.format("(cumsum %s 1)", fr._key); Val val = Rapids.exec(x); Assert.assertTrue(val instanceof ValFrame); fr2 = val.getFrame(); Assert.assertEquals(fr2.vec(0).at8(0L), 1); Assert.assertEquals(fr2.vec(1).at8(0L), 3); Assert.assertEquals(fr2.vec(2).at8(0L), 6); Assert.assertEquals(fr2.vec(3).at8(0L), 10); fr2.remove(); x = String.format("(cumsum %s 0)", fr._key); val = Rapids.exec(x); Assert.assertTrue(val instanceof ValFrame); fr2 = val.getFrame(); Assert.assertEquals(fr2.vec(0).at8(1L), 2); Assert.assertEquals(fr2.vec(1).at8(1L), 4); Assert.assertEquals(fr2.vec(2).at8(1L), 6); Assert.assertEquals(fr2.vec(3).at8(1L), 8); fr2.remove(); x = String.format("(cummax %s 1)", fr._key); val = Rapids.exec(x); Assert.assertTrue(val instanceof ValFrame); fr2 = val.getFrame(); Assert.assertEquals(fr2.vec(0).at8(0L), 1); Assert.assertEquals(fr2.vec(1).at8(0L), 2); Assert.assertEquals(fr2.vec(2).at8(0L), 3); Assert.assertEquals(fr2.vec(3).at8(0L), 4); fr2.remove(); } finally { if (fr!=null) fr.delete(); } } private static void astNumList_ok(String expr) { assertTrue(Rapids.parse(expr) instanceof AstNumList); } private static void astStr_ok(String expr, String expected) { AstRoot res = Rapids.parse(expr); assertTrue(res instanceof AstStr); assertEquals(expected, ((AstStr)res).getStr()); } private static void parse_err(String expr) { try { Rapids.parse(expr); fail(); } catch (IllegalASTException ignored) {} } }
package h2o.dao; import h2o.common.util.ioc.ButterflyFactory; import h2o.common.util.ioc.Factory; public final class DbConfigProvider { public static Factory getDbConfig() { ButterflyFactory dbButterflyFactory = new ButterflyFactory( "db" , "db.bcs"); Factory factory = dbButterflyFactory.silentlyGet("dbConfig"); if ( factory == null ) { return dbButterflyFactory; } else { try { dbButterflyFactory.dispose(); } catch ( Exception e ) { } return factory; } } }
package wraith.library.LWJGL; public class Camera extends Object3D{ public float goalX, goalY, goalZ, goalRX, goalRY, goalRZ, goalSX, goalSY, goalSZ; public float cameraSpeed = 1; public Camera(float fov, float aspect, float near, float far){ MatrixUtils.setupPerspective(fov, aspect, near, far); } public Camera(float scale, float near, float far){ MatrixUtils.setupOrtho(scale, near, far); } public void update(float delta, long time){ delta*=cameraSpeed; x=x+delta*(goalX-x); y=y+delta*(goalY-y); z=z+delta*(goalZ-z); rx=(((((goalRX-rx)%360)+540)%360)-180)*delta; ry=(((((goalRY-ry)%360)+540)%360)-180)*delta; rz=(((((goalRZ-rz)%360)+540)%360)-180)*delta; sx=sx+delta*(goalSX-sx); sy=sy+delta*(goalSY-sy); sz=sz+delta*(goalSZ-sz); } }
package alien4cloud.paas.cloudify3.blueprint; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import alien4cloud.rest.utils.JsonUtil; import com.fasterxml.jackson.core.JsonProcessingException; import org.alien4cloud.tosca.model.definitions.AbstractPropertyValue; import org.alien4cloud.tosca.model.definitions.ComplexPropertyValue; import org.alien4cloud.tosca.model.definitions.ConcatPropertyValue; import org.alien4cloud.tosca.model.definitions.DeploymentArtifact; import org.alien4cloud.tosca.model.definitions.FunctionPropertyValue; import org.alien4cloud.tosca.model.definitions.IValue; import org.alien4cloud.tosca.model.definitions.ImplementationArtifact; import org.alien4cloud.tosca.model.definitions.Interface; import org.alien4cloud.tosca.model.definitions.ListPropertyValue; import org.alien4cloud.tosca.model.definitions.Operation; import org.alien4cloud.tosca.model.definitions.OperationOutput; import org.alien4cloud.tosca.model.definitions.PropertyDefinition; import org.alien4cloud.tosca.model.definitions.PropertyValue; import org.alien4cloud.tosca.model.definitions.ScalarPropertyValue; import org.alien4cloud.tosca.model.templates.ServiceNodeTemplate; import org.alien4cloud.tosca.model.types.CapabilityType; import org.alien4cloud.tosca.model.types.NodeType; import org.alien4cloud.tosca.normative.ToscaNormativeUtil; import org.alien4cloud.tosca.normative.constants.NormativeCapabilityTypes; import org.alien4cloud.tosca.normative.constants.NormativeComputeConstants; import org.alien4cloud.tosca.normative.constants.ToscaFunctionConstants; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.StringUtils; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import alien4cloud.exception.InvalidArgumentException; import alien4cloud.paas.IPaaSTemplate; import alien4cloud.paas.cloudify3.artifacts.ICloudifyImplementationArtifact; import alien4cloud.paas.cloudify3.configuration.MappingConfiguration; import alien4cloud.paas.cloudify3.shared.ArtifactRegistryService; import alien4cloud.paas.cloudify3.service.PropertyEvaluatorService; import alien4cloud.paas.cloudify3.service.model.CloudifyDeployment; import alien4cloud.paas.cloudify3.service.model.OperationWrapper; import alien4cloud.paas.cloudify3.service.model.Relationship; import alien4cloud.paas.exception.NotSupportedException; import alien4cloud.paas.function.FunctionEvaluator; import alien4cloud.paas.model.PaaSNodeTemplate; import alien4cloud.paas.model.PaaSRelationshipTemplate; import alien4cloud.paas.plan.ToscaNodeLifecycleConstants; import alien4cloud.paas.plan.ToscaRelationshipLifecycleConstants; import alien4cloud.topology.TopologyUtils; import alien4cloud.tosca.PaaSUtils; import alien4cloud.utils.FileUtil; import lombok.extern.slf4j.Slf4j; @Slf4j public class NonNativeTypeGenerationUtil extends AbstractGenerationUtil { private ArtifactRegistryService artifactRegistryService; public NonNativeTypeGenerationUtil(MappingConfiguration mappingConfiguration, CloudifyDeployment alienDeployment, Path recipePath, PropertyEvaluatorService propertyEvaluatorService, ArtifactRegistryService artifactRegistryService) { super(mappingConfiguration, alienDeployment, recipePath, propertyEvaluatorService); this.artifactRegistryService = artifactRegistryService; } public boolean isStandardLifecycleInterface(String interfaceName) { return ToscaNodeLifecycleConstants.STANDARD.equals(interfaceName) || ToscaNodeLifecycleConstants.STANDARD_SHORT.equals(interfaceName); } public String tryToMapToCloudifyInterface(String interfaceName) { if (isStandardLifecycleInterface(interfaceName)) { return "cloudify.interfaces.lifecycle"; } else { return interfaceName; } } public String tryToMapToCloudifyRelationshipInterface(String interfaceName) { if (ToscaRelationshipLifecycleConstants.CONFIGURE.equals(interfaceName) || ToscaRelationshipLifecycleConstants.CONFIGURE_SHORT.equals(interfaceName)) { return "cloudify.interfaces.relationship_lifecycle"; } else { return interfaceName; } } public Map<String, Interface> filterRelationshipSourceInterfaces(Map<String, Interface> interfaces) { return TopologyUtils.filterInterfaces(interfaces, mappingConfiguration.getRelationships().getLifeCycle().getSource().keySet()); } public Map<String, Interface> filterRelationshipTargetInterfaces(Map<String, Interface> interfaces) { return TopologyUtils.filterInterfaces(interfaces, mappingConfiguration.getRelationships().getLifeCycle().getTarget().keySet()); } public Map<String, Interface> getNodeInterfaces(PaaSNodeTemplate node) { return TopologyUtils.filterAbstractInterfaces(node.getInterfaces()); } public Map<String, Interface> getRelationshipInterfaces(PaaSRelationshipTemplate relationship) { return TopologyUtils.filterAbstractInterfaces(relationship.getInterfaces()); } public Map<String, IValue> getNodeAttributes(PaaSNodeTemplate nodeTemplate) { if (!isNonNative(nodeTemplate)) { // Do not try to publish attributes for non native nodes return null; } if (MapUtils.isEmpty(nodeTemplate.getNodeTemplate().getAttributes())) { return null; } Map<String, IValue> attributesThatCanBeSet = Maps.newLinkedHashMap(); for (Map.Entry<String, IValue> attributeEntry : nodeTemplate.getNodeTemplate().getAttributes().entrySet()) { if (attributeEntry.getValue() instanceof AbstractPropertyValue) { // Replace all get_property with the static value in all attributes attributesThatCanBeSet.put(attributeEntry.getKey(), attributeEntry.getValue()); } } return attributesThatCanBeSet; } // TODO: manage concat ? public Map<String, String> getNodeProperties(PaaSNodeTemplate node) { Map<String, String> propertyValues = Maps.newHashMap(); Map<String, AbstractPropertyValue> nodeProperties = node.getTemplate().getProperties(); if (MapUtils.isNotEmpty(nodeProperties)) { for (Entry<String, AbstractPropertyValue> propertyEntry : nodeProperties.entrySet()) { String propertyName = propertyEntry.getKey(); String propertyValue = null; if (propertyEntry.getValue() instanceof FunctionPropertyValue) { FunctionPropertyValue function = (FunctionPropertyValue) propertyEntry.getValue(); if (ToscaFunctionConstants.GET_PROPERTY.equals(function.getFunction())) { propertyValue = FunctionEvaluator.evaluateGetPropertyFunction(function, node, alienDeployment.getAllNodes()); } } else if (propertyEntry.getValue() instanceof ScalarPropertyValue) { propertyValue = ((ScalarPropertyValue) propertyEntry.getValue()).getValue(); } if (propertyValue != null) { propertyValues.put(propertyName, propertyValue); } } } return propertyValues; } public PaaSNodeTemplate getSourceNode(PaaSRelationshipTemplate relationshipTemplate) { return alienDeployment.getAllNodes().get(relationshipTemplate.getSource()); } public PaaSNodeTemplate getTargetNode(PaaSRelationshipTemplate relationshipTemplate) { return alienDeployment.getAllNodes().get(relationshipTemplate.getRelationshipTemplate().getTarget()); } public Map<String, IValue> getSourceRelationshipAttributes(PaaSRelationshipTemplate owner) { return getNodeAttributes(getSourceNode(owner)); } public Map<String, IValue> getTargetRelationshipAttributes(PaaSRelationshipTemplate owner) { return getNodeAttributes(getTargetNode(owner)); } public boolean isGetAttributeFunctionPropertyValue(IValue input) { return (input instanceof FunctionPropertyValue) && ToscaFunctionConstants.GET_ATTRIBUTE.equals(((FunctionPropertyValue) input).getFunction()); } public boolean isFunctionPropertyValue(IValue input) { return input instanceof FunctionPropertyValue; } public boolean isConcatPropertyValue(IValue input) { return input instanceof ConcatPropertyValue; } public String formatValue(IPaaSTemplate<?> owner, IValue input) throws JsonProcessingException { if (input instanceof FunctionPropertyValue) { return formatFunctionPropertyValue(owner, (FunctionPropertyValue) input); } else if (input instanceof ConcatPropertyValue) { return formatConcatPropertyValue(owner, (ConcatPropertyValue) input); } else if (input instanceof ScalarPropertyValue) { return formatTextValueToPython(((ScalarPropertyValue) input).getValue()); } else if (input instanceof ComplexPropertyValue || input instanceof ListPropertyValue) { return formatTextValueToPython(JsonUtil.toString(((PropertyValue) input).getValue())); } else if (input instanceof PropertyDefinition) { // Custom command do nothing return "''"; } else { String ownerId = owner == null ? "" : "for " + owner.getId(); throw new NotSupportedException("The value " + input + "'s type is not supported as operation input "); } } public String formatTextValueToPython(String text) { if (StringUtils.isEmpty(text)) { return "''"; } if (text.contains("'")) { text = text.replace("'", "\\'"); } if (text.contains("\n") || text.contains("\r")) { return "r'''" + text + "'''"; } else { return "r'" + text + "'"; } } public String formatConcatPropertyValue(IPaaSTemplate<?> owner, ConcatPropertyValue concatPropertyValue) { return formatConcatPropertyValue("", owner, concatPropertyValue); } public String formatConcatPropertyValue(String context, IPaaSTemplate<?> owner, ConcatPropertyValue concatPropertyValue) { StringBuilder pythonCall = new StringBuilder(); if (concatPropertyValue.getParameters() == null || concatPropertyValue.getParameters().isEmpty()) { throw new InvalidArgumentException("Parameter list for concat function is empty"); } for (IValue concatParam : concatPropertyValue.getParameters()) { // scalar type if (concatParam instanceof ScalarPropertyValue) { // scalar case String value = ((ScalarPropertyValue) concatParam).getValue(); if (StringUtils.isNotEmpty(value)) { pythonCall.append(formatTextValueToPython(value)).append(" + "); } } else if (concatParam instanceof PropertyDefinition) { throw new NotSupportedException("Do not support property definition in a concat"); } else if (concatParam instanceof FunctionPropertyValue) { // Function case FunctionPropertyValue functionPropertyValue = (FunctionPropertyValue) concatParam; switch (functionPropertyValue.getFunction()) { case ToscaFunctionConstants.GET_ATTRIBUTE: pythonCall.append(formatFunctionPropertyValue(context, owner, functionPropertyValue)).append(" + "); break; case ToscaFunctionConstants.GET_PROPERTY: pythonCall.append(formatFunctionPropertyValue(context, owner, functionPropertyValue)).append(" + "); break; case ToscaFunctionConstants.GET_OPERATION_OUTPUT: pythonCall.append(formatFunctionPropertyValue(context, owner, functionPropertyValue)).append(" + "); break; default: throw new NotSupportedException("Function " + functionPropertyValue.getFunction() + " is not yet supported"); } } else { throw new NotSupportedException("Do not support nested concat in a concat, please simplify your usage"); } } // Remove the last " + " pythonCall.setLength(pythonCall.length() - 3); return pythonCall.toString(); } public String formatFunctionPropertyValue(IPaaSTemplate<?> owner, FunctionPropertyValue functionPropertyValue) { return formatFunctionPropertyValue("", owner, functionPropertyValue); } public String formatFunctionPropertyValue(String context, IPaaSTemplate<?> owner, FunctionPropertyValue functionPropertyValue) { if (owner instanceof PaaSNodeTemplate) { return formatNodeFunctionPropertyValue(context, functionPropertyValue); } else if (owner instanceof PaaSRelationshipTemplate) { return formatRelationshipFunctionPropertyValue(context, (PaaSRelationshipTemplate) owner, functionPropertyValue); } else { throw new NotSupportedException("Un-managed paaS template type " + owner.getClass().getSimpleName()); } } /** * Format operation parameter of a node * * @param functionPropertyValue the input which can be a function or a scalar * @return the formatted parameter understandable by Cloudify */ public String formatNodeFunctionPropertyValue(String context, FunctionPropertyValue functionPropertyValue) { if (ToscaFunctionConstants.GET_ATTRIBUTE.equals(functionPropertyValue.getFunction())) { return "get_attribute(ctx" + context + ", '" + functionPropertyValue.getElementNameToFetch() + "')"; } else if (ToscaFunctionConstants.GET_PROPERTY.equals(functionPropertyValue.getFunction())) { return "get_property(ctx" + context + ", '" + functionPropertyValue.getElementNameToFetch() + "')"; } else if (ToscaFunctionConstants.GET_OPERATION_OUTPUT.equals(functionPropertyValue.getFunction())) { // a fake attribute is used in order to handle Operation Outputs return "get_attribute(ctx" + context + ", '_a4c_OO:" + functionPropertyValue.getInterfaceName() + ':' + functionPropertyValue.getOperationName() + ":" + functionPropertyValue.getElementNameToFetch() + "')"; } else { throw new NotSupportedException("Function " + functionPropertyValue.getFunction() + " is not yet supported"); } } /** * Format operation parameter of a node * * @param functionPropertyValue the input which can be a function or a scalar * @param relationshipTemplate The relationship template for which to format the function request. * @return the formatted parameter understandable by Cloudify */ private String formatRelationshipFunctionPropertyValue(String context, PaaSRelationshipTemplate relationshipTemplate, FunctionPropertyValue functionPropertyValue) { if (ToscaFunctionConstants.GET_ATTRIBUTE.equals(functionPropertyValue.getFunction())) { if (ToscaFunctionConstants.R_TARGET.equals(functionPropertyValue.getTemplateName().toUpperCase()) && relationshipTemplate.getTemplate().getTargetedCapabilityName() != null) { // If fetching from target and we know then try to fetch attribute from the target capability first and then the from the node. return "get_target_capa_or_node_attribute(ctx." + ToscaFunctionConstants.TARGET.toLowerCase() + context + ", 'capabilities." + relationshipTemplate.getTemplate().getTargetedCapabilityName() + "." + functionPropertyValue.getElementNameToFetch() + "', '" + functionPropertyValue.getElementNameToFetch() + "')"; } else if (ToscaFunctionConstants.SOURCE.equals(functionPropertyValue.getTemplateName().toUpperCase())) { // If fetching from source and we know then try to fetch attribute from the target requirement first and then the from the node. return "get_target_capa_or_node_attribute(ctx." + functionPropertyValue.getTemplateName().toLowerCase() + context + ", 'requirements." + relationshipTemplate.getTemplate().getRequirementName() + "." + functionPropertyValue.getElementNameToFetch() + "', '" + functionPropertyValue.getElementNameToFetch() + "')"; } if (functionPropertyValue.getParameters().size() > 2) { StringBuilder builder = new StringBuilder(); builder.append("get_nested_attribute(ctx.").append(functionPropertyValue.getTemplateName().toLowerCase()).append(context).append(", ["); for (int i = 1; i < functionPropertyValue.getParameters().size(); i++) { if (i > 1) { builder.append(", "); } builder.append("'").append(functionPropertyValue.getParameters().get(i)).append("'"); } builder.append("])"); return builder.toString(); } return "get_attribute(ctx." + functionPropertyValue.getTemplateName().toLowerCase() + context + ", '" + functionPropertyValue.getElementNameToFetch() + "')"; } else if (ToscaFunctionConstants.GET_PROPERTY.equals(functionPropertyValue.getFunction())) { return "get_property(ctx." + functionPropertyValue.getTemplateName().toLowerCase() + context + ", '" + functionPropertyValue.getElementNameToFetch() + "')"; } else if (ToscaFunctionConstants.GET_OPERATION_OUTPUT.equals(functionPropertyValue.getFunction())) { return "get_attribute(ctx." + functionPropertyValue.getTemplateName().toLowerCase() + context + ", '_a4c_OO:" + functionPropertyValue.getInterfaceName() + ':' + functionPropertyValue.getOperationName() + ":" + functionPropertyValue.getElementNameToFetch() + "')"; } else { throw new NotSupportedException("Function " + functionPropertyValue.getFunction() + " is not supported"); } } public List<PaaSRelationshipTemplate> getSourceRelationships(PaaSNodeTemplate nodeTemplate) { List<PaaSRelationshipTemplate> relationshipTemplates = nodeTemplate.getRelationshipTemplates(); List<PaaSRelationshipTemplate> sourceRelationshipTemplates = Lists.newArrayList(); for (PaaSRelationshipTemplate relationshipTemplate : relationshipTemplates) { if (relationshipTemplate.getSource().equals(nodeTemplate.getId())) { sourceRelationshipTemplates.add(relationshipTemplate); } } return sourceRelationshipTemplates; } private String tryToMapToCloudifyRelationshipInterfaceOperation(String operationName, boolean isSource) { Map<String, String> mapping; if (isSource) { mapping = mappingConfiguration.getRelationships().getLifeCycle().getSource(); } else { mapping = mappingConfiguration.getRelationships().getLifeCycle().getTarget(); } String mappedName = mapping.get(operationName); return mappedName != null ? mappedName : operationName; } public String tryToMapToCloudifyRelationshipSourceInterfaceOperation(String operationName) { return tryToMapToCloudifyRelationshipInterfaceOperation(operationName, true); } public String tryToMapToCloudifyRelationshipTargetInterfaceOperation(String operationName) { return tryToMapToCloudifyRelationshipInterfaceOperation(operationName, false); } public String getDerivedFromType(List<String> allDerivedFromsTypes) { for (String derivedFromType : allDerivedFromsTypes) { if (typeMustBeMappedToCloudifyType(derivedFromType)) { return tryToMapToCloudifyType(derivedFromType); } } // This must never happens return allDerivedFromsTypes.get(0); } public PaaSNodeTemplate getHost(PaaSNodeTemplate node) { return PaaSUtils.getMandatoryHostTemplate(node); } public boolean relationshipHasDeploymentArtifacts(PaaSRelationshipTemplate relationshipTemplate) { return alienDeployment.getAllRelationshipDeploymentArtifacts().containsKey( new Relationship(relationshipTemplate.getId(), relationshipTemplate.getSource(), relationshipTemplate.getRelationshipTemplate().getTarget())); } public List<Relationship> getAllRelationshipWithDeploymentArtifacts(PaaSNodeTemplate nodeTemplate) { List<Relationship> relationships = Lists.newArrayList(); for (Relationship relationship : alienDeployment.getAllRelationshipDeploymentArtifacts().keySet()) { if (relationship.getTarget().equals(nodeTemplate.getId())) { relationships.add(relationship); } } return relationships; } public Map<String, String> listArtifactDirectory(final String artifactPath) throws IOException { final Map<String, String> children = Maps.newHashMap(); final Path realArtifactPath = recipePath.resolve(artifactPath); Files.walkFileTree(realArtifactPath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String relativePath = FileUtil.getChildEntryRelativePath(realArtifactPath, file, true); String absolutePath = FileUtil.getChildEntryRelativePath(recipePath, file, true); children.put(relativePath, absolutePath); return super.visitFile(file, attrs); } }); return children; } public boolean isArtifactDirectory(String artifactPath) { return Files.isDirectory(recipePath.resolve(artifactPath)); } public boolean operationHasDeploymentArtifacts(OperationWrapper operationWrapper) { return MapUtils.isNotEmpty(operationWrapper.getAllDeploymentArtifacts()) || MapUtils.isNotEmpty(operationWrapper.getAllRelationshipDeploymentArtifacts()); } public String getOperationOutputNames(Operation operation) { if (operation.getOutputs() != null && !operation.getOutputs().isEmpty()) { StringBuilder result = new StringBuilder(); for (OperationOutput operationOutput : operation.getOutputs()) { if (result.length() > 0) { result.append(";"); } result.append(operationOutput.getName()); } return result.toString(); } else { return null; } } public boolean isOperationOwnedByRelationship(OperationWrapper operationWrapper) { return (operationWrapper.getOwner() instanceof PaaSRelationshipTemplate); } public boolean isOperationOwnedByNode(OperationWrapper operationWrapper) { return (operationWrapper.getOwner() instanceof PaaSNodeTemplate); } public boolean isNonNative(PaaSNodeTemplate nodeTemplate) { return alienDeployment.getNonNatives().contains(nodeTemplate); } public String getArtifactPath(String nodeId, String artifactId, DeploymentArtifact artifact) { return mappingConfiguration.getArtifactDirectoryName() + "/" + nodeId + "/" + artifactId + "/" + Paths.get(artifact.getArtifactPath()).getFileName().toString(); } public String getRelationshipArtifactPath(String sourceId, String relationshipId, String artifactId, DeploymentArtifact artifact) { return mappingConfiguration.getArtifactDirectoryName() + "/" + sourceId + "/" + relationshipId + "/" + artifactId + "/" + Paths.get(artifact.getArtifactPath()).getFileName().toString(); } public String getImplementationArtifactPath(PaaSNodeTemplate owner, String interfaceName, String operationName, ImplementationArtifact artifact) { return mappingConfiguration.getImplementationArtifactDirectoryName() + "/" + owner.getId() + "/" + interfaceName + "/" + operationName + "/" + Paths.get(artifact.getArtifactPath()).getFileName().toString(); } public String getRelationshipImplementationArtifactPath(PaaSRelationshipTemplate owner, String interfaceName, String operationName, ImplementationArtifact artifact) { return mappingConfiguration.getImplementationArtifactDirectoryName() + "/" + owner.getSource() + "_" + owner.getTemplate().getTarget() + "/" + owner.getId() + "/" + interfaceName + "/" + operationName + "/" + Paths.get(artifact.getArtifactPath()).getFileName().toString(); } public String getArtifactWrapperPath(IPaaSTemplate<?> owner, String interfaceName, String operationName) { String wrapperPath = mappingConfiguration.getGeneratedArtifactPrefix() + "_" + operationName + ".py"; if (owner instanceof PaaSNodeTemplate) { PaaSNodeTemplate ownerNode = (PaaSNodeTemplate) owner; return "wrapper/" + ownerNode.getId() + "/" + interfaceName + "/" + operationName + "/" + wrapperPath; } else if (owner instanceof PaaSRelationshipTemplate) { PaaSRelationshipTemplate ownerRelationship = (PaaSRelationshipTemplate) owner; return "wrapper/" + ownerRelationship.getSource() + "_" + ownerRelationship.getTemplate().getTarget() + "/" + ownerRelationship.getId() + "/" + interfaceName + "/" + operationName + "/" + wrapperPath; } else { throw new NotSupportedException("Not supported template type " + owner.getId()); } } /** * Utility method to know where the operation should be executed (on the host node or management node). * * @param operation The operation for which to check hosting. * @return True if the operation should be executed on the host node and false if the operation should be executed on the management agent. */ public boolean isHostAgent(PaaSNodeTemplate node, Operation operation) { if (isCustomResource(node)) { return false; } // If the node is compute only the create operation is executed on central node. Other operations are called on the compute instance (that we should be // able to connect to after create). // We also check the artifact as some artifacts are anyway executed on central node. ICloudifyImplementationArtifact cloudifyImplementationArtifact = artifactRegistryService .getCloudifyImplementationArtifact(operation.getImplementationArtifact().getArtifactType()); if (cloudifyImplementationArtifact != null) { return cloudifyImplementationArtifact.hostAgentExecution(); } return true; } /** * In the node properties, isolate: * <ul> * <li>those related to cloudify type inherited properties.</li> * <li>properties that can be serailized as string (for kubernetes)</li> * </ul> */ public Map<String, AbstractPropertyValue> getCloudifyAndSimpleProperties(PaaSNodeTemplate node) { String cloudifyType = this.getDerivedFromType(node.getIndexedToscaElement().getDerivedFrom()); Set<String> cloudifyProperies = this.mappingConfiguration.getCloudifyProperties().get(cloudifyType); Map<String, String> propertyValuesAsString = this.getNodeProperties(node); Map<String, AbstractPropertyValue> result = Maps.newHashMap(); if (cloudifyProperies == null) { cloudifyProperies = Sets.newHashSet(); } for (Entry<String, AbstractPropertyValue> e : node.getTemplate().getProperties().entrySet()) { if (cloudifyProperies.contains(e.getKey())) { // for custom native nodes we add inherited cloudify properties result.put(e.getKey(), e.getValue()); } else if (propertyValuesAsString.containsKey(e.getKey())) { // for kubernetes we add simple scalar properties result.put(e.getKey(), new ScalarPropertyValue(propertyValuesAsString.get(e.getKey()))); } } return result; } /** * In the node propertiy definitions, exclude those inherited from cloudify type. */ public Map<String, PropertyDefinition> excludeCloudifyPropertyDefinitions(NodeType nodeType) { String cloudifyType = this.getDerivedFromType(nodeType.getDerivedFrom()); Set<String> cloudifyProperies = this.mappingConfiguration.getCloudifyProperties().get(cloudifyType); Map<String, PropertyDefinition> result = Maps.newHashMap(); if (cloudifyProperies != null && !cloudifyProperies.isEmpty()) { for (Entry<String, PropertyDefinition> e : nodeType.getProperties().entrySet()) { if (!cloudifyProperies.contains(e.getKey())) { result.put(e.getKey(), e.getValue()); } } } else if (nodeType.getProperties() != null) { result.putAll(nodeType.getProperties()); } return result; } /** * A custom resource is a template that: * <ul> * <li>is not of a type provided by the location</li> * <li>AND doesn't have a host</li> * </ul> * * @param node * @return true is the node is considered as a custom template. */ public boolean isCustomResource(PaaSNodeTemplate node) { return this.alienDeployment.getCustomResources().containsValue(node); } public boolean isCompute(PaaSNodeTemplate node) { return ToscaNormativeUtil.isFromType(NormativeComputeConstants.COMPUTE_TYPE, node.getIndexedToscaElement()); } public boolean isServiceNodeTemplate(PaaSNodeTemplate node) { return node.getTemplate() instanceof ServiceNodeTemplate; } public boolean isEndpoint(String capabilityTypeName) { CapabilityType capabilityType = alienDeployment.getCapabilityTypes().get(capabilityTypeName); return capabilityType != null && (NormativeCapabilityTypes.ENDPOINT.equals(capabilityType.getElementId()) || (capabilityType.getDerivedFrom() != null && capabilityType.getDerivedFrom().contains(NormativeCapabilityTypes.ENDPOINT))); } }
package com.creativemd.littletiles.common.structure; import java.util.ArrayList; import java.util.List; import com.creativemd.creativecore.common.utils.ColorUtils; import com.creativemd.creativecore.common.utils.ColoredCube; import com.creativemd.littletiles.client.tiles.LittleRenderingCube; import com.creativemd.littletiles.common.tileentity.TileEntityLittleTiles; import com.creativemd.littletiles.common.tiles.LittleTile; import com.creativemd.littletiles.common.tiles.place.PlacePreviewTile; import com.creativemd.littletiles.common.tiles.preview.LittleTilePreview; import com.creativemd.littletiles.common.tiles.vec.LittleTileBox; import com.creativemd.littletiles.common.tiles.vec.LittleTileVec; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; public class PlacePreviewTileAxis extends PlacePreviewTile{ public static int red = ColorUtils.VecToInt(new Vec3d(1, 0, 0)); public EnumFacing.Axis axis; public LittleTileVec additionalOffset; public PlacePreviewTileAxis(LittleTileBox box, LittleTilePreview preview, EnumFacing.Axis axis, LittleTileVec additionalOffset) { super(box, preview); this.axis = axis; this.additionalOffset = additionalOffset; } @Override public boolean needsCollisionTest() { return false; } @Override public PlacePreviewTile copy() { return new PlacePreviewTileAxis(box.copy(), null, axis, additionalOffset.copy()); } @Override public List<LittleRenderingCube> getPreviews() { ArrayList<LittleRenderingCube> cubes = new ArrayList<>(); LittleTileBox preview = box.copy(); int max = 40*LittleTile.gridSize; int min = -max; switch(axis) { case X: preview.minX = min; preview.maxX = max; break; case Y: preview.minY = min; preview.maxY = max; break; case Z: preview.minZ = min; preview.maxZ = max; break; default: break; } LittleRenderingCube cube = preview.getRenderingCube(null, 0); cube.sub(new Vec3d(LittleTile.gridMCLength/2, LittleTile.gridMCLength/2, LittleTile.gridMCLength/2)); cube.add(additionalOffset.getVec().scale(0.5)); cube.color = red; cubes.add(cube); return cubes; } @Override public LittleTile placeTile(EntityPlayer player, ItemStack stack, BlockPos pos, TileEntityLittleTiles teLT, LittleStructure structure, ArrayList<LittleTile> unplaceableTiles, boolean forced, EnumFacing facing, boolean requiresCollisionTest) { if(structure instanceof LittleDoor) { LittleDoor door = (LittleDoor) structure; door.doubledRelativeAxis = box.getMinVec(); door.doubledRelativeAxis.add(pos); if(door.getMainTile() == null) door.selectMainTile(); if(door.getMainTile() != null) door.doubledRelativeAxis.sub(door.getMainTile().getAbsoluteCoordinates()); door.doubledRelativeAxis.scale(2); door.doubledRelativeAxis.add(additionalOffset); } return null; } /*@Override public boolean split(HashMapList<ChunkCoordinates, PreviewTile> tiles, int x, int y, int z) { tiles.add(new ChunkCoordinates(x, y, z), this); return true; }*/ }
package com.planet_ink.coffee_mud.Behaviors; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.CMSecurity.DbgFlag; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.MaskingLibrary.CompiledZMask; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; public class Sailor extends StdBehavior { @Override public String ID() { return "Sailor"; } public Sailor() { } protected volatile int tickDown = -1; protected int tickWait = -1; protected int tickBonus = 0; protected Boardable loyalShipArea = null; protected Item loyalShipItem = null; protected Rideable targetShipItem = null; protected boolean combatIsOver = false; protected boolean peaceMover = false; protected boolean combatMover = true; protected boolean combatTech = true; protected boolean boarder = false; protected boolean defender = false; protected boolean aggressive = false; protected boolean aggrMobs = false; protected boolean aggrLvlChk = false; protected CompiledZMask aggrMask = null; protected boolean areaOnly = true; protected boolean wimpy = true; protected volatile int complaintTick = 0; //protected int targetShipDist = -1; @Override public String accountForYourself() { if(getParms().trim().length()>0) return "aggression against "+CMLib.masking().maskDesc(getParms(),true).toLowerCase(); else return "aggressiveness"; } @Override public long flags() { if(boarder) return Behavior.FLAG_MOBILITY | Behavior.FLAG_POTENTIALLYAGGRESSIVE | Behavior.FLAG_TROUBLEMAKING; else if(defender) return Behavior.FLAG_POTENTIALLYAGGRESSIVE | Behavior.FLAG_TROUBLEMAKING; else return 0; } public Item getShip(final MOB M) { if(M.getStartRoom() instanceof Boardable) { final Item hisShip=((Boardable)M.getStartRoom()).getBoardableItem(); if(hisShip != null) return hisShip; } if(M.amFollowing()!=null) { final Item folship = getShip(M.amFollowing()); if(folship != null) return folship; } if(M.isPlayer()) { final Room R=M.location(); if((R!=null)&&(R.getArea() instanceof Boardable)) { final Item shipI=((Boardable)R.getArea()).getBoardableItem(); if((shipI!=null)&&(CMLib.law().doesHaveWeakPriviledgesHere(M, M.location()))) return shipI; final Room shipR=CMLib.map().roomLocation(shipI); if(shipR!=null) { for(final Enumeration<Item> i=shipR.items();i.hasMoreElements();) { final Item I=i.nextElement(); if((I instanceof Boardable)&&(I!=shipI)) { final Item otherShipI=((Boardable)I).getBoardableItem(); final Area otherShipA=((Boardable)I).getArea(); if((otherShipI!=null) &&(otherShipA!=null) &&(CMLib.law().doesHaveWeakPriviledgesHere(M, otherShipA.getRandomProperRoom()))) return otherShipI; } } } } } return null; } public boolean amOnMyShip(final MOB M) { final Room R=M.location(); if((R!=null)&&(R.getArea() instanceof Boardable)) return (((Boardable)R.getArea()).getBoardableItem() == loyalShipItem); return false; } public boolean isMyShipInCombat(final MOB M) { if(loyalShipItem instanceof NavigableItem) { return ((NavigableItem)loyalShipItem).isInCombat(); } return false; } @Override public boolean grantsAggressivenessTo(final MOB M) { if(boarder || defender) { final Item hisShipI=getShip(M); if((hisShipI == this.loyalShipItem)||(this.loyalShipItem==null)||(hisShipI==null)) return false; if(this.loyalShipItem instanceof NavigableItem) { final NavigableItem myShip=(NavigableItem)this.loyalShipItem; final ItemTicker I1=(ItemTicker)myShip.fetchEffect("ItemRejuv"); final ItemTicker I2=(ItemTicker)hisShipI.fetchEffect("ItemRejuv"); if((I1!=null) &&(I2!=null) &&(I1.properLocation()==I2.properLocation())) return false; final PhysicalAgent myCombatTarget=myShip.getCombatant(); if((myCombatTarget != null) &&(myCombatTarget == hisShipI)) return true; } if(hisShipI instanceof NavigableItem) { final PhysicalAgent hisCombatTarget=((NavigableItem)hisShipI).getCombatant(); if((hisCombatTarget != null) &&(hisCombatTarget == this.loyalShipItem)) return true; } if(M.amFollowing()!=null) return grantsAggressivenessTo(M.amFollowing()); } return false; } @Override public void setParms(final String newParms) { super.setParms(newParms); tickWait = CMParms.getParmInt(newParms, "TICKDELAY", -1); tickBonus = CMParms.getParmInt(newParms, "TICKBONUS", 0); peaceMover = CMParms.getParmBool(newParms, "PEACEMOVER", false); areaOnly = CMParms.getParmBool(newParms, "AREAONLY", true); combatMover = CMParms.getParmBool(newParms, "FIGHTMOVER", true); combatTech = CMParms.getParmBool(newParms, "FIGHTTECH", true); boarder = CMParms.getParmBool(newParms, "BOARDER", false); defender = CMParms.getParmBool(newParms, "DEFENDER", false); aggressive = CMParms.getParmBool(newParms, "AGGRO", false); aggrMobs = CMParms.getParmBool(newParms, "AGGROMOBS", false); aggrLvlChk = CMParms.getParmBool(newParms, "AGGROLEVELCHECK", false); aggrMask = CMLib.masking().maskCompile(CMParms.getParmStr(newParms, "AGGROMASK", "")); wimpy = CMParms.getParmBool(newParms, "WIMPY", true); loyalShipArea = null; loyalShipItem = null; } @Override public CMObject copyOf() { final Sailor S=(Sailor)super.copyOf(); S.loyalShipArea=null; S.loyalShipItem=null; return S; } @Override public boolean okMessage(final Environmental host, final CMMsg msg) { if(!super.okMessage(host, msg)) return false; switch(msg.sourceMinor()) { case CMMsg.TYP_ENTER: if((this.loyalShipItem!=null) &&(msg.source().riding() == this.loyalShipItem) &&(msg.target() instanceof Room) &&(msg.source().isMonster()) &&(msg.source().Name().equals(this.loyalShipItem.Name())) ) { final Area shipA=CMLib.map().areaLocation(loyalShipItem); final Room targetR=(Room)msg.target(); if((areaOnly) && (shipA != targetR.getArea())) return false; } break; } return true; } @Override public void executeMsg(final Environmental affecting, final CMMsg msg) { super.executeMsg(affecting, msg); if(this.loyalShipItem!=null) { switch(msg.sourceMinor()) { case CMMsg.TYP_ADVANCE: if((msg.target() instanceof Rideable) &&(msg.target() instanceof Item) &&(CMath.bset(msg.targetMajor(), CMMsg.MASK_MALICIOUS)) &&(msg.source().riding() == loyalShipItem)) { targetShipItem = (Rideable)msg.target(); } else if((msg.target() == loyalShipItem) &&(CMath.bset(msg.targetMajor(), CMMsg.MASK_MALICIOUS)) &&(msg.source().riding() != loyalShipItem)) { targetShipItem = (Rideable)msg.target(); } break; case CMMsg.TYP_ENTER: if((msg.source()!=null) &&(msg.source().riding() == this.loyalShipItem) &&(msg.source().isMonster()) &&(msg.source().Name().equals(this.loyalShipItem.Name()))) { } break; } } } public boolean tryMend(final MOB mob) { if(((NavigableItem)loyalShipItem).navBasis() == Rideable.Basis.LAND_BASED) { if(CMLib.flags().domainAffects(mob, Ability.ACODE_COMMON_SKILL).size()==0) { final Ability A=CMClass.getAbility("CaravanBuilding"); if((A!=null) &&((A.proficiency()==0)||(A.proficiency()==100))) { A.setProficiency((mob.phyStats().level()+1) * 4 * 3); if(A.proficiency() >= 100) A.setProficiency(99); } final Ability mend=mob.fetchAbility("CaravanBuilding"); if(mend != null) { mob.enqueCommand(new XVector<String>("CARAVANBUILD","MEND",loyalShipItem.Name()), 0, 0); return true; } } } else { if(CMLib.flags().domainAffects(mob, Ability.ACODE_COMMON_SKILL).size()==0) { final Ability A=CMClass.getAbility("Shipwright"); if((A!=null) &&((A.proficiency()==0)||(A.proficiency()==100))) { A.setProficiency((mob.phyStats().level()+1) * 4 * 3); if(A.proficiency() >= 100) A.setProficiency(99); } final Ability mend=mob.fetchAbility("Shipwright"); if(mend != null) { mob.enqueCommand(new XVector<String>("SHIPWRIGHT","MEND",loyalShipItem.Name()), 0, 0); return true; } } } return false; } public boolean tryTrawl(final MOB mob) { if(((NavigableItem)loyalShipItem).navBasis() == Rideable.Basis.WATER_BASED) { if(CMLib.flags().domainAffects(mob, Ability.ACODE_COMMON_SKILL).size()==0) { final Ability A=CMClass.getAbility("Trawling"); if((A!=null) &&((A.proficiency()==0)||(A.proficiency()==100))) { A.setProficiency((mob.phyStats().level()+1) * 4 * 3); if(A.proficiency() >= 100) A.setProficiency(99); } final Ability mend=mob.fetchAbility("Trawling"); if(mend != null) { mob.enqueCommand(new XVector<String>("TRAWL"), 0, 0); return true; } } } return false; } protected boolean amInTrouble() { return (wimpy &&(loyalShipItem!=null) &&(this.targetShipItem!=null) &&(combatMover) &&(((Item)targetShipItem).subjectToWearAndTear()) &&(loyalShipItem.subjectToWearAndTear()) &&((((Item)targetShipItem).usesRemaining() - loyalShipItem.usesRemaining()) > 33)); } protected boolean isGoodShipDir(final Room shipR, final int dir) { final Room R=shipR.getRoomInDir(dir); final Exit E=shipR.getExitInDir(dir); if((R!=null) &&(CMLib.flags().isWateryRoom(R)) &&(E!=null) &&(E.isOpen()) &&((!areaOnly)||(CMLib.map().areaLocation(shipR)==CMLib.map().areaLocation(R)))) return true; return false; } protected int getEscapeRoute(final int directionToTarget) { if(directionToTarget < 0) return directionToTarget; final Room shipR=CMLib.map().roomLocation(loyalShipItem); if(shipR!=null) { final int opDir=Directions.getOpDirectionCode(directionToTarget); if(isGoodShipDir(shipR,opDir)) return opDir; final List<Integer> goodDirs = new ArrayList<Integer>(); for(final int dir : Directions.CODES()) { if(isGoodShipDir(shipR,dir)) goodDirs.add(Integer.valueOf(dir)); } final Integer dirI=Integer.valueOf(directionToTarget); if(goodDirs.contains(dirI) &&(goodDirs.size()>1)) goodDirs.remove(dirI); if(goodDirs.size()>0) return goodDirs.get(0).intValue(); } return -1; } protected boolean canMoveShip() { return ((loyalShipItem!=null) &&(!CMSecurity.isDisabled(CMSecurity.DisFlag.MOBILITY)) &&(loyalShipItem.owner() instanceof Room) &&(((Room)loyalShipItem.owner()).getMobility()) &&(!CMLib.tracking().isAnAdminHere((Room)loyalShipItem.owner(), true))); } @Override public boolean tick(final Tickable ticking, final int tickID) { super.tick(ticking,tickID); if((tickID!=Tickable.TICKID_MOB) ||(!(ticking instanceof MOB))) return true; if(tickWait < 0) { if(ticking instanceof Physical) { tickWait = (20 - tickBonus - ((Physical)ticking).phyStats().level() / 4); if(tickWait < 0) tickWait=0; } else tickWait = 10000; } if((--tickDown)<0) { tickDown=tickWait; if((ticking instanceof MOB) &&(CMLib.flags().canFreelyBehaveNormal(ticking))) { final MOB mob=(MOB)ticking; final Room mobRoom=mob.location(); if(mobRoom==null) return true; if((loyalShipItem==null) &&(mobRoom.getArea() instanceof Boardable)) { loyalShipArea = (Boardable)mobRoom.getArea(); loyalShipItem = loyalShipArea.getBoardableItem(); if((mob.isMonster()) &&(mob.amFollowing()==null) &&(!CMLib.flags().isAnimalIntelligence(mob))) { if(mob.getStartRoom()==null) mob.setStartRoom(mob.location()); else if((mob.getStartRoom().getArea()!=loyalShipArea) &&(mob.getStartRoom().roomID().length()>0) &&(mob.isSavable())) { final MOB newM = (MOB) mob.copyOf(); newM.basePhyStats().setRejuv(PhyStats.NO_REJUV); newM.phyStats().setRejuv(PhyStats.NO_REJUV); newM.setStartRoom(mob.location()); mob.location().addInhabitant(newM); mob.delBehavior(this); newM.delBehavior(newM.fetchBehavior(ID())); this.tickDown=0; newM.addBehavior(this); newM.text(); mob.killMeDead(false); return true; } } } if(loyalShipItem==null) return true; final boolean inShipCombat = this.isMyShipInCombat(mob); if((inShipCombat) &&(this.targetShipItem==null) &&(loyalShipItem instanceof NavigableItem) &&(((NavigableItem)loyalShipItem).getCombatant() instanceof Rideable)) this.targetShipItem = (Rideable)((NavigableItem)loyalShipItem).getCombatant(); boolean amIInCombat = mob.isInCombat(); if((defender || boarder)&&(!amIInCombat)) { if(inShipCombat) { if(mobRoom.numInhabitants()>1) { for(final Enumeration<MOB> m=mobRoom.inhabitants();m.hasMoreElements();) { final MOB M=m.nextElement(); if((M!=null) &&(M!=mob) &&(mob.mayPhysicallyAttack(M)) &&(grantsAggressivenessTo(M)) &&((!aggrLvlChk)||(mob.phyStats().level()<(M.phyStats().level()+5))) &&(CMLib.masking().maskCheck(aggrMask,M,false))) { if(CMLib.combat().postAttack(mob, M, mob.fetchWieldedItem())) { amIInCombat=true; break; } } } } if(boarder && (!amIInCombat) && (!this.amOnMyShip(mob))) { CMLib.tracking().beMobile(mob, true, false, false, false, null, null); } } else if(!amOnMyShip(mob)) { if((mob.getStartRoom() != null)&&(mob.getStartRoom().getArea() instanceof Boardable)) { CMLib.tracking().wanderAway(mob, false, true); } } } if(mobRoom.getArea() != loyalShipArea) return true; if((targetShipItem!=null) &&CMLib.map().roomLocation(targetShipItem)!=CMLib.map().roomLocation(loyalShipItem)) { combatIsOver=true; targetShipItem = null; //stop combat signal } if((loyalShipItem instanceof NavigableItem) && (((combatMover && (targetShipItem != null)) || peaceMover))) { if((((NavigableItem)loyalShipItem).isAnchorDown()) &&(canMoveShip())) { if(((NavigableItem)loyalShipItem).navBasis() == Rideable.Basis.WATER_BASED) mob.enqueCommand(new XVector<String>("RAISE","ANCHOR"), 0, 0); else mob.enqueCommand(new XVector<String>("UNSET","BRAKE"), 0, 0); return true; } } if((loyalShipItem.owner() instanceof Room) &&(loyalShipItem.owner() instanceof GridLocale) &&(((Room)loyalShipItem.owner()).getGridParent()==null) &&(canMoveShip())) ((GridLocale)loyalShipItem.owner()).getRandomGridChild().moveItemTo(loyalShipItem); if((targetShipItem != null)&&(loyalShipItem instanceof SiegableItem)) { final SiegableItem sailShip=(SiegableItem)loyalShipItem; final int distanceToTarget= sailShip.rangeToTarget(); if(loyalShipItem.subjectToWearAndTear() &&(CMLib.dice().rollPercentage() >= loyalShipItem.usesRemaining()) &&(CMLib.dice().rollPercentage()<50) &&(tryMend(mob))) return true; if(combatTech) { boolean roomHasWeapons = false; for(final Enumeration<Item> i=mobRoom.items();i.hasMoreElements();) { final Item I=i.nextElement(); if(CMLib.combat().isASiegeWeapon(I) &&(I instanceof AmmunitionWeapon) &&(((AmmunitionWeapon)I).ammunitionCapacity() > 0) &&(((AmmunitionWeapon)I).ammunitionRemaining() < ((AmmunitionWeapon)I).ammunitionCapacity())) { // found one to load! for(final Enumeration<Item> i2=mob.items();i2.hasMoreElements();) { final Item I2=i2.nextElement(); if((I2 instanceof Ammunition) &&(I2.container()==null) &&(((Ammunition)I2).ammunitionType().equals(((AmmunitionWeapon)I).ammunitionType()))) { mob.enqueCommand(new XVector<String>("LOAD",I2.Name(),mobRoom.getContextName(I)), 0, 0); complaintTick=0; return true; } } for(final Enumeration<Item> i2=mobRoom.items();i2.hasMoreElements();) { final Item I2=i2.nextElement(); if((I2 instanceof Ammunition) &&(I2.container()==null) &&(((Ammunition)I2).ammunitionType().equals(((AmmunitionWeapon)I).ammunitionType()))) { if(complaintTick>2) { CMLib.commands().postSay(mob, L("I can't seem to get any @x1.",((AmmunitionWeapon)I).ammunitionType())); complaintTick=0; } mob.enqueCommand(new XVector<String>("GET",""+((AmmunitionWeapon)I).ammunitionCapacity(),I2.Name()), 0, 0); complaintTick++; return true; } } } } int targetSpeed = (targetShipItem instanceof NavigableItem)?((NavigableItem)targetShipItem).getMaxSpeed():1; if(targetSpeed == 0) targetSpeed = 1; final PairList<Weapon,int[]> aimings = sailShip.getSiegeWeaponAimings(); for(final Enumeration<Item> i=mobRoom.items();i.hasMoreElements();) { final Item I=i.nextElement(); if(CMLib.combat().isASiegeWeapon(I)) { roomHasWeapons = true; if((I instanceof AmmunitionWeapon) &&(!aimings.containsFirst((Weapon)I)) &&(((AmmunitionWeapon)I).ammunitionRemaining() >= ((AmmunitionWeapon)I).ammunitionCapacity()) &&(distanceToTarget >= ((AmmunitionWeapon)I).minRange()) &&(distanceToTarget <= ((AmmunitionWeapon)I).maxRange())) { final int aimPt = CMLib.dice().roll(1, targetSpeed, -1); mob.enqueCommand(new XVector<String>(SiegableItem.SiegeCommand.AIM.name(),mobRoom.getContextName(I),""+aimPt), 0, 0); return true; } } } boolean isSecondFiddle=false; if(roomHasWeapons) { for(final Enumeration<MOB> m=mobRoom.inhabitants();m.hasMoreElements();) { final MOB M=m.nextElement(); if(M==mob) break; if(M!=null) { final Sailor S=(Sailor)M.fetchBehavior(ID()); if((S!=null)&&(S.combatTech)&&(S.loyalShipItem==loyalShipItem)) { isSecondFiddle=true; break; } } } } if(isSecondFiddle || (!roomHasWeapons)) { final List<Integer> choices=new ArrayList<Integer>(1); for(int d=0;d<Directions.NUM_DIRECTIONS();d++) { final Room nextR=mobRoom.getRoomInDir(d); final Exit nextE=mobRoom.getExitInDir(d); if((nextR!=null)&&(nextE!=null)&&(nextE.isOpen())) { for(final Enumeration<Item> i=nextR.items();i.hasMoreElements();) { final Item I=i.nextElement(); if(CMLib.combat().isASiegeWeapon(I)) { choices.add(Integer.valueOf(d)); } } } } if(choices.size()>0) CMLib.tracking().walk(mob, choices.get(CMLib.dice().roll(1, choices.size(), -1)).intValue(), false, false); else if(!roomHasWeapons) { CMLib.tracking().beMobile(mob, true, false, false, false, null, null); } } } if(defender && ((mobRoom.domainType() & Room.INDOORS) != 0)) { CMLib.tracking().beMobile(mob, true, false, false, false, null, null); } if((boarder || CMLib.flags().isMobile(mob))) { if (distanceToTarget==0) { for(final Enumeration<Item> i=mob.items();i.hasMoreElements();) { final Item I=i.nextElement(); if((I!=null) &&(I.ID().endsWith("Grapples")) &&(I.container()==null)) mob.enqueCommand(new XVector<String>("HOLD",I.Name()), 0, 0); } final Item heldI=mob.fetchHeldItem(); if((heldI != null)&&(heldI.ID().endsWith("Grapples"))) mob.enqueCommand(new XVector<String>("THROW",heldI.Name(),this.targetShipItem.Name()), 0, 0); for(final Enumeration<Item> i=mobRoom.items();i.hasMoreElements();) { final Item I=i.nextElement(); if((I!=null) &&(I.ID().endsWith("Grapples")) &&(I instanceof Exit) &&(((Exit)I).lastRoomUsedFrom(mobRoom)!=null)) mob.enqueCommand(new XVector<String>("ENTER",mobRoom.getContextName(I)), 0, 0); } } if(boarder) { CMLib.tracking().beMobile(mob, true, false, false, false, null, null); } } if((combatMover) &&((!(loyalShipItem instanceof PrivateProperty)) ||(((PrivateProperty)loyalShipItem).getOwnerName().length()==0) ||CMLib.law().doesOwnThisProperty(mob, (PrivateProperty)loyalShipItem)) &&(loyalShipItem instanceof NavigableItem) &&(canMoveShip()) ) { int ourSpeed = ((NavigableItem)loyalShipItem).getMaxSpeed(); if(ourSpeed == 0) ourSpeed = 1; ourSpeed=CMLib.dice().roll(1, ourSpeed, 0); final XVector<String> course=new XVector<String>("COURSE"); final int lastDirI = ((NavigableItem)loyalShipItem).getDirectionFacing(); String lastDir=(lastDirI>=0)?CMLib.directions().getDirectionName(lastDirI):""; if((lastDir==null)||(lastDir.length()==0)) lastDir = CMLib.directions().getDirectionName(CMLib.dice().roll(1, 4, -1)); final int directionToTarget = ((NavigableItem)loyalShipItem).getDirectionToTarget(); if(this.amInTrouble() && (ourSpeed >0)) { final int escapeDir = this.getEscapeRoute(directionToTarget); if(escapeDir >=0) { if((ourSpeed>1)&&(((NavigableItem)loyalShipItem).getDirectionFacing() != escapeDir)) ourSpeed=1; for(int i=0;i<ourSpeed;i++) course.add(CMLib.directions().getDirectionName(escapeDir)); ourSpeed = 0; } } while(ourSpeed > 0) { if(ourSpeed == 1) { if((distanceToTarget > 5)&&(directionToTarget>=0)) course.add(CMLib.directions().getDirectionName(directionToTarget)); else if((CMLib.dice().rollPercentage()<30)&&(directionToTarget>=0)) course.add(CMLib.directions().getDirectionName(directionToTarget)); else course.add(lastDir); } else course.add(lastDir); ourSpeed } if(CMSecurity.isDebugging(DbgFlag.SIEGECOMBAT)) Log.debugOut("Sailor chose "+CMParms.toListString(course)+" for "+loyalShipItem.Name()); mob.enqueCommand(course, 0, 0); } } else { if(loyalShipItem.subjectToWearAndTear() &&(loyalShipItem.usesRemaining() < 100)) { tryMend(mob); } tryTrawl(mob); if(combatIsOver && (boarder || CMLib.flags().isMobile(mob))) { combatIsOver = false; if(combatMover && (!peaceMover)) { mob.enqueCommand(new XVector<String>("COURSE"), 0, 0); if(((NavigableItem)loyalShipItem).navBasis() == Rideable.Basis.WATER_BASED) mob.enqueCommand(new XVector<String>("LOWER","ANCHOR"), 0, 0); else mob.enqueCommand(new XVector<String>("SET","BRAKE"), 0, 0); } for(final Enumeration<Item> i=mobRoom.items();i.hasMoreElements();) { final Item I=i.nextElement(); if((I!=null)&&(I.ID().endsWith("Grapples"))) mob.enqueCommand(new XVector<String>("GET",mobRoom.getContextName(I)), 0, 0); } } final Room shipRoom=CMLib.map().roomLocation(loyalShipItem); if((aggressive)&&(shipRoom!=null)) { for(final Enumeration<Item> i=shipRoom.items();i.hasMoreElements();) { final Item I=i.nextElement(); if((I!=null) &&(I.container()==null) &&(I!=loyalShipItem) &&((I instanceof Boardable) ||((I instanceof Rideable)&&(((Rideable)I).rideBasis()==Rideable.Basis.WATER_BASED))) &&(CMLib.flags().canBeSeenBy(I, mob))) { final LinkedList<MOB> eligible=new LinkedList<MOB>(); if(I instanceof Rideable) { for(final Enumeration<Rider> r=((Rideable)I).riders();r.hasMoreElements();) { final Rider R=r.nextElement(); if((R instanceof MOB) &&((aggrMobs) || (((MOB)R).isPlayer()))) eligible.add((MOB)R); } } if(I instanceof Boardable) { final Area shipArea=((Boardable)I).getArea(); if(shipArea!=null) { for(final Enumeration<Room> r=shipArea.getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); if(R!=null) { for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();) { final MOB M=m.nextElement(); if((M!=null) &&((aggrMobs) || M.isPlayer())) eligible.add(M); } } } } } if(eligible.size()>0) { MOB captaiM = null; for(final MOB M : eligible) { if((M.isPlayer()) &&(CMLib.law().doesHaveWeakPriviledgesHere(M, M.location()))) captaiM=M; } if(captaiM == null) { final MOB[] Ms=new MOB[5]; for(final MOB M : eligible) { if(!M.isPlayer()) { final Sailor oS=(Sailor)M.fetchBehavior(ID()); if(oS!=null) { if(oS.combatMover) Ms[0]=M; if(oS.peaceMover) Ms[1]=M; if(oS.combatTech) Ms[2]=M; if(oS.boarder) Ms[3]=M; if(oS.defender) Ms[4]=M; } } } for(int x=0;x<Ms.length;x++) { if(Ms[x]!=null) captaiM=Ms[x]; } } if(captaiM == null) { for(final MOB M : eligible) { if((!M.isPlayer()) &&(CMLib.law().doesHaveWeakPriviledgesHere(M, M.location()))) captaiM=M; } } if(captaiM==null) { for(final MOB M : eligible) { if(M.isPlayer()) captaiM=M; } } if(captaiM==null) captaiM=eligible.get(0); if((captaiM!=null) &&((!aggrLvlChk)||(mob.phyStats().level()<(captaiM.phyStats().level()+5))) &&(CMLib.masking().maskCheck(aggrMask,captaiM,false))) mob.enqueCommand(new XVector<String>(SiegableItem.SiegeCommand.TARGET.name(),mobRoom.getContextName(I)), 0, 0); } } } } if((peaceMover) &&((!(loyalShipItem instanceof PrivateProperty)) ||(((PrivateProperty)loyalShipItem).getOwnerName().length()==0) ||CMLib.law().doesOwnThisProperty(mob, (PrivateProperty)loyalShipItem)) &&(loyalShipItem instanceof NavigableItem) &&(canMoveShip()) ) { int ourSpeed = ((NavigableItem)loyalShipItem).getMaxSpeed(); if(ourSpeed == 0) ourSpeed = 1; ourSpeed=CMLib.dice().roll(1, ourSpeed, 0); final XVector<String> course=new XVector<String>("COURSE"); Room curRoom=CMLib.map().roomLocation(loyalShipItem); final Integer lastDir = Integer.valueOf(CMLib.dice().roll(1, 4, -1)); int tries=99; while((ourSpeed > 0)&&(--tries>0) && (curRoom!=null)) { Integer nextDir=lastDir; if(ourSpeed == 1) { if(CMLib.dice().rollPercentage()<30) nextDir=Integer.valueOf(CMLib.dice().roll(1, 4, -1)); } if(nextDir != null) { final Room nextRoom=curRoom.getRoomInDir(nextDir.intValue()); if((nextRoom == null) ||((areaOnly)&&(nextRoom.getArea()!=curRoom.getArea()))) nextDir = null; } if(nextDir != null) { course.add(CMLib.directions().getDirectionName(nextDir.intValue())); curRoom=curRoom.getRoomInDir(nextDir.intValue()); ourSpeed } if((tries<20)&&(ourSpeed>1)) ourSpeed=1; } mob.enqueCommand(course, 0, 0); } } } } return true; } }
package com.foundationdb.sql.optimizer.rule; import com.foundationdb.ais.model.Column; import com.foundationdb.ais.model.ColumnContainer; import com.foundationdb.ais.model.Routine; import com.foundationdb.qp.operator.QueryContext; import com.foundationdb.server.error.AkibanInternalException; import com.foundationdb.server.error.SQLParserInternalException; import com.foundationdb.server.types.service.OverloadResolver; import com.foundationdb.server.types.service.OverloadResolver.OverloadResult; import com.foundationdb.server.types.service.TypesRegistryService; import com.foundationdb.server.types.service.TCastResolver; import com.foundationdb.server.types.ErrorHandlingMode; import com.foundationdb.server.types.LazyList; import com.foundationdb.server.types.LazyListBase; import com.foundationdb.server.types.TCast; import com.foundationdb.server.types.TClass; import com.foundationdb.server.types.TExecutionContext; import com.foundationdb.server.types.TInstance; import com.foundationdb.server.types.TKeyComparable; import com.foundationdb.server.types.TOverloadResult; import com.foundationdb.server.types.TPreptimeContext; import com.foundationdb.server.types.TPreptimeValue; import com.foundationdb.server.types.aksql.aktypes.AkBool; import com.foundationdb.server.types.common.types.StringAttribute; import com.foundationdb.server.types.common.types.TBinary; import com.foundationdb.server.types.common.types.TString; import com.foundationdb.server.types.common.types.TypesTranslator; import com.foundationdb.server.types.value.Value; import com.foundationdb.server.types.value.ValueSource; import com.foundationdb.server.types.value.ValueSources; import com.foundationdb.server.types.texpressions.TValidatedScalar; import com.foundationdb.server.types.texpressions.TValidatedOverload; import com.foundationdb.sql.StandardException; import com.foundationdb.sql.optimizer.plan.AggregateFunctionExpression; import com.foundationdb.sql.optimizer.plan.AggregateSource; import com.foundationdb.sql.optimizer.plan.AnyCondition; import com.foundationdb.sql.optimizer.plan.BasePlanWithInput; import com.foundationdb.sql.optimizer.plan.BooleanCastExpression; import com.foundationdb.sql.optimizer.plan.BooleanConstantExpression; import com.foundationdb.sql.optimizer.plan.BooleanOperationExpression; import com.foundationdb.sql.optimizer.plan.CastExpression; import com.foundationdb.sql.optimizer.plan.ColumnDefaultExpression; import com.foundationdb.sql.optimizer.plan.ColumnExpression; import com.foundationdb.sql.optimizer.plan.ColumnSource; import com.foundationdb.sql.optimizer.plan.ComparisonCondition; import com.foundationdb.sql.optimizer.plan.ConditionList; import com.foundationdb.sql.optimizer.plan.ConstantExpression; import com.foundationdb.sql.optimizer.plan.Distinct; import com.foundationdb.sql.optimizer.plan.DMLStatement; import com.foundationdb.sql.optimizer.plan.ExistsCondition; import com.foundationdb.sql.optimizer.plan.ExpressionNode; import com.foundationdb.sql.optimizer.plan.ExpressionRewriteVisitor; import com.foundationdb.sql.optimizer.plan.ExpressionsSource; import com.foundationdb.sql.optimizer.plan.FunctionCondition; import com.foundationdb.sql.optimizer.plan.FunctionExpression; import com.foundationdb.sql.optimizer.plan.IfElseExpression; import com.foundationdb.sql.optimizer.plan.InListCondition; import com.foundationdb.sql.optimizer.plan.InsertStatement; import com.foundationdb.sql.optimizer.plan.Limit; import com.foundationdb.sql.optimizer.plan.NullSource; import com.foundationdb.sql.optimizer.plan.ParameterCondition; import com.foundationdb.sql.optimizer.plan.ParameterExpression; import com.foundationdb.sql.optimizer.plan.PlanNode; import com.foundationdb.sql.optimizer.plan.PlanVisitor; import com.foundationdb.sql.optimizer.plan.Project; import com.foundationdb.sql.optimizer.plan.ResolvableExpression; import com.foundationdb.sql.optimizer.plan.ResultSet; import com.foundationdb.sql.optimizer.plan.ResultSet.ResultField; import com.foundationdb.sql.optimizer.plan.RoutineExpression; import com.foundationdb.sql.optimizer.plan.Select; import com.foundationdb.sql.optimizer.plan.Sort; import com.foundationdb.sql.optimizer.plan.Subquery; import com.foundationdb.sql.optimizer.plan.SubqueryResultSetExpression; import com.foundationdb.sql.optimizer.plan.SubquerySource; import com.foundationdb.sql.optimizer.plan.SubqueryValueExpression; import com.foundationdb.sql.optimizer.plan.TableSource; import com.foundationdb.sql.optimizer.plan.TypedPlan; import com.foundationdb.sql.optimizer.plan.UpdateStatement; import com.foundationdb.sql.optimizer.plan.UpdateStatement.UpdateColumn; import com.foundationdb.sql.optimizer.rule.ConstantFolder.Folder; import com.foundationdb.sql.optimizer.rule.PlanContext.WhiteboardMarker; import com.foundationdb.sql.optimizer.rule.PlanContext.DefaultWhiteboardMarker; import com.foundationdb.sql.types.DataTypeDescriptor; import com.foundationdb.sql.types.TypeId; import com.foundationdb.sql.types.CharacterTypeAttributes; import com.foundationdb.util.SparseArray; import com.google.common.base.Objects; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.List; public final class OverloadAndTInstanceResolver extends BaseRule { private static final Logger logger = LoggerFactory.getLogger(OverloadAndTInstanceResolver.class); @Override protected Logger getLogger() { return logger; } @Override public void apply(PlanContext plan) { Folder folder = new Folder(plan); ResolvingVisitor resolvingVisitor = new ResolvingVisitor(plan, folder); folder.initResolvingVisitor(resolvingVisitor); plan.putWhiteboard(RESOLVER_MARKER, resolvingVisitor); resolvingVisitor.resolve(plan.getPlan()); new TopLevelCastingVisitor(folder, resolvingVisitor.parametersSync).apply(plan.getPlan()); plan.getPlan().accept(ParameterCastInliner.instance); } public static final WhiteboardMarker<ExpressionRewriteVisitor> RESOLVER_MARKER = new DefaultWhiteboardMarker<>(); public static ExpressionRewriteVisitor getResolver(PlanContext plan) { return plan.getWhiteboard(RESOLVER_MARKER); } public static class ResolvingVisitor implements PlanVisitor, ExpressionRewriteVisitor { private Folder folder; private TypesRegistryService registry; private TypesTranslator typesTranslator; private QueryContext queryContext; private ParametersSync parametersSync; public ResolvingVisitor(PlanContext context, Folder folder) { this.folder = folder; SchemaRulesContext src = (SchemaRulesContext)context.getRulesContext(); registry = src.getTypesRegistry(); typesTranslator = src.getTypesTranslator(); parametersSync = new ParametersSync(registry.getCastsResolver()); this.queryContext = context.getQueryContext(); } public void resolve(PlanNode root) { root.accept(this); parametersSync.updateTypes(); } @Override public boolean visitChildrenFirst(ExpressionNode n) { return true; } @Override public boolean visitEnter(PlanNode n) { return visit(n); } @Override public boolean visitLeave(PlanNode n) { if (n instanceof ResultSet) { updateResultFields(n, ((ResultSet)n).getFields()); } else if (n instanceof DMLStatement) { updateResultFields(n, ((DMLStatement)n).getResultField()); } else if (n instanceof ExpressionsSource) { handleExpressionsSource((ExpressionsSource)n); } return true; } private void updateResultFields(PlanNode n, List<ResultField> rsFields) { if (rsFields == null) return; TypedPlan typedInput = findTypedPlanNode(n); if (typedInput != null) { assert rsFields.size() == typedInput.nFields() : rsFields + " not applicable to " + typedInput; for (int i = 0, size = rsFields.size(); i < size; i++) { ResultField rsField = rsFields.get(i); rsField.setTInstance(typedInput.getTypeAt(i)); } } else { logger.warn("no Project node found for result fields: {}", n); } } private TypedPlan findTypedPlanNode(PlanNode n) { while (true) { if (n instanceof TypedPlan) return (TypedPlan) n; if ( (n instanceof ResultSet) || (n instanceof DMLStatement) || (n instanceof Select) || (n instanceof Sort) || (n instanceof Limit) || (n instanceof Distinct)) n = ((BasePlanWithInput)n).getInput(); else return null; } } @Override public boolean visit(PlanNode n) { return true; } @Override public ExpressionNode visit(ExpressionNode n) { if (n instanceof CastExpression) n = handleCastExpression((CastExpression) n); else if (n instanceof FunctionExpression) n = handleFunctionExpression((FunctionExpression) n); else if (n instanceof IfElseExpression) n = handleIfElseExpression((IfElseExpression) n); else if (n instanceof AggregateFunctionExpression) n = handleAggregateFunctionExpression((AggregateFunctionExpression) n); else if (n instanceof ExistsCondition) n = handleExistsCondition((ExistsCondition) n); else if (n instanceof SubqueryValueExpression) n = handleSubqueryValueExpression((SubqueryValueExpression) n); else if (n instanceof SubqueryResultSetExpression) n = handleSubqueryResultSetExpression((SubqueryResultSetExpression) n); else if (n instanceof AnyCondition) n = handleAnyCondition((AnyCondition) n); else if (n instanceof ComparisonCondition) n = handleComparisonCondition((ComparisonCondition) n); else if (n instanceof ColumnExpression) n = handleColumnExpression((ColumnExpression) n); else if (n instanceof InListCondition) n = handleInListCondition((InListCondition) n); else if (n instanceof ParameterCondition) n = handleParameterCondition((ParameterCondition) n); else if (n instanceof ParameterExpression) n = handleParameterExpression((ParameterExpression) n); else if (n instanceof BooleanOperationExpression) n = handleBooleanOperationExpression((BooleanOperationExpression) n); else if (n instanceof BooleanConstantExpression) n = handleBooleanConstantExpression((BooleanConstantExpression) n); else if (n instanceof ConstantExpression) n = handleConstantExpression((ConstantExpression) n); else if (n instanceof RoutineExpression) n = handleRoutineExpression((RoutineExpression) n); else if (n instanceof ColumnDefaultExpression) n = handleColumnDefaultExpression((ColumnDefaultExpression) n); else logger.warn("unrecognized ExpressionNode subclass: {}", n.getClass()); n = folder.foldConstants(n); // Set nullability of TInstance if it hasn't been given explicitly // At the same time, update the node's DataTypeDescriptor to match its TInstance TPreptimeValue tpv = n.getPreptimeValue(); if (tpv != null) { TInstance tInstance = tpv.instance(); if ((n.getSQLtype() != null) && (n.getSQLtype().getCharacterAttributes() != null) && (n.getSQLtype().getCharacterAttributes().getCollationDerivation() == CharacterTypeAttributes.CollationDerivation.EXPLICIT)) { // Apply result of explicit COLLATE, which will otherwise get lost. // No way to mutate the existing instance, so replace entire tpv. tInstance = StringAttribute.copyWithCollation(tInstance, n.getSQLtype().getCharacterAttributes()); tpv = new TPreptimeValue(tInstance, tpv.value()); n.setPreptimeValue(tpv); } if (tInstance != null) { DataTypeDescriptor newDtd = tInstance.dataTypeDescriptor(); n.setSQLtype(newDtd); } } return n; } private void handleExpressionsSource(ExpressionsSource node) { // For each field, we'll fold the instances of that field per row into common types. At the same time, // we'll record on a per-field basis whether any expressions of that field need to be casted (that is, // are not the eventual common type). If so, we'll do the casts in a second pass; if we tried to do them // all in the same path, some fields could end up with unnecessary (and potentially wrong) chained casts. // A null TInstance means an unknown type, which could be a parameter, a literal NULL or of course the // initial fold state. List<List<ExpressionNode>> rows = node.getExpressions(); List<ExpressionNode> firstRow = rows.get(0); int nfields = firstRow.size(); TInstance[] instances = new TInstance[nfields]; BitSet needCasts = new BitSet(nfields); BitSet widened = new BitSet(nfields); // First pass. Assume that instances[f] contains the TInstance of the top operand at field f. This could // be null, if that operand doesn't have a type; this is definitely true of the first row, but it can // also happen if an ExpressionNode is a constant NULL. for (int rownum = 0, expressionsSize = rows.size(); rownum < expressionsSize; rownum++) { List<ExpressionNode> row = rows.get(rownum); assert row.size() == nfields : "jagged rows: " + node; for (int field = 0; field < nfields; ++field) { TInstance botInstance = tinst(row.get(field)); special: if (botInstance == null) { // type is unknown (parameter or literal NULL), so it doesn't participate in determining a // type, but a cast is needed. needCasts.set(field); // If it is a parameter, it needs to be allowed to be wider than // any of the existing values, while still consistent with them. if (row.get(field) instanceof ParameterExpression) { // Force use of commonTClass(existing,null) below to widen. if (!widened.get(field)) { widened.set(field); break special; } } continue; } else if (instances[field] == null) { // Take type from first non-NULL, unless we have to widen, // which commonTClass(null,expr) will take care of. if (widened.get(field)) { break special; } instances[field] = botInstance; continue; } // If the two are the same, we know we don't need to cast them. // This logic also handles the case where both are null, which is not a valid argument // to resolver.commonTClass. if (Objects.equal(instances[field], botInstance)) continue; TClass topClass = tclass(instances[field]); TClass botClass = tclass(botInstance); TClass commonTClass = registry.getCastsResolver().commonTClass(topClass, botClass); if (commonTClass == null) { throw new AkibanInternalException("no common type found found between row " + (rownum-1) + " and " + rownum + " at field " + field); } // The two rows have different TClasses at this index, so we'll need at least one of them to // be casted. Also the common class will be the widest comparable. needCasts.set(field); widened.set(field); boolean eitherIsNullable; if (botInstance == null) eitherIsNullable = true; else eitherIsNullable = botInstance.nullability(); if ( (!eitherIsNullable) && (instances[field] != null)) { // bottom is not nullable, and there is a top. See if it's nullable eitherIsNullable = instances[field].nullability(); } // need to set a new instances[field]. Rules: // - if topClass and botClass are the same as common, use picking algorithm // - else, if one of them == commonTClass, use topInstance or botInstance (whichever is == common) // - else, use commonTClass.instance() boolean topIsCommon = (topClass == commonTClass); boolean botIsCommon = (botClass == commonTClass); if (topIsCommon && botIsCommon) { // TODO: The special case here for TClass VARCHAR with mismatched charsets // is a limitation of the TClass#pickInstance, as there is no current way // to create a common TInstance for TString with difference charsets. if (commonTClass instanceof TString && botInstance.attribute(StringAttribute.CHARSET) != instances[field].attribute(StringAttribute.CHARSET)) { ; } else { instances[field] = topClass.pickInstance(instances[field], botInstance); } } else if (botIsCommon) { instances[field] = botInstance; } else if (!topIsCommon) { // this of this as "else if (topIsBottom) { <noop> } else { ..." instances[field] = commonTClass.instance(eitherIsNullable); } // See if the top instance is not nullable but should be if (instances[field] != null) { instances[field] = instances[field].withNullable(eitherIsNullable); } } } // See if we need any casts if (!needCasts.isEmpty()) { for (int field = 0; field < nfields; field++) { if (widened.get(field)) { // A parameter should get a really wide VARCHAR so that it // won't be truncated because of other non-parameters. // Also make sure it's VARBINARY, as BINARY means pad, which // we don't want here. TClass tclass = TInstance.tClass(instances[field]); if (tclass instanceof TString) { if (((TString)tclass).getFixedLength() < 0) { instances[field] = typesTranslator.stringType() .instance(Integer.MAX_VALUE, instances[field].attribute(StringAttribute.CHARSET), instances[field].attribute(StringAttribute.COLLATION), instances[field].nullability()); } } else if (tclass instanceof TBinary) { if (((TBinary)tclass).getDefaultLength() < 0) { instances[field] = typesTranslator.binaryType() .instance(Integer.MAX_VALUE, instances[field].nullability()); } } } } for (List<ExpressionNode> row : rows) { for (int field = 0; field < nfields; ++field) { if (needCasts.get(field) && instances[field] != null) { ExpressionNode orig = row.get(field); ExpressionNode cast = castTo(orig, instances[field], folder, parametersSync); row.set(field, cast); } } } } node.setTInstances(instances); } ExpressionNode handleCastExpression(CastExpression expression) { DataTypeDescriptor dtd = expression.getSQLtype(); TInstance instance = typesTranslator.toTInstance(dtd); expression.setPreptimeValue(new TPreptimeValue(instance)); return finishCast(expression, folder, parametersSync); } private <V extends TValidatedOverload> ExpressionNode resolve( ResolvableExpression<V> expression, List<ExpressionNode> operands, OverloadResolver<V> resolver, boolean createPreptimeContext) { List<TPreptimeValue> operandClasses = new ArrayList<>(operands.size()); for (ExpressionNode operand : operands) operandClasses.add(operand.getPreptimeValue()); OverloadResult<V> resolutionResult = resolver.get(expression.getFunction(), operandClasses); // cast operands for (int i = 0, operandsSize = operands.size(); i < operandsSize; i++) { TInstance targetType = resolutionResult.getTypeClass(i); if (targetType != null) { ExpressionNode operand = castTo(operands.get(i), targetType, folder, parametersSync); operands.set(i, operand); } } V overload = resolutionResult.getOverload(); expression.setResolved(overload); final List<TPreptimeValue> operandValues = new ArrayList<>(operands.size()); List<TInstance> operandInstances = new ArrayList<>(operands.size()); boolean anyOperandsNullable = false; for (ExpressionNode operand : operands) { TPreptimeValue preptimeValue = operand.getPreptimeValue(); operandValues.add(preptimeValue); operandInstances.add(preptimeValue.instance()); if (Boolean.TRUE.equals(preptimeValue.isNullable())) anyOperandsNullable = true; } TOverloadResult overloadResultStrategy = overload.resultStrategy(); TInstance resultInstance; TInstance castTo; TPreptimeContext context; if (createPreptimeContext) { context = new TPreptimeContext(operandInstances, queryContext); expression.setPreptimeContext(context); } else { context = null; } switch (overloadResultStrategy.category()) { case CUSTOM: TInstance castSource = overloadResultStrategy.customRuleCastSource(anyOperandsNullable); if (context == null) context = new TPreptimeContext(operandInstances, queryContext); expression.setPreptimeContext(context); if (castSource == null) { castTo = null; resultInstance = overloadResultStrategy.customRule().resultInstance(operandValues, context); } else { castTo = overloadResultStrategy.customRule().resultInstance(operandValues, context); resultInstance = castSource; } break; case FIXED: resultInstance = overloadResultStrategy.fixed(anyOperandsNullable); castTo = null; break; case PICKING: resultInstance = resolutionResult.getPickedInstance(); castTo = null; break; default: throw new AssertionError(overloadResultStrategy.category()); } if (createPreptimeContext) context.setOutputType(resultInstance); expression.setPreptimeValue(new TPreptimeValue(resultInstance)); ExpressionNode resultExpression; if (castTo == null) { resultExpression = expression; } else { resultExpression = castTo(expression, castTo, folder, parametersSync); resultInstance = castTo; } if (expression instanceof FunctionCondition) { // Didn't know whether function would return boolean or not earlier, // so just assumed it would. if (resultInstance.typeClass() != AkBool.INSTANCE) { castTo = AkBool.INSTANCE.instance(resultInstance.nullability()); resultExpression = castTo(resultExpression, castTo, folder, parametersSync); } } return resultExpression; } ExpressionNode handleFunctionExpression(FunctionExpression expression) { List<ExpressionNode> operands = expression.getOperands(); ExpressionNode result = resolve(expression, operands, registry.getScalarsResolver(), true); TValidatedScalar overload = expression.getResolved(); TPreptimeContext context = expression.getPreptimeContext(); final List<TPreptimeValue> operandValues = new ArrayList<>(operands.size()); for (ExpressionNode operand : operands) { TPreptimeValue preptimeValue = operand.getPreptimeValue(); operandValues.add(preptimeValue); } overload.finishPreptimePhase(context); // Put the preptime value, possibly including nullness, into the expression. The constant folder // will use it. LazyList<TPreptimeValue> lazyInputs = new LazyListBase<TPreptimeValue>() { @Override public TPreptimeValue get(int i) { return operandValues.get(i); } @Override public int size() { return operandValues.size(); } }; TPreptimeValue constantTpv = overload.evaluateConstant(context, overload.filterInputs(lazyInputs)); if (constantTpv != null) { TPreptimeValue oldTpv = expression.getPreptimeValue(); assert oldTpv.instance().equals(constantTpv.instance()) : oldTpv.instance() + " != " + constantTpv.instance(); expression.setPreptimeValue(constantTpv); } SparseArray<Object> values = context.getValues(); if ((values != null) && !values.isEmpty()) expression.setPreptimeValues(values); return result; } ExpressionNode handleIfElseExpression(IfElseExpression expression) { ConditionList conditions = expression.getTestConditions(); ExpressionNode thenExpr = expression.getThenExpression(); ExpressionNode elseExpr = expression.getElseExpression(); // constant-fold if the condition is constant if (conditions.size() == 1) { ValueSource conditionVal = pval(conditions.get(0)); if (conditionVal != null) { boolean conditionMet = conditionVal.getBoolean(false); return conditionMet ? thenExpr : elseExpr; } } TInstance commonInstance = commonInstance(registry.getCastsResolver(), tinst(thenExpr), tinst(elseExpr)); if (commonInstance == null) return ConstantExpression.typedNull(null, null, null); thenExpr = castTo(thenExpr, commonInstance, folder, parametersSync); elseExpr = castTo(elseExpr, commonInstance, folder, parametersSync); expression.setThenExpression(thenExpr); expression.setElseExpression(elseExpr); expression.setPreptimeValue(new TPreptimeValue(commonInstance)); return expression; } ExpressionNode handleAggregateFunctionExpression(AggregateFunctionExpression expression) { List<ExpressionNode> operands = new ArrayList<>(); ExpressionNode operand = expression.getOperand(); if (operand != null) operands.add(operand); ExpressionNode result = resolve(expression, operands, registry.getAggregatesResolver(), false); if (operand != null) expression.setOperand(operands.get(0)); // in case the original operand was casted return result; } ExpressionNode handleExistsCondition(ExistsCondition expression) { return boolExpr(expression, true); } ExpressionNode handleSubqueryValueExpression(SubqueryValueExpression expression) { TypedPlan typedSubquery = findTypedPlanNode(expression.getSubquery().getInput()); TPreptimeValue tpv; assert typedSubquery.nFields() == 1 : typedSubquery; if (typedSubquery instanceof Project) { Project project = (Project) typedSubquery; List<ExpressionNode> projectFields = project.getFields(); assert projectFields.size() == 1 : projectFields; tpv = projectFields.get(0).getPreptimeValue(); } else { tpv = new TPreptimeValue(typedSubquery.getTypeAt(0)); } expression.setPreptimeValue(tpv); return expression; } ExpressionNode handleSubqueryResultSetExpression(SubqueryResultSetExpression expression) { DataTypeDescriptor sqlType = expression.getSQLtype(); if (sqlType.isRowMultiSet()) { setMissingRowMultiSetColumnTypes(sqlType, expression.getSubquery()); } TPreptimeValue tpv = new TPreptimeValue(typesTranslator.toTInstance(sqlType)); expression.setPreptimeValue(tpv); return expression; } // If a RowMultiSet column is a function expression, it won't have an SQL type // when the RowMultiSet type is built. Must get it now. static void setMissingRowMultiSetColumnTypes(DataTypeDescriptor sqlType, Subquery subquery) { if (subquery.getInput() instanceof ResultSet) { List<ResultField> fields = ((ResultSet)subquery.getInput()).getFields(); DataTypeDescriptor[] columnTypes = ((TypeId.RowMultiSetTypeId)sqlType.getTypeId()).getColumnTypes(); for (int i = 0; i < columnTypes.length; i++) { if (columnTypes[i] == null) { // TInstance should have been computed earlier in walk. columnTypes[i] = fields.get(i).getSQLtype(); } } } } ExpressionNode handleAnyCondition(AnyCondition expression) { return boolExpr(expression, true); } ExpressionNode handleComparisonCondition(ComparisonCondition expression) { ExpressionNode left = expression.getLeft(); ExpressionNode right = expression.getRight(); TInstance leftTInst = tinst(left); TInstance rightTInst = tinst(right); boolean nullable = isNullable(left) || isNullable(right); TKeyComparable keyComparable = registry.getKeyComparable(tclass(leftTInst), tclass(rightTInst)); if (keyComparable != null) { expression.setKeyComparable(keyComparable); } else if (TClass.comparisonNeedsCasting(leftTInst, rightTInst)) { boolean needCasts = true; TCastResolver casts = registry.getCastsResolver(); if ( (left.getClass() == ColumnExpression.class)&& (right.getClass() == ConstantExpression.class)) { // Left is a Column, right is a Constant. Ideally, we'd like to keep the Column as a Column, // and not a CAST(Column AS _) -- otherwise, we can't use it in an index lookup. // So, try to cast the const to the column's type. To do this, CAST(Const -> Column) must be // indexFriendly, *and* casting this result back to the original Const type must equal the same // const. if (rightTInst == null) { // literal null, so a comparison always returns UNKNOWN return new BooleanConstantExpression(null); } if (casts.isIndexFriendly(tclass(leftTInst), tclass(rightTInst))) { TInstance columnType = tinst(left); TInstance constType = tinst(right); TCast constToCol = casts.cast(constType, columnType); if (constToCol != null) { TCast colToConst = casts.cast(columnType, constType); if (colToConst != null) { TPreptimeValue constValue = right.getPreptimeValue(); ValueSource asColType = castValue(constToCol, constValue, columnType); TPreptimeValue asColTypeTpv = (asColType == null) ? null : new TPreptimeValue(columnType, asColType); ValueSource backToConstType = castValue(colToConst, asColTypeTpv, constType); if (ValueSources.areEqual(constValue.value(), backToConstType, constType)) { TPreptimeValue constTpv = new TPreptimeValue(columnType, asColType); ConstantExpression constCasted = new ConstantExpression(constTpv); expression.setRight(constCasted); assert columnType.equals(tinst(expression.getRight())); needCasts = false; } } } } } if (needCasts) { TInstance common = commonInstance(casts, left, right); if (common == null) { // TODO this means we have something like '? = ?' or '? = NULL'. What to do? Varchar for now? common = typesTranslator.stringTInstance(); } left = castTo(left, common, folder, parametersSync); right = castTo(right, common, folder, parametersSync); expression.setLeft(left); expression.setRight(right); } } return boolExpr(expression, nullable); } private boolean isNullable(ExpressionNode node) { TInstance tinst = tinst(node); return tinst == null || tinst.nullability(); } ExpressionNode handleColumnExpression(ColumnExpression expression) { Column column = expression.getColumn(); ColumnSource columnSource = expression.getTable(); if (column != null) { assert columnSource instanceof TableSource : columnSource; TInstance columnInstance = column.tInstance(); if ((Boolean.FALSE == columnInstance.nullability()) && (expression.getSQLtype() != null) && (expression.getSQLtype().isNullable())) { // With an outer join, the column can still be nullable. columnInstance = columnInstance.withNullable(true); } expression.setPreptimeValue(new TPreptimeValue(columnInstance)); } else if (columnSource instanceof AggregateSource) { AggregateSource aggTable = (AggregateSource) columnSource; TPreptimeValue ptv = aggTable.getField(expression.getPosition()).getPreptimeValue(); expression.setPreptimeValue(ptv); } else if (columnSource instanceof SubquerySource) { TPreptimeValue tpv; Subquery subquery = ((SubquerySource)columnSource).getSubquery(); TypedPlan typedSubquery = findTypedPlanNode(subquery.getInput()); if (typedSubquery != null) { tpv = new TPreptimeValue(typedSubquery.getTypeAt(expression.getPosition())); } else { logger.warn("no Project found for subquery: {}", columnSource); tpv = new TPreptimeValue(typesTranslator.toTInstance(expression.getSQLtype())); } expression.setPreptimeValue(tpv); return expression; } else if (columnSource instanceof NullSource) { expression.setPreptimeValue(new TPreptimeValue(null)); return expression; } else if (columnSource instanceof Project) { Project pTable = (Project) columnSource; TPreptimeValue ptv = pTable.getFields().get(expression.getPosition()).getPreptimeValue(); expression.setPreptimeValue(ptv); } else if (columnSource instanceof ExpressionsSource) { ExpressionsSource exprsTable = (ExpressionsSource) columnSource; List<List<ExpressionNode>> expressions = exprsTable.getExpressions(); TPreptimeValue tpv; if (expressions.size() == 1) { // get the TPV straight from the expression, since there's just one row tpv = expressions.get(0).get(expression.getPosition()).getPreptimeValue(); } else { TInstance tInstance = exprsTable.getTypeAt(expression.getPosition()); tpv = new TPreptimeValue(tInstance); } expression.setPreptimeValue(tpv); } else { throw new AssertionError(columnSource + "(" + columnSource.getClass() + ")"); } return expression; } ExpressionNode handleInListCondition(InListCondition expression) { boolean nullable = isNullable(expression.getOperand()); if (!nullable) { List<ExpressionNode> expressions = expression.getExpressions(); for (int i = 0, expressionsSize = expressions.size(); (!nullable) && i < expressionsSize; i++) { ExpressionNode rhs = expressions.get(i); nullable = isNullable(rhs); } } return boolExpr(expression, nullable); } ExpressionNode handleParameterCondition(ParameterCondition expression) { parametersSync.uninferred(expression); TInstance instance = AkBool.INSTANCE.instance(true); return castTo(expression, instance, folder, parametersSync); } ExpressionNode handleParameterExpression(ParameterExpression expression) { parametersSync.uninferred(expression); return expression; } ExpressionNode handleBooleanOperationExpression(BooleanOperationExpression expression) { boolean isNullable; DataTypeDescriptor sqLtype = expression.getSQLtype(); isNullable = sqLtype == null // TODO if no SQL type, assume nullable for now || sqLtype.isNullable(); // TODO rely on the previous type computer for now return boolExpr(expression, isNullable); } ExpressionNode handleBooleanConstantExpression(BooleanConstantExpression expression) { return boolExpr(expression, expression.isNullable()); } ExpressionNode handleConstantExpression(ConstantExpression expression) { // will be lazily loaded as necessary return expression; } ExpressionNode handleRoutineExpression(RoutineExpression expression) { Routine routine = expression.getRoutine(); List<ExpressionNode> operands = expression.getOperands(); for (int i = 0; i < operands.size(); i++) { ExpressionNode operand = castTo(operands.get(i), routine.getParameters().get(i).tInstance(), folder, parametersSync); operands.set(i, operand); } TPreptimeValue tpv = new TPreptimeValue(routine.getReturnValue().tInstance()); expression.setPreptimeValue(tpv); return expression; } ExpressionNode handleColumnDefaultExpression(ColumnDefaultExpression expression) { if (expression.getPreptimeValue() == null) { TPreptimeValue tpv = new TPreptimeValue(expression.getColumn().tInstance()); expression.setPreptimeValue(tpv); } return expression; } private static ValueSource pval(ExpressionNode expression) { return expression.getPreptimeValue().value(); } } private static ValueSource castValue(TCast cast, TPreptimeValue source, TInstance targetInstance) { if (source == null) return null; boolean targetsMatch = targetInstance.typeClass() == cast.targetClass(); boolean sourcesMatch = source.instance().typeClass() == cast.sourceClass(); if ( (!targetsMatch) || (!sourcesMatch) ) throw new IllegalArgumentException("cast <" + cast + "> not applicable to CAST(" + source + " AS " + targetInstance); TExecutionContext context = new TExecutionContext( null, Collections.singletonList(source.instance()), targetInstance, null, // TODO ErrorHandlingMode.ERROR, ErrorHandlingMode.ERROR, ErrorHandlingMode.ERROR ); Value result = new Value(targetInstance); try { cast.evaluate(context, source.value(), result); } catch (Exception e) { if (logger.isTraceEnabled()) { logger.trace("while casting values " + source + " to " + targetInstance + " using " + cast, e); } result = null; } return result; } private static ExpressionNode boolExpr(ExpressionNode expression, boolean nullable) { TInstance instance = AkBool.INSTANCE.instance(nullable); ValueSource value = null; if (expression.getPreptimeValue() != null) { if (instance.equals(expression.getPreptimeValue().instance())) return expression; value = expression.getPreptimeValue().value(); } expression.setPreptimeValue(new TPreptimeValue(instance, value)); return expression; } static class TopLevelCastingVisitor implements PlanVisitor { private List<? extends ColumnContainer> targetColumns; private Folder folder; private ParametersSync parametersSync; TopLevelCastingVisitor(Folder folder, ParametersSync parametersSync) { this.folder = folder; this.parametersSync = parametersSync; } public void apply(PlanNode plan) { plan.accept(this); } // PlanVisitor @Override public boolean visitEnter(PlanNode n) { // set up the targets if (n instanceof InsertStatement) { InsertStatement insert = (InsertStatement) n; setTargets(insert.getTargetColumns()); } else if (n instanceof UpdateStatement) { UpdateStatement update = (UpdateStatement) n; setTargets(update.getUpdateColumns()); for (UpdateColumn updateColumn : update.getUpdateColumns()) { Column target = updateColumn.getColumn(); ExpressionNode value = updateColumn.getExpression(); TInstance targetInst = target.tInstance(); ExpressionNode casted = castTo(value, targetInst.typeClass(), targetInst.nullability(), folder, parametersSync); if (casted != value) updateColumn.setExpression(casted); } } // use the targets if (targetColumns != null) { if (n instanceof Project) handleProject((Project) n); else if (n instanceof ExpressionsSource) handleExpressionSource((ExpressionsSource) n); } return true; } @Override public boolean visitLeave(PlanNode n) { return true; } private void handleExpressionSource(ExpressionsSource source) { for (List<ExpressionNode> row : source.getExpressions()) { castToTarget(row, source); } } private void castToTarget(List<ExpressionNode> row, TypedPlan plan) { for (int i = 0, ncols = row.size(); i < ncols; ++i) { Column target = targetColumns.get(i).getColumn(); ExpressionNode column = row.get(i); ExpressionNode casted = castTo(column, target.tInstance(), folder, parametersSync); row.set(i, casted); plan.setTypeAt(i, casted.getPreptimeValue()); } } private void handleProject(Project source) { castToTarget(source.getFields(), source); } @Override public boolean visit(PlanNode n) { return true; } private void setTargets(List<? extends ColumnContainer> targetColumns) { assert this.targetColumns == null : this.targetColumns; this.targetColumns = targetColumns; } } private static class ParameterCastInliner implements PlanVisitor, ExpressionRewriteVisitor { private static final ParameterCastInliner instance = new ParameterCastInliner(); // ExpressionRewriteVisitor @Override public ExpressionNode visit(ExpressionNode n) { if (n instanceof CastExpression) { CastExpression cast = (CastExpression) n; ExpressionNode operand = cast.getOperand(); if (operand instanceof ParameterExpression) { TInstance castTarget = tinst(cast); TInstance parameterType = tinst(operand); if (castTarget.equals(parameterType)) n = operand; } } return n; } @Override public boolean visitChildrenFirst(ExpressionNode n) { return false; } // PlanVisitor @Override public boolean visitEnter(PlanNode n) { return true; } @Override public boolean visitLeave(PlanNode n) { return true; } @Override public boolean visit(PlanNode n) { return true; } } private static ExpressionNode castTo(ExpressionNode expression, TClass targetClass, boolean nullable, Folder folder, ParametersSync parametersSync) { if (targetClass == tclass(expression)) return expression; return castTo(expression, targetClass.instance(nullable), folder, parametersSync); } private static ExpressionNode castTo(ExpressionNode expression, TInstance targetInstance, Folder folder, ParametersSync parametersSync) { // parameters and literal nulls have no type, so just set the type -- they'll be polymorphic about it. if (expression instanceof ParameterExpression) { targetInstance = targetInstance.withNullable(true); CastExpression castExpression = newCastExpression(expression, targetInstance); castExpression.setPreptimeValue(new TPreptimeValue(targetInstance)); parametersSync.set(expression, targetInstance); return castExpression; } if (expression instanceof NullSource) { ValueSource nullSource = ValueSources.getNullSource(targetInstance); expression.setPreptimeValue(new TPreptimeValue(targetInstance, nullSource)); return expression; } if (equalForCast(targetInstance, tinst(expression))) return expression; DataTypeDescriptor sqlType = expression.getSQLtype(); targetInstance = targetInstance.withNullable(sqlType == null || sqlType.isNullable()); CastExpression castExpression = newCastExpression(expression, targetInstance); castExpression.setPreptimeValue(new TPreptimeValue(targetInstance)); ExpressionNode result = finishCast(castExpression, folder, parametersSync); result = folder.foldConstants(result); return result; } private static boolean equalForCast(TInstance target, TInstance source) { if (source == null) return false; if (!target.typeClass().equals(source.typeClass())) return false; if (target.typeClass() instanceof TString) { // Operations between strings do not require that the // charsets / collations be the same. return (target.attribute(StringAttribute.MAX_LENGTH) == source.attribute(StringAttribute.MAX_LENGTH)); } return target.equalsExcludingNullable(source); } private static CastExpression newCastExpression(ExpressionNode expression, TInstance targetInstance) { if (targetInstance.typeClass() == AkBool.INSTANCE) // Allow use as a condition. return new BooleanCastExpression(expression, targetInstance.dataTypeDescriptor(), expression.getSQLsource(), targetInstance); else return new CastExpression(expression, targetInstance.dataTypeDescriptor(), expression.getSQLsource(), targetInstance); } protected static ExpressionNode finishCast(CastExpression castNode, Folder folder, ParametersSync parametersSync) { // If we have something like CAST( (VALUE[n] of ExpressionsSource) to FOO ), // refactor it to VALUE[n] of ExpressionsSource2, where ExpressionsSource2 has columns at n cast to FOO. ExpressionNode inner = castNode.getOperand(); ExpressionNode result = castNode; if (inner instanceof ColumnExpression) { ColumnExpression columnNode = (ColumnExpression) inner; ColumnSource source = columnNode.getTable(); if (source instanceof ExpressionsSource) { ExpressionsSource expressionsTable = (ExpressionsSource) source; List<List<ExpressionNode>> rows = expressionsTable.getExpressions(); int pos = columnNode.getPosition(); TInstance castType = castNode.getTInstance(); for (int i = 0, nrows = rows.size(); i < nrows; ++i) { List<ExpressionNode> row = rows.get(i); ExpressionNode targetColumn = row.get(pos); targetColumn = castTo(targetColumn, castType, folder, parametersSync); row.set(pos, targetColumn); } result = columnNode; result.setPreptimeValue(castNode.getPreptimeValue()); expressionsTable.getFieldTInstances()[pos] = castType; } } return result; } private static TClass tclass(ExpressionNode operand) { return tclass(tinst(operand)); } private static TClass tclass(TInstance tInstance) { return (tInstance == null) ? null : tInstance.typeClass(); } private static TInstance tinst(ExpressionNode node) { TPreptimeValue ptv = node.getPreptimeValue(); return ptv == null ? null : ptv.instance(); } private static TInstance commonInstance(TCastResolver resolver, ExpressionNode left, ExpressionNode right) { return commonInstance(resolver, tinst(left), tinst(right)); } public static TInstance commonInstance(TCastResolver resolver, TInstance left, TInstance right) { if (left == null && right == null) return null; else if (left == null) return right; else if (right == null) return left; TClass leftTClass = left.typeClass(); TClass rightTClass = right.typeClass(); if (leftTClass == rightTClass) return leftTClass.pickInstance(left, right); TClass commonClass = resolver.commonTClass(leftTClass, rightTClass); if (commonClass == null) throw error("couldn't determine a type for CASE expression"); if (commonClass == leftTClass) return left; if (commonClass == rightTClass) return right; return commonClass.instance(left.nullability() || right.nullability()); } private static RuntimeException error(String message) { throw new RuntimeException(message); // TODO what actual error type? } /** * Helper class for keeping various instances of the same parameter in sync, in terms of their TInstance. So for * instance, in an expression IF($0 == $1, $1, $0) we'd want both $0s to have the same TInstance, and ditto for * both $1s. */ protected static class ParametersSync { private TCastResolver resolver; private SparseArray<List<ExpressionNode>> instancesMap; public ParametersSync(TCastResolver resolver) { this.resolver = resolver; this.instancesMap = new SparseArray<>(); } public void uninferred(ParameterExpression parameterExpression) { //assert parameterExpression.getPreptimeValue() == null : parameterExpression; TPreptimeValue preptimeValue; List<ExpressionNode> siblings = siblings(parameterExpression); if (siblings.isEmpty()) { preptimeValue = new TPreptimeValue(); if (parameterExpression.getSQLsource() != null) // Start with type client intends to send, if any. preptimeValue.instance((TInstance)parameterExpression.getSQLsource().getUserData()); parameterExpression.setPreptimeValue(new TPreptimeValue()); } else { preptimeValue = siblings.get(0).getPreptimeValue(); } parameterExpression.setPreptimeValue(preptimeValue); siblings.add(parameterExpression); } private List<ExpressionNode> siblings(ParameterExpression parameterNode) { int pos = parameterNode.getPosition(); List<ExpressionNode> siblings = instancesMap.get(pos); if (siblings == null) { siblings = new ArrayList<>(4); // guess at capacity. this should be plenty instancesMap.set(pos, siblings); } return siblings; } public void set(ExpressionNode node, TInstance tInstance) { List<ExpressionNode> siblings = siblings((ParameterExpression) node); TPreptimeValue sharedTpv = siblings.get(0).getPreptimeValue(); TInstance previousInstance = sharedTpv.instance(); tInstance = commonInstance(resolver, tInstance, previousInstance); sharedTpv.instance(tInstance); } public void updateTypes() { int nparams = instancesMap.lastDefinedIndex(); for (int i = 0; i < nparams; i++) { if (!instancesMap.isDefined(i)) continue; List<ExpressionNode> siblings = instancesMap.get(i); TPreptimeValue sharedTpv = siblings.get(0).getPreptimeValue(); TInstance tInstance = sharedTpv.instance(); if (tInstance != null) { DataTypeDescriptor dtd = tInstance.dataTypeDescriptor(); for (ExpressionNode param : siblings) { param.setSQLtype(dtd); if (param.getSQLsource() != null) { try { param.getSQLsource().setType(dtd); param.getSQLsource().setUserData(tInstance); } catch (StandardException ex) { throw new SQLParserInternalException(ex); } } } } } } } }
package com.github.davidmoten.rx2.internal.flowable; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.util.concurrent.Callable; import com.github.davidmoten.rx2.Bytes; import com.github.davidmoten.rx2.Consumers; import io.reactivex.Emitter; import io.reactivex.Flowable; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.functions.Predicate; public final class FlowableServerSocket { private FlowableServerSocket() { // prevent instantiation } public static Flowable<Flowable<byte[]>> create( final Callable<? extends ServerSocket> serverSocketFactory, final int timeoutMs, final int bufferSize, Action preAcceptAction, int acceptTimeoutMs, Predicate<? super Socket> acceptSocket) { Function<ServerSocket, Flowable<Flowable<byte[]>>> FlowableFactory = createFlowableFactory( timeoutMs, bufferSize, preAcceptAction, acceptSocket); return Flowable.<Flowable<byte[]>, ServerSocket>using( createServerSocketFactory(serverSocketFactory, acceptTimeoutMs), FlowableFactory, Consumers.<ServerSocket>close(), true); } private static Callable<ServerSocket> createServerSocketFactory( final Callable<? extends ServerSocket> serverSocketFactory, final int acceptTimeoutMs) { return new Callable<ServerSocket>() { @Override public ServerSocket call() throws Exception { return createServerSocket(serverSocketFactory, acceptTimeoutMs); } }; } private static ServerSocket createServerSocket( Callable<? extends ServerSocket> serverSocketCreator, long timeoutMs) throws Exception { ServerSocket s = serverSocketCreator.call(); s.setSoTimeout((int) timeoutMs); return s; } private static Function<ServerSocket, Flowable<Flowable<byte[]>>> createFlowableFactory( final int timeoutMs, final int bufferSize, final Action preAcceptAction, final Predicate<? super Socket> acceptSocket) { return new Function<ServerSocket, Flowable<Flowable<byte[]>>>() { @Override public Flowable<Flowable<byte[]>> apply(ServerSocket serverSocket) { return createServerSocketFlowable(serverSocket, timeoutMs, bufferSize, preAcceptAction, acceptSocket); } }; } private static Flowable<Flowable<byte[]>> createServerSocketFlowable( final ServerSocket serverSocket, final long timeoutMs, final int bufferSize, final Action preAcceptAction, final Predicate<? super Socket> acceptSocket) { return Flowable.generate( new Consumer<Emitter<Flowable<byte[]>>>() { @Override public void accept(Emitter<Flowable<byte[]>> emitter) throws Exception { acceptConnection(timeoutMs, bufferSize, serverSocket, emitter, preAcceptAction, acceptSocket); } }); } private static void acceptConnection(long timeoutMs, int bufferSize, ServerSocket ss, Emitter<Flowable<byte[]>> emitter, Action preAcceptAction, Predicate<? super Socket> acceptSocket) { Socket socket; while (true) { try { preAcceptAction.run(); socket = ss.accept(); if (!acceptSocket.test(socket)) { closeQuietly(socket); } else { emitter.onNext(createSocketFlowable(socket, timeoutMs, bufferSize)); break; } } catch (SocketTimeoutException e) { // timed out so will loop around again } catch (Throwable e) { // if the server socket has been closed then this is most likely // an unsubscribe so we don't try to report an error which would // just end up in RxJavaPlugins.onError as a stack trace in the // console. if (e instanceof SocketException && ("Socket closed".equals(e.getMessage()) || "Socket operation on nonsocket: configureBlocking" .equals(e.getMessage()))) { break; } else { // unknown problem emitter.onError(e); break; } } } } // visible for testing static void closeQuietly(Socket socket) { try { socket.close(); } catch (IOException e) { // ignore exception } } private static Flowable<byte[]> createSocketFlowable(final Socket socket, long timeoutMs, final int bufferSize) { setTimeout(socket, timeoutMs); return Flowable.using( new Callable<InputStream>() { @Override public InputStream call() throws Exception { return socket.getInputStream(); } }, new Function<InputStream, Flowable<byte[]>>() { @Override public Flowable<byte[]> apply(InputStream is) { return Bytes.from(is, bufferSize); } }, Consumers.close(), true); } private static void setTimeout(Socket socket, long timeoutMs) { try { socket.setSoTimeout((int) timeoutMs); } catch (SocketException e) { throw new RuntimeException(e); } } }
package com.github.frankfarrell.snowball.controller; import com.github.frankfarrell.snowball.exceptions.AlreadyExistsException; import com.github.frankfarrell.snowball.exceptions.NotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.interceptor.CacheOperationInvoker; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.concurrent.ExecutionException; @ControllerAdvice() public class RestExceptionHandler { private final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * Return 404 when an attempt to read an entity that does not exist is made * @param req * @param ex * @return */ @ExceptionHandler(NotFoundException.class) @ResponseStatus(value= HttpStatus.NOT_FOUND) @ResponseBody public NotFoundResponse handleNotFound(HttpServletRequest req, NotFoundException ex) { String errorURL = req.getRequestURL().toString(); logger.info(HttpStatus.NOT_FOUND+"|"+ errorURL); NotFoundResponse response = new NotFoundResponse(errorURL, ex.getField(), ex.getValue()); return response; } protected class NotFoundResponse{ public final String url; public final String field; public final Object value; public NotFoundResponse(String url, String field, Object value){ this.url =url; this.field = field; this.value = value; } } /** * Return 409 When an attempt to create a resource that already exists is made * @param req * @param ex * @return */ @ExceptionHandler(AlreadyExistsException.class) @ResponseStatus(value= HttpStatus.CONFLICT) @ResponseBody public AlreadyExistsResponse handleAlreadyExists(HttpServletRequest req, AlreadyExistsException ex) { String errorURL = req.getRequestURL().toString(); //For instance if a user is searched for by UUID, type would be User field wouuld be UUID and value the value logger.info(HttpStatus.CONFLICT+"|"+ errorURL); AlreadyExistsResponse response = new AlreadyExistsResponse(errorURL, ex.field, ex.value); return response; } protected class AlreadyExistsResponse{ public final String url; public final String field; public final Object value; public AlreadyExistsResponse(String url, String field, Object value){ this.url =url; this.field = field; this.value = value; } } /** * Return 400 When a JSON With invlaid types (eg a boolean where an array is expected) is passed in body for create/update * @param req * @param ex * @return */ @ExceptionHandler(HttpMessageNotReadableException.class) @ResponseStatus(value= HttpStatus.BAD_REQUEST) @ResponseBody public ExceptionMessageResponse handleMethodArgumentNotValid(HttpServletRequest req, HttpMessageNotReadableException ex) { String errorURL = req.getRequestURL().toString(); logger.info(HttpStatus.BAD_REQUEST + "|" + errorURL); return new ExceptionMessageResponse("The HTTP Request was unreadable"); } public class ExceptionMessageResponse { public final String message; public ExceptionMessageResponse(String message) { this.message = message; } } /* Exception handlr for async calls This is not ideal, but seems to be the only solution */ @ExceptionHandler(ExecutionException.class) public ResponseEntity handleMethodArgumentNotValid(HttpServletRequest req, ExecutionException ex) throws CacheOperationInvoker.ThrowableWrapper { if(ex.getCause() instanceof AlreadyExistsException){ return new ResponseEntity(handleAlreadyExists(req, (AlreadyExistsException)ex.getCause()), HttpStatus.CONFLICT); } else if(ex.getCause() instanceof NotFoundException){ return new ResponseEntity(handleNotFound(req, (NotFoundException)ex.getCause()), HttpStatus.NOT_FOUND); } else{ return new ResponseEntity(new ExceptionMessageResponse("Something went wrong!"), HttpStatus.INTERNAL_SERVER_ERROR); } } }
package com.github.kongchen.swagger.docgen.spring; import com.github.kongchen.swagger.docgen.reader.AbstractReader; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.converter.ModelConverters; import com.wordnik.swagger.jaxrs.ext.AbstractSwaggerExtension; import com.wordnik.swagger.jaxrs.ext.SwaggerExtension; import com.wordnik.swagger.models.parameters.CookieParameter; import com.wordnik.swagger.models.parameters.FormParameter; import com.wordnik.swagger.models.parameters.HeaderParameter; import com.wordnik.swagger.models.parameters.Parameter; import com.wordnik.swagger.models.parameters.PathParameter; import com.wordnik.swagger.models.parameters.QueryParameter; import com.wordnik.swagger.models.properties.Property; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestParam; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Set; import org.reflections.util.Utils; import org.springframework.beans.BeanUtils; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.web.bind.annotation.ModelAttribute; import java.beans.PropertyDescriptor; import com.wordnik.swagger.annotations.ApiParam; import com.wordnik.swagger.jaxrs.utils.ParameterUtils; import java.lang.reflect.Type; public class SpringSwaggerExtension extends AbstractSwaggerExtension implements SwaggerExtension { @Override public List<Parameter> extractParameters(Annotation[] annotations, Class<?> cls, boolean isArray, Set<Class<?>> classesToSkip, Iterator<SwaggerExtension> chain) { String defaultValue = ""; if (this.shouldIgnoreClass(cls)) { return new ArrayList<Parameter>(); } List<Parameter> parameters = new ArrayList<Parameter>(); Parameter parameter = null; for (Annotation annotation : annotations) { if (annotation instanceof ModelAttribute) { parameters.addAll(this.extractParametersFromModelAttributeAnnotation(annotation, cls)); } else { parameter = this.extractParameterFromAnnotation(annotation, defaultValue, cls, isArray); } } if (parameter != null) { parameters.add(parameter); } return parameters; } private Parameter extractParameterFromAnnotation(Annotation annotation, String defaultValue, Class<?> cls, boolean isArray) { Parameter parameter = null; if (annotation instanceof RequestParam) { RequestParam param = (RequestParam) annotation; QueryParameter qp = new QueryParameter() .name(param.value()); if (!defaultValue.isEmpty()) { qp.setDefaultValue(defaultValue); } Property schema = ModelConverters.getInstance().readAsProperty(cls); if (schema != null) { qp.setProperty(schema); } if (isArray || cls.isArray() || cls.isAssignableFrom(Collection.class)) { qp.setType("string"); } qp.setRequired(param.required()); parameter = qp; } else if (annotation instanceof PathVariable) { PathVariable param = (PathVariable) annotation; PathParameter pp = new PathParameter() .name(param.value()); if (!defaultValue.isEmpty()) { pp.setDefaultValue(defaultValue); } Property schema = ModelConverters.getInstance().readAsProperty(cls); if (schema != null) { pp.setProperty(schema); } parameter = pp; } else if (annotation instanceof RequestHeader) { RequestHeader param = (RequestHeader) annotation; HeaderParameter hp = new HeaderParameter() .name(param.value()); hp.setDefaultValue(defaultValue); Property schema = ModelConverters.getInstance().readAsProperty(cls); if (schema != null) { hp.setProperty(schema); } hp.setRequired(param.required()); parameter = hp; } else if (annotation instanceof CookieValue) { CookieValue param = (CookieValue) annotation; CookieParameter cp = new CookieParameter() .name(param.value()); if (!defaultValue.isEmpty()) { cp.setDefaultValue(defaultValue); } Property schema = ModelConverters.getInstance().readAsProperty(cls); if (schema != null) { cp.setProperty(schema); } cp.setRequired(param.required()); parameter = cp; } return parameter; } private List<Parameter> extractParametersFromModelAttributeAnnotation(Annotation annotation, Class beanClass) { if (false == (annotation instanceof ModelAttribute)) { return null; } List<Parameter> parameters = new ArrayList<Parameter>(); // If ModelAttribute annotation is present, check for possible APIparam annotation in beans for (PropertyDescriptor propertyDescriptor : BeanUtils.getPropertyDescriptors(beanClass)) { // Get all the valid setter methods inside the bean Method propertyDescriptorSetter = propertyDescriptor.getWriteMethod(); if (propertyDescriptorSetter != null) { Annotation propertySetterApiParam = AnnotationUtils.findAnnotation(propertyDescriptorSetter, ApiParam.class); if (false == (propertySetterApiParam instanceof ApiParam)) { // If we find a setter that doesn't have @ApiParam annotation, then skip it continue; } // Here we have a bean setter method that is annotted with @ApiParam, but we still // need to know what type of parameter to create. In order to do this, we look for // any annotation attached to the first method parameter of the setter fucntion. Parameter propertySetterExtractedParameter = null; Annotation[][] methodAnnotations = propertyDescriptorSetter.getParameterAnnotations(); if (methodAnnotations == null || methodAnnotations.length == 0) { continue; } String defaultValue = ""; for (Annotation firstMethodParameterAnnotation : methodAnnotations[0]) { Class parameterClass = propertyDescriptor.getPropertyType(); Type type = propertyDescriptorSetter.getGenericParameterTypes()[0]; boolean isArray = ParameterUtils.isMethodArgumentAnArray(parameterClass, type); propertySetterExtractedParameter = this.extractParameterFromAnnotation( firstMethodParameterAnnotation, defaultValue, parameterClass, isArray); if (propertySetterExtractedParameter instanceof Parameter) { // When we find a valid parameter type to use, keep it break; } } if (false == (propertySetterExtractedParameter instanceof Parameter)) { QueryParameter qp = new QueryParameter().name(propertyDescriptor.getDisplayName()); Property schema = ModelConverters.getInstance().readAsProperty(propertyDescriptor.getPropertyType()); if (schema != null) { qp.setProperty(schema); } // Copy the attributes from the @ApiParam annotation into the new QueryParam ApiParam methodApiParamAnnotation = (ApiParam) propertySetterApiParam; qp.setDescription(methodApiParamAnnotation.value()); qp.setRequired(methodApiParamAnnotation.required()); qp.setAccess(methodApiParamAnnotation.access()); if (!Utils.isEmpty(methodApiParamAnnotation.name())) { qp.setName(methodApiParamAnnotation.name()); } parameters.add(qp); } else { parameters.add(propertySetterExtractedParameter); } } } return parameters; } @Override public boolean shouldIgnoreClass(Class<?> cls) { boolean output = false; if (cls.getName().startsWith("org.springframework")) { output = true; } else { output = false; } return output; } }
package com.gmail.at.zhuikov.aleksandr.driveddoc.service; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.logging.Logger; import javax.inject.Singleton; import org.apache.commons.compress.utils.IOUtils; import com.google.appengine.api.modules.ModulesService; import com.google.appengine.api.modules.ModulesServiceFactory; import ee.sk.digidoc.Base64Util; import ee.sk.digidoc.DataFile; import ee.sk.digidoc.DigiDocException; import ee.sk.digidoc.Signature; import ee.sk.digidoc.SignedDoc; import ee.sk.utils.ConvertUtils; @Singleton public class MobileIdService { private static final Logger LOG = Logger.getLogger(DigiDocService.class.getName()); public static final String STAT_OUTSTANDING_TRANSACTION = "OUTSTANDING_TRANSACTION"; public static final String STAT_SIGNATURE = "SIGNATURE"; public static final String STAT_ERROR = "ERROR"; private static final String g_xmlHdr1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http: private static final String g_xmlEnd1 = "</d:MobileCreateSignature></SOAP-ENV:Body></SOAP-ENV:Envelope>"; private static final String g_xmlHdr2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http: private static final String g_xmlEnd2 = "</d:GetMobileCreateSignatureStatus></SOAP-ENV:Body></SOAP-ENV:Envelope>"; private final ModulesService modulesApi = ModulesServiceFactory.getModulesService(); private static String findElemValue(String msg, String tag) { int nIdx1 = 0, nIdx2 = 0; if (msg != null && tag != null) { nIdx1 = msg.indexOf("<" + tag); if (nIdx1 != -1) { while (msg.charAt(nIdx1) != '>') nIdx1++; nIdx1++; nIdx2 = msg.indexOf("</" + tag, nIdx1); if (nIdx1 > 0 && nIdx2 > 0) return msg.substring(nIdx1, nIdx2); } } return null; } private static void addElem(StringBuffer xml, String tag, String value) { if (value != null && value.trim().length() > 0) { xml.append("<"); xml.append(tag); xml.append(">"); xml.append(value); xml.append("</"); xml.append(tag); xml.append(">"); } } private static String findAttrValue(String msg, String attr) { int nIdx1 = 0, nIdx2 = 0; if (msg != null && attr != null) { nIdx1 = msg.indexOf(attr); if (nIdx1 != -1) { while (msg.charAt(nIdx1) != '=') nIdx1++; nIdx1++; if (msg.charAt(nIdx1) == '\"') nIdx1++; nIdx2 = msg.indexOf("\"", nIdx1); if (nIdx1 > 0 && nIdx2 > 0) return msg.substring(nIdx1, nIdx2); } } return null; } public String startSigningSession(SignedDoc sdoc, String sIdCode, String sPhoneNo, String sLang, String sServiceName, String sManifest, String sCity, String sState, String sZip, String sCountry, StringBuffer sbChallenge) throws DigiDocException { String sSessCode = null; if(sdoc == null) throw new DigiDocException(DigiDocException.ERR_DIGIDOC_SERVICE, "Missing SignedDoc object", null); if(sIdCode == null || sIdCode.trim().length() < 11) throw new DigiDocException(DigiDocException.ERR_DIGIDOC_SERVICE, "Missing or invalid personal id-code", null); if(sPhoneNo == null || sPhoneNo.trim().length() < 5) // min 5 kohaline mobiili nr ? throw new DigiDocException(DigiDocException.ERR_DIGIDOC_SERVICE, "Missing or invalid phone number", null); if(sCountry == null || sCountry.trim().length() < 2) throw new DigiDocException(DigiDocException.ERR_DIGIDOC_SERVICE, "Missing or invalid country code", null); //String sProxyHost = cfg.getProperty("DIGIDOC_PROXY_HOST"); //String sProxyPort = cfg.getProperty("DIGIDOC_PROXY_PORT"); // compose soap msg StringBuffer sbMsg = new StringBuffer(g_xmlHdr1); addElem(sbMsg, "IDCode", sIdCode); addElem(sbMsg, "SignersCountry", sCountry); addElem(sbMsg, "PhoneNo", sPhoneNo); addElem(sbMsg, "Language", sLang); addElem(sbMsg, "ServiceName", sServiceName); addElem(sbMsg, "Role", sManifest); addElem(sbMsg, "City", sCity); addElem(sbMsg, "StateOrProvince", sState); addElem(sbMsg, "PostalCode", sZip); addElem(sbMsg, "CountryName", sCountry); sbMsg.append("<DataFiles>"); for(int i = 0; i < sdoc.countDataFiles(); i++) { DataFile df = sdoc.getDataFile(i); sbMsg.append("<DataFileDigest>"); addElem(sbMsg, "Id", df.getId()); addElem(sbMsg, "DigestType", "sha1"); String sHash = Base64Util.encode(df.getDigest()); addElem(sbMsg, "DigestValue", sHash); sbMsg.append("</DataFileDigest>"); } sbMsg.append("</DataFiles>"); addElem(sbMsg, "Format", sdoc.getFormat()); addElem(sbMsg, "Version", sdoc.getVersion()); String sId = sdoc.getNewSignatureId(); addElem(sbMsg, "SignatureID", sId); addElem(sbMsg, "MessagingMode", "asynchClientServer"); addElem(sbMsg, "AsyncConfiguration", "0"); sbMsg.append(g_xmlEnd1); // send soap message LOG.fine("Sending:\n String sResp = pullUrl(sbMsg.toString()); LOG.fine("Received:\n if(sResp != null && sResp.trim().length() > 0) { sSessCode = findElemValue(sResp, "Sesscode"); String s = findElemValue(sResp, "ChallengeID"); if(s != null) sbChallenge.append(s); } return sSessCode; } public String getStatus(SignedDoc sdoc, String sSesscode) throws DigiDocException { String sStatus = null; if (sdoc == null) throw new DigiDocException(DigiDocException.ERR_DIGIDOC_SERVICE, "Missing SignedDoc object", null); if (sSesscode == null || sSesscode.trim().length() == 0) throw new DigiDocException(DigiDocException.ERR_DIGIDOC_SERVICE, "Missing or invalid session code", null); // compose soap msg StringBuffer sbMsg = new StringBuffer(g_xmlHdr2); addElem(sbMsg, "Sesscode", sSesscode); addElem(sbMsg, "WaitSignature", "false"); sbMsg.append(g_xmlEnd2); // send soap message LOG.fine("Sending:\n String sResp = pullUrl(sbMsg.toString()); LOG.fine("Received:\n if (sResp != null && sResp.trim().length() > 0) { sStatus = findElemValue(sResp, "Status"); if (sStatus != null && sStatus.equals(STAT_SIGNATURE)) { String s = findElemValue(sResp, "Signature"); if (s != null) { String sSig = ConvertUtils.unescapeXmlSymbols(s); String sId = findAttrValue(sSig, "Id"); LOG.fine("Signature: " + sId + "\n Signature sig = new Signature(sdoc); sig.setId(sId); try { sig.setOrigContent(sSig.getBytes("UTF-8")); } catch (Exception ex) { LOG.warning("Error adding signature: " + ex); DigiDocException.handleException(ex, DigiDocException.ERR_DIGIDOC_SERVICE); } sdoc.addSignature(sig); } } } return sStatus; } private String pullUrl(String msg) { try { URL url = new URL("http://" + modulesApi.getVersionHostname("digidoc-service-adapter","v1") + "/proxy"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setConnectTimeout(20 * 1000); connection.setRequestMethod("POST"); IOUtils.copy(new ByteArrayInputStream(msg.getBytes("utf-8")), connection.getOutputStream()); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { return new String(IOUtils.toByteArray(connection.getInputStream())); } else { LOG.warning("digidoc-service-adapter returned " + connection.getResponseCode() + " -> " + connection.getResponseMessage()); return null; } } catch (IOException e) { throw new RuntimeException(e); } } }
package de.espend.idea.shopware.inspection.quickfix; import com.intellij.codeInspection.LocalQuickFix; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiRecursiveElementWalkingVisitor; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.php.codeInsight.PhpCodeInsightUtil; import com.jetbrains.php.lang.PhpCodeUtil; import com.jetbrains.php.lang.psi.PhpFile; import com.jetbrains.php.lang.psi.elements.*; import com.jetbrains.php.lang.psi.resolve.types.PhpType; import de.espend.idea.shopware.index.utils.SubscriberIndexUtil; import de.espend.idea.shopware.reference.LazySubscriberReferenceProvider; import de.espend.idea.shopware.util.HookSubscriberUtil; import de.espend.idea.shopware.util.ShopwareUtil; import fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Daniel Espendiller <daniel@espendiller.net> */ public class CreateMethodQuickFix implements LocalQuickFix { private final StringLiteralExpression context; private final GeneratorContainer generatorContainer; private List<String> ormEvents = Arrays.asList("prePersist", "preRemove", "preUpdate", "postPersist", "postUpdate", "postRemove"); public CreateMethodQuickFix(StringLiteralExpression context, GeneratorContainer generatorContainer) { this.context = context; this.generatorContainer = generatorContainer; } @NotNull @Override public String getName() { return "Create method"; } @NotNull @Override public String getFamilyName() { return "Method"; } @Override public void applyFix(@NotNull final Project project, @NotNull ProblemDescriptor problemDescriptor) { Method method = PsiTreeUtil.getParentOfType(context, Method.class); if(method == null) { return; } boolean isOrmEvent = false; int insertPos = method.getTextRange().getEndOffset(); // Enlight_Controller_Action_PostDispatch_Frontend_Blog String typeHint = "Enlight_Event_EventArgs"; if(generatorContainer.getHookName() != null && generatorContainer.getHookName().contains("::")) { // Enlight_Controller_Action::dispatch::replace typeHint = "Enlight_Hook_HookArgs"; for (String ormEvent : ormEvents) { if (generatorContainer.getHookName().endsWith(ormEvent)) { // Shopware\Models\Article\Article::postRemove typeHint = "Enlight_Event_EventArgs"; isOrmEvent = true; } } } PsiFile containingFile = method.getContainingFile(); if(containingFile instanceof PhpFile && PhpCodeInsightUtil.collectNamespaces(containingFile).size() > 0) { typeHint = "\\" + typeHint; } final StringBuilder stringBuilder = new StringBuilder(); final String contents = context.getContents(); stringBuilder.append("public function ").append(contents).append("(").append(typeHint).append(" $args) {"); String subjectDoc = generatorContainer.getSubjectDoc(); // find subject on controller "Enlight_Controller_Action_PostDispatchSecure_Frontend_Payment" if(subjectDoc == null && generatorContainer.getHookName() != null && !generatorContainer.getHookName().contains("::")) { PhpClass phpClass = ShopwareUtil.getControllerOnActionSubscriberName(project, generatorContainer.getHookName()); if(phpClass != null) { subjectDoc = phpClass.getFQN(); } } if(subjectDoc == null && generatorContainer.getHookName() != null && SubscriberIndexUtil.isContainerServiceEventAndContains(project, generatorContainer.getHookName())) { subjectDoc = "Shopware\\Components\\DependencyInjection\\Container"; } if(subjectDoc != null) { if (isOrmEvent) { stringBuilder.append("/** @var \\").append(StringUtils.stripStart(subjectDoc, "\\")).append(" $entity */\n"); stringBuilder.append("$entity = $args->get('entity');\n"); } else { stringBuilder.append("/** @var \\").append(StringUtils.stripStart(subjectDoc, "\\")).append(" $subject */\n"); stringBuilder.append("$subject = $args->getSubject();\n"); } } if (!isOrmEvent) { if(generatorContainer.getHookName() != null && generatorContainer.getHookName().contains("::")) { stringBuilder.append("\n"); stringBuilder.append("$return = $args->getReturn();\n"); attachVariablesInScope(project, stringBuilder); stringBuilder.append("\n"); stringBuilder.append("$args->setReturn($return);\n"); } else { attachVariablesInScope(project, stringBuilder); } } if(generatorContainer.getHookName() != null) { Pattern pattern = Pattern.compile("Enlight_Controller_Dispatcher_ControllerPath_(Frontend|Backend|Widget|Api)_(\\w+)"); Matcher matcher = pattern.matcher(generatorContainer.getHookName()); if(matcher.find()) { stringBuilder.append("\n"); stringBuilder.append(String.format("return $this->Path() . 'Controllers/%s/%s.php';", matcher.group(1), matcher.group(2))); stringBuilder.append("\n"); } } stringBuilder.append("}"); PhpClass phpClass = method.getContainingClass(); Method methodCreated = PhpCodeUtil.createMethodFromTemplate(phpClass, phpClass.getProject(), stringBuilder.toString()); if(methodCreated == null) { return; } StringBuffer textBuf = new StringBuffer(); textBuf.append("\n"); textBuf.append(methodCreated.getText()); Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); if(editor == null) { return; } editor.getDocument().insertString(insertPos, textBuf); int endPos = insertPos + textBuf.length(); CodeStyleManager.getInstance(project).reformatText(phpClass.getContainingFile(), insertPos, endPos); PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); Method insertedMethod = phpClass.findMethodByName(contents); if(insertedMethod != null) { editor.getCaretModel().moveToOffset(insertedMethod.getTextRange().getStartOffset()); editor.getScrollingModel().scrollToCaret(ScrollType.CENTER_UP); } } private void attachVariablesInScope(@NotNull Project project, StringBuilder stringBuilder) { // Events if(HookSubscriberUtil.NOTIFY_EVENTS_MAP.containsKey(generatorContainer.getHookName())) { Collection<String> references = HookSubscriberUtil.NOTIFY_EVENTS_MAP.get(generatorContainer.getHookName()); for (String value : references) { String[] split = value.split("\\."); Method classMethod = PhpElementsUtil.getClassMethod(project, split[0], split[1]); if(classMethod == null) { continue; } buildEventVariables(project, stringBuilder, classMethod); } } else if(generatorContainer.getHookMethod() != null) { // add hook parameter Parameter[] hookMethodParameters = generatorContainer.getHookMethod().getParameters(); if(hookMethodParameters.length > 0 ) { stringBuilder.append("\n"); for(Parameter parameter : hookMethodParameters) { String name = parameter.getName(); stringBuilder.append("$").append(name).append(" = ").append("$args->get('").append(name).append("');\n"); } } } } private void buildEventVariables(@NotNull final Project project, final StringBuilder stringBuilder, Method classMethod) { classMethod.acceptChildren(new PsiRecursiveElementWalkingVisitor() { @Override public void visitElement(PsiElement element) { if ((element instanceof StringLiteralExpression) && ((StringLiteralExpression) element).getContents().equals(generatorContainer.getHookName())) { PsiElement parent = element.getParent(); if(parent instanceof ParameterList) { PsiElement[] parameterList = ((ParameterList) parent).getParameters(); if(parameterList.length > 1) { if(parameterList[1] instanceof ArrayCreationExpression) { Map<String, PsiElement> eventParameters = PhpElementsUtil.getArrayCreationKeyMap((ArrayCreationExpression) parameterList[1]); for(Map.Entry<String, PsiElement> entrySet : eventParameters.entrySet()) { stringBuilder.append("\n"); PhpPsiElement psiElement = PhpElementsUtil.getArrayValue((ArrayCreationExpression) parameterList[1], entrySet.getKey()); if(psiElement instanceof PhpTypedElement) { Set<String> classes = new HashSet<>(); PhpType type = ((PhpTypedElement) psiElement).getType(); for (PhpClass aClass : PhpElementsUtil.getClassFromPhpTypeSet(project, type.getTypes())) { // force absolute namespace classes.add("\\" + StringUtils.stripStart(aClass.getPresentableFQN(), "\\")); } if(classes.size() > 0) { stringBuilder.append("/** @var ").append(StringUtils.join(classes, "|")).append("$").append(entrySet.getKey()).append(" */\n"); } } stringBuilder.append("$").append(entrySet.getKey()).append(" = ").append("$args->get('").append(entrySet.getKey()).append("');\n"); } } } } } super.visitElement(element); } }); } @Nullable public static PsiElement getSubjectTargetOnHook(Project project, final String contents) { for(PsiElement psiElement : LazySubscriberReferenceProvider.getHookTargets(project, contents)) { if(psiElement instanceof Method) { return psiElement; } else if(psiElement instanceof PhpClass) { return psiElement; } } if(HookSubscriberUtil.NOTIFY_EVENTS_MAP.containsKey(contents)) { Collection<String> references = HookSubscriberUtil.NOTIFY_EVENTS_MAP.get(contents); for (String value : references) { String[] split = value.split("\\."); Method classMethod = PhpElementsUtil.getClassMethod(project, split[0], split[1]); if(classMethod == null) { continue; } return classMethod; } } return null; } public static class GeneratorContainer { private String hookName = null; private String subjectDoc = null; private Method hookMethod = null; public GeneratorContainer(String subjectDoc, Method hookMethod, String hookName) { this.subjectDoc = subjectDoc; this.hookMethod = hookMethod; this.hookName = hookName; } public String getHookName() { return hookName; } public String getSubjectDoc() { return subjectDoc; } public Method getHookMethod() { return hookMethod; } } }
package edu.ucar.unidata.rosetta.repository.wizard; import edu.ucar.unidata.rosetta.domain.MetadataProfile; import org.apache.commons.io.FilenameUtils; import org.apache.log4j.Logger; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.w3c.dom.*; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; /** * Implementation for metadata profiles DAO. */ public class XmlMetadataProfileDao implements MetadataProfileDao { private static final Logger logger = Logger.getLogger(XmlMetadataProfileDao.class); /** * Retrieves the metadata profile attributes to ignore in the wizard interface. * * @return A list of MetadataProfile objects containing the attributes to ignore. */ public List<MetadataProfile> getIgnoredMetadataProfileAttributes() { return loadMetadataProfiles("ignorelist", "IGNORE"); } /** * Retrieves the persisted metadata profile associated with the given type. * * @param metadataProfileType The metadata profile type. * @return A list of MetadataProfile objects created from the persisted metadata profile data. */ public List<MetadataProfile> getMetadataProfileByType(String metadataProfileType) { return loadMetadataProfiles(metadataProfileType, "ROW"); } /** * Cracks open the XML file corresponding to the given file name, parses the data found using * the given tag name, and populates/returns a list of MetadataProfile objects using the data. * * @param fileName The name of the XML file to use. * @param tagName The XML tag name from which to get the data. * @return A list of MetadataProfile objects created from the persisted metadata profile data. */ private List<MetadataProfile> loadMetadataProfiles(String fileName, String tagName) { List<MetadataProfile> profiles = new ArrayList<>(); try { // Get the metadata profile file. Resource r = new ClassPathResource(FilenameUtils.concat("resources/MpsProfilesRosetta/", fileName + ".xml")); File file = r.getFile(); // Need a DocumentBuilder to work with XML files. DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Parse file as an XML document and return a new DOM Document object. Document doc = dBuilder.parse(file); doc.getDocumentElement().normalize(); // Get all elements in document with a given tag name. NodeList ignoreNodeList = doc.getElementsByTagName(tagName); // Process all the nodes. for (int i = 0; i < ignoreNodeList.getLength(); i++) { // Create a new MetadataProfile object. MetadataProfile metadataProfile = new MetadataProfile(); // Get the attributes for the node. Node row = ignoreNodeList.item(i); NamedNodeMap attributes = row.getAttributes(); for (int j = 0; j < attributes.getLength(); j++) { // Get the name of the attribute. Node attribute = attributes.item(j); String attributeName = attribute.getNodeName(); // Create a setter method name from the attribute name. String setterMethodName = "set" + attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1); // Get attribute value. String attributeValue = attribute.getNodeValue(); // Access the actual setter method using the setter method name. Method setter = metadataProfile.getClass().getMethod(setterMethodName, String.class); setter.invoke(metadataProfile, attributeValue); } // Add our MetadataProfile object to the list. profiles.add(i, metadataProfile); } } catch (DOMException | ParserConfigurationException | SAXException | IOException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { StringWriter errors = new StringWriter(); e.printStackTrace(new PrintWriter(errors)); logger.error("Unable to load resources: " + errors); } return profiles; } }
package info.u_team.u_team_core.intern.discord; import info.u_team.u_team_core.UCoreMod; import info.u_team.u_team_core.intern.config.ClientConfig; import info.u_team.u_team_core.intern.discord.DiscordRichPresence.*; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.player.ClientPlayerEntity; import net.minecraft.client.gui.screen.*; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.GuiScreenEvent.InitGuiEvent; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.eventbus.api.*; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.event.lifecycle.*; public class UpdateDiscordEventHandler { public static void on(InitGuiEvent.Pre event) { if (!DiscordRichPresence.isEnabled()) { return; } if (event.getGui() instanceof MainMenuScreen || event.getGui() instanceof WorldSelectionScreen || event.getGui() instanceof MultiplayerScreen) { final State state = DiscordRichPresence.getCurrent(); if (state == null || state.getState() != EnumState.MENU) { DiscordRichPresence.setIdling(); } } } public static void on(EntityJoinWorldEvent event) { if (!DiscordRichPresence.isEnabled()) { return; } if (event.getEntity() instanceof ClientPlayerEntity) { final ClientPlayerEntity player = (ClientPlayerEntity) event.getEntity(); if (player.getUniqueID().equals(Minecraft.getInstance().player.getUniqueID())) { DiscordRichPresence.setDimension(player.getEntityWorld()); } } } private static void setup(FMLCommonSetupEvent event) { if (ClientConfig.getInstance().discordRichPresence.get()) { DiscordRichPresence.start(); } } public static void registerMod(IEventBus bus) { bus.addListener(UpdateDiscordEventHandler::setup); } public static void registerForge(IEventBus bus) { } }
package io.github.lukehutch.fastclasspathscanner.scanner; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import io.github.lukehutch.fastclasspathscanner.classloaderhandler.ClassLoaderHandler; import io.github.lukehutch.fastclasspathscanner.classloaderhandler.EquinoxClassLoaderHandler; import io.github.lukehutch.fastclasspathscanner.classloaderhandler.JBossClassLoaderHandler; import io.github.lukehutch.fastclasspathscanner.classloaderhandler.URLClassLoaderHandler; import io.github.lukehutch.fastclasspathscanner.classloaderhandler.WeblogicClassLoaderHandler; import io.github.lukehutch.fastclasspathscanner.utils.LogNode; /** A class to find the unique ordered classpath elements. */ public class ClasspathFinder { /** The list of raw classpath elements. */ private final List<String> rawClasspathElements = new ArrayList<>(); /** * Default ClassLoaderHandlers. If a ClassLoaderHandler is added to FastClasspathScanner, it should be added to * this list. */ private static final List<Class<? extends ClassLoaderHandler>> DEFAULT_CLASS_LOADER_HANDLERS = Arrays.asList( // The main default ClassLoaderHandler -- URLClassLoader is the most common ClassLoader URLClassLoaderHandler.class, // ClassLoaderHandlers for other ClassLoaders that are handled by FastClasspathScanner EquinoxClassLoaderHandler.class, JBossClassLoaderHandler.class, WeblogicClassLoaderHandler.class); /** * Add a classpath element relative to a base file. May be called by a ClassLoaderHandler to add classpath * elements that it knows about. */ public void addClasspathElement(final String pathElement, final LogNode log) { if (pathElement != null && !pathElement.isEmpty()) { rawClasspathElements.add(pathElement); if (log != null) { log.log("Adding classpath element: " + pathElement); } } } /** * Add classpath elements, separated by the system path separator character. May be called by a * ClassLoaderHandler to add a path string that it knows about. */ public void addClasspathElements(final String pathStr, final LogNode log) { if (pathStr != null && !pathStr.isEmpty()) { for (final String pathElement : pathStr.split(File.pathSeparator)) { addClasspathElement(pathElement, log); } } } /** A class to find the unique ordered classpath elements. */ ClasspathFinder(final ScanSpec scanSpec, final LogNode log) { if (scanSpec.overrideClasspath != null) { // Manual classpath override final LogNode overrideLog = log == null ? null : log.log("Overriding classpath"); addClasspathElements(scanSpec.overrideClasspath, overrideLog); } else { // Always include a ClassLoaderHandler for URLClassLoader subclasses as a default, so that we can // handle URLClassLoaders (the most common form of ClassLoader) even if ServiceLoader can't find // other ClassLoaderHandlers (this can happen if FastClasspathScanner's package is renamed using // Maven Shade). final List<ClassLoaderHandler> classLoaderHandlers = new ArrayList<>(); for (final Class<? extends ClassLoaderHandler> classLoaderHandlerClass : DEFAULT_CLASS_LOADER_HANDLERS) { try { classLoaderHandlers.add(classLoaderHandlerClass.newInstance()); } catch (InstantiationException | IllegalAccessException e) { if (log != null) { log.log("Could not instantiate " + classLoaderHandlerClass.getName(), e); } } } for (final Class<? extends ClassLoaderHandler> classLoaderHandler : scanSpec.extraClassLoaderHandlers) { try { classLoaderHandlers.add(classLoaderHandler.newInstance()); } catch (InstantiationException | IllegalAccessException e) { if (log != null) { log.log("Could not instantiate " + classLoaderHandler.getName(), e); } } } if (log != null) { final LogNode classLoaderHandlerLog = log.log("ClassLoaderHandlers loaded:"); for (final ClassLoaderHandler classLoaderHandler : classLoaderHandlers) { classLoaderHandlerLog.log(classLoaderHandler.getClass().getName()); } } // Try finding a handler for each of the classloaders discovered above for (final ClassLoader classLoader : scanSpec.classLoaders) { final LogNode classLoaderLog = log == null ? null : log.log("Finding classpath elements in ClassLoader " + classLoader); // Iterate through registered ClassLoaderHandlers boolean classloaderFound = false; for (final ClassLoaderHandler handler : classLoaderHandlers) { try { if (handler.handle(classLoader, this, classLoaderLog)) { classloaderFound = true; break; } } catch (final Exception e) { if (classLoaderLog != null) { classLoaderLog.log("Exception in ClassLoaderHandler", e); } } } if (!classloaderFound) { if (classLoaderLog != null) { classLoaderLog.log("Unknown ClassLoader type, cannot scan classes"); } } } if (!scanSpec.overrideClassLoaders) { // Add entries found in java.class.path, in case those entries were missed above due to some // non-standard classloader that uses this property final LogNode sysPropLog = log == null ? null : log.log("Getting classpath entries from java.class.path"); addClasspathElements(System.getProperty("java.class.path"), sysPropLog); } } } /** Get the raw classpath elements obtained from ClassLoaders. */ public List<String> getRawClasspathElements() { return rawClasspathElements; } }
package nom.bdezonia.zorbage.type.data.float64.real; import nom.bdezonia.zorbage.groups.G; //note that many implementations of tensors on the internet treat them as generalized matrices. //they do not worry about upper and lower indices or even matching shapes. They do element by //element ops like sin() of each elem. //do I skip Vector and Matrix and even Scalar? //TODO: make one tensor/member pair for each of float64, complex64, quat64, oct64 //TODO: determine if this is a field or something else or two things for float/complex vs. quat/oct // this implies it is an OrderedField. Do tensors have an ordering? abs() exists in TensorFlow. //@Override //public void abs(TensorMember a, TensorMember b) {} // tensorflow also has trigonometric and hyperbolic //public void contract(int i, int j, TensorMember a, TensorMember b, TensorMember c) {} //public void takeDiagonal(TensorMember a, Object b) {} // change Object to Vector //many more import nom.bdezonia.zorbage.type.algebra.TensorProduct; import nom.bdezonia.zorbage.type.ctor.ConstructibleNdLong; import nom.bdezonia.zorbage.type.ctor.MemoryConstruction; import nom.bdezonia.zorbage.type.ctor.StorageConstruction; /** * * @author Barry DeZonia * */ public class Float64TensorProduct implements TensorProduct<Float64TensorProduct,Float64TensorProductMember,Float64Group,Float64Member>, ConstructibleNdLong<Float64TensorProductMember> { @Override public Float64TensorProductMember construct() { return new Float64TensorProductMember(); } @Override public Float64TensorProductMember construct(Float64TensorProductMember other) { return new Float64TensorProductMember(other); } @Override public Float64TensorProductMember construct(String s) { return new Float64TensorProductMember(s); } @Override public Float64TensorProductMember construct(MemoryConstruction m, StorageConstruction s, long[] nd) { return new Float64TensorProductMember(m, s, nd); } @Override public boolean isEqual(Float64TensorProductMember a, Float64TensorProductMember b) { if (!shapesMatch(a,b)) return false; Float64Member aTmp = new Float64Member(); Float64Member bTmp = new Float64Member(); long numElems = a.numElems(); for (long i = 0; i < numElems; i++) { a.v(i, aTmp); b.v(i, bTmp); if (G.DBL.isNotEqual(aTmp, bTmp)) return false; } return true; } @Override public boolean isNotEqual(Float64TensorProductMember a, Float64TensorProductMember b) { return !isEqual(a,b); } @Override public void assign(Float64TensorProductMember from, Float64TensorProductMember to) { if (to == from) return; Float64Member tmp = new Float64Member(); long[] dims = new long[from.numDimensions()]; for (int i = 0; i < dims.length; i++) { dims[i] = from.dimension(i); } to.reshape(dims); long numElems = from.numElems(); for (long i = 0; i < numElems; i++) { from.v(i, tmp); to.setV(i, tmp); } } @Override public void zero(Float64TensorProductMember a) { Float64Member tmp = new Float64Member(); long numElems = a.numElems(); for (long i = 0; i < numElems; i++) { a.setV(i, tmp); } } @Override public void negate(Float64TensorProductMember a, Float64TensorProductMember b) { Float64Member tmp = new Float64Member(); assign(a,b); long numElems = b.numElems(); for (long i = 0; i < numElems; i++) { b.v(i, tmp); G.DBL.negate(tmp, tmp); b.setV(i, tmp); } } @Override public void add(Float64TensorProductMember a, Float64TensorProductMember b, Float64TensorProductMember c) { if (!shapesMatch(a,b)) throw new IllegalArgumentException("tensor add shape mismatch"); long[] newDims = new long[a.numDimensions()]; for (int i = 0; i < newDims.length; i++) { newDims[i] = a.dimension(i); } c.reshape(newDims); Float64Member aTmp = new Float64Member(); Float64Member bTmp = new Float64Member(); Float64Member cTmp = new Float64Member(); long numElems = a.numElems(); for (long i = 0; i < numElems; i++) { a.v(i, aTmp); b.v(i, bTmp); G.DBL.add(aTmp, bTmp, cTmp); c.setV(i, cTmp); } } @Override public void subtract(Float64TensorProductMember a, Float64TensorProductMember b, Float64TensorProductMember c) { if (!shapesMatch(a,b)) throw new IllegalArgumentException("tensor subtract shape mismatch"); long[] newDims = new long[a.numDimensions()]; for (int i = 0; i < newDims.length; i++) { newDims[i] = a.dimension(i); } c.reshape(newDims); Float64Member aTmp = new Float64Member(); Float64Member bTmp = new Float64Member(); Float64Member cTmp = new Float64Member(); long numElems = a.numElems(); for (long i = 0; i < numElems; i++) { a.v(i, aTmp); b.v(i, bTmp); G.DBL.subtract(aTmp, bTmp, cTmp); c.setV(i, cTmp); } } @Override public void norm(Float64TensorProductMember a, Float64Member b) { throw new IllegalArgumentException("to be implemented"); } @Override public void crossProduct(Float64TensorProductMember a, Float64TensorProductMember b, Float64TensorProductMember c) { // TODO Auto-generated method stub } @Override public void dotProduct(Float64TensorProductMember a, Float64TensorProductMember b, Float64Member c) { // TODO Auto-generated method stub } @Override public void perpDotProduct(Float64TensorProductMember a, Float64TensorProductMember b, Float64Member c) { // TODO Auto-generated method stub } @Override public void vectorTripleProduct(Float64TensorProductMember a, Float64TensorProductMember b, Float64TensorProductMember c, Float64TensorProductMember d) { // TODO Auto-generated method stub } @Override public void scalarTripleProduct(Float64TensorProductMember a, Float64TensorProductMember b, Float64TensorProductMember c, Float64Member d) { // TODO Auto-generated method stub } @Override public void conjugate(Float64TensorProductMember a, Float64TensorProductMember b) { throw new IllegalArgumentException("to be implemented"); } @Override public void scale(Float64Member scalar, Float64TensorProductMember a, Float64TensorProductMember b) { Float64Member tmp = new Float64Member(); assign(a,b); for (long i = 0; i < b.numElems(); i++) { b.v(i, tmp); G.DBL.multiply(scalar, tmp, tmp); b.setV(i, tmp); } } // TODO: need some interface to override public void add(Float64Member scalar, Float64TensorProductMember a, Float64TensorProductMember b) { Float64Member tmp = new Float64Member(); assign(a,b); for (long i = 0; i < b.numElems(); i++) { b.v(i, tmp); G.DBL.add(scalar, tmp, tmp); b.setV(i, tmp); } } // TODO: need some interface to override public void multiplyElements(Float64TensorProductMember a, Float64TensorProductMember b, Float64TensorProductMember c) { if (!shapesMatch(a, b)) throw new IllegalArgumentException("mismatched shapes"); long[] newDims = new long[a.numDimensions()]; for (int i = 0; i < newDims.length; i++) { newDims[i] = a.dimension(i); } c.reshape(newDims); Float64Member aTmp = new Float64Member(); Float64Member bTmp = new Float64Member(); Float64Member cTmp = new Float64Member(); long numElems = a.numElems(); for (long i = 0; i < numElems; i++) { a.v(i, aTmp); b.v(i, bTmp); G.DBL.multiply(aTmp, bTmp, cTmp); c.setV(i, cTmp); } } // TODO: need some interface to override public void divideElements(Float64TensorProductMember a, Float64TensorProductMember b, Float64TensorProductMember c) { if (!shapesMatch(a, b)) throw new IllegalArgumentException("mismatched shapes"); long[] newDims = new long[a.numDimensions()]; for (int i = 0; i < newDims.length; i++) { newDims[i] = a.dimension(i); } c.reshape(newDims); Float64Member aTmp = new Float64Member(); Float64Member bTmp = new Float64Member(); Float64Member cTmp = new Float64Member(); long numElems = a.numElems(); for (long i = 0; i < numElems; i++) { a.v(i, aTmp); b.v(i, bTmp); G.DBL.divide(aTmp, bTmp, cTmp); c.setV(i, cTmp); } } // TODO: need some interface to override public void product(Float64TensorProductMember a, Float64TensorProductMember b, Float64TensorProductMember c) { if (c == a || c == b) throw new IllegalArgumentException("destination tensor cannot be one of the inputs"); long dimA = a.dimension(0); long dimB = b.dimension(0); if (dimA != dimB) throw new IllegalArgumentException("dimension of tensors must match"); int rankA = a.numDimensions(); int rankB = b.numDimensions(); int rankC = rankA + rankB; long[] cDims = new long[rankC]; for (int i = 0; i < cDims.length; i++) { cDims[i] = dimA; } c.reshape(cDims); Float64Member aTmp = new Float64Member(); Float64Member bTmp = new Float64Member(); Float64Member cTmp = new Float64Member(); long k = 0; for (long i = 0; i < a.componentCount(); i++) { a.v(i, aTmp); for (long j = 0; j < b.componentCount(); j++) { b.v(i, bTmp); G.DBL.multiply(aTmp, bTmp, cTmp); c.setV(k, cTmp); k++; } } } // TODO: need some interface to override public void contract(int i, int j, Float64TensorProductMember a, Float64TensorProductMember b) { if (a.rank() < 2) throw new IllegalArgumentException("input tensor must be rank 2 or greater to contract"); if (i < 0 || j < 0 || i >= a.rank() || j >= a.rank()) throw new IllegalArgumentException("bad contraction indices given"); if (i == j) throw new IllegalArgumentException("cannot contract along a single axis"); if (a == b) throw new IllegalArgumentException("destination tensor cannot be one of the inputs"); int rank = a.rank() - 2; long[] newDims = new long[rank]; for (int k = 0; k < newDims.length; k++) { newDims[k] = a.dimension(0); } b.reshape(newDims); throw new IllegalArgumentException("must finish"); } private boolean shapesMatch(Float64TensorProductMember a, Float64TensorProductMember b) { int numDims = a.numDimensions(); if (numDims != b.numDimensions()) return false; for (int i = 0; i < numDims; i++) { if (a.dimension(i) != b.dimension(i)) return false; } return true; } }
package nu.studer.teamcity.buildscan.internal; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Charsets; import jetbrains.buildServer.ArtifactsConstants; import jetbrains.buildServer.serverSide.SBuild; import nu.studer.teamcity.buildscan.BuildScanDataStore; import nu.studer.teamcity.buildscan.BuildScanReference; import org.apache.log4j.Logger; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public final class ArtifactBuildScanDataStore implements BuildScanDataStore { private static final Logger LOGGER = Logger.getLogger("jetbrains.buildServer.BUILDSCAN"); // storage related coordinates private static final String BUILD_SCANS_DIR = "build_scans"; private static final String BUILD_SCAN_LINKS_FILE = "build_scans.txt"; private final BuildScanDataStore delegate; public ArtifactBuildScanDataStore(@NotNull BuildScanDataStore delegate) { this.delegate = delegate; } @Override public void mark(SBuild build) { final Path buildScanLinksFile = getBuildScanLinksFile(build.getArtifactsDirectory()); try { createFileIfNotExists(buildScanLinksFile); } catch (IOException ex) { LOGGER.error(String.format("Could not create buildscan file %s", buildScanLinksFile), ex); } } @Override public void store(SBuild build, String buildScanUrl) { final Path buildScanLinksFile = getBuildScanLinksFile(build.getArtifactsDirectory()); try { createFileIfNotExists(buildScanLinksFile); Files.write(buildScanLinksFile, Collections.singletonList(buildScanUrl), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND); LOGGER.debug(String.format("Successfully stored buildscan url %s for build %s in directory %s", buildScanUrl, build.getBuildId(), build.getArtifactsDirectory())); } catch (IOException ex) { LOGGER.error(String.format("Could not store build scan url %s into buildscan file %s", buildScanUrl, buildScanLinksFile), ex); } } @Override public List<BuildScanReference> fetch(SBuild build) { final Path buildScanLinksFile = getBuildScanLinksFile(build.getArtifactsDirectory()); List<BuildScanReference> result; if (Files.exists(buildScanLinksFile)) { try { result = Files.lines(buildScanLinksFile, Charsets.UTF_8).map(scanUrl -> new BuildScanReference(Util.getBuildScanId(scanUrl), scanUrl)).collect(Collectors.toList()); } catch (IOException ex) { LOGGER.error(String.format("Could not read buildscan file %s", buildScanLinksFile), ex); result = Collections.emptyList(); } } else { return delegate.fetch(build); } return result; } @NotNull @VisibleForTesting Path getBuildScanLinksFile(File dir) { return Paths.get(dir.getAbsolutePath(), ArtifactsConstants.TEAMCITY_ARTIFACTS_DIR, BUILD_SCANS_DIR, BUILD_SCAN_LINKS_FILE); } private static void createFileIfNotExists(Path file) throws IOException { if (!Files.exists(file)) { Files.createDirectories(file.getParent()); try { Files.createFile(file); } catch (FileAlreadyExistsException e) { // not a failure scenario, this can happen since our check for existence and // the possible creation are not atomic (while createFile _is_ atomic) } } } }
package org.jenkinsci.plugins.ghprb.extensions.comments; import hudson.Extension; import hudson.FilePath; import hudson.model.Build; import hudson.model.Run; import hudson.model.TaskListener; import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.ghprb.Ghprb; import org.jenkinsci.plugins.ghprb.extensions.GhprbCommentAppender; import org.jenkinsci.plugins.ghprb.extensions.GhprbExtension; import org.jenkinsci.plugins.ghprb.extensions.GhprbExtensionDescriptor; import org.jenkinsci.plugins.ghprb.extensions.GhprbProjectExtension; import org.kohsuke.stapler.DataBoundConstructor; import java.io.File; import java.io.IOException; public class GhprbCommentFile extends GhprbExtension implements GhprbCommentAppender, GhprbProjectExtension { @Extension public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl(); private final String commentFilePath; @DataBoundConstructor public GhprbCommentFile(String commentFilePath) { this.commentFilePath = commentFilePath; } public String getCommentFilePath() { return commentFilePath != null ? commentFilePath : ""; } public boolean ignorePublishedUrl() { return false; } public String postBuildComment(Run<?, ?> build, TaskListener listener) { StringBuilder msg = new StringBuilder(); if (commentFilePath != null && !commentFilePath.isEmpty()) { String scriptFilePathResolved = Ghprb.replaceMacros(build, listener, commentFilePath); try { String content = null; if (build instanceof Build<?, ?>) { final FilePath workspace = ((Build<?, ?>) build).getWorkspace(); final FilePath path = workspace.child(scriptFilePathResolved); if (path.exists()) { content = path.readToString(); } else { listener.getLogger().println( "Didn't find comment file in workspace at " + path.absolutize().getRemote() + ", falling back to file operations on master." ); } } if (content == null) { content = FileUtils.readFileToString(new File(scriptFilePathResolved)); } msg.append("Build comment file: \n msg.append(content); msg.append("\n } catch (IOException e) { msg.append("\n!!! Couldn't read commit file !!!\n"); listener.getLogger().println("Couldn't read comment file at " + scriptFilePathResolved); e.printStackTrace(listener.getLogger()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // set interrupt flag msg.append("\n!!! Couldn't read commit file !!!\n"); listener.getLogger().println("Reading comment file at " + scriptFilePathResolved + " was interrupted"); e.printStackTrace(listener.getLogger()); } } return msg.toString(); } @Override public DescriptorImpl getDescriptor() { return DESCRIPTOR; } public static final class DescriptorImpl extends GhprbExtensionDescriptor implements GhprbProjectExtension { @Override public String getDisplayName() { return "Comment File"; } } }
package org.spongepowered.common.mixin.core.entity; import static com.google.common.base.Preconditions.checkNotNull; import com.flowpowered.math.vector.Vector3d; import net.minecraft.block.state.IBlockState; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.ai.attributes.AbstractAttributeMap; import net.minecraft.entity.ai.attributes.IAttribute; import net.minecraft.entity.ai.attributes.IAttributeInstance; import net.minecraft.entity.passive.EntityWolf; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.MobEffects; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.potion.Potion; import net.minecraft.util.CombatTracker; import net.minecraft.util.DamageSource; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.SoundEvent; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import org.spongepowered.api.Sponge; import org.spongepowered.api.data.key.Keys; import org.spongepowered.api.data.manipulator.DataManipulator; import org.spongepowered.api.data.manipulator.mutable.entity.DamageableData; import org.spongepowered.api.data.manipulator.mutable.entity.HealthData; import org.spongepowered.api.data.value.mutable.MutableBoundedValue; import org.spongepowered.api.data.value.mutable.OptionalValue; import org.spongepowered.api.entity.EntitySnapshot; import org.spongepowered.api.entity.Transform; import org.spongepowered.api.entity.living.Living; import org.spongepowered.api.entity.projectile.Projectile; import org.spongepowered.api.event.CauseStackManager; import org.spongepowered.api.event.CauseStackManager.StackFrame; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.cause.entity.damage.DamageFunction; import org.spongepowered.api.event.cause.entity.damage.DamageModifier; import org.spongepowered.api.event.cause.entity.damage.source.FallingBlockDamageSource; import org.spongepowered.api.event.entity.DamageEntityEvent; import org.spongepowered.api.event.entity.MoveEntityEvent; import org.spongepowered.api.text.Text; import org.spongepowered.api.util.annotation.NonnullByDefault; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.common.data.manipulator.mutable.entity.SpongeDamageableData; import org.spongepowered.common.data.manipulator.mutable.entity.SpongeHealthData; import org.spongepowered.common.data.value.SpongeValueFactory; import org.spongepowered.common.data.value.mutable.SpongeOptionalValue; import org.spongepowered.common.entity.EntityUtil; import org.spongepowered.common.entity.living.human.EntityHuman; import org.spongepowered.common.entity.projectile.ProjectileLauncher; import org.spongepowered.common.event.SpongeCommonEventFactory; import org.spongepowered.common.event.damage.DamageEventHandler; import org.spongepowered.common.event.damage.DamageObject; import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.event.tracking.IPhaseState; import org.spongepowered.common.event.tracking.PhaseContext; import org.spongepowered.common.event.tracking.PhaseData; import org.spongepowered.common.event.tracking.phase.entity.EntityPhase; import org.spongepowered.common.interfaces.entity.IMixinEntityLivingBase; import org.spongepowered.common.interfaces.entity.player.IMixinEntityPlayerMP; import org.spongepowered.common.registry.type.event.DamageSourceRegistryModule; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.Random; import javax.annotation.Nullable; @SuppressWarnings("rawtypes") @NonnullByDefault @Mixin(value = EntityLivingBase.class, priority = 999) public abstract class MixinEntityLivingBase extends MixinEntity implements Living, IMixinEntityLivingBase { private static final String WORLD_SPAWN_PARTICLE = "Lnet/minecraft/world/World;spawnParticle(Lnet/minecraft/util/EnumParticleTypes;DDDDDD[I)V"; private int maxAir = 300; @Shadow public int maxHurtResistantTime; @Shadow public int hurtTime; @Shadow public int maxHurtTime; @Shadow public int deathTime; @Shadow protected int scoreValue; @Shadow public float attackedAtYaw; @Shadow public float limbSwingAmount; @Shadow public boolean potionsNeedUpdate; @Shadow public boolean dead; @Shadow public CombatTracker _combatTracker; @Shadow @Nullable public EntityLivingBase revengeTarget; @Shadow protected AbstractAttributeMap attributeMap; @Shadow protected int idleTime; @Shadow protected int recentlyHit; @Shadow protected float lastDamage; @Shadow @Nullable protected EntityPlayer attackingPlayer; @Shadow protected ItemStack activeItemStack; @Shadow private DamageSource lastDamageSource; @Shadow private long lastDamageStamp; // Empty body so that we can call super() in MixinEntityPlayer @Shadow public void stopActiveHand() { } @Shadow protected abstract void markVelocityChanged(); @Shadow protected abstract SoundEvent getDeathSound(); @Shadow protected abstract float getSoundVolume(); @Shadow protected abstract float getSoundPitch(); @Shadow protected abstract SoundEvent getHurtSound(DamageSource cause); @Shadow public abstract void setHealth(float health); @Shadow public abstract void addPotionEffect(net.minecraft.potion.PotionEffect potionEffect); @Shadow protected abstract void markPotionsDirty(); @Shadow public abstract void clearActivePotions(); @Shadow public abstract void setLastAttackedEntity(net.minecraft.entity.Entity entity); @Shadow public abstract boolean isPotionActive(Potion potion); @Shadow public abstract float getHealth(); @Shadow public abstract float getMaxHealth(); @Shadow public abstract float getRotationYawHead(); @Shadow public abstract void setRotationYawHead(float rotation); @Shadow public abstract Collection getActivePotionEffects(); @Shadow @Nullable public abstract EntityLivingBase getLastAttackedEntity(); @Shadow public abstract IAttributeInstance getEntityAttribute(IAttribute attribute); @Shadow public abstract ItemStack getItemStackFromSlot(EntityEquipmentSlot slotIn); @Shadow protected abstract void applyEntityAttributes(); @Shadow protected abstract void playHurtSound(net.minecraft.util.DamageSource p_184581_1_); @Shadow protected abstract void damageShield(float p_184590_1_); @Shadow public abstract void setActiveHand(EnumHand hand); @Shadow public abstract ItemStack getHeldItem(EnumHand hand); @Shadow public abstract void setHeldItem(EnumHand hand, @Nullable ItemStack stack); @Shadow public abstract ItemStack getHeldItemMainhand(); @Shadow public abstract boolean isHandActive(); @Shadow protected abstract void onDeathUpdate(); @Shadow public abstract void knockBack(net.minecraft.entity.Entity entityIn, float p_70653_2_, double p_70653_3_, double p_70653_5_); @Shadow public abstract void setRevengeTarget(EntityLivingBase livingBase); @Shadow public abstract void setAbsorptionAmount(float amount); @Shadow public abstract float getAbsorptionAmount(); @Shadow public abstract CombatTracker getCombatTracker(); @Shadow public abstract void setSprinting(boolean sprinting); @Shadow public abstract boolean isOnLadder(); @Shadow @Nullable public abstract EntityLivingBase getAttackingEntity(); @Shadow protected abstract void dropLoot(boolean wasRecentlyHit, int lootingModifier, DamageSource source); @Shadow protected abstract boolean canDropLoot(); @Shadow public abstract Random getRNG(); @Shadow protected abstract void blockUsingShield(EntityLivingBase p_190629_1_); @Shadow public abstract boolean canBlockDamageSource(DamageSource p_184583_1_); @Shadow private boolean checkTotemDeathProtection(DamageSource p_190628_1_) { return false; // SHADOWED } @Shadow public abstract AbstractAttributeMap getAttributeMap(); @Shadow protected abstract int getExperiencePoints(EntityPlayer attackingPlayer); @Shadow @Nullable public abstract EntityLivingBase getRevengeTarget(); @Override public Vector3d getHeadRotation() { // pitch, yaw, roll -- Minecraft does not currently support head roll return new Vector3d(getRotation().getX(), getRotationYawHead(), 0); } @Override public void setHeadRotation(Vector3d rotation) { setRotation(getRotation().mul(0, 1, 1).add(rotation.getX(), 0, 0)); setRotationYawHead((float) rotation.getY()); } @Override public int getMaxAir() { return this.maxAir; } @Override public void setMaxAir(int air) { this.maxAir = air; } @Override public double getLastDamage() { return this.lastDamage; } @Override public void setLastDamage(double damage) { this.lastDamage = (float) damage; } @Override public void readFromNbt(NBTTagCompound compound) { super.readFromNbt(compound); if (compound.hasKey("maxAir")) { this.maxAir = compound.getInteger("maxAir"); } } @Override public void writeToNbt(NBTTagCompound compound) { super.writeToNbt(compound); compound.setInteger("maxAir", this.maxAir); } @Override public Text getTeamRepresentation() { return Text.of(this.getUniqueID().toString()); } protected boolean tracksEntityDeaths = false; /** * @author blood - May 12th, 2016 * @author gabizou - June 4th, 2016 - Update for 1.9.4 and Cause Tracker changes * * @reason SpongeForge requires an overwrite so we do it here instead. This handles all living entity death events * (except players). Note should be taken that normally, there are lists for drops captured, however, the drops * are retroactively captured by the PhaseTracker and associated through the different phases, depending on * how they are handled, so no lists and flags on the entities themselves are needed as they are tracked through * the {@link PhaseContext} of the current {@link IPhaseState} at which this method is called. The compatibility * for Forge's events to throw are handled specially in SpongeForge. */ @Overwrite public void onDeath(DamageSource cause) { // Sponge Start - Call our event, and forge's event // This will transitively call the forge event SpongeCommonEventFactory.callDestructEntityEventDeath((EntityLivingBase) (Object) this, cause); // Double check that the PhaseTracker is already capturing the Death phase final PhaseTracker phaseTracker = PhaseTracker.getInstance(); final boolean isMainThread = !this.world.isRemote || Sponge.isServerAvailable() && Sponge.getServer().isMainThread(); try (final StackFrame frame = isMainThread ? Sponge.getCauseStackManager().pushCauseFrame() : null) { if (!this.world.isRemote) { final PhaseData peek = phaseTracker.getCurrentPhaseData(); final IPhaseState state = peek.state; this.tracksEntityDeaths = !phaseTracker.getCurrentState().tracksEntityDeaths() && state != EntityPhase.State.DEATH; if (this.tracksEntityDeaths) { Sponge.getCauseStackManager().pushCause(this); final PhaseContext<?> context = EntityPhase.State.DEATH.createPhaseContext() .setDamageSource((org.spongepowered.api.event.cause.entity.damage.source.DamageSource) cause) .source(this); this.getNotifierUser().ifPresent(context::notifier); this.getCreatorUser().ifPresent(context::owner); context.buildAndSwitch(); } } else { this.tracksEntityDeaths = false; } // Sponge End if (this.dead) { // Sponge Start - ensure that we finish the tracker if necessary if (this.tracksEntityDeaths && !properlyOverridesOnDeathForCauseTrackerCompletion()) { phaseTracker.completePhase(EntityPhase.State.DEATH); } // Sponge End return; } Entity entity = cause.getTrueSource(); EntityLivingBase entitylivingbase = this.getAttackingEntity(); if (this.scoreValue >= 0 && entitylivingbase != null) { entitylivingbase.awardKillScore((EntityLivingBase) (Object) this, this.scoreValue, cause); } if (entity != null) { entity.onKillEntity((EntityLivingBase) (Object) this); } this.dead = true; this.getCombatTracker().reset(); if (!this.world.isRemote) { int i = 0; if (entity instanceof EntityPlayer) { i = EnchantmentHelper.getLootingModifier((EntityLivingBase) entity); } if (this.canDropLoot() && this.world.getGameRules().getBoolean("doMobLoot")) { boolean flag = this.recentlyHit > 0; this.dropLoot(flag, i, cause); } } // Sponge Start - Don't send the state if this is a human. Fixes ghost items on client. if (!((EntityLivingBase) (Object) this instanceof EntityHuman)) { this.world.setEntityState((EntityLivingBase) (Object) this, (byte) 3); } if (phaseTracker != null && this.tracksEntityDeaths && !properlyOverridesOnDeathForCauseTrackerCompletion()) { this.tracksEntityDeaths = false; phaseTracker.completePhase(EntityPhase.State.DEATH); } } // Sponge End } @Redirect(method = "onDeath(Lnet/minecraft/util/DamageSource;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/World;setEntityState(Lnet/minecraft/entity/Entity;B)V")) private void onDeathSendEntityState(World world, net.minecraft.entity.Entity self, byte state) { // Don't send the state if this is a human. Fixes ghost items on client. if (!((net.minecraft.entity.Entity) (Object) this instanceof EntityHuman)) { world.setEntityState(self, state); } } @Redirect(method = "applyPotionDamageCalculations", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/EntityLivingBase;isPotionActive(Lnet/minecraft/potion/Potion;)Z") ) private boolean onIsPotionActive(EntityLivingBase entityIn, Potion potion) { return false; // handled in our damageEntityHook } @Redirect(method = "applyArmorCalculations", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/EntityLivingBase;damageArmor(F)V") ) protected void onDamageArmor(EntityLivingBase entityIn, float damage) { // do nothing as this is handled in our damageEntityHook } /** * @author bloodmc - November 21, 2015 * @reason This shouldn't be used internally but a mod may still call it so we simply reroute to our hook. */ @Overwrite protected void damageEntity(DamageSource damageSource, float damage) { this.damageEntityHook(damageSource, damage); } /** * @author bloodmc - November 22, 2015 * @author gabizou - Updated April 11th, 2016 - Update for 1.9 changes * @author Aaron1011 - Updated Nov 11th, 2016 - Update for 1.11 changes * * @reason Reroute damageEntity calls to our hook in order to prevent damage. */ @Override @Overwrite public boolean attackEntityFrom(DamageSource source, float amount) { // Sponge start - Add certain hooks for necessities this.lastDamageSource = source; if (source == null) { Thread.dumpStack(); } // Sponge - This hook is for forge use mainly if (!hookModAttack((EntityLivingBase) (Object) this, source, amount)) return false; // Sponge end if (this.isEntityInvulnerable(source)) { return false; } else if (this.world.isRemote) { return false; } else { this.idleTime = 0; // Sponge - if the damage source is ignored, then do not return false here, as the health // has already been set to zero if Keys#HEALTH or SpongeHealthData is set to zero. if (this.getHealth() <= 0.0F && source != DamageSourceRegistryModule.IGNORED_DAMAGE_SOURCE) { return false; } else if (source.isFireDamage() && this.isPotionActive(MobEffects.FIRE_RESISTANCE)) { return false; } else { // Sponge - ignore as this is handled in our damageEntityHookge // if (false && (source == DamageSource.anvil || source == DamageSource.fallingBlock) // && this.getEquipmentInSlot(4) != null) { // this.getEquipmentInSlot(4).damageItem((int) (amount * 4.0F + this.rand.nextFloat() * amount * 2.0F), // (EntityLivingBase) (Object) this); // amount *= 0.75F; // Sponge End // Sponge - set the 'shield blocking ran' flag to the proper value, since // we comment out the logic below boolean flag = amount > 0.0F && this.canBlockDamageSource(source); // Sponge start - this is handled in our damageEntityHook /*boolean flag = false; if (amount > 0.0F && this.canBlockDamageSource(source)) { this.damageShield(amount); if (!source.isProjectile()) { Entity entity = source.getSourceOfDamage(); if (entity instanceof EntityLivingBase) { this.blockUsingShield((EntityLivingBase)entity); } } flag = true; }*/ // Sponge end this.limbSwingAmount = 1.5F; boolean flag1 = true; if ((float) this.hurtResistantTime > (float) this.maxHurtResistantTime / 2.0F) { if (amount <= this.lastDamage) { // Technically, this is wrong since 'amount' won't be 0 if a shield is used. However, we need damageEntityHook so that we process the shield, so we leave it as-is return false; } // Sponge start - reroute to our damage hook if (!this.damageEntityHook(source, amount - this.lastDamage)) { return false; } // Sponge end this.lastDamage = amount; flag1 = false; } else { // Sponge start - reroute to our damage hook if (!this.damageEntityHook(source, amount)) { return false; } this.lastDamage = amount; this.hurtResistantTime = this.maxHurtResistantTime; // this.damageEntity(source, amount); // handled above // Sponge end this.hurtTime = this.maxHurtTime = 10; } this.attackedAtYaw = 0.0F; net.minecraft.entity.Entity entity = source.getTrueSource(); if (entity != null) { if (entity instanceof EntityLivingBase) { this.setRevengeTarget((EntityLivingBase) entity); } if (entity instanceof EntityPlayer) { this.recentlyHit = 100; this.attackingPlayer = (EntityPlayer) entity; } else if (entity instanceof EntityWolf) { EntityWolf entityWolf = (EntityWolf) entity; if (entityWolf.isTamed()) { this.recentlyHit = 100; this.attackingPlayer = null; } } } if (flag1) { if (flag) { this.world.setEntityState((EntityLivingBase) (Object) this, (byte) 29); } else if (source instanceof net.minecraft.util.EntityDamageSource && ((net.minecraft.util.EntityDamageSource) source).getIsThornsDamage()) { this.world.setEntityState((EntityLivingBase) (Object) this, (byte) 33); } else { this.world.setEntityState((EntityLivingBase) (Object) this, (byte) 2); } if (source != DamageSource.DROWN && !flag) { // Sponge - remove 'amount > 0.0F' - it's redundant in Vanilla, and breaks our handling of shields this.markVelocityChanged(); } if (entity != null) { double d1 = entity.posX - this.posX; double d0; for (d0 = entity.posZ - this.posZ; d1 * d1 + d0 * d0 < 1.0E-4D; d0 = (Math.random() - Math.random()) * 0.01D) { d1 = (Math.random() - Math.random()) * 0.01D; } this.attackedAtYaw = (float) (MathHelper.atan2(d0, d1) * 180.0D / Math.PI - (double) this.rotationYaw); this.knockBack(entity, 0.4F, d1, d0); } else { this.attackedAtYaw = (float) ((Math.random() * 2.0D) * 180); } } if (this.getHealth() <= 0.0F) { if (!this.checkTotemDeathProtection(source)) { SoundEvent soundevent = this.getDeathSound(); if (flag1 && soundevent != null) { this.playSound(soundevent, this.getSoundVolume(), this.getSoundPitch()); } // Sponge Start - notify the cause tracker final PhaseTracker phaseTracker = PhaseTracker.getInstance(); try (StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { final boolean enterDeathPhase = !phaseTracker.getCurrentState().tracksEntityDeaths(); if (enterDeathPhase) { Sponge.getCauseStackManager().pushCause(this); } try (final PhaseContext<?> context = !enterDeathPhase ? null : EntityPhase.State.DEATH.createPhaseContext() .source(this) .setDamageSource((org.spongepowered.api.event.cause.entity.damage.source.DamageSource) source) .owner(this::getCreatorUser) .notifier(this::getNotifierUser) .buildAndSwitch()) { this.onDeath(source); } } } // Sponge End } else if (flag1) { this.playHurtSound(source); } if (!flag) // Sponge - remove 'amount > 0.0F' { this.lastDamageSource = source; this.lastDamageStamp = this.world.getTotalWorldTime(); } return !flag; // Sponge - remove 'amount > 0.0F' } } } /** * @author gabizou - January 4th, 2016 * This is necessary for invisibility checks so that vanish players don't actually send the particle stuffs. */ @Redirect(method = "updateItemUse", at = @At(value = "INVOKE", target = WORLD_SPAWN_PARTICLE)) public void spawnItemParticle(World world, EnumParticleTypes particleTypes, double xCoord, double yCoord, double zCoord, double xOffset, double yOffset, double zOffset, int ... p_175688_14_) { if (!this.isVanished()) { this.world.spawnParticle(particleTypes, xCoord, yCoord, zCoord, xOffset, yOffset, zOffset, p_175688_14_); } } @Override public boolean damageEntityHook(DamageSource damageSource, float damage) { if (!this.isEntityInvulnerable(damageSource)) { final boolean human = (Object) this instanceof EntityPlayer; // apply forge damage hook damage = applyModDamage((EntityLivingBase) (Object) this, damageSource, damage); float originalDamage = damage; // set after forge hook. if (damage <= 0) { damage = 0; } List<DamageFunction> originalFunctions = new ArrayList<>(); Optional<DamageFunction> hardHatFunction = DamageEventHandler.createHardHatModifier((EntityLivingBase) (Object) this, damageSource); Optional<List<DamageFunction>> armorFunction = provideArmorModifiers((EntityLivingBase) (Object) this, damageSource, damage); Optional<DamageFunction> resistanceFunction = DamageEventHandler.createResistanceModifier((EntityLivingBase) (Object) this, damageSource); Optional<List<DamageFunction>> armorEnchantments = DamageEventHandler.createEnchantmentModifiers((EntityLivingBase) (Object) this, damageSource); Optional<DamageFunction> absorptionFunction = DamageEventHandler.createAbsorptionModifier((EntityLivingBase) (Object) this, damageSource); Optional<DamageFunction> shieldFunction = DamageEventHandler.createShieldFunction((EntityLivingBase) (Object) this, damageSource, damage); if (hardHatFunction.isPresent()) { originalFunctions.add(hardHatFunction.get()); } if (shieldFunction.isPresent()) { originalFunctions.add(shieldFunction.get()); } if (armorFunction.isPresent()) { originalFunctions.addAll(armorFunction.get()); } if (resistanceFunction.isPresent()) { originalFunctions.add(resistanceFunction.get()); } if (armorEnchantments.isPresent()) { originalFunctions.addAll(armorEnchantments.get()); } if (absorptionFunction.isPresent()) { originalFunctions.add(absorptionFunction.get()); } try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { DamageEventHandler.generateCauseFor(damageSource); DamageEntityEvent event = SpongeEventFactory.createDamageEntityEvent(Sponge.getCauseStackManager().getCurrentCause(), originalFunctions, this, originalDamage); if (damageSource != DamageSourceRegistryModule.IGNORED_DAMAGE_SOURCE) { // Basically, don't throw an event if it's our own damage source Sponge.getEventManager().post(event); } if (event.isCancelled()) { return false; } damage = (float) event.getFinalDamage(); // Helmet final ItemStack mainHandItem = this.getItemStackFromSlot(EntityEquipmentSlot.MAINHAND); if ((damageSource instanceof FallingBlockDamageSource) && mainHandItem != null) { mainHandItem.damageItem((int) (event.getBaseDamage() * 4.0F + this.rand.nextFloat() * event.getBaseDamage() * 2.0F), (EntityLivingBase) (Object) this); } // Shield if (shieldFunction.isPresent()) { this.damageShield((float) event.getBaseDamage()); // TODO gabizou: Should this be in the API? if (!damageSource.isProjectile()) { Entity entity = damageSource.getImmediateSource(); if (entity instanceof EntityLivingBase) { this.blockUsingShield((EntityLivingBase) entity); } } } // Armor if (!damageSource.isUnblockable()) { for (DamageFunction modifier : event.getModifiers()) { applyArmorDamage((EntityLivingBase) (Object) this, damageSource, event, modifier.getModifier()); } } double absorptionModifier = absorptionFunction.map(function -> event.getDamage(function.getModifier())).orElse(0d); if (absorptionFunction.isPresent()) { absorptionModifier = event.getDamage(absorptionFunction.get().getModifier()); } this.setAbsorptionAmount(Math.max(this.getAbsorptionAmount() + (float) absorptionModifier, 0.0F)); if (damage != 0.0F) { if (human) { ((EntityPlayer) (Object) this).addExhaustion(damageSource.getHungerDamage()); } float f2 = this.getHealth(); this.setHealth(f2 - damage); this.getCombatTracker().trackDamage(damageSource, f2, damage); if (human) { return true; } this.setAbsorptionAmount(this.getAbsorptionAmount() - damage); } return true; } } return false; } /** * @author Aaron1011 - August 15, 2016 * @reason An overwrite avoids the need for a local-capture inject and two redirects */ // TODO: Investigate mixing into setPositionAndUpdate to catch more teleports @Overwrite public boolean attemptTeleport(double x, double y, double z) { double d0 = this.posX; double d1 = this.posY; double d2 = this.posZ; this.posX = x; this.posY = y; this.posZ = z; boolean flag = false; BlockPos blockpos = new BlockPos((Entity) (Object) this); World world = this.world; Random random = this.getRNG(); if (world.isBlockLoaded(blockpos)) { boolean flag1 = false; while (!flag1 && blockpos.getY() > 0) { BlockPos blockpos1 = blockpos.down(); IBlockState iblockstate = world.getBlockState(blockpos1); if (iblockstate.getMaterial().blocksMovement()) { flag1 = true; } else { --this.posY; blockpos = blockpos1; } } if (flag1) { // Sponge start if (!world.isRemote) { Transform<org.spongepowered.api.world.World> fromTransform = this.getTransform().setPosition(new Vector3d(d0, d1, d2)); Transform<org.spongepowered.api.world.World> toTransform = this.getTransform().setPosition(new Vector3d(this.posX, this.posY, this.posZ)); MoveEntityEvent.Teleport event = EntityUtil.handleDisplaceEntityTeleportEvent((Entity) (Object) this, fromTransform, toTransform, false); if (event.isCancelled()) { this.posX = d0; this.posY = d1; this.posZ = d2; return false; } Vector3d position = event.getToTransform().getPosition(); this.rotationYaw = (float) event.getToTransform().getYaw(); this.rotationPitch = (float) event.getToTransform().getPitch(); this.setPositionAndUpdate(position.getX(), position.getY(), position.getZ()); } else { this.setPositionAndUpdate(this.posX, this.posY, this.posZ); } // Sponge end if (world.getCollisionBoxes((Entity) (Object) this, this.getEntityBoundingBox()).isEmpty() && !world.containsAnyLiquid(this.getEntityBoundingBox())) { flag = true; } } } if (!flag) { // Sponge start - this is technically a teleport, since it sends packets to players and calls 'updateEntityWithOptionalForce' - even though it doesn't really move the entity at all if (!world.isRemote) { Transform<org.spongepowered.api.world.World> transform = this.getTransform().setPosition(new Vector3d(d0, d1, d2)); MoveEntityEvent.Teleport event = EntityUtil.handleDisplaceEntityTeleportEvent((Entity) (Object) this, transform, transform, false); if (event.isCancelled()) { return false; } Vector3d position = event.getToTransform().getPosition(); this.rotationYaw = (float) event.getToTransform().getYaw(); this.rotationPitch = (float) event.getToTransform().getPitch(); this.setPositionAndUpdate(position.getX(), position.getY(), position.getZ()); } else { this.setPositionAndUpdate(d0, d1, d2); } // Sponge end return false; } else { // int i = 128; for (int j = 0; j < 128; ++j) { double d6 = (double)j / 127.0D; float f = (random.nextFloat() - 0.5F) * 0.2F; float f1 = (random.nextFloat() - 0.5F) * 0.2F; float f2 = (random.nextFloat() - 0.5F) * 0.2F; double d3 = d0 + (this.posX - d0) * d6 + (random.nextDouble() - 0.5D) * (double)this.width * 2.0D; double d4 = d1 + (this.posY - d1) * d6 + random.nextDouble() * (double)this.height; double d5 = d2 + (this.posZ - d2) * d6 + (random.nextDouble() - 0.5D) * (double)this.width * 2.0D; world.spawnParticle(EnumParticleTypes.PORTAL, d3, d4, d5, (double)f, (double)f1, (double)f2, new int[0]); } if ((Object) this instanceof EntityCreature) { ((EntityCreature) (Object) this).getNavigator().clearPath(); } return true; } } @Override public float applyModDamage(EntityLivingBase entityLivingBase, DamageSource source, float damage) { return damage; } @Override public Optional<List<DamageFunction>> provideArmorModifiers(EntityLivingBase entityLivingBase, DamageSource source, double damage) { return DamageEventHandler.createArmorModifiers(entityLivingBase, source, damage); } @Override public void applyArmorDamage(EntityLivingBase entityLivingBase, DamageSource source, DamageEntityEvent entityEvent, DamageModifier modifier) { Optional<DamageObject> optional = modifier.getCause().first(DamageObject.class); if (optional.isPresent()) { DamageEventHandler.acceptArmorModifier((EntityLivingBase) (Object) this, source, modifier, entityEvent.getDamage(modifier)); } } @Override public boolean hookModAttack(EntityLivingBase entityLivingBase, DamageSource source, float amount) { return true; } /** * @author gabizou - January 4th, 2016 * @reason This allows invisiblity to ignore entity collisions. */ @Overwrite public boolean canBeCollidedWith() { return !(this.isVanished() && this.ignoresCollision()) && !this.isDead; } @Override public int getRecentlyHit() { return this.recentlyHit; } @Redirect(method = "updateFallState", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/WorldServer;spawnParticle(Lnet/minecraft/util/EnumParticleTypes;DDDIDDDD[I)V")) private void spongeSpawnParticleForFallState(WorldServer worldServer, EnumParticleTypes particleTypes, double xCoord, double yCoord, double zCoord, int numberOfParticles, double xOffset, double yOffset, double zOffset, double particleSpeed, int... extraArgs) { if (!this.isVanished()) { worldServer.spawnParticle(particleTypes, xCoord, yCoord, zCoord, numberOfParticles, xOffset, yOffset, zOffset, particleSpeed, extraArgs); } } @Redirect(method = "onEntityUpdate", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/EntityLivingBase;onDeathUpdate()V")) private void causeTrackDeathUpdate(EntityLivingBase entityLivingBase) { if (!entityLivingBase.world.isRemote) { final PhaseTracker phaseTracker = PhaseTracker.getInstance(); try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame(); PhaseContext<?> context = EntityPhase.State.DEATH_UPDATE.createPhaseContext() .source(entityLivingBase) .buildAndSwitch()) { Sponge.getCauseStackManager().pushCause(entityLivingBase); ((IMixinEntityLivingBase) entityLivingBase).onSpongeDeathUpdate(); } } else { ((IMixinEntityLivingBase) entityLivingBase).onSpongeDeathUpdate(); } } @Override public void onSpongeDeathUpdate() { this.onDeathUpdate(); } @Redirect(method = "onDeathUpdate", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/EntityLivingBase;getExperiencePoints(Lnet/minecraft/entity/player/EntityPlayer;)I")) private int onGetExperiencePoints(EntityLivingBase entity, EntityPlayer attackingPlayer) { if (entity instanceof IMixinEntityPlayerMP) { if (((IMixinEntityPlayerMP) entity).keepInventory()) { return 0; } } return this.getExperiencePoints(attackingPlayer); } @Inject(method = "onItemPickup", at = @At("HEAD")) public void onEntityItemPickup(net.minecraft.entity.Entity entityItem, int unused, CallbackInfo ci) { if (!this.world.isRemote) { // EntityUtil.toMixin(entityItem).setDestructCause(Cause.of(NamedCause.of("PickedUp", this))); } } @Inject(method = "onItemUseFinish", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/EntityLivingBase;resetActiveHand()V")) private void updateHealthForUseFinish(CallbackInfo ci) { if (this instanceof IMixinEntityPlayerMP) { ((IMixinEntityPlayerMP) this).refreshScaledHealth(); } } // Data delegated methods @Override public HealthData getHealthData() { return new SpongeHealthData(this.getHealth(), this.getMaxHealth()); } @Override public MutableBoundedValue<Double> health() { return SpongeValueFactory.boundedBuilder(Keys.HEALTH) .minimum(0D) .maximum((double) this.getMaxHealth()) .defaultValue((double) this.getMaxHealth()) .actualValue((double) this.getHealth()) .build(); } @Override public MutableBoundedValue<Double> maxHealth() { return SpongeValueFactory.boundedBuilder(Keys.MAX_HEALTH) .minimum(1D) .maximum((double) Float.MAX_VALUE) .defaultValue(20D) .actualValue((double) this.getMaxHealth()) .build(); } @Override public DamageableData getDamageableData() { return new SpongeDamageableData((Living) this.revengeTarget, (double) this.lastDamage); } @Override public OptionalValue<EntitySnapshot> lastAttacker() { return new SpongeOptionalValue<>(Keys.LAST_ATTACKER, Optional.empty(), Optional.ofNullable(this.revengeTarget == null ? null : ((Living) this.revengeTarget).createSnapshot())); } @Override public OptionalValue<Double> lastDamage() { return new SpongeOptionalValue<>(Keys.LAST_DAMAGE, Optional.empty(), Optional.ofNullable(this.revengeTarget == null ? null : (double) (this.lastDamage))); } @Override public double getLastDamageTaken() { return this.lastDamage; } @Override public void supplyVanillaManipulators(List<DataManipulator<?, ?>> manipulators) { super.supplyVanillaManipulators(manipulators); manipulators.add(getHealthData()); } @Override public <T extends Projectile> Optional<T> launchProjectile(Class<T> projectileClass) { return ProjectileLauncher.launch(checkNotNull(projectileClass, "projectile class"), this, null); } @Override public <T extends Projectile> Optional<T> launchProjectile(Class<T> projectileClass, Vector3d velocity) { return ProjectileLauncher.launch(checkNotNull(projectileClass, "projectile class"), this, checkNotNull(velocity, "velocity")); } }
package org.ucombinator.jaam.visualizer.controllers; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.Label; import javafx.scene.control.MenuItem; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.util.Pair; import org.ucombinator.jaam.tools.taint3.Address; import org.ucombinator.jaam.visualizer.graph.GraphTransform; import org.ucombinator.jaam.visualizer.graph.GraphUtils; import org.ucombinator.jaam.visualizer.gui.MethodGuiNode; import org.ucombinator.jaam.visualizer.gui.SelectEvent; import org.ucombinator.jaam.visualizer.graph.Graph; import org.ucombinator.jaam.visualizer.layout.*; import org.ucombinator.jaam.visualizer.state.StateLoopVertex; import org.ucombinator.jaam.visualizer.state.StateMethodVertex; import org.ucombinator.jaam.visualizer.state.StateVertex; import org.ucombinator.jaam.visualizer.taint.*; import soot.SootMethod; import soot.Value; import soot.jimple.internal.JimpleLocal; import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.util.*; import java.util.stream.Collectors; public class TaintPanelController extends GraphPanelController<TaintVertex, TaintEdge> implements EventHandler<SelectEvent<TaintVertex>> { private HashMap<String, TaintAddress> fieldVertices; private boolean collapseAll = false, expandAll = false; private CodeViewController codeController; private HashSet<TaintVertex> immAncestors; private GraphTransform<TaintRootVertex, TaintVertex> immAndVisAncestors; private HashSet<TaintVertex> immDescendants; private GraphTransform<TaintRootVertex, TaintVertex> immAndVisDescendants; private Set<TaintVertex> immsplitVertices; // Nodes that split the visible graph private Set<TaintVertex> visibleSplitVertices; // Graph is the statement graph public TaintPanelController(Graph<TaintVertex, TaintEdge> graph, CodeViewController codeController, MainTabController tabController) throws IOException { super(TaintRootVertex::new, tabController); this.codeController = codeController; fillLegend(); for (TaintVertex v : graph.getVertices()) { if (v.getClassName() == null && v.getMethodName() == null) { System.out.println("Don't have class or method for " + v.toString()); } else if (v.getClassName() == null) { System.out.println("Don't have class for " + v.toString()); } } // Custom event handlers graphContentGroup.addEventFilter(SelectEvent.TAINT_VERTEX_SELECTED, this); this.visibleRoot = new TaintRootVertex(); this.immutableRoot = new TaintRootVertex(); //this.immutableRoot.setInnerGraph(this.cleanTaintGraph(graph)); for (TaintVertex v : graph.getVertices()) { v.setOuterGraph(graph); } this.immutableRoot.setInnerGraph(graph); fillFieldDictionary(); immAndVisAncestors = null; immAndVisDescendants = null; } private void fillLegend() { { ArrayList<Pair<Color, String>> colorLegend = TaintAddress.getColorLegend(); for(Pair<Color,String> legend : colorLegend) { MenuItem theLegend = new MenuItem(); HBox loopRow = new HBox(); loopRow.setSpacing(legendInnerRowSpacing); Rectangle loopColor = new Rectangle(legendSquareSize, legendSquareSize); loopColor.setFill(legend.getKey()); loopRow.getChildren().addAll(loopColor, new Label(legend.getValue())); theLegend.setGraphic(loopRow); this.legend.getItems().add(theLegend); } } { MenuItem theLegend = new MenuItem(); HBox libRow = new HBox(); libRow.setSpacing(legendInnerRowSpacing); Rectangle sccColor = new Rectangle(legendSquareSize, legendSquareSize); sccColor.setFill(TaintMethodVertex.libraryMethodColor); libRow.getChildren().addAll(sccColor, new Label("Library Method")); theLegend.setGraphic(libRow); this.legend.getItems().add(theLegend); } } public TaintRootVertex getVisibleRoot() { return (TaintRootVertex) this.visibleRoot; } public TaintRootVertex getImmutableRoot() { return (TaintRootVertex) this.immutableRoot; } public void drawGraph() { visibleRoot.setVisible(false); Instant startDraw = Instant.now(); immAndVisAncestors = prepareGraph(immAncestors); immAndVisDescendants = prepareGraph(immDescendants); immsplitVertices.removeIf(v -> ((TaintAddress)v).type == TaintAddress.Type.Inner); Instant afterPrepare = Instant.now(); // Merge ascendants and descendants into special split graph createSplitGraph(); Instant afterSplitGraph = Instant.now(); this.visibleRoot = immAndVisAncestors.newRoot; /* if (expandAll) { for (TaintVertex v : visibleRoot.getInnerGraph().getVertices()) { if (v instanceof TaintMethodVertex) { v.setExpanded(true); } } expandAll = false; } if (collapseAll) { for (TaintVertex v : visibleRoot.getInnerGraph().getVertices()) { if (v instanceof TaintMethodVertex) { v.setExpanded(false); } } collapseAll = false; } */ LayoutAlgorithm.layoutSplitGraph(getVisibleRoot(), visibleSplitVertices); Instant afterLayout = Instant.now(); //LayoutAlgorithm.layout(visibleRoot); drawNodes(null, visibleRoot); /* for (TaintVertex v : visibleSplitVertices) { if (v instanceof TaintMethodVertex) { ((MethodGuiNode)v.getGraphics()).setBackgroundFill(Color.GREEN); } //v.getGraphics().setFill(Color.GREEN); } */ Instant afterNodeDraw = Instant.now(); //visibleRoot.getGraphics().requestLayout(); drawEdges(visibleRoot); Instant endDraw = Instant.now(); { long totalDraw = Duration.between(startDraw, endDraw).toMillis(); long prepare = Duration.between(startDraw,afterPrepare).toMillis(); long createSplit = Duration.between(afterPrepare,afterSplitGraph).toMillis(); long layout = Duration.between(afterSplitGraph, afterLayout).toMillis(); long nodeDraw = Duration.between(afterLayout, afterNodeDraw).toMillis(); long edgeDraw = Duration.between(afterNodeDraw, endDraw).toMillis(); System.out.println("TIME\tDraw Taint Graph took: " + totalDraw); System.out.println("TIME\t\tPrepare:\t" + prepare); System.out.println("TIME\t\tCreateSplit:\t" + createSplit); System.out.println("TIME\t\tLayout:\t" + layout); System.out.println("TIME\t\tNodeDraw:\t" + nodeDraw); System.out.println("TIME\t\tEdgeDraw:\t" + edgeDraw); } visibleRoot.setVisible(true); } // Recieves a set of immutable vertices to draw private GraphTransform<TaintRootVertex, TaintVertex> prepareGraph(Set<TaintVertex> verticesToDraw) { Instant startPrepare = Instant.now(); System.out.println("Taint Vertices to draw: " + verticesToDraw.size()); GraphTransform<TaintRootVertex, TaintVertex> immToFlatVisible = this.getImmutableRoot().constructVisibleGraph(verticesToDraw); Instant afterFlatVisible = Instant.now(); GraphTransform<TaintRootVertex, TaintVertex> visibleToNonInner = this.compressInnerNodes(immToFlatVisible.newRoot); Instant afterNonInner = Instant.now(); GraphTransform<TaintRootVertex, TaintVertex> immToNonInner = GraphTransform.transfer(immToFlatVisible, visibleToNonInner); Instant afterNonInnerTransf = Instant.now(); // Groups by method GraphTransform<TaintRootVertex, TaintVertex> nonInnerToLayerVisible = LayerFactory.getLayeredTaintGraph(visibleToNonInner.newRoot); Instant endPrepare = Instant.now(); { long totalPrepare = Duration.between(startPrepare,endPrepare).toMillis(); long flatVisible = Duration.between(startPrepare,afterFlatVisible).toMillis(); long nonInner = Duration.between(afterFlatVisible,afterNonInner).toMillis(); long nonInnerTranf = Duration.between(afterNonInner,afterNonInnerTransf).toMillis(); long layerVisible = Duration.between(afterNonInnerTransf,endPrepare).toMillis(); System.out.println("TIME\t\t\tPrepare took: " + totalPrepare); System.out.println("TIME\t\t\t\tFlatVisible:\t" + flatVisible); System.out.println("TIME\t\t\t\tNonInner:\t" + nonInner); System.out.println("TIME\t\t\t\tTransfer:\t" + nonInnerTranf); System.out.println("TIME\t\t\t\tLayerVisible:\t" + layerVisible); } // Groups by Class //GraphTransform<TaintRootVertex, TaintVertex> flatToLayerVisible = LayerFactory.getTaintClassGrouping(immToFlatVisible.newRoot); return GraphTransform.transfer(immToNonInner, nonInnerToLayerVisible); } // "Merges" ancestors and descendants into a single graph. To maintain connectivity the special // node of the ascendants replaces the descendant version. private void createSplitGraph() { HashSet<TaintVertex> ascSplit = new HashSet<>(), desSplit = new HashSet<>(); HashMap<TaintVertex, TaintVertex> desToSplit = new HashMap<>(); System.out.println("Imm Split vertices"); for (TaintVertex imm : immsplitVertices) { System.out.println("\t" + imm); } for (TaintVertex imm : immsplitVertices) { TaintVertex splitA = getSplit(immAndVisAncestors.getNew(imm), ascSplit, immAndVisAncestors.newRoot); ascSplit.add(splitA); TaintVertex splitD = getSplit(immAndVisDescendants.getNew(imm), desSplit, immAndVisDescendants.newRoot); desSplit.add(splitD); desToSplit.putIfAbsent(splitD, splitA); } // Seed with the ascendant graph Graph<TaintVertex, TaintEdge> splitGraph = immAndVisAncestors.newRoot.getInnerGraph(); visibleSplitVertices = ascSplit; // Add descendantVertices immAndVisDescendants.newRoot.getInnerGraph().getVertices().stream() .filter(d -> !desSplit.contains(d)) .forEach(d -> { splitGraph.addVertex(d); d.setOuterGraph(splitGraph); }); System.out.println("Now adding edges: " + "\n\tA : " + immAndVisAncestors.newRoot.getInnerGraph().getEdges().size() + "\n\tD : " + immAndVisDescendants.newRoot.getInnerGraph().getEdges().size() ); // Now add the edges, only the outgoing to do the edges once for (TaintEdge e : immAndVisDescendants.newRoot.getInnerGraph().getEdges()) { TaintVertex src = desSplit.contains(e.getSrc()) ? desToSplit.get(e.getSrc()) : e.getSrc(); TaintVertex dest = desSplit.contains(e.getDest()) ? desToSplit.get(e.getDest()) : e.getDest(); splitGraph.addEdge(new TaintEdge(src, dest)); } System.out.println("\tF: " + splitGraph.getEdges().size()); immAndVisDescendants.newRoot = immAndVisAncestors.newRoot; } private TaintVertex getSplit(TaintVertex vis, HashSet<TaintVertex> alreadyFound, TaintRootVertex root ) { System.out.print("Checking " + vis); if (vis.getOuterGraph() == root.getInnerGraph()) { System.out.println(" Was not part of a method"); return vis; } // Find which method node I am part of // This is a horrible piece of code but there isn't anyway of going up the hierarchy // Adding that (which should have always been there) would improve this code a lot... // Have we seen your method before? Optional<TaintVertex> alreadyAdded = alreadyFound.stream() .filter(v -> v.getInnerGraph() == vis.getOuterGraph()) .findAny(); if (alreadyAdded.isPresent()) { System.out.println(" my method was already added"); return alreadyAdded.get(); } else { // So slow... Optional<TaintVertex> any = root.getInnerGraph().getVertices().stream() .filter(v -> v.getInnerGraph() == vis.getOuterGraph()) .findAny(); if (!any.isPresent()) { throw new IllegalArgumentException("Found a wrong method vertex while splitting"); } System.out.println("Found method " + any.get()); return any.get(); } } public void redrawGraph() { // System.out.println("Redrawing loop graph..."); //this.graphContentGroup.getChildren().remove(this.visibleRoot.getGraphics()); //this.drawGraph(); } public void addSelectHandler(BorderPane centerPane) { centerPane.addEventHandler(SelectEvent.STATE_VERTEX_SELECTED, onVertexSelect); } @Override public void redrawGraphAction(ActionEvent event) throws IOException { event.consume(); this.redrawGraph(); } @Override public void hideSelectedAction(ActionEvent event) throws IOException { event.consume(); this.tabController.hideSelectedTaintNodes(); } @Override public void hideUnrelatedAction(ActionEvent event) throws IOException { event.consume(); this.tabController.hideUnrelatedToHighlightedTaint(); } @Override public void expandAll(ActionEvent event) throws IOException { event.consume(); expandAll = true; this.redrawGraph(); } @Override public void collapseAll(ActionEvent event) throws IOException { event.consume(); collapseAll = true; this.redrawGraph(); } /* // Changes to the visible set @Override public void onChanged(Change<? extends TaintVertex> change) { // System.out.println("TaintPanel responding to change in visible set..."); if (change.wasAdded()) { TaintVertex immV = change.getElementAdded(); immV.setHidden(); if (immAndVis != null && immAndVis.getNew(immV) != null) { immAndVis.getNew(immV).setHidden(); } } else { TaintVertex immV = change.getElementRemoved(); immV.setUnhidden(); if (immAndVis != null && immAndVis.getNew(immV) != null) { immAndVis.getNew(immV).setUnhidden(); } } } */ @Override public void handle(SelectEvent<TaintVertex> event) { TaintVertex vertex = event.getVertex(); // A visible vertex if (vertex.getType() == AbstractLayoutVertex.VertexType.ROOT) { System.out.println("Ignoring click on vertex root."); event.consume(); return; } System.out.println("Received event from vertex " + vertex.toString()); this.tabController.setTaintRightText(vertex); } // Draw the graph of taint addresses for the selected state vertex, and addresses connected to them. private EventHandler<SelectEvent<StateVertex>> onVertexSelect = new EventHandler<SelectEvent<StateVertex>>() { @Override public void handle(SelectEvent<StateVertex> selectEvent) { Instant handleStart = Instant.now(); StateVertex v = selectEvent.getVertex(); Set<TaintVertex> startVertices = new HashSet<>(); VizPanelController vizController = TaintPanelController.this.tabController.vizPanelController; if (v instanceof StateMethodVertex) { StateVertex immV = vizController.getImmutable(v); // If we click on a method vertex, we should get all taint addresses for that method. startVertices = findAddressesByMethods(immV.getMethodNames()); } else if (v instanceof StateLoopVertex) { // Otherwise, if we click on a loop, we just want the addresses controlling the loop. StateLoopVertex immV = (StateLoopVertex)vizController.getImmutable(v); SootMethod method = immV.getCompilationUnit().method(); if (immV.isUnidentifiedLoop()) { // Default to drawing methods startVertices = findAddressesByMethods(immV.getMethodNames()); } else { ArrayList<Value> loopValues = immV.getLoopValues(); for (Value value : loopValues) { addTaintVertex(startVertices, value, method); } } } Instant afterGetting = Instant.now(); /* System.out.println("Start vertices: " + startVertices.size()); for (TaintVertex V : startVertices) { System.out.println("\t" + V); } */ drawConnectedVertices(startVertices); Instant handleEnd = Instant.now(); long totalHandle = Duration.between(handleStart, handleEnd).toMillis(); long gettingTook = Duration.between(handleStart, afterGetting).toMillis(); long drawingTook = Duration.between(afterGetting, handleEnd).toMillis(); System.out.println("TIME Handle took " + totalHandle); System.out.println("TIME \tGetting took " + gettingTook + "\nTIME \tDrawing took " + drawingTook); } }; private void addTaintVertex(Set<TaintVertex> taintVertices, Value value, SootMethod method) { TaintVertex v = getTaintVertex(value, method); if (v != null) { taintVertices.add(v); } } private TaintVertex getTaintVertex(Value value, SootMethod method) { for (TaintVertex v : this.getImmutableRoot().getInnerGraph().getVertices()) { if (!v.getInnerGraph().isEmpty()) { System.out.println("Found a non empty inner graph " + v); } if(v instanceof TaintAddress) { TaintAddress vAddr = (TaintAddress) v; if (testAddress(vAddr, value, method)) { return v; } } else if (v instanceof TaintStmtVertex) { // Might be the loop for (TaintAddress a : ((TaintStmtVertex) v).getAddresses()) { if (testAddress(a, value, method)) { return v; } } } } return null; } private boolean testAddress(TaintAddress vAddr, Value value, SootMethod method) { Address addr = vAddr.getAddress(); if (addr instanceof Address.Value) { Value taintValue = ((Address.Value) addr).sootValue(); //System.out.println("Comparing values: " + taintValue.equivTo(value) + ", " + taintValue + ", " + value); //System.out.println("Method: " + addr.sootMethod().toString()); //System.out.println("Classes: " + taintValue.getClass() + ", " + value.getClass()); if (compareValues(taintValue, value, vAddr.getSootMethod(), method)) { //System.out.println("Found match!"); return true; } } return false; } private TaintVertex getTaintVertexRec(TaintVertex v, Value value, SootMethod method) { if(v instanceof TaintAddress) { TaintAddress vAddr = (TaintAddress) v; Address addr = vAddr.getAddress(); if (addr instanceof Address.Value) { Value taintValue = ((Address.Value) addr).sootValue(); System.out.println("Comparing values: " + taintValue.equivTo(value) + ", " + taintValue + ", " + value); System.out.println("Method: " + addr.sootMethod().toString()); System.out.println("Classes: " + taintValue.getClass() + ", " + value.getClass()); if (compareValues(taintValue, value, vAddr.getSootMethod(), method)) { System.out.println("Found match!"); return v; } } } for (TaintVertex w : v.getInnerGraph().getVertices()) { TaintVertex result = getTaintVertexRec(w, value, method); if (result != null) { return result; } } return null; } private boolean compareValues(Value taintValue, Value value, SootMethod taintMethod, SootMethod method) { if (taintValue.equals(value)) { //System.out.println("Equal taint values!"); return true; } else if (taintValue.equivTo(value)) { //System.out.println("Equivalent taint values!"); return true; } else if (value instanceof JimpleLocal) { //System.out.println("One JimpleLocal!"); if (taintValue instanceof JimpleLocal) { //System.out.println("Both JimpleLocal!"); if (taintMethod.getSubSignature().equals(method.getSubSignature())) { //System.out.println("Equal methods!"); //System.out.println("SubSignature: " + taintMethod.getSubSignature()); if (((JimpleLocal) taintValue).getName().equals(((JimpleLocal) value).getName())) { //System.out.println("Equal names!"); return true; } } } } return false; } private void drawConnectedVertices(Set<TaintVertex> addresses) { Instant startDraw = Instant.now(); immsplitVertices = addresses; Pair<HashSet<TaintVertex>, HashSet<TaintVertex>> verticesToDraw = findConnectedAddresses(addresses); immAncestors = verticesToDraw.getKey(); immDescendants = verticesToDraw.getValue(); Instant afterFind = Instant.now(); this.drawGraph(); Instant afterDraw = Instant.now(); System.out.println("TIME\t\t Time to compute connected vertices: " + Duration.between(startDraw,afterFind).toMillis()); System.out.println("TIME\t\t Time to draw graph: " + Duration.between(afterFind,afterDraw).toMillis()); } private HashSet<TaintVertex> findAddressesByMethods(Set<String> methodNames) { HashSet<TaintVertex> results = new HashSet<>(); this.immutableRoot.searchByMethodNames(methodNames, results); // TODO: This step is a little inefficient. return results; } private Pair<HashSet<TaintVertex>, HashSet<TaintVertex> > findConnectedAddresses(Set<TaintVertex> startVertices) { HashSet<TaintVertex> ancestors = new HashSet<>(); HashSet<TaintVertex> descendants = new HashSet<>(); for (TaintVertex v : startVertices) { v.getAncestors(ancestors); v.getDescendants(descendants); } return new Pair<>(ancestors, descendants); } public void showFieldTaintGraph(String fullClassName, String fieldName) { String fieldId = fullClassName + ":" + fieldName; TaintAddress a = fieldVertices.get(fieldId); if (a != null) { HashSet<TaintVertex> vertices = new HashSet<>(); vertices.add(a); drawConnectedVertices(vertices); } else { System.out.println("\tWarning: Did not find taint vertex " + fieldId); } } private void fillFieldDictionary() { fieldVertices = new HashMap<>(); ArrayList<TaintAddress> allFields = new ArrayList<>(); this.immutableRoot.getFields(allFields); allFields.forEach(v -> { fieldVertices.put(v.getFieldId(), v); }); } private GraphTransform<TaintRootVertex, TaintVertex> compressInnerNodes(TaintRootVertex root) { return GraphUtils.constructVisibleGraph(root, (TaintVertex superV) -> { if (! (superV instanceof TaintAddress)){ throw new IllegalArgumentException("Non address immutable vertex"); } TaintAddress v = (TaintAddress)superV; return v.type != TaintAddress.Type.Inner; }, TaintEdge::new); } private Graph<TaintVertex, TaintEdge> cleanTaintGraph(Graph<TaintVertex, TaintEdge> graph) { int initialSize = graph.getVertices().size(); graph = removeNonCodeRootAddresses(graph); graph = removeNonCodePaths(graph); graph = removeDegree2Addresses(graph); int numRemoved = initialSize-graph.getVertices().size(); System.out.println("Removed " + numRemoved + "(" + (((double)numRemoved)/initialSize)*100 + ") final taint size " + graph.getVertices().size()); return graph; } private Graph<TaintVertex, TaintEdge> removeNonCodeRootAddresses(Graph<TaintVertex, TaintEdge> graph) { HashSet<TaintVertex> toRemove; do { toRemove = graph.getSources().stream() .filter(v -> v instanceof TaintAddress && isLibrary(v)) .collect(Collectors.toCollection(HashSet::new)); System.out.println("JUAN: Removing " + toRemove.size() + " Non Code Roots of " + graph.getVertices().size() + "(" + ((double)graph.getVertices().size())/toRemove.size() + ")"); for (TaintVertex v : toRemove) { graph.cutVertex(v); } }while (!toRemove.isEmpty()); return graph; } private boolean isLibrary(TaintVertex v) { if (v instanceof TaintAddress && ((TaintAddress)v).isArrayRef()) { return false; } return !codeController.haveCode(v.getClassName()); } private Graph<TaintVertex, TaintEdge> removeDegree2Addresses(Graph<TaintVertex, TaintEdge> graph) { int initialSize = graph.getVertices().size(); TaintRootVertex temp = new TaintRootVertex(); temp.setInnerGraph(graph); GraphTransform<TaintRootVertex, TaintVertex> transform = GraphUtils.constructVisibleGraph(temp, v -> { return graph.getOutEdges(v).size() != 1 || graph.getInEdges(v).size() != 1; }, TaintEdge::new); int numRemoved = initialSize - transform.newRoot.getInnerGraph().getVertices().size(); System.out.println("JUAN: Removing " + numRemoved + " Degree 2 addresses " + transform.newRoot.getInnerGraph().getVertices().size() + "(" + ((double)graph.getVertices().size())/numRemoved + ")"); return transform.newRoot.getInnerGraph(); } private Graph<TaintVertex, TaintEdge> removeNonCodePaths(Graph<TaintVertex, TaintEdge> graph) { List<TaintVertex> nonCodeLeafs; do { nonCodeLeafs = graph.getVertices().stream() .filter(v -> graph.getOutNeighbors(v).isEmpty() && isLibrary(v)) .collect(Collectors.toList()); System.out.println("JUAN: Removing " + nonCodeLeafs.size() + " Non Code Leafs of " + graph.getVertices().size() + "(" + ((double)graph.getVertices().size())/nonCodeLeafs.size() + ")"); for (TaintVertex v : nonCodeLeafs) { graph.cutVertex(v); } } while (!nonCodeLeafs.isEmpty()); return graph; } public HashSet<TaintVertex> getImmutable(HashSet<TaintVertex> visible) { return visible.stream() .flatMap(v -> v.expand().stream()) .map(v -> immAndVisAncestors.containsNew(v) ? immAndVisAncestors.getOld(v) : immAndVisDescendants.getOld(v)) .collect(Collectors.toCollection(HashSet::new)); } public TaintVertex getImmutable(TaintVertex visible) { if (immAndVisAncestors.containsNew(visible)) { return immAndVisAncestors.getOld(visible); } if (immAndVisDescendants.containsNew(visible)) { return immAndVisDescendants.getOld(visible); } return null; } // Selection are **visible** nodes // Returns the immutable nodes related to the selection of visible nodes public HashSet<TaintVertex> getUnrelatedVisible(HashSet<TaintVertex> selection) { HashSet<TaintVertex> keep = new HashSet<>(); Graph<TaintVertex, TaintEdge> topLevel = getVisibleRoot().getInnerGraph(); selection.forEach(v -> keep.addAll(v.getAncestors())); selection.forEach(v -> keep.addAll(v.getDescendants())); HashSet<TaintVertex> toHide = new HashSet<>(); topLevel.getVertices().forEach(v -> { if (!keep.contains(v) && !keepAnyInterior(v, keep, toHide)) { toHide.add(v); } }); return toHide; } private boolean keepAnyInterior(TaintVertex root, HashSet<TaintVertex> keep, HashSet<TaintVertex> toHide) { boolean foundAVertexToKeep = false; for (TaintVertex v : root.getInnerGraph().getVertices()) { if (keep.contains(v) || keepAnyInterior(v, keep, toHide)) { foundAVertexToKeep = true; } else { toHide.add(v); } } return foundAVertexToKeep; } public void hideVisibleVertices(HashSet<TaintVertex> taintHighlighted) { immAncestors.removeAll(taintHighlighted); immDescendants.removeAll(taintHighlighted); redrawGraph(); } }
// MinimumWriter.java import loci.common.services.ServiceFactory; import loci.formats.*; import loci.formats.meta.IMetadata; import loci.formats.services.OMEXMLService; import ome.xml.model.enums.DimensionOrder; import ome.xml.model.enums.PixelType; import ome.xml.model.primitives.PositiveInteger; public class MinimumWriter { public static void main(String[] args) throws Exception { if (args.length < 1) { System.out.println("Please specify an output file name."); System.exit(1); } String id = args[0]; // create blank 512x512 image System.out.println("Creating random image..."); int w = 512, h = 512, c = 1; int pixelType = FormatTools.UINT16; byte[] img = new byte[w * h * c * FormatTools.getBytesPerPixel(pixelType)]; // fill with random data for (int i=0; i<img.length; i++) img[i] = (byte) (256 * Math.random()); // create metadata object with minimum required metadata fields System.out.println("Populating metadata..."); ServiceFactory factory = new ServiceFactory(); OMEXMLService service = factory.getInstance(OMEXMLService.class); IMetadata meta = service.createOMEXMLMetadata(); meta.createRoot(); meta.setImageID("Image:0", 0); meta.setPixelsID("Pixels:0", 0); meta.setPixelsBinDataBigEndian(Boolean.TRUE, 0, 0); meta.setPixelsDimensionOrder(DimensionOrder.XYZCT, 0); meta.setPixelsType( PixelType.fromString(FormatTools.getPixelTypeString(pixelType)), 0); meta.setPixelsSizeX(new PositiveInteger(w), 0); meta.setPixelsSizeY(new PositiveInteger(h), 0); meta.setPixelsSizeZ(new PositiveInteger(1), 0); meta.setPixelsSizeC(new PositiveInteger(c), 0); meta.setPixelsSizeT(new PositiveInteger(1), 0); meta.setChannelID("Channel:0:0", 0, 0); meta.setChannelSamplesPerPixel(new PositiveInteger(c), 0, 0); // write image plane to disk System.out.println("Writing image to '" + id + "'..."); IFormatWriter writer = new ImageWriter(); writer.setMetadataRetrieve(meta); writer.setId(id); writer.saveBytes(0, img); writer.close(); System.out.println("Done."); } }
package net.java.sip.communicator.impl.protocol.icq; import java.util.*; import net.java.sip.communicator.impl.protocol.gibberish.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.util.*; import net.kano.joscar.flap.*; import net.kano.joscar.flapcmd.*; import net.kano.joscar.snaccmd.auth.*; import net.kano.joustsim.*; import net.kano.joustsim.oscar.*; import net.kano.joustsim.oscar.oscar.loginstatus.*; import net.kano.joustsim.oscar.oscar.service.*; import net.kano.joustsim.oscar.oscar.service.icbm.*; import net.kano.joustsim.oscar.proxy.*; /** * An implementation of the protocol provider service over the AIM/ICQ protocol * * @author Emil Ivov * @author Damian Minkov */ public class ProtocolProviderServiceIcqImpl implements ProtocolProviderService { private static final Logger logger = Logger.getLogger(ProtocolProviderServiceIcqImpl.class); /** * The hashtable with the operation sets that we support locally. */ private Hashtable supportedOperationSets = new Hashtable(); private DefaultAppSession session = null; private AimSession aimSession = null; private AimConnection aimConnection = null; private IcbmService icbmService = null; /** * Listener that catches all connection events originating from joscar * during connection to icq. */ private AimConnStateListener aimConnStateListener = null; /** * Listener that catches all incoming and outgoing chat events generated * by joscar. */ private AimIcbmListener aimIcbmListener = new AimIcbmListener(); /** * indicates whether or not the provider is initialized and ready for use. */ private boolean isInitialized = false; /** * We use this to lock access to initialization. */ private Object initializationLock = new Object(); /** * A list of all listeners registered for * <tt>RegistrationStateChangeEvent</tt>s. */ private List registrationListeners = new ArrayList(); /** * The identifier of the account that this provider represents. */ private AccountID accountID = null; /** * Retrieves short or full user info, such as Name, Address, Nickname etc. */ private InfoRetreiver infoRetreiver = null; /** * The icon corresponding to the icq protocol. */ private ProtocolIconIcqImpl icqIcon = new ProtocolIconIcqImpl(); /** * The icon corresponding to the aim protocol. */ private ProtocolIconAimImpl aimIcon = new ProtocolIconAimImpl(); /** * Property whether we are using AIM or ICQ service */ boolean USING_ICQ = true; /** * Returns the state of the registration of this protocol provider * @return the <tt>RegistrationState</tt> that this provider is * currently in or null in case it is in a unknown state. */ public RegistrationState getRegistrationState() { if(getAimConnection() == null) return RegistrationState.UNREGISTERED; State connState = getAimConnection().getState(); return joustSimStateToRegistrationState(connState); } /** * Converts the specified joust sim connection state to a corresponding * RegistrationState. * @param jsState the joust sim connection state. * @return a RegistrationState corresponding best to the specified * joustSimState. */ private RegistrationState joustSimStateToRegistrationState(State jsState) { return joustSimStateToRegistrationState(jsState, null); } /** * Converts the specified joust sim connection state to a corresponding * RegistrationState. * @param joustSimConnState the joust sim connection state. * @param joustSimConnStateInfo additional stateinfo if available (may be * null) * @return a RegistrationState corresponding best to the specified * joustSimState. */ private RegistrationState joustSimStateToRegistrationState( State joustSimConnState, StateInfo joustSimConnStateInfo) { if(joustSimConnState == State.ONLINE) return RegistrationState.REGISTERED; else if (joustSimConnState == State.CONNECTING) return RegistrationState.REGISTERING; else if( joustSimConnState == State.AUTHORIZING) return RegistrationState.AUTHENTICATING; else if (joustSimConnState == State.CONNECTINGAUTH) return RegistrationState.AUTHENTICATING; else if (joustSimConnState == State.SIGNINGON) return RegistrationState.REGISTERING; else if (joustSimConnState == State.DISCONNECTED || joustSimConnState == State.NOTCONNECTED) { if(joustSimConnStateInfo != null && joustSimConnStateInfo instanceof DisconnectedStateInfo && !((DisconnectedStateInfo)joustSimConnStateInfo).isOnPurpose()) { return RegistrationState.CONNECTION_FAILED; } return RegistrationState.UNREGISTERED; } else if (joustSimConnState == State.FAILED) { if(joustSimConnStateInfo != null && joustSimConnStateInfo instanceof LoginFailureStateInfo) { LoginFailureInfo lfInfo = ((LoginFailureStateInfo) joustSimConnStateInfo).getLoginFailureInfo(); if (lfInfo instanceof AuthFailureInfo) return RegistrationState.AUTHENTICATION_FAILED; } return RegistrationState.CONNECTION_FAILED; } else{ logger.warn("Unknown state " + joustSimConnState + ". Defaulting to " + RegistrationState.UNREGISTERED); return RegistrationState.UNREGISTERED; } } /** * Starts the registration process. Connection details such as * registration server, user name/number are provided through the * configuration service through implementation specific properties. * * @param authority the security authority that will be used for resolving * any security challenges that may be returned during the * registration or at any moment while wer're registered. * * @throws OperationFailedException with the corresponding code it the * registration fails for some reason (e.g. a networking error or an * implementation problem). */ public void register(SecurityAuthority authority) throws OperationFailedException { if(authority == null) throw new IllegalArgumentException( "The register method needs a valid non-null authority impl " + " in order to be able and retrieve passwords."); synchronized(initializationLock) { ProtocolProviderFactoryIcqImpl protocolProviderFactory = null; if(USING_ICQ) protocolProviderFactory = IcqActivator.getIcqProtocolProviderFactory(); else protocolProviderFactory = IcqActivator.getAimProtocolProviderFactory(); //verify whether a password has already been stored for this account String password = protocolProviderFactory.loadPassword(getAccountID()); //decode if( password == null ) { //create a default credentials object UserCredentials credentials = new UserCredentials(); credentials.setUserName(this.getAccountID().getUserID()); //request a password from the user credentials = authority.obtainCredentials(getProtocolName() , credentials); // in case user has canceled the login window if(credentials == null) { fireRegistrationStateChanged( getRegistrationState(), RegistrationState.UNREGISTERED, RegistrationStateChangeEvent.REASON_USER_REQUEST, ""); return; } //extract the password the user passed us. char[] pass = credentials.getPassword(); // the user didn't provide us a password (canceled the operation) if(pass == null) { fireRegistrationStateChanged( RegistrationState.UNREGISTERED, RegistrationState.UNREGISTERED, RegistrationStateChangeEvent.REASON_USER_REQUEST, ""); return; } password = new String(pass); if (credentials.isPasswordPersistent()) { protocolProviderFactory .storePassword(getAccountID(), password); } } // it seems icq servers doesn't accept password with // length more then 8. But allow such registrations // we must trim such passwords to 8 characters if(USING_ICQ && password.length() > 8) password = password.substring(0, 8); //init the necessary objects session = new DefaultAppSession(); aimSession = session.openAimSession( new Screenname(getAccountID().getUserID())); String proxyAddress = (String)getAccountID().getAccountProperties().get( ProtocolProviderFactory.PROXY_ADDRESS); if(proxyAddress != null && proxyAddress.length() > 0) { String proxyPortStr = (String)getAccountID().getAccountProperties().get( ProtocolProviderFactory.PROXY_PORT); int proxyPort; try { proxyPort = Integer.parseInt(proxyPortStr); } catch (NumberFormatException ex) { throw new OperationFailedException("Wrong port", OperationFailedException.INVALID_ACCOUNT_PROPERTIES, ex); } String proxyType = (String)getAccountID().getAccountProperties().get( ProtocolProviderFactory.PROXY_TYPE); if(proxyType == null) throw new OperationFailedException("Missing proxy type", OperationFailedException.INVALID_ACCOUNT_PROPERTIES); String proxyUsername = (String)getAccountID().getAccountProperties().get( ProtocolProviderFactory.PROXY_USERNAME); String proxyPassword = (String)getAccountID().getAccountProperties().get( ProtocolProviderFactory.PROXY_PASSWORD); if(proxyType.equals("http")) { // If we are using http proxy, sometimes // default port 5190 is forbidden, so force // http/https port AimConnectionProperties connProps = new AimConnectionProperties( new Screenname(getAccountID().getUserID()) , password); connProps.setLoginHost("login.icq.com"); connProps.setLoginPort(443); aimConnection = aimSession.openConnection(connProps); aimConnection.setProxy( AimProxyInfo.forHttp(proxyAddress, proxyPort, proxyUsername, proxyPassword)); } else { aimConnection = aimSession.openConnection( new AimConnectionProperties( new Screenname(getAccountID().getUserID()) , password)); if(proxyType.equals("socks4")) aimConnection.setProxy( AimProxyInfo.forSocks4(proxyAddress, proxyPort, proxyUsername)); else if(proxyType.equals("socks5")) aimConnection.setProxy( AimProxyInfo.forSocks5(proxyAddress, proxyPort, proxyUsername, proxyPassword)); } } else { aimConnection = aimSession.openConnection( new AimConnectionProperties( new Screenname(getAccountID().getUserID()) , password)); } aimConnStateListener = new AimConnStateListener(); aimConnection.addStateListener(aimConnStateListener); aimConnection.connect(); } } /** * Ends the registration of this protocol provider with the service. */ public void unregister() { if(aimConnection != null) aimConnection.disconnect(true); } /** * Indicates whether or not this provider is signed on the icq service * @return true if the provider is currently signed on (and hence online) * and false otherwise. */ public boolean isRegistered() { return getRegistrationState().equals(RegistrationState.REGISTERED); } /** * Returns the short name of the protocol that the implementation of this * provider is based upon (like SIP, Jabber, ICQ/AIM, or others for * example). * * @return a String containing the short name of the protocol this * service is taking care of. */ public String getProtocolName() { if(USING_ICQ) return ProtocolNames.ICQ; else return ProtocolNames.AIM; } /** * Returns an array containing all operation sets supported by the * current implementation. * * @return an array of OperationSet-s supported by this protocol * provider implementation. */ public Map getSupportedOperationSets() { return supportedOperationSets; } /** * Returns the operation set corresponding to the specified class or null * if this operation set is not supported by the provider implementation. * * @param opsetClass the <tt>Class</tt> of the operation set that we're * looking for. * @return returns an OperationSet of the specified <tt>Class</tt> if the * undelying implementation supports it or null otherwise. */ public OperationSet getOperationSet(Class opsetClass) { return (OperationSet)getSupportedOperationSets() .get(opsetClass.getName()); } /** * Initialized the service implementation, and puts it in a sate where it * could interoperate with other services. It is strongly recomended that * properties in this Map be mapped to property names as specified by * <tt>AccountProperties</tt>. * * @param screenname the account id/uin/screenname of the account that * we're about to create * @param accountID the identifier of the account that this protocol * provider represents. * * @see net.java.sip.communicator.service.protocol.AccountID */ protected void initialize(String screenname, AccountID accountID) { synchronized(initializationLock) { this.accountID = accountID; if(IcqAccountID.isAIM(accountID.getAccountProperties())) USING_ICQ = false; //initialize the presence operationset OperationSetPersistentPresence persistentPresence = new OperationSetPersistentPresenceIcqImpl(this, screenname); supportedOperationSets.put( OperationSetPersistentPresence.class.getName(), persistentPresence); //register it once again for those that simply need presence supportedOperationSets.put( OperationSetPresence.class.getName(), persistentPresence); //initialize the IM operation set OperationSetBasicInstantMessaging basicInstantMessaging = new OperationSetBasicInstantMessagingIcqImpl(this); supportedOperationSets.put( OperationSetBasicInstantMessaging.class.getName(), basicInstantMessaging); //initialize the typing notifications operation set OperationSetTypingNotifications typingNotifications = new OperationSetTypingNotificationsIcqImpl(this); supportedOperationSets.put( OperationSetTypingNotifications.class.getName(), typingNotifications); if(USING_ICQ) { this.infoRetreiver = new InfoRetreiver(this, screenname); OperationSetServerStoredContactInfo serverStoredContactInfo = new OperationSetServerStoredContactInfoIcqImpl(infoRetreiver); supportedOperationSets.put( OperationSetServerStoredContactInfo.class.getName(), serverStoredContactInfo); OperationSetServerStoredAccountInfo serverStoredAccountInfo = new OperationSetServerStoredAccountInfoIcqImpl (infoRetreiver, screenname, this); supportedOperationSets.put( OperationSetServerStoredAccountInfo.class.getName(), serverStoredAccountInfo); OperationSetWebAccountRegistration webAccountRegistration = new OperationSetWebAccountRegistrationIcqImpl(); supportedOperationSets.put( OperationSetWebAccountRegistration.class.getName(), webAccountRegistration); OperationSetWebContactInfo webContactInfo = new OperationSetWebContactInfoIcqImpl(); supportedOperationSets.put( OperationSetWebContactInfo.class.getName(), webContactInfo); OperationSetExtendedAuthorizationsIcqImpl extendedAuth = new OperationSetExtendedAuthorizationsIcqImpl(this); supportedOperationSets.put( OperationSetExtendedAuthorizations.class.getName(), extendedAuth); } isInitialized = true; } } /** * Makes the service implementation close all open sockets and release * any resources that it might have taken and prepare for * shutdown/garbage collection. */ public void shutdown() { /** @todo is there anything else to add here? */ synchronized(initializationLock){ icbmService = null; session = null; aimSession = null; aimConnection = null; aimConnStateListener = null; aimIcbmListener = null; isInitialized = false; } } /** * Returns true if the provider service implementation is initialized and * ready for use by other services, and false otherwise. * * @return true if the provider is initialized and ready for use and false * otherwise */ public boolean isInitialized() { return isInitialized; } /** * Removes the specified registration state change listener so that it does * not receive any further notifications upon changes of the * RegistrationState of this provider. * * @param listener the listener to register for * <tt>RegistrationStateChangeEvent</tt>s. */ public void removeRegistrationStateChangeListener( RegistrationStateChangeListener listener) { synchronized(registrationListeners) { registrationListeners.remove(listener); } } /** * Registers the specified listener with this provider so that it would * receive notifications on changes of its state or other properties such * as its local address and display name. * * @param listener the listener to register. */ public void addRegistrationStateChangeListener( RegistrationStateChangeListener listener) { synchronized(registrationListeners) { if (!registrationListeners.contains(listener)) registrationListeners.add(listener); } } /** * Returns the AccountID that uniquely identifies the account represented * by this instance of the ProtocolProviderService. * @return the id of the account represented by this provider. */ public AccountID getAccountID() { return accountID; } /** * Creates a RegistrationStateChange event corresponding to the specified * old and new joust sim states and notifies all currently registered * listeners. * * @param oldJoustSimState the state that the joust sim connection had * before the change occurred * @param oldJoustSimStateInfo the state info associated with the state of * the underlying connection state as it is after the change. * @param newJoustSimState the state that the underlying joust sim * connection is currently in. * @param newJoustSimStateInfo the state info associated with the state of * the underlying connection state as it was before the change. * @param reasonCode a value corresponding to one of the REASON_XXX fields * of the RegistrationStateChangeEvent class, indicating the reason for this * state transition. * @param reason a String further explaining the reason code or null if * no such explanation is necessary. */ private void fireRegistrationStateChanged( State oldJoustSimState, StateInfo oldJoustSimStateInfo, State newJoustSimState, StateInfo newJoustSimStateInfo, int reasonCode, String reason) { RegistrationState oldRegistrationState = joustSimStateToRegistrationState(oldJoustSimState , oldJoustSimStateInfo); RegistrationState newRegistrationState = joustSimStateToRegistrationState(newJoustSimState , newJoustSimStateInfo); if(newJoustSimStateInfo instanceof LoginFailureStateInfo) { LoginFailureInfo loginFailure = ((LoginFailureStateInfo)newJoustSimStateInfo) .getLoginFailureInfo(); if(loginFailure instanceof AuthFailureInfo) { AuthFailureInfo afi = (AuthFailureInfo)loginFailure; logger.debug("AuthFailureInfo code : " + afi.getErrorCode()); int code = ConnectionClosedListener .convertAuthCodeToReasonCode(afi); reasonCode = ConnectionClosedListener .convertCodeToRegistrationStateChangeEvent(code); reason = ConnectionClosedListener .convertCodeToStringReason(code); } } fireRegistrationStateChanged(oldRegistrationState, newRegistrationState , reasonCode, reason); } /** * Creates a RegistrationStateChange event corresponding to the specified * old and new states and notifies all currently registered listeners. * * @param oldState the state that the provider had before the change * occurred * @param newState the state that the provider is currently in. * @param reasonCode a value corresponding to one of the REASON_XXX fields * of the RegistrationStateChangeEvent class, indicating the reason for * this state transition. * @param reason a String further explaining the reason code or null if * no such explanation is necessary. */ void fireRegistrationStateChanged( RegistrationState oldState, RegistrationState newState, int reasonCode, String reason) { RegistrationStateChangeEvent event = new RegistrationStateChangeEvent( this, oldState, newState, reasonCode, reason); if(newState.equals(RegistrationState.CONNECTION_FAILED) && isRegistered()) { // if for some reason (keep alive failed) and connection is // still connected disconneted unregister(); } logger.debug("Dispatching " + event + " to " + registrationListeners.size()+ " listeners."); Iterator listeners = null; synchronized (registrationListeners) { listeners = new ArrayList(registrationListeners).iterator(); } while (listeners.hasNext()) { RegistrationStateChangeListener listener = (RegistrationStateChangeListener) listeners.next(); listener.registrationStateChanged(event); } logger.trace("Done."); } /** * Returns the info retriever that we've initialized for the current * session. * * @return the info retriever that we've initialized for the current * session. */ protected InfoRetreiver getInfoRetreiver() { return infoRetreiver; } /** * This class handles connection state events that have originated in this * provider's aim connection. Events are acted upon accordingly and, * if necessary, forwarded to registered listeners (asynchronously). */ private class AimConnStateListener implements StateListener { public void handleStateChange(StateEvent event) { State newState = event.getNewState(); State oldState = event.getOldState(); AimConnection conn = event.getAimConnection(); logger.debug("ICQ protocol provider " + getProtocolName() + " changed registration status from " + oldState + " to " + newState); int reasonCode = RegistrationStateChangeEvent.REASON_NOT_SPECIFIED; String reasonStr = null; if (newState == State.ONLINE) { icbmService = conn.getIcbmService(); icbmService.addIcbmListener(aimIcbmListener); conn.getInfoService(). getOscarConnection().getSnacProcessor(). getFlapProcessor().addPacketListener( new ConnectionClosedListener(conn)); } else if (newState == State.DISCONNECTED) { // we need a Service here. no metter which // I've choose BosService // we just need the oscar conenction from the service Service service = aimConnection.getBosService(); if(service != null) { int discconectCode = service.getOscarConnection() .getLastCloseCode(); reasonCode = ConnectionClosedListener .convertCodeToRegistrationStateChangeEvent( discconectCode); reasonStr = ConnectionClosedListener .convertCodeToStringReason(discconectCode); logger.debug( "The aim Connection was disconnected! with reason : " + reasonStr); } else logger.debug("The aim Connection was disconnected!"); } else if(newState == State.FAILED) { logger.debug("The aim Connection failed! " + event.getNewStateInfo()); } //as a side note - if this was an AuthenticationFailed error //set the stored password to null so that we don't use it any more. if(reasonCode == RegistrationStateChangeEvent .REASON_AUTHENTICATION_FAILED) { if(USING_ICQ) IcqActivator.getIcqProtocolProviderFactory().storePassword( getAccountID(), null); else IcqActivator.getAimProtocolProviderFactory().storePassword( getAccountID(), null); } //now tell all interested parties about what happened. fireRegistrationStateChanged(oldState, event.getOldStateInfo() , newState, event.getNewStateInfo() , reasonCode, reasonStr); } } /** * Returns the <tt>AimSession</tt> opened by this provider. * @return a reference to the <tt>AimSession</tt> that this provider * last opened. */ protected AimSession getAimSession() { return aimSession; } /** * Returns the <tt>AimConnection</tt>opened by this provider * @return a reference to the <tt>AimConnection</tt> last opened by this * provider. */ protected AimConnection getAimConnection() { return aimConnection; } public class AimIcbmListener implements IcbmListener { public void newConversation(IcbmService service, Conversation conv) { logger.debug("Received a new conversation event"); conv.addConversationListener(new AimConversationListener()); } public void buddyInfoUpdated(IcbmService service, Screenname buddy, IcbmBuddyInfo info) { logger.debug("Got a BuddINFO event"); } public void sendAutomaticallyFailed( IcbmService service, net.kano.joustsim.oscar.oscar.service.icbm.Message message, Set triedConversations) { } } public class AimConversationListener implements ConversationListener{ public void sentOtherEvent(Conversation conversation, ConversationEventInfo event) { logger.debug("reveived ConversationEventInfo:" + event); } // This may be called without ever calling conversationOpened public void conversationClosed(Conversation co) { logger.debug("conversation closed"); } public void gotOtherEvent(Conversation conversation, ConversationEventInfo event) { logger.debug("goet other event"); if(event instanceof TypingInfo) { TypingInfo ti = (TypingInfo)event; logger.debug("got typing info and state is: " + ti.getTypingState()); } else if (event instanceof MessageInfo) { MessageInfo ti = (MessageInfo)event; logger.debug("got message info for msg: " + ti.getMessage()); } } public void canSendMessageChanged(Conversation con, boolean canSend) { logger.debug("can send message event"); } // This may never be called public void conversationOpened(Conversation con) { logger.debug("conversation opened event"); } // This may be called after conversationClosed is called public void sentMessage(Conversation con, MessageInfo minfo) { logger.debug("sent message event"); } // This may be called after conversationClosed is called. public void gotMessage(Conversation con, MessageInfo minfo) { logger.debug("got message event" + minfo.getMessage().getMessageBody()); } } /** * Fix for late close conenction due to * multiple logins. * Listening for incoming packets for the close command * when this is received we discconect the session to force it * because otherwise is wait for timeout of reading from the socket stream * which leads to from 10 to 20 seconds delay of closing the session * and connection * */ public static class ConnectionClosedListener implements FlapPacketListener { private AimConnection aimConnection = null; private final static int REASON_MULTIPLE_LOGINS = 0x0001; private final static int REASON_BAD_PASSWORD_A = 0x0004; private final static int REASON_BAD_PASSWORD_B = 0x0005; private final static int REASON_NON_EXISTING_ICQ_UIN_A = 0x0007; private final static int REASON_NON_EXISTING_ICQ_UIN_B = 0x0008; private final static int REASON_MANY_CLIENTS_FROM_SAME_IP_A = 0x0015; private final static int REASON_MANY_CLIENTS_FROM_SAME_IP_B = 0x0016; private final static int REASON_CONNECTION_RATE_EXCEEDED = 0x0018; private final static int REASON_CONNECTION_TOO_FAST = 0x001D; private final static int REASON_TRY_AGAIN = 0x001E; private final static String REASON_STRING_MULTIPLE_LOGINS = "multiple logins (on same UIN)"; private final static String REASON_STRING_BAD_PASSWORD = "bad password"; private final static String REASON_STRING_NON_EXISTING_ICQ_UIN = "non-existant UIN"; private final static String REASON_STRING_MANY_CLIENTS_FROM_SAME_IP = "too many clients from same IP"; private final static String REASON_STRING_CONNECTION_RATE_EXCEEDED = "Rate exceeded. The server temporarily bans you."; private final static String REASON_STRING_CONNECTION_TOO_FAST = "You are reconnecting too fast"; private final static String REASON_STRING_TRY_AGAIN = "Can't register on ICQ network, try again soon."; private final static String REASON_STRING_NOT_SPECIFIED = "Not Specified"; ConnectionClosedListener(AimConnection aimConnection) { this.aimConnection = aimConnection; } public void handleFlapPacket(FlapPacketEvent evt) { FlapCommand flapCommand = evt.getFlapCommand(); if (flapCommand instanceof CloseFlapCmd) { CloseFlapCmd closeCmd = (CloseFlapCmd)flapCommand; logger.trace("received close command with code : " + closeCmd.getCode()); aimConnection.disconnect(); } } /** * Converts the codes in the close command * or the lastCloseCode of OscarConnection to the states * which are registered in the service protocol events * * @param reasonCode int the reason of close connection * @return int corresponding RegistrationStateChangeEvent */ static int convertCodeToRegistrationStateChangeEvent(int reasonCode) { switch(reasonCode) { case REASON_MULTIPLE_LOGINS : return RegistrationStateChangeEvent .REASON_MULTIPLE_LOGINS; case REASON_BAD_PASSWORD_A : return RegistrationStateChangeEvent .REASON_AUTHENTICATION_FAILED; case REASON_BAD_PASSWORD_B : return RegistrationStateChangeEvent .REASON_AUTHENTICATION_FAILED; case REASON_NON_EXISTING_ICQ_UIN_A : return RegistrationStateChangeEvent .REASON_NON_EXISTING_USER_ID; case REASON_NON_EXISTING_ICQ_UIN_B : return RegistrationStateChangeEvent .REASON_NON_EXISTING_USER_ID; case REASON_MANY_CLIENTS_FROM_SAME_IP_A : return RegistrationStateChangeEvent .REASON_CLIENT_LIMIT_REACHED_FOR_IP; case REASON_MANY_CLIENTS_FROM_SAME_IP_B : return RegistrationStateChangeEvent .REASON_CLIENT_LIMIT_REACHED_FOR_IP; case REASON_CONNECTION_RATE_EXCEEDED : return RegistrationStateChangeEvent .REASON_RECONNECTION_RATE_LIMIT_EXCEEDED; case REASON_CONNECTION_TOO_FAST : return RegistrationStateChangeEvent .REASON_RECONNECTION_RATE_LIMIT_EXCEEDED; case REASON_TRY_AGAIN : return RegistrationStateChangeEvent .REASON_RECONNECTION_RATE_LIMIT_EXCEEDED; default : return RegistrationStateChangeEvent .REASON_NOT_SPECIFIED; } } /** * returns the reason string corresponding to the code * in the close command * * @param reasonCode int the reason of close connection * @return String describing the reason */ static String convertCodeToStringReason(int reasonCode) { switch(reasonCode) { case REASON_MULTIPLE_LOGINS : return REASON_STRING_MULTIPLE_LOGINS; case REASON_BAD_PASSWORD_A : return REASON_STRING_BAD_PASSWORD; case REASON_BAD_PASSWORD_B : return REASON_STRING_BAD_PASSWORD; case REASON_NON_EXISTING_ICQ_UIN_A : return REASON_STRING_NON_EXISTING_ICQ_UIN; case REASON_NON_EXISTING_ICQ_UIN_B : return REASON_STRING_NON_EXISTING_ICQ_UIN; case REASON_MANY_CLIENTS_FROM_SAME_IP_A : return REASON_STRING_MANY_CLIENTS_FROM_SAME_IP; case REASON_MANY_CLIENTS_FROM_SAME_IP_B : return REASON_STRING_MANY_CLIENTS_FROM_SAME_IP; case REASON_CONNECTION_RATE_EXCEEDED : return REASON_STRING_CONNECTION_RATE_EXCEEDED; case REASON_CONNECTION_TOO_FAST : return REASON_STRING_CONNECTION_TOO_FAST; case REASON_TRY_AGAIN : return REASON_STRING_TRY_AGAIN; default : return REASON_STRING_NOT_SPECIFIED; } } /** * When receiving login failure * the reasons for the failure are in the authorization * part of the protocol ( 0x13 ) * In the AuthResponse are the possible reason codes * here they are converted to those in the ConnectionClosedListener * so the they can be converted to the one in service protocol events * * @param afi AuthFailureInfo the failure info * @return int the corresponding code to this failure */ static int convertAuthCodeToReasonCode(AuthFailureInfo afi) { switch(afi.getErrorCode()) { case AuthResponse.ERROR_BAD_PASSWORD : return REASON_BAD_PASSWORD_A; case AuthResponse.ERROR_CONNECTING_TOO_MUCH_A : return REASON_CONNECTION_RATE_EXCEEDED; case AuthResponse.ERROR_CONNECTING_TOO_MUCH_B : return REASON_CONNECTION_RATE_EXCEEDED; case AuthResponse.ERROR_INVALID_SN_OR_PASS_A : return REASON_NON_EXISTING_ICQ_UIN_A; case AuthResponse.ERROR_INVALID_SN_OR_PASS_B : return REASON_NON_EXISTING_ICQ_UIN_B; // 16 is also used for blocked from same IP case 16 : return REASON_MANY_CLIENTS_FROM_SAME_IP_A; case AuthResponse.ERROR_SIGNON_BLOCKED : return REASON_MANY_CLIENTS_FROM_SAME_IP_B; default : return RegistrationStateChangeEvent.REASON_NOT_SPECIFIED; } } } /** * Returns the icq/aim protocol icon. * @return the icq/aim protocol icon */ public ProtocolIcon getProtocolIcon() { if(USING_ICQ) return icqIcon; else return aimIcon; } }
package net.java.sip.communicator.impl.protocol.sip; import gov.nist.javax.sip.address.*; import gov.nist.javax.sip.header.*; import gov.nist.javax.sip.message.*; import net.java.sip.communicator.impl.protocol.sip.net.*; import net.java.sip.communicator.impl.protocol.sip.security.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.service.version.Version; import net.java.sip.communicator.util.*; import net.java.sip.communicator.util.dns.*; import org.osgi.framework.*; import javax.sip.*; import javax.sip.address.*; import javax.sip.header.*; import javax.sip.message.*; import java.net.*; import java.text.*; import java.util.*; /** * A SIP implementation of the Protocol Provider Service. * * @author Emil Ivov * @author Lubomir Marinov * @author Alan Kelly * @author Grigorii Balutsel */ public class ProtocolProviderServiceSipImpl extends AbstractProtocolProviderService implements SipListener, RegistrationStateChangeListener { /** * Our class logger. */ private static final Logger logger = Logger.getLogger(ProtocolProviderServiceSipImpl.class); /** * The identifier of the account that this provider represents. */ private AccountID accountID = null; /** * We use this to lock access to initialization. */ private final Object initializationLock = new Object(); /** * indicates whether or not the provider is initialized and ready for use. */ private boolean isInitialized = false; /** * A list of all events registered for this provider. */ private final List<String> registeredEvents = new ArrayList<String>(); /** * The AddressFactory used to create URLs ans Address objects. */ private AddressFactoryEx addressFactory; /** * The HeaderFactory used to create SIP message headers. */ private HeaderFactory headerFactory; /** * The Message Factory used to create SIP messages. */ private SipMessageFactory messageFactory; /** * The class in charge of event dispatching and managing common JAIN-SIP * resources */ private static SipStackSharing sipStackSharing = null; /** * A table mapping SIP methods to method processors (every processor must * implement the SipListener interface). Whenever a new message arrives we * extract its method and hand it to the processor instance registered */ private final Hashtable<String, List<MethodProcessor>> methodProcessors = new Hashtable<String, List<MethodProcessor>>(); /** * The name of the property under which the user may specify a transport * to use for destinations whose preferred transport is unknown. */ private static final String DEFAULT_TRANSPORT = "net.java.sip.communicator.impl.protocol.sip.DEFAULT_TRANSPORT"; /** * The name of the property under which the user may specify if the desktop * streaming or sharing should be disabled. */ private static final String IS_DESKTOP_STREAMING_DISABLED = "net.java.sip.communicator.impl.protocol.sip.DESKTOP_STREAMING_DISABLED"; /** * The name of the property under which the user may specify if the video * calls should be disabled. */ private static final String IS_CALLING_DISABLED = "net.java.sip.communicator.impl.protocol.sip.CALLING_DISABLED"; /** * Default number of times that our requests can be forwarded. */ private static final int MAX_FORWARDS = 70; /** * Keep-alive method can be - register,options or udp */ public static final String KEEP_ALIVE_METHOD = "KEEP_ALIVE_METHOD"; /** * The interval for keep-alive */ public static final String KEEP_ALIVE_INTERVAL = "KEEP_ALIVE_INTERVAL"; /** * The default maxForwards header that we use in our requests. */ private MaxForwardsHeader maxForwardsHeader = null; /** * The header that we use to identify ourselves. */ private UserAgentHeader userAgentHeader = null; /** * The name that we want to send others when calling or chatting with them. */ private String ourDisplayName = null; /** * Our current connection with the registrar. */ private SipRegistrarConnection sipRegistrarConnection = null; /** * The SipSecurityManager instance that would be taking care of our * authentications. */ private SipSecurityManager sipSecurityManager = null; /** * Address resolver for the outbound proxy connection. */ private ProxyConnection connection; /** * The logo corresponding to the jabber protocol. */ private ProtocolIconSipImpl protocolIcon; /** * The presence status set supported by this provider */ private SipStatusEnum sipStatusEnum; /** * A list of early processors that can do early processing of received * messages (requests or responses). */ private final List<SipMessageProcessor> earlyProcessors = new ArrayList<SipMessageProcessor>(); /** * Whether we has enabled FORCE_PROXY_BYPASS for current account. */ private boolean forceLooseRouting = false; /** * Returns the AccountID that uniquely identifies the account represented by * this instance of the ProtocolProviderService. * @return the id of the account represented by this provider. */ public AccountID getAccountID() { return accountID; } /** * Returns the state of the registration of this protocol provider with the * corresponding registration service. * @return ProviderRegistrationState */ public RegistrationState getRegistrationState() { if(this.sipRegistrarConnection == null ) { return RegistrationState.UNREGISTERED; } return sipRegistrarConnection.getRegistrationState(); } /** * Returns the short name of the protocol that the implementation of this * provider is based upon (like SIP, Jabber, ICQ/AIM, or others for * example). If the name of the protocol has been enumerated in * ProtocolNames then the value returned by this method must be the same as * the one in ProtocolNames. * @return a String containing the short name of the protocol this service * is implementing (most often that would be a name in ProtocolNames). */ public String getProtocolName() { return ProtocolNames.SIP; } /** * Register a new event taken in account by this provider. This is usefull * to generate the Allow-Events header of the OPTIONS responses and to * generate 489 responses. * * @param event The event to register */ public void registerEvent(String event) { synchronized (this.registeredEvents) { if (!this.registeredEvents.contains(event)) { this.registeredEvents.add(event); } } } /** * Returns the list of all the registered events for this provider. * * @return The list of all the registered events */ public List<String> getKnownEventsList() { return this.registeredEvents; } /** * Starts the registration process. Connection details such as * registration server, user name/number are provided through the * configuration service through implementation specific properties. * * @param authority the security authority that will be used for resolving * any security challenges that may be returned during the * registration or at any moment while wer're registered. * * @throws OperationFailedException with the corresponding code it the * registration fails for some reason (e.g. a networking error or an * implementation problem). */ public void register(SecurityAuthority authority) throws OperationFailedException { if(!isInitialized) { throw new OperationFailedException( "Provided must be initialized before being able to register." , OperationFailedException.GENERAL_ERROR); } if (isRegistered()) { return; } /** * Evaluate whether FORCE_PROXY_BYPASS is enabled for the account * before registering. */ forceLooseRouting = Boolean.valueOf((String) getAccountID().getAccountProperty( ProtocolProviderFactory.FORCE_PROXY_BYPASS)); sipStackSharing.addSipListener(this); // be warned when we will unregister, so that we can // then remove us as SipListener this.addRegistrationStateChangeListener(this); // Enable the user name modification. Setting this property to true // we'll allow the user to change the user name stored in the given //authority. authority.setUserNameEditable(true); //init the security manager before doing the actual registration to //avoid being asked for credentials before being ready to provide them sipSecurityManager.setSecurityAuthority(authority); initRegistrarConnection(); //connect to the Registrar. connection = ProxyConnection.create(this); if(!registerUsingNextAddress()) { logger.error("No address found for " + this); fireRegistrationStateChanged( RegistrationState.REGISTERING, RegistrationState.CONNECTION_FAILED, RegistrationStateChangeEvent.REASON_SERVER_NOT_FOUND, "Invalid or inaccessible server address."); } } /** * Ends the registration of this protocol provider with the current * registration service. * * @throws OperationFailedException with the corresponding code it the * registration fails for some reason (e.g. a networking error or an * implementation problem). */ public void unregister() throws OperationFailedException { if(getRegistrationState().equals(RegistrationState.UNREGISTERED) || getRegistrationState().equals(RegistrationState.UNREGISTERING) || getRegistrationState().equals(RegistrationState.CONNECTION_FAILED)) { return; } sipRegistrarConnection.unregister(); sipSecurityManager.setSecurityAuthority(null); } protected void initialize(String sipAddress, SipAccountID accountID) throws OperationFailedException, IllegalArgumentException { synchronized (initializationLock) { this.accountID = accountID; String protocolIconPath = accountID .getAccountPropertyString(ProtocolProviderFactory.PROTOCOL_ICON_PATH); if (protocolIconPath == null) protocolIconPath = "resources/images/protocol/sip"; this.protocolIcon = new ProtocolIconSipImpl(protocolIconPath); this.sipStatusEnum = new SipStatusEnum(protocolIconPath); if(sipStackSharing == null) sipStackSharing = new SipStackSharing(); // get the presence options boolean enablePresence = accountID.getAccountPropertyBoolean( ProtocolProviderFactory.IS_PRESENCE_ENABLED, true); boolean forceP2P = accountID.getAccountPropertyBoolean( ProtocolProviderFactory.FORCE_P2P_MODE, true); int pollingValue = accountID.getAccountPropertyInt( ProtocolProviderFactory.POLLING_PERIOD, 30); int subscriptionExpiration = accountID.getAccountPropertyInt( ProtocolProviderFactory.SUBSCRIPTION_EXPIRATION, 3600); //create SIP factories. headerFactory = new HeaderFactoryImpl(); addressFactory = new AddressFactoryImpl(); //initialize our display name ourDisplayName = accountID.getAccountPropertyString( ProtocolProviderFactory.DISPLAY_NAME); if(ourDisplayName == null || ourDisplayName.trim().length() == 0) { ourDisplayName = accountID.getUserID(); } //init our call processor OperationSetBasicTelephonySipImpl opSetBasicTelephonySipImpl = new OperationSetBasicTelephonySipImpl(this); boolean isCallingDisabled = SipActivator.getConfigurationService() .getBoolean(IS_CALLING_DISABLED, false); boolean isCallingDisabledForAccount = accountID.getAccountPropertyBoolean( ProtocolProviderFactory.IS_CALLING_DISABLED_FOR_ACCOUNT, false); if (!isCallingDisabled && !isCallingDisabledForAccount) { addSupportedOperationSet( OperationSetBasicTelephony.class, opSetBasicTelephonySipImpl); addSupportedOperationSet( OperationSetAdvancedTelephony.class, opSetBasicTelephonySipImpl); // init call security addSupportedOperationSet( OperationSetSecureZrtpTelephony.class, opSetBasicTelephonySipImpl); addSupportedOperationSet( OperationSetSecureSDesTelephony.class, opSetBasicTelephonySipImpl); // OperationSetVideoTelephony addSupportedOperationSet( OperationSetVideoTelephony.class, new OperationSetVideoTelephonySipImpl( opSetBasicTelephonySipImpl)); addSupportedOperationSet( OperationSetTelephonyConferencing.class, new OperationSetTelephonyConferencingSipImpl(this)); // init DTMF (from JM Heitz) addSupportedOperationSet( OperationSetDTMF.class, new OperationSetDTMFSipImpl(this)); boolean isDesktopStreamingDisabled = SipActivator.getConfigurationService() .getBoolean(IS_DESKTOP_STREAMING_DISABLED, false); boolean isAccountDesktopStreamingDisabled = accountID.getAccountPropertyBoolean( ProtocolProviderFactory.IS_DESKTOP_STREAMING_DISABLED, false); if (!isDesktopStreamingDisabled && !isAccountDesktopStreamingDisabled) { // OperationSetDesktopStreaming addSupportedOperationSet( OperationSetDesktopStreaming.class, new OperationSetDesktopStreamingSipImpl( opSetBasicTelephonySipImpl)); // OperationSetDesktopSharingServer addSupportedOperationSet( OperationSetDesktopSharingServer.class, new OperationSetDesktopSharingServerSipImpl( opSetBasicTelephonySipImpl)); // OperationSetDesktopSharingClient addSupportedOperationSet( OperationSetDesktopSharingClient.class, new OperationSetDesktopSharingClientSipImpl(this)); } } //init presence op set. OperationSetPersistentPresence opSetPersPresence = new OperationSetPresenceSipImpl(this, enablePresence, forceP2P, pollingValue, subscriptionExpiration); addSupportedOperationSet( OperationSetPersistentPresence.class, opSetPersPresence); //also register with standard presence addSupportedOperationSet( OperationSetPresence.class, opSetPersPresence); if (enablePresence) { // init instant messaging OperationSetBasicInstantMessagingSipImpl opSetBasicIM = new OperationSetBasicInstantMessagingSipImpl(this); addSupportedOperationSet( OperationSetBasicInstantMessaging.class, opSetBasicIM); // init typing notifications addSupportedOperationSet( OperationSetTypingNotifications.class, new OperationSetTypingNotificationsSipImpl( this, opSetBasicIM)); OperationSetServerStoredAccountInfoSipImpl opSetSSAccountInfo = new OperationSetServerStoredAccountInfoSipImpl(this); // Set the display name. if(opSetSSAccountInfo != null) opSetSSAccountInfo.setOurDisplayName(ourDisplayName); // init avatar addSupportedOperationSet( OperationSetServerStoredAccountInfo.class, opSetSSAccountInfo); addSupportedOperationSet( OperationSetAvatar.class, new OperationSetAvatarSipImpl(this, opSetSSAccountInfo)); } addSupportedOperationSet( OperationSetMessageWaiting.class, new OperationSetMessageWaitingSipImpl(this)); //initialize our OPTIONS handler new ClientCapabilities(this); //init the security manager this.sipSecurityManager = new SipSecurityManager(accountID); sipSecurityManager.setHeaderFactory(headerFactory); // register any available custom extensions ProtocolProviderExtensions.registerCustomOperationSets(this); isInitialized = true; } } /** * Adds a specific <tt>OperationSet</tt> implementation to the set of * supported <tt>OperationSet</tt>s of this instance. Serves as a type-safe * wrapper around {@link #supportedOperationSets} which works with class * names instead of <tt>Class</tt> and also shortens the code which performs * such additions. * * @param <T> the exact type of the <tt>OperationSet</tt> implementation to * be added * @param opsetClass the <tt>Class</tt> of <tt>OperationSet</tt> under the * name of which the specified implementation is to be added * @param opset the <tt>OperationSet</tt> implementation to be added */ @Override protected <T extends OperationSet> void addSupportedOperationSet( Class<T> opsetClass, T opset) { super.addSupportedOperationSet(opsetClass, opset); } /** * Removes an <tt>OperationSet</tt> implementation from the set of * supported <tt>OperationSet</tt>s for this instance. * * @param <T> the exact type of the <tt>OperationSet</tt> implementation to * be added * @param opsetClass the <tt>Class</tt> of <tt>OperationSet</tt> under the * name of which the specified implementation is to be added */ @Override protected <T extends OperationSet> void removeSupportedOperationSet( Class<T> opsetClass) { super.removeSupportedOperationSet(opsetClass); } /** * Never called. * * @param exceptionEvent the IOExceptionEvent containing the cause. */ public void processIOException(IOExceptionEvent exceptionEvent) {} /** * Processes a Response received on a SipProvider upon which this * SipListener is registered. * <p> * * @param responseEvent the responseEvent fired from the SipProvider to the * SipListener representing a Response received from the network. */ public void processResponse(ResponseEvent responseEvent) { ClientTransaction clientTransaction = responseEvent .getClientTransaction(); if (clientTransaction == null) { if (logger.isDebugEnabled()) logger.debug("ignoring a transactionless response"); return; } Response response = responseEvent.getResponse(); earlyProcessMessage(responseEvent); String method = ( (CSeqHeader) response.getHeader(CSeqHeader.NAME)) .getMethod(); //find the object that is supposed to take care of responses with the //corresponding method List<MethodProcessor> processors = methodProcessors.get(method); if (processors != null) { if (logger.isDebugEnabled()) logger.debug("Found " + processors.size() + " processor(s) for method " + method); for (MethodProcessor processor : processors) if (processor.processResponse(responseEvent)) break; } } /** * Processes a retransmit or expiration Timeout of an underlying * {@link Transaction} handled by this SipListener. This Event notifies the * application that a retransmission or transaction Timer expired in the * SipProvider's transaction state machine. The TimeoutEvent encapsulates * the specific timeout type and the transaction identifier either client or * server upon which the timeout occurred. The type of Timeout can by * determined by: * <code>timeoutType = timeoutEvent.getTimeout().getValue();</code> * * @param timeoutEvent - * the timeoutEvent received indicating either the message * retransmit or transaction timed out. */ public void processTimeout(TimeoutEvent timeoutEvent) { Transaction transaction; if(timeoutEvent.isServerTransaction()) transaction = timeoutEvent.getServerTransaction(); else transaction = timeoutEvent.getClientTransaction(); if (transaction == null) { if (logger.isDebugEnabled()) logger.debug("ignoring a transactionless timeout event"); return; } earlyProcessMessage(timeoutEvent); Request request = transaction.getRequest(); if (logger.isDebugEnabled()) logger.debug("received timeout for req=" + request); //find the object that is supposed to take care of responses with the //corresponding method String method = request.getMethod(); List<MethodProcessor> processors = methodProcessors.get(method); if (processors != null) { if (logger.isDebugEnabled()) logger.debug("Found " + processors.size() + " processor(s) for method " + method); for (MethodProcessor processor : processors) { if (processor.processTimeout(timeoutEvent)) { break; } } } } /** * Process an asynchronously reported TransactionTerminatedEvent. * When a transaction transitions to the Terminated state, the stack * keeps no further records of the transaction. This notification can be used by * applications to clean up any auxiliary data that is being maintained * for the given transaction. * * @param transactionTerminatedEvent -- an event that indicates that the * transaction has transitioned into the terminated state. * @since v1.2 */ public void processTransactionTerminated(TransactionTerminatedEvent transactionTerminatedEvent) { Transaction transaction; if(transactionTerminatedEvent.isServerTransaction()) transaction = transactionTerminatedEvent.getServerTransaction(); else transaction = transactionTerminatedEvent.getClientTransaction(); if (transaction == null) { if (logger.isDebugEnabled()) logger.debug( "ignoring a transactionless transaction terminated event"); return; } Request request = transaction.getRequest(); //find the object that is supposed to take care of responses with the //corresponding method String method = request.getMethod(); List<MethodProcessor> processors = methodProcessors.get(method); if (processors != null) { if (logger.isDebugEnabled()) logger.debug("Found " + processors.size() + " processor(s) for method " + method); for (MethodProcessor processor : processors) { if (processor.processTransactionTerminated( transactionTerminatedEvent)) { break; } } } } /** * Process an asynchronously reported DialogTerminatedEvent. * When a dialog transitions to the Terminated state, the stack * keeps no further records of the dialog. This notification can be used by * applications to clean up any auxiliary data that is being maintained * for the given dialog. * * @param dialogTerminatedEvent -- an event that indicates that the * dialog has transitioned into the terminated state. * @since v1.2 */ public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) { if (logger.isDebugEnabled()) logger.debug("Dialog terminated for req=" + dialogTerminatedEvent.getDialog()); } /** * Processes a Request received on a SipProvider upon which this SipListener * is registered. * <p> * @param requestEvent requestEvent fired from the SipProvider to the * SipListener representing a Request received from the network. */ public void processRequest(RequestEvent requestEvent) { Request request = requestEvent.getRequest(); if(sipRegistrarConnection != null && !sipRegistrarConnection.isRegistrarless() && !sipRegistrarConnection.isRequestFromSameConnection(request) && !forceLooseRouting) { logger.warn("Received request not from our proxy, ignoring it! " + "Request:" + request); if (requestEvent.getServerTransaction() != null) { try { requestEvent.getServerTransaction().terminate(); } catch (Throwable e) { logger.warn("Failed to properly terminate transaction for " +"a rogue request. Well ... so be it " + "Request:" + request); } } return; } earlyProcessMessage(requestEvent); // test if an Event header is present and known EventHeader eventHeader = (EventHeader) request.getHeader(EventHeader.NAME); if (eventHeader != null) { boolean eventKnown; synchronized (this.registeredEvents) { eventKnown = this.registeredEvents.contains( eventHeader.getEventType()); } if (!eventKnown) { // send a 489 / Bad Event response ServerTransaction serverTransaction = requestEvent .getServerTransaction(); if (serverTransaction == null) { try { serverTransaction = SipStackSharing. getOrCreateServerTransaction(requestEvent); } catch (TransactionAlreadyExistsException ex) { //let's not scare the user and only log a message logger.error("Failed to create a new server" + "transaction for an incoming request\n" + "(Next message contains the request)" , ex); return; } catch (TransactionUnavailableException ex) { //let's not scare the user and only log a message logger.error("Failed to create a new server" + "transaction for an incoming request\n" + "(Next message contains the request)" , ex); return; } } Response response = null; try { response = this.getMessageFactory().createResponse( Response.BAD_EVENT, request); } catch (ParseException e) { logger.error("failed to create the 489 response", e); return; } try { serverTransaction.sendResponse(response); return; } catch (SipException e) { logger.error("failed to send the response", e); } catch (InvalidArgumentException e) { // should not happen logger.error("invalid argument provided while trying" + " to send the response", e); } } } String method = request.getMethod(); //find the object that is supposed to take care of responses with the //corresponding method List<MethodProcessor> processors = methodProcessors.get(method); //raise this flag if at least one processor handles the request. boolean processedAtLeastOnce = false; if (processors != null) { if (logger.isDebugEnabled()) logger.debug("Found " + processors.size() + " processor(s) for method " + method); for (MethodProcessor processor : processors) { if (processor.processRequest(requestEvent)) { processedAtLeastOnce = true; break; } } } //send an error response if no one processes this if (!processedAtLeastOnce) { ServerTransaction serverTransaction; try { serverTransaction = SipStackSharing.getOrCreateServerTransaction(requestEvent); if (serverTransaction == null) { logger.warn("Could not create a transaction for a " +"non-supported method " + request.getMethod()); return; } TransactionState state = serverTransaction.getState(); if( TransactionState.TRYING.equals(state)) { Response response = this.getMessageFactory().createResponse( Response.NOT_IMPLEMENTED, request); serverTransaction.sendResponse(response); } } catch (Throwable exc) { logger.warn("Could not respond to a non-supported method " + request.getMethod(), exc); } } } /** * Makes the service implementation close all open sockets and release * any resources that it might have taken and prepare for shutdown/garbage * collection. */ public void shutdown() { if(!isInitialized) { return; } // don't run in Thread cause shutting down may finish before // we were able to unregister new ShutdownThread().run(); } /** * The thread that we use in order to send our unREGISTER request upon * system shut down. */ protected class ShutdownThread implements Runnable { /** * Shutdowns operation sets that need it then calls the * <tt>SipRegistrarConnection.unregister()</tt> method. */ public void run() { if (logger.isTraceEnabled()) logger.trace("Killing the SIP Protocol Provider."); //kill all active calls OperationSetBasicTelephonySipImpl telephony = (OperationSetBasicTelephonySipImpl)getOperationSet( OperationSetBasicTelephony.class); telephony.shutdown(); if(isRegistered()) { try { //create a listener that would notify us when //un-registration has completed. ShutdownUnregistrationBlockListener listener = new ShutdownUnregistrationBlockListener(); addRegistrationStateChangeListener(listener); //do the un-registration unregister(); //leave ourselves time to complete un-registration (may include //2 REGISTER requests in case notification is needed.) listener.waitForEvent(3000L); } catch (OperationFailedException ex) { //we're shutting down so we need to silence the exception here logger.error( "Failed to properly unregister before shutting down. " + getAccountID() , ex); } } headerFactory = null; messageFactory = null; addressFactory = null; sipSecurityManager = null; connection = null; methodProcessors.clear(); isInitialized = false; } } /** * Initializes and returns an ArrayList with a single ViaHeader * containing a localhost address usable with the specified * s<tt>destination</tt>. This ArrayList may be used when sending * requests to that destination. * <p> * @param intendedDestination The address of the destination that the * request using the via headers will be sent to. * * @return ViaHeader-s list to be used when sending requests. * @throws OperationFailedException code INTERNAL_ERROR if a ParseException * occurs while initializing the array list. * */ public ArrayList<ViaHeader> getLocalViaHeaders(Address intendedDestination) throws OperationFailedException { return getLocalViaHeaders((SipURI)intendedDestination.getURI()); } /** * Initializes and returns an ArrayList with a single ViaHeader * containing a localhost address usable with the specified * s<tt>destination</tt>. This ArrayList may be used when sending * requests to that destination. * <p> * @param intendedDestination The address of the destination that the * request using the via headers will be sent to. * * @return ViaHeader-s list to be used when sending requests. * @throws OperationFailedException code INTERNAL_ERROR if a ParseException * occurs while initializing the array list. * */ public ArrayList<ViaHeader> getLocalViaHeaders(SipURI intendedDestination) throws OperationFailedException { ArrayList<ViaHeader> viaHeaders = new ArrayList<ViaHeader>(); ListeningPoint srcListeningPoint = getListeningPoint(intendedDestination.getTransportParam()); try { InetSocketAddress targetAddress = getIntendedDestination(intendedDestination); InetAddress localAddress = SipActivator .getNetworkAddressManagerService().getLocalHost( targetAddress.getAddress()); int localPort = srcListeningPoint.getPort(); String transport = srcListeningPoint.getTransport(); if (ListeningPoint.TCP.equalsIgnoreCase(transport) || ListeningPoint.TLS.equalsIgnoreCase(transport)) { InetSocketAddress localSockAddr = sipStackSharing.getLocalAddressForDestination( targetAddress.getAddress(), targetAddress.getPort(), localAddress, transport); localPort = localSockAddr.getPort(); } ViaHeader viaHeader = headerFactory.createViaHeader( localAddress.getHostAddress(), localPort, transport, null ); viaHeaders.add(viaHeader); if (logger.isDebugEnabled()) logger.debug("generated via headers:" + viaHeader); return viaHeaders; } catch (ParseException ex) { logger.error( "A ParseException occurred while creating Via Headers!", ex); throw new OperationFailedException( "A ParseException occurred while creating Via Headers!" ,OperationFailedException.INTERNAL_ERROR ,ex); } catch (InvalidArgumentException ex) { logger.error( "Unable to create a via header for port " + sipStackSharing.getLP(ListeningPoint.UDP).getPort(), ex); throw new OperationFailedException( "Unable to create a via header for port " + sipStackSharing.getLP(ListeningPoint.UDP).getPort() ,OperationFailedException.INTERNAL_ERROR ,ex); } catch (java.io.IOException ex) { logger.error( "Unable to create a via header for port " + sipStackSharing.getLP(ListeningPoint.UDP).getPort(), ex); throw new OperationFailedException( "Unable to create a via header for port " + sipStackSharing.getLP(ListeningPoint.UDP).getPort() ,OperationFailedException.NETWORK_FAILURE ,ex); } } /** * Initializes and returns this provider's default maxForwardsHeader field * using the value specified by MAX_FORWARDS. * * @return an instance of a MaxForwardsHeader that can be used when * sending requests * * @throws OperationFailedException with code INTERNAL_ERROR if MAX_FORWARDS * has an invalid value. */ public MaxForwardsHeader getMaxForwardsHeader() throws OperationFailedException { if (maxForwardsHeader == null) { try { maxForwardsHeader = headerFactory.createMaxForwardsHeader( MAX_FORWARDS); if (logger.isDebugEnabled()) logger.debug("generated max forwards: " + maxForwardsHeader.toString()); } catch (InvalidArgumentException ex) { throw new OperationFailedException( "A problem occurred while creating MaxForwardsHeader" , OperationFailedException.INTERNAL_ERROR , ex); } } return maxForwardsHeader; } /** * Returns a Contact header containing a sip URI based on a localhost * address. * * @param intendedDestination the destination that we plan to be sending * this contact header to. * * @return a Contact header based upon a local inet address. */ public ContactHeader getContactHeader(Address intendedDestination) { return getContactHeader((SipURI)intendedDestination.getURI()); } /** * Returns a Contact header containing a sip URI based on a localhost * address and therefore usable in REGISTER requests only. * * @param intendedDestination the destination that we plan to be sending * this contact header to. * * @return a Contact header based upon a local inet address. */ public ContactHeader getContactHeader(SipURI intendedDestination) { ContactHeader registrationContactHeader = null; ListeningPoint srcListeningPoint = getListeningPoint(intendedDestination); InetSocketAddress targetAddress = getIntendedDestination(intendedDestination); try { //find the address to use with the target InetAddress localAddress = SipActivator .getNetworkAddressManagerService() .getLocalHost(targetAddress.getAddress()); SipURI contactURI = addressFactory.createSipURI( getAccountID().getUserID() , localAddress.getHostAddress() ); String transport = srcListeningPoint.getTransport(); contactURI.setTransportParam(transport); int localPort = srcListeningPoint.getPort(); //if we are using tcp, make sure that we include the port of the //socket that we are actually using and not that of LP if (ListeningPoint.TCP.equalsIgnoreCase(transport) || ListeningPoint.TLS.equalsIgnoreCase(transport)) { InetSocketAddress localSockAddr = sipStackSharing.getLocalAddressForDestination( targetAddress.getAddress(), targetAddress.getPort(), localAddress, transport); localPort = localSockAddr.getPort(); } contactURI.setPort(localPort); // set a custom param to ease incoming requests dispatching in case // we have several registrar accounts with the same username String paramValue = getContactAddressCustomParamValue(); if (paramValue != null) { contactURI.setParameter( SipStackSharing.CONTACT_ADDRESS_CUSTOM_PARAM_NAME, paramValue); } Address contactAddress = addressFactory.createAddress( contactURI ); String ourDisplayName = getOurDisplayName(); if (ourDisplayName != null) { contactAddress.setDisplayName(ourDisplayName); } registrationContactHeader = headerFactory.createContactHeader( contactAddress); if (logger.isDebugEnabled()) logger.debug("generated contactHeader:" + registrationContactHeader); } catch (ParseException ex) { logger.error( "A ParseException occurred while creating From Header!", ex); throw new IllegalArgumentException( "A ParseException occurred while creating From Header!" , ex); } catch (java.io.IOException ex) { logger.error( "A ParseException occurred while creating From Header!", ex); throw new IllegalArgumentException( "A ParseException occurred while creating From Header!" , ex); } return registrationContactHeader; } /** * Returns null for a registraless account, a value for the contact address * custom parameter otherwise. This will help the dispatching of incoming * requests between accounts with the same username. For address-of-record * user@example.com, the returned value woud be example_com. * * @return null for a registraless account, a value for the * "registering_acc" contact address parameter otherwise */ public String getContactAddressCustomParamValue() { SipRegistrarConnection src = sipRegistrarConnection; if (src != null && !src.isRegistrarless()) { // if we don't replace the dots in the hostname, we get // "476 No Server Address in Contacts Allowed" // from certain registrars (ippi.fr for instance) String hostValue = ((SipURI) src.getAddressOfRecord().getURI()) .getHost().replace('.', '_'); return hostValue; } return null; } /** * Returns the AddressFactory used to create URLs ans Address objects. * * @return the AddressFactory used to create URLs ans Address objects. */ public AddressFactoryEx getAddressFactory() { return addressFactory; } /** * Returns the HeaderFactory used to create SIP message headers. * * @return the HeaderFactory used to create SIP message headers. */ public HeaderFactory getHeaderFactory() { return headerFactory; } /** * Returns the Message Factory used to create SIP messages. * * @return the Message Factory used to create SIP messages. */ public SipMessageFactory getMessageFactory() { if (messageFactory == null) { messageFactory = new SipMessageFactory(this, new MessageFactoryImpl()); } return messageFactory; } /** * Returns all running instances of ProtocolProviderServiceSipImpl * * @return all running instances of ProtocolProviderServiceSipImpl */ public static Set<ProtocolProviderServiceSipImpl> getAllInstances() { try { Set<ProtocolProviderServiceSipImpl> instances = new HashSet<ProtocolProviderServiceSipImpl>(); BundleContext context = SipActivator.getBundleContext(); ServiceReference[] references = context.getServiceReferences( ProtocolProviderService.class.getName(), null ); for(ServiceReference reference : references) { Object service = context.getService(reference); if(service instanceof ProtocolProviderServiceSipImpl) instances.add((ProtocolProviderServiceSipImpl) service); } return instances; } catch(InvalidSyntaxException ex) { if (logger.isDebugEnabled()) logger.debug("Problem parcing an osgi expression", ex); // should never happen so crash if it ever happens throw new RuntimeException( "getServiceReferences() wasn't supposed to fail!" ); } } /** * Returns the default listening point that we use for communication over * <tt>transport</tt>. * * @param transport the transport that the returned listening point needs * to support. * * @return the default listening point that we use for communication over * <tt>transport</tt> or null if no such transport is supported. */ public ListeningPoint getListeningPoint(String transport) { if(logger.isTraceEnabled()) logger.trace("Query for a " + transport + " listening point"); //override the transport in case we have an outbound proxy. if(connection.getAddress() != null) { if (logger.isTraceEnabled()) logger.trace("Will use proxy address"); transport = connection.getTransport(); } if(!isValidTransport(transport)) { transport = getDefaultTransport(); } ListeningPoint lp = null; if(transport.equalsIgnoreCase(ListeningPoint.UDP)) { lp = sipStackSharing.getLP(ListeningPoint.UDP); } else if(transport.equalsIgnoreCase(ListeningPoint.TCP)) { lp = sipStackSharing.getLP(ListeningPoint.TCP); } else if(transport.equalsIgnoreCase(ListeningPoint.TLS)) { lp = sipStackSharing.getLP(ListeningPoint.TLS); } if(logger.isTraceEnabled()) { logger.trace("Returning LP " + lp + " for transport [" + transport + "] and "); } return lp; } /** * Returns the default listening point that we should use to contact the * intended destination. * * @param intendedDestination the address that we will be trying to contact * through the listening point we are trying to obtain. * * @return the listening point that we should use to contact the * intended destination. */ public ListeningPoint getListeningPoint(SipURI intendedDestination) { return getListeningPoint(intendedDestination.getTransportParam()); } /** * Returns the default jain sip provider that we use for communication over * <tt>transport</tt>. * * @param transport the transport that the returned provider needs * to support. * * @return the default jain sip provider that we use for communication over * <tt>transport</tt> or null if no such transport is supported. */ public SipProvider getJainSipProvider(String transport) { return sipStackSharing.getJainSipProvider(transport); } /** * Reurns the currently valid sip security manager that everyone should * use to authenticate SIP Requests. * @return the currently valid instace of a SipSecurityManager that everyone * sould use to authenticate SIP Requests. */ public SipSecurityManager getSipSecurityManager() { return sipSecurityManager; } private void initRegistrarConnection() throws IllegalArgumentException { //First init the registrar address String registrarAddressStr = accountID .getAccountPropertyString(ProtocolProviderFactory.SERVER_ADDRESS); //if there is no registrar address, parse the user_id and extract it //from the domain part of the SIP URI. if (registrarAddressStr == null) { String userID = accountID .getAccountPropertyString(ProtocolProviderFactory.USER_ID); int index = userID.indexOf('@'); if ( index > -1 ) registrarAddressStr = userID.substring( index+1); } //if we still have no registrar address or if the registrar address //string is one of our local host addresses this means the users does //not want to use a registrar connection if(registrarAddressStr == null || registrarAddressStr.trim().length() == 0) { initRegistrarlessConnection(); return; } //init registrar port int registrarPort = ListeningPoint.PORT_5060; // check if user has overridden the registrar port. registrarPort = accountID.getAccountPropertyInt( ProtocolProviderFactory.SERVER_PORT, registrarPort); if (registrarPort > NetworkUtils.MAX_PORT_NUMBER) { throw new IllegalArgumentException(registrarPort + " is larger than " + NetworkUtils.MAX_PORT_NUMBER + " and does not therefore represent a valid port number."); } //Initialize our connection with the registrar // we insert the default transport if none is specified // use it for registrar connection this.sipRegistrarConnection = new SipRegistrarConnection( registrarAddressStr , registrarPort , getDefaultTransport() , this); } private void initRegistrarlessConnection() throws IllegalArgumentException { //registrar transport String registrarTransport = accountID .getAccountPropertyString(ProtocolProviderFactory.PREFERRED_TRANSPORT); if(registrarTransport != null && registrarTransport.length() > 0) { if( ! registrarTransport.equals(ListeningPoint.UDP) && !registrarTransport.equals(ListeningPoint.TCP) && !registrarTransport.equals(ListeningPoint.TLS)) { throw new IllegalArgumentException(registrarTransport + " is not a valid transport protocol. Transport must be " +"left blanc or set to TCP, UDP or TLS."); } } else { registrarTransport = ListeningPoint.UDP; } //Initialize our connection with the registrar this.sipRegistrarConnection = new SipRegistrarlessConnection(this, registrarTransport); } /** * Returns the SIP address of record (Display Name <user@server.net>) that * this account is created for. The method takes into account whether or * not we are running in Registar or "No Registar" mode and either returns * the AOR we are using to register or an address constructed using the * local address. * * @param intendedDestination the destination that we would be using the * local address to communicate with. * * @return our Address Of Record that we should use in From headers. */ public Address getOurSipAddress(Address intendedDestination) { return getOurSipAddress((SipURI)intendedDestination.getURI()); } /** * Returns the SIP address of record (Display Name <user@server.net>) that * this account is created for. The method takes into account whether or * not we are running in Registar or "No Registar" mode and either returns * the AOR we are using to register or an address constructed using the * local address * * @param intendedDestination the destination that we would be using the * local address to communicate with. * . * @return our Address Of Record that we should use in From headers. */ public Address getOurSipAddress(SipURI intendedDestination) { SipRegistrarConnection src = sipRegistrarConnection; if (src != null && !src.isRegistrarless()) return src.getAddressOfRecord(); //we are apparently running in "No Registrar" mode so let's create an //address by ourselves. InetSocketAddress destinationAddr = getIntendedDestination(intendedDestination); InetAddress localHost = SipActivator.getNetworkAddressManagerService() .getLocalHost(destinationAddr.getAddress()); String userID = getAccountID().getUserID(); try { SipURI ourSipURI = getAddressFactory() .createSipURI(userID, localHost.getHostAddress()); ListeningPoint lp = getListeningPoint(intendedDestination); ourSipURI.setTransportParam(lp.getTransport()); ourSipURI.setPort(lp.getPort()); Address ourSipAddress = getAddressFactory() .createAddress(getOurDisplayName(), ourSipURI); ourSipAddress.setDisplayName(getOurDisplayName()); return ourSipAddress; } catch (ParseException exc) { if (logger.isTraceEnabled()) logger.trace("Failed to create our SIP AOR address", exc); // this should never happen since we are using InetAddresses // everywhere so parsing could hardly go wrong. throw new IllegalArgumentException( "Failed to create our SIP AOR address" , exc); } } public ProxyConnection getConnection() { return connection; } /** * Indicates if the SIP transport channel is using a TLS secured socket. * * @return True when TLS is used the SIP transport protocol, false * otherwise or when no proxy is being used. */ public boolean isSignalingTransportSecure() { return ListeningPoint.TLS.equalsIgnoreCase(connection.getTransport()); } /** * Registers <tt>methodProcessor</tt> in the <tt>methorProcessors</tt> table * so that it would receives all messages in a transaction initiated by a * <tt>method</tt> request. If any previous processors exist for the same * method, they will be replaced by this one. * * @param method a String representing the SIP method that we're registering * the processor for (e.g. INVITE, REGISTER, or SUBSCRIBE). * @param methodProcessor a <tt>MethodProcessor</tt> implementation that * would handle all messages received within a <tt>method</tt> * transaction. */ public void registerMethodProcessor(String method, MethodProcessor methodProcessor) { List<MethodProcessor> processors = methodProcessors.get(method); if (processors == null) { processors = new LinkedList<MethodProcessor>(); methodProcessors.put(method, processors); } else { /* * Prevent the registering of multiple instances of one and the same * OperationSet class and take only the latest registration into * account. */ Iterator<MethodProcessor> processorIter = processors.iterator(); Class<? extends MethodProcessor> methodProcessorClass = methodProcessor.getClass(); /* * EventPackageSupport and its extenders provide a generic mechanizm * for building support for a specific event package so allow them * to register multiple instances of one and the same class as long * as they are handling different event packages. */ String eventPackage = (methodProcessor instanceof EventPackageSupport) ? ((EventPackageSupport) methodProcessor).getEventPackage() : null; while (processorIter.hasNext()) { MethodProcessor processor = processorIter.next(); if (!processor.getClass().equals(methodProcessorClass)) continue; if ((eventPackage != null) && (processor instanceof EventPackageSupport) && !eventPackage .equals( ((EventPackageSupport) processor) .getEventPackage())) continue; processorIter.remove(); } } processors.add(methodProcessor); } /** * Unregisters <tt>methodProcessor</tt> from the <tt>methorProcessors</tt> * table so that it won't receive further messages in a transaction * initiated by a <tt>method</tt> request. * * @param method the name of the method whose processor we'd like to * unregister. * @param methodProcessor the <tt>MethodProcessor</tt> that we'd like to * unregister. */ public void unregisterMethodProcessor(String method, MethodProcessor methodProcessor) { List<MethodProcessor> processors = methodProcessors.get(method); if ((processors != null) && processors.remove(methodProcessor) && (processors.size() <= 0)) { methodProcessors.remove(method); } } /** * Returns the transport that we should use if we have no clear idea of our * destination's preferred transport. The method would first check if * we are running behind an outbound proxy and if so return its transport. * If no outbound proxy is set, the method would check the contents of the * DEFAULT_TRANSPORT property and return it if not null. Otherwise the * method would return UDP; * * @return The first non null password of the following: * a) the transport we use to communicate with our registrar * b) the transport of our outbound proxy, * c) the transport specified by the DEFAULT_TRANSPORT property, UDP. */ public String getDefaultTransport() { if(sipRegistrarConnection != null && !sipRegistrarConnection.isRegistrarless() && connection != null && connection.getAddress() != null && connection.getTransport() != null) { return connection.getTransport(); } else { String userSpecifiedDefaultTransport = SipActivator.getConfigurationService() .getString(DEFAULT_TRANSPORT); if(userSpecifiedDefaultTransport != null) { return userSpecifiedDefaultTransport; } else { String defTransportDefaultValue = SipActivator.getResources() .getSettingsString(DEFAULT_TRANSPORT); if(!StringUtils.isNullOrEmpty(defTransportDefaultValue)) return defTransportDefaultValue; else return ListeningPoint.UDP; } } } /** * Returns the provider that corresponds to the transport returned by * getDefaultTransport(). Equivalent to calling * getJainSipProvider(getDefaultTransport()) * * @return the Jain SipProvider that corresponds to the transport returned * by getDefaultTransport(). */ public SipProvider getDefaultJainSipProvider() { return getJainSipProvider(getDefaultTransport()); } /** * Returns the display name string that the user has set as a display name * for this account. * * @return the display name string that the user has set as a display name * for this account. */ public String getOurDisplayName() { return ourDisplayName; } /** * Changes the display name string. * * @return whether we have successfully changed the display name. */ boolean setOurDisplayName(String newDisplayName) { // if we really want to change the display name // and it is existing, change it. if(newDisplayName != null && !ourDisplayName.equals(newDisplayName)) { getAccountID().putAccountProperty( ProtocolProviderFactory.DISPLAY_NAME, newDisplayName); ourDisplayName = newDisplayName; OperationSetServerStoredAccountInfoSipImpl accountInfoOpSet = (OperationSetServerStoredAccountInfoSipImpl)getOperationSet( OperationSetServerStoredAccountInfo.class); if(accountInfoOpSet != null) accountInfoOpSet.setOurDisplayName(newDisplayName); return true; } return false; } /** * Returns a User Agent header that could be used for signing our requests. * * @return a <tt>UserAgentHeader</tt> that could be used for signing our * requests. */ public UserAgentHeader getSipCommUserAgentHeader() { if(userAgentHeader == null) { try { List<String> userAgentTokens = new LinkedList<String>(); Version ver = SipActivator.getVersionService().getCurrentVersion(); userAgentTokens.add(ver.getApplicationName()); userAgentTokens.add(ver.toString()); String osName = System.getProperty("os.name"); userAgentTokens.add(osName); userAgentHeader = this.headerFactory.createUserAgentHeader(userAgentTokens); } catch (ParseException ex) { //shouldn't happen return null; } } return userAgentHeader; } /** * Send an error response with the <tt>errorCode</tt> code using * <tt>serverTransaction</tt> and do not surface exceptions. The method * is useful when we are sending the error response in a stack initiated * operation and don't have the possibility to escalate potential * exceptions, so we can only log them. * * @param serverTransaction the transaction that we'd like to send an error * response in. * @param errorCode the code that the response should have. */ public void sayErrorSilently(ServerTransaction serverTransaction, int errorCode) { try { sayError(serverTransaction, errorCode); } catch (OperationFailedException exc) { if (logger.isDebugEnabled()) logger.debug("Failed to send an error " + errorCode + " response", exc); } } /** * Sends an ACK request in the specified dialog. * * @param clientTransaction the transaction that resulted in the ACK we are * about to send (MUST be an INVITE transaction). * * @throws InvalidArgumentException if there is a problem with the supplied * CSeq ( for example <= 0 ). * @throws SipException if the CSeq does not relate to a previously sent * INVITE or if the Method that created the Dialog is not an INVITE ( for * example SUBSCRIBE) or if we fail to send the INVITE for whatever reason. */ public void sendAck(ClientTransaction clientTransaction) throws SipException, InvalidArgumentException { Request ack = messageFactory.createAck(clientTransaction); clientTransaction.getDialog().sendAck(ack); } /** * Send an error response with the <tt>errorCode</tt> code using * <tt>serverTransaction</tt>. * * @param serverTransaction the transaction that we'd like to send an error * response in. * @param errorCode the code that the response should have. * * @throws OperationFailedException if we failed constructing or sending a * SIP Message. */ public void sayError(ServerTransaction serverTransaction, int errorCode) throws OperationFailedException { Request request = serverTransaction.getRequest(); Response errorResponse = null; try { errorResponse = getMessageFactory().createResponse( errorCode, request); //we used to be adding a To tag here and we shouldn't. 3261 says: //"Dialogs are created through [...] non-failure responses". and //we are using this method for failure responses only. } catch (ParseException ex) { ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to construct an OK response to an INVITE request", OperationFailedException.INTERNAL_ERROR, ex, logger); } try { serverTransaction.sendResponse(errorResponse); if (logger.isDebugEnabled()) logger.debug("sent response: " + errorResponse); } catch (Exception ex) { ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to send an OK response to an INVITE request", OperationFailedException.INTERNAL_ERROR, ex, logger); } } /** * Sends a specific <tt>Request</tt> through a given * <tt>SipProvider</tt> as part of the conversation associated with a * specific <tt>Dialog</tt>. * * @param sipProvider the <tt>SipProvider</tt> to send the specified * request through * @param request the <tt>Request</tt> to send through * <tt>sipProvider</tt> * @param dialog the <tt>Dialog</tt> as part of which the specified * <tt>request</tt> is to be sent * * @throws OperationFailedException if creating a transaction or sending * the <tt>request</tt> fails. */ public void sendInDialogRequest(SipProvider sipProvider, Request request, Dialog dialog) throws OperationFailedException { ClientTransaction clientTransaction = null; try { clientTransaction = sipProvider.getNewClientTransaction(request); } catch (TransactionUnavailableException ex) { ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to create a client transaction for request:\n" + request, OperationFailedException.INTERNAL_ERROR, ex, logger); } try { dialog.sendRequest(clientTransaction); } catch (SipException ex) { ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to send request:\n" + request, OperationFailedException.NETWORK_FAILURE, ex, logger); } if (logger.isDebugEnabled()) logger.debug("Sent request:\n" + request); } /** * Returns a List of Strings corresponding to all methods that we have a * processor for. * * @return a List of methods that we support. */ public List<String> getSupportedMethods() { return new ArrayList<String>(methodProcessors.keySet()); } /** * A utility class that allows us to block until we receive a * <tt>RegistrationStateChangeEvent</tt> notifying us of an unregistration. */ private static class ShutdownUnregistrationBlockListener implements RegistrationStateChangeListener { /** * The list where we store <tt>RegistationState</tt>s received while * waiting. */ public List<RegistrationState> collectedNewStates = new LinkedList<RegistrationState>(); /** * The method would simply register all received events so that they * could be available for later inspection by the unit tests. In the * case where a registration event notifying us of a completed * registration is seen, the method would call notifyAll(). * * @param evt ProviderStatusChangeEvent the event describing the * status change. */ public void registrationStateChanged(RegistrationStateChangeEvent evt) { if (logger.isDebugEnabled()) logger.debug("Received a RegistrationStateChangeEvent: " + evt); collectedNewStates.add(evt.getNewState()); if (evt.getNewState().equals(RegistrationState.UNREGISTERED)) { if (logger.isDebugEnabled()) logger.debug( "We're unregistered and will notify those who wait"); synchronized (this) { notifyAll(); } } } /** * Blocks until an event notifying us of the awaited state change is * received or until waitFor milliseconds pass (whichever happens first). * * @param waitFor the number of milliseconds that we should be waiting * for an event before simply bailing out. */ public void waitForEvent(long waitFor) { if (logger.isTraceEnabled()) logger.trace("Waiting for a " +"RegistrationStateChangeEvent.UNREGISTERED"); synchronized (this) { if (collectedNewStates.contains( RegistrationState.UNREGISTERED)) { if (logger.isTraceEnabled()) logger.trace("Event already received. " + collectedNewStates); return; } try { wait(waitFor); if (collectedNewStates.size() > 0) if (logger.isTraceEnabled()) logger.trace( "Received a RegistrationStateChangeEvent."); else if (logger.isTraceEnabled()) logger.trace( "No RegistrationStateChangeEvent received for " + waitFor + "ms."); } catch (InterruptedException ex) { if (logger.isDebugEnabled()) logger.debug( "Interrupted while waiting for a " +"RegistrationStateChangeEvent" , ex); } } } } /** * Returns the sip protocol icon. * @return the sip protocol icon */ public ProtocolIcon getProtocolIcon() { return protocolIcon; } /** * Returns the current instance of <tt>SipStatusEnum</tt>. * * @return the current instance of <tt>SipStatusEnum</tt>. */ SipStatusEnum getSipStatusEnum() { return sipStatusEnum; } /** * Returns the current instance of <tt>SipRegistrarConnection</tt>. * @return SipRegistrarConnection */ SipRegistrarConnection getRegistrarConnection() { return sipRegistrarConnection; } /** * Parses the the <tt>uriStr</tt> string and returns a JAIN SIP URI. * * @param uriStr a <tt>String</tt> containing the uri to parse. * * @return a URI object corresponding to the <tt>uriStr</tt> string. * @throws ParseException if uriStr is not properly formatted. */ public Address parseAddressString(String uriStr) throws ParseException { uriStr = uriStr.trim(); //we don't know how to handle the "tel:" scheme ... or rather we handle //it same as sip so replace: if(uriStr.toLowerCase().startsWith("tel:")) uriStr = "sip:" + uriStr.substring("tel:".length()); //Handle default domain name (i.e. transform 1234 -> 1234@sip.com) //assuming that if no domain name is specified then it should be the //same as ours. if (uriStr.indexOf('@') == -1) { //if we have a registrar, then we could append its domain name as //default SipRegistrarConnection src = sipRegistrarConnection; if(src != null && !src.isRegistrarless() ) { uriStr = uriStr + "@" + ((SipURI)src.getAddressOfRecord().getURI()).getHost(); } //else this could only be a host ... but this should work as is. } //Let's be uri fault tolerant and add the sip: scheme if there is none. if (!uriStr.toLowerCase().startsWith("sip:")) //no sip scheme { uriStr = "sip:" + uriStr; } Address toAddress = getAddressFactory().createAddress(uriStr); return toAddress; } public InetSocketAddress getIntendedDestination(Address destination) throws IllegalArgumentException { return getIntendedDestination((SipURI)destination.getURI()); } public InetSocketAddress getIntendedDestination(SipURI destination) throws IllegalArgumentException { return getIntendedDestination(destination.getHost()); } public InetSocketAddress getIntendedDestination(String host) throws IllegalArgumentException { // Address InetSocketAddress destinationInetAddress = null; //resolveSipAddress() verifies whether our destination is valid //but the destination could only be known to our outbound proxy //if we have one. If this is the case replace the destination //address with that of the proxy.(report by Dan Bogos) InetSocketAddress outboundProxy = connection.getAddress(); if(outboundProxy != null) { if (logger.isTraceEnabled()) logger.trace("Will use proxy address"); destinationInetAddress = outboundProxy; } else { ProxyConnection tempConn = new AutoProxyConnection( (SipAccountID)getAccountID(), host, getDefaultTransport()); try { if(tempConn.getNextAddress()) destinationInetAddress = tempConn.getAddress(); else throw new IllegalArgumentException(host + " could not be resolved to an internet address."); } catch (DnssecException e) { logger.error("unable to obtain next hop address", e); } } if(logger.isDebugEnabled()) logger.debug("Returning address " + destinationInetAddress + " for destination " + host); return destinationInetAddress; } /** * Stops dispatching SIP messages to a SIP protocol provider service * once it's been unregistered. * * @param event the change event in the registration state of a provider. */ public void registrationStateChanged(RegistrationStateChangeEvent event) { if(event.getNewState() == RegistrationState.UNREGISTERED || event.getNewState() == RegistrationState.CONNECTION_FAILED) { ProtocolProviderServiceSipImpl listener = (ProtocolProviderServiceSipImpl) event.getProvider(); sipStackSharing.removeSipListener(listener); listener.removeRegistrationStateChangeListener(this); } } /** * Logs a specific message and associated <tt>Throwable</tt> cause as an * error using the current <tt>Logger</tt> and then throws a new * <tt>OperationFailedException</tt> with the message, a specific error code * and the cause. * * @param message the message to be logged and then wrapped in a new * <tt>OperationFailedException</tt> * @param errorCode the error code to be assigned to the new * <tt>OperationFailedException</tt> * @param cause the <tt>Throwable</tt> that has caused the necessity to log * an error and have a new <tt>OperationFailedException</tt> thrown * @param logger the logger that we'd like to log the error <tt>message</tt> * and <tt>cause</tt>. * * @throws OperationFailedException the exception that we wanted this method * to throw. */ public static void throwOperationFailedException( String message, int errorCode, Throwable cause, Logger logger) throws OperationFailedException { logger.error(message, cause); if(cause == null) throw new OperationFailedException(message, errorCode); else throw new OperationFailedException(message, errorCode, cause); } /** * Registers early message processor. * @param processor early message processor. */ void addEarlyMessageProcessor(SipMessageProcessor processor) { synchronized (earlyProcessors) { if (!earlyProcessors.contains(processor)) { this.earlyProcessors.add(processor); } } } /** * Removes the early message processor. * @param processor early message processor. */ void removeEarlyMessageProcessor(SipMessageProcessor processor) { synchronized (earlyProcessors) { this.earlyProcessors.remove(processor); } } /** * Early process an incoming message from interested listeners. * @param message the message to process. */ void earlyProcessMessage(EventObject message) { synchronized(earlyProcessors) { for (SipMessageProcessor listener : earlyProcessors) { try { if(message instanceof RequestEvent) listener.processMessage((RequestEvent)message); else if(message instanceof ResponseEvent) listener.processResponse((ResponseEvent)message, null); else if(message instanceof TimeoutEvent) listener.processTimeout((TimeoutEvent)message, null); } catch(Throwable t) { logger.error("Error pre-processing message", t); } } } } /** * Finds the next address to retry registering. If doesn't process anything * (we have already tried the last one) return false. * * @return <tt>true</tt> if we triggered new register with next address. */ boolean registerUsingNextAddress() { if(connection == null) return false; try { if(sipRegistrarConnection.isRegistrarless()) { sipRegistrarConnection.setTransport(getDefaultTransport()); sipRegistrarConnection.register(); return true; } else if(connection.getNextAddress()) { sipRegistrarConnection.setTransport(connection.getTransport()); sipRegistrarConnection.register(); return true; } } catch (DnssecException e) { logger.error("DNSSEC failure while getting address for " + this, e); fireRegistrationStateChanged( RegistrationState.REGISTERING, RegistrationState.UNREGISTERED, RegistrationStateChangeEvent.REASON_USER_REQUEST, "Invalid or inaccessible server address."); return true; } catch (Throwable e) { logger.error("Cannot send register!", e); sipRegistrarConnection.setRegistrationState( RegistrationState.CONNECTION_FAILED, RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, "A timeout occurred while trying to connect to the server."); } // as we reached the last address lets change it to the first one // so we don't get stuck to the last one forever, and the next time // use again the first one connection.reset(); return false; } /** * If somewhere we got for example timeout of receiving answer to our * requests we consider problem with network and notify the provider. */ protected void notifyConnectionFailed() { if(getRegistrationState().equals(RegistrationState.REGISTERED) && sipRegistrarConnection != null) sipRegistrarConnection.setRegistrationState( RegistrationState.CONNECTION_FAILED, RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, "A timeout occurred while trying to connect to the server."); if(registerUsingNextAddress()) return; // don't alert the user if we're already off if (!getRegistrationState().equals(RegistrationState.UNREGISTERED)) { sipRegistrarConnection.setRegistrationState( RegistrationState.CONNECTION_FAILED, RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, "A timeout occurred while trying to connect to the server."); } } /** * Determines whether the supplied transport is a known SIP transport method * * @param transport the SIP transport to check * @return True when transport is one of UDP, TCP or TLS. */ public static boolean isValidTransport(String transport) { return ListeningPoint.UDP.equalsIgnoreCase(transport) || ListeningPoint.TLS.equalsIgnoreCase(transport) || ListeningPoint.TCP.equalsIgnoreCase(transport); } }
package org.mtransit.parser.ca_gtha_go_transit_train; import java.util.HashSet; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.Utils; import org.mtransit.parser.gtfs.data.GCalendar; import org.mtransit.parser.gtfs.data.GCalendarDate; import org.mtransit.parser.gtfs.data.GRoute; import org.mtransit.parser.gtfs.data.GSpec; import org.mtransit.parser.gtfs.data.GStop; import org.mtransit.parser.gtfs.data.GTrip; import org.mtransit.parser.mt.data.MAgency; import org.mtransit.parser.mt.data.MRoute; import org.mtransit.parser.CleanUtils; import org.mtransit.parser.mt.data.MTrip; import org.mtransit.parser.mt.data.MTripStop; public class GTHAGOTransitTrainAgencyTools extends DefaultAgencyTools { public static void main(String[] args) { if (args == null || args.length == 0) { args = new String[3]; args[0] = "input/gtfs.zip"; args[1] = "../../mtransitapps/ca-gtha-go-transit-train-android/res/raw/"; args[2] = ""; // files-prefix } new GTHAGOTransitTrainAgencyTools().start(args); } private HashSet<String> serviceIds; @Override public void start(String[] args) { System.out.printf("\nGenerating GO Transit train data...\n"); long start = System.currentTimeMillis(); this.serviceIds = extractUsefulServiceIds(args, this); super.start(args); System.out.printf("\nGenerating GO Transit train data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start)); } @Override public boolean excludeCalendar(GCalendar gCalendar) { if (this.serviceIds != null) { return excludeUselessCalendar(gCalendar, this.serviceIds); } return super.excludeCalendar(gCalendar); } @Override public boolean excludeCalendarDate(GCalendarDate gCalendarDates) { if (this.serviceIds != null) { return excludeUselessCalendarDate(gCalendarDates, this.serviceIds); } return super.excludeCalendarDate(gCalendarDates); } @Override public boolean excludeTrip(GTrip gTrip) { if (this.serviceIds != null) { return excludeUselessTrip(gTrip, this.serviceIds); } return super.excludeTrip(gTrip); } @Override public Integer getAgencyRouteType() { return MAgency.ROUTE_TYPE_TRAIN; } private static final Pattern DIGITS = Pattern.compile("[\\d]+"); private static final long LW_RID = 1l; // Lakeshore West private static final long MI_RID = 2l; // Milton private static final long GT_RID = 3l; // Kitchener private static final long BR_RID = 5l; // Barrie private static final long RH_RID = 6l; // Richmond Hill private static final long ST_RID = 7l; // Stouffville private static final long LE_RID = 9l; // Lakeshore East @Override public long getRouteId(GRoute gRoute) { if (ST_RSN.equals(gRoute.route_short_name)) { return ST_RID; } else if (RH_RSN.equals(gRoute.route_short_name)) { return RH_RID; } else if (MI_RSN.equals(gRoute.route_short_name)) { return MI_RID; } else if (LW_RSN.equals(gRoute.route_short_name)) { return LW_RID; } else if (LE_RSN.equals(gRoute.route_short_name)) { return LE_RID; } else if (GT_RSN.equals(gRoute.route_short_name)) { return GT_RID; } else if (BR_RSN.equals(gRoute.route_short_name)) { return BR_RID; } else { System.out.println("Unexpected route ID " + gRoute); System.exit(-1); return -1l; } } @Override public String getRouteLongName(GRoute gRoute) { String routeLongName = gRoute.route_long_name; routeLongName = CleanUtils.cleanStreetTypes(routeLongName); return CleanUtils.cleanLabel(routeLongName); } private static final String ST_RSN = "ST"; // Stouffville private static final String RH_RSN = "RH"; // Richmond Hill private static final String MI_RSN = "MI"; // Milton private static final String LW_RSN = "LW"; // Lakeshore West private static final String LE_RSN = "LE"; // Lakeshore East private static final String GT_RSN = "GT"; // Kitchener private static final String BR_RSN = "BR"; // Barrie private static final String AGENCY_COLOR = "387C2B"; // GREEN (AGENCY WEB SITE CSS) @Override public String getAgencyColor() { return AGENCY_COLOR; } private static final String COLOR_BC6277 = "BC6277"; private static final String COLOR_F46F1A = "F46F1A"; private static final String COLOR_098137 = "098137"; private static final String COLOR_0B335E = "0B335E"; private static final String COLOR_0098C9 = "0098C9"; private static final String COLOR_713907 = "713907"; private static final String COLOR_96092B = "96092B"; private static final String COLOR_EE3124 = "EE3124"; @Override public String getRouteColor(GRoute gRoute) { if (StringUtils.isEmpty(gRoute.route_color)) { Matcher matcher = DIGITS.matcher(gRoute.route_id); matcher.find(); int routeId = Integer.parseInt(matcher.group()); switch (routeId) { // @formatter:off case 1: return COLOR_96092B; // Lakeshore West case 2: return COLOR_F46F1A; // Milton case 3: return COLOR_098137; // Kitchener case 5: return COLOR_0B335E; // Barrie case 6: return COLOR_0098C9; // Richmond Hill case 7: return COLOR_713907; // Stouffville case 8: return COLOR_BC6277; // Niagara Falls case 9: return COLOR_EE3124; // Lakeshore East // @formatter:on default: System.out.println("getRouteColor() > Unexpected route ID color '" + routeId + "' (" + gRoute + ")"); System.exit(-1); return null; } } return super.getRouteColor(gRoute); } @Override public int compare(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) { if (routeId == LW_RID) { if (ts1.getTripId() == 101) { if (SID_EX.equals(ts1GStop.stop_id) && SID_UN.equals(ts2GStop.stop_id)) { return +1; } } } System.out.printf("\n%s: Unexpected compare early route!\n", routeId); System.exit(-1); return -1; } private static final String STOUFFVILLE = "Stouffville"; private static final String BARRIE = "Barrie"; private static final String KITCHENER = "Kitchener"; private static final String UNION = "Union"; private static final String EAST = "East"; private static final String WEST = "West"; @Override public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) { if (mRoute.id == LW_RID) { // Lakeshore West if (gTrip.direction_id == 0) { mTrip.setHeadsignString(UNION, gTrip.direction_id); return; } else if (gTrip.direction_id == 1) { mTrip.setHeadsignString(WEST, gTrip.direction_id); return; } } else if (mRoute.id == GT_RID) { // Kitchener if (gTrip.direction_id == 1) { mTrip.setHeadsignString(KITCHENER, gTrip.direction_id); return; } } else if (mRoute.id == BR_RID) { // Barrie if (gTrip.direction_id == 1) { mTrip.setHeadsignString(BARRIE, gTrip.direction_id); return; } } else if (mRoute.id == ST_RID) { // Stouffville if (gTrip.direction_id == 0) { mTrip.setHeadsignString(STOUFFVILLE, gTrip.direction_id); return; } } else if (mRoute.id == LE_RID) { // Lakeshore East if (gTrip.direction_id == 0) { mTrip.setHeadsignString(EAST, gTrip.direction_id); return; } } mTrip.setHeadsignString(cleanTripHeadsign(gTrip.trip_headsign), gTrip.direction_id); } private static final Pattern START_WITH_RSN = Pattern.compile("(^[A-Z]{2}\\-)", Pattern.CASE_INSENSITIVE); @Override public String cleanTripHeadsign(String tripHeadsign) { tripHeadsign = START_WITH_RSN.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY); tripHeadsign = GO.matcher(tripHeadsign).replaceAll(GO_REPLACEMENT); tripHeadsign = STATION.matcher(tripHeadsign).replaceAll(STATION_REPLACEMENT); tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign); return CleanUtils.cleanLabel(tripHeadsign); } private static final Pattern AT = Pattern.compile("( at )", Pattern.CASE_INSENSITIVE); private static final String AT_REPLACEMENT = " / "; private static final Pattern GO = Pattern.compile("(^|\\s){1}(go)($|\\s){1}", Pattern.CASE_INSENSITIVE); private static final String GO_REPLACEMENT = " "; private static final Pattern VIA = Pattern.compile("(^|\\s){1}(via)($|\\s){1}", Pattern.CASE_INSENSITIVE); private static final String VIA_REPLACEMENT = " "; private static final Pattern RAIL = Pattern.compile("(^|\\s){1}(rail)($|\\s){1}", Pattern.CASE_INSENSITIVE); private static final String RAIL_REPLACEMENT = " "; private static final Pattern STATION = Pattern.compile("(^|\\s){1}(station)($|\\s){1}", Pattern.CASE_INSENSITIVE); private static final String STATION_REPLACEMENT = " "; @Override public String cleanStopName(String gStopName) { gStopName = AT.matcher(gStopName).replaceAll(AT_REPLACEMENT); gStopName = VIA.matcher(gStopName).replaceAll(VIA_REPLACEMENT); gStopName = GO.matcher(gStopName).replaceAll(GO_REPLACEMENT); gStopName = RAIL.matcher(gStopName).replaceAll(RAIL_REPLACEMENT); gStopName = STATION.matcher(gStopName).replaceAll(STATION_REPLACEMENT); gStopName = CleanUtils.cleanNumbers(gStopName); gStopName = CleanUtils.cleanStreetTypes(gStopName); return CleanUtils.cleanLabel(gStopName); } private static final String SID_UN = "UN"; private static final int UN_SID = 9021; private static final String SID_EX = "EX"; private static final int EX_SID = 9022; private static final String SID_MI = "MI"; private static final int MI_SID = 9031; private static final String SID_LO = "LO"; private static final int LO_SID = 9033; private static final String SID_DA = "DA"; private static final int DA_SID = 9061; private static final String SID_SC = "SC"; private static final int SC_SID = 9062; private static final String SID_EG = "EG"; private static final int EG_SID = 9063; private static final String SID_GU = "GU"; private static final int GU_SID = 9081; private static final String SID_RO = "RO"; private static final int RO_SID = 9091; private static final String SID_PO = "PO"; private static final int PO_SID = 9111; private static final String SID_CL = "CL"; private static final int CL_SID = 9121; private static final String SID_OA = "OA"; private static final int OA_SID = 9131; private static final String SID_BO = "BO"; private static final int BO_SID = 9141; private static final String SID_AP = "AP"; private static final int AP_SID = 9151; private static final String SID_BU = "BU"; private static final int BU_SID = 9161; private static final String SID_AL = "AL"; private static final int AL_SID = 9171; private static final String SID_PIN = "PIN"; private static final int PIN_SID = 9911; private static final String SID_AJ = "AJ"; private static final int AJ_SID = 9921; private static final String SID_WH = "WH"; private static final int WH_SID = 9939; private static final String SID_OS = "OS"; private static final int OS_SID = 9941; private static final String SID_BL = "BL"; private static final int BL_SID = 9023; private static final String SID_KP = "KP"; private static final int KP_SID = 9032; private static final String SID_WE = "WE"; private static final int WE_SID = 9041; private static final String SID_ET = "ET"; private static final int ET_SID = 9042; private static final String SID_OR = "OR"; private static final int OR_SID = 9051; private static final String SID_OL = "OL"; private static final int OL_SID = 9052; private static final String SID_AG = "AG"; private static final int AG_SID = 9071; private static final String SID_DI = "DI"; private static final int DI_SID = 9113; private static final String SID_CO = "CO"; private static final int CO_SID = 9114; private static final String SID_ER = "ER"; private static final int ER_SID = 9123; private static final String SID_HA = "HA"; private static final int HA_SID = 9181; private static final String SID_YO = "YO"; private static final int YO_SID = 9191; private static final String SID_SR = "SR"; private static final int SR_SID = 9211; private static final String SID_ME = "ME"; private static final int ME_SID = 9221; private static final String SID_LS = "LS"; private static final int LS_SID = 9231; private static final String SID_ML = "ML"; private static final int ML_SID = 9241; private static final String SID_KI = "KI"; private static final int KI_SID = 9271; private static final String SID_MA = "MA"; private static final int MA_SID = 9311; private static final String SID_BE = "BE"; private static final int BE_SID = 9321; private static final String SID_BR = "BR"; private static final int BR_SID = 9331; private static final String SID_MO = "MO"; private static final int MO_SID = 9341; private static final String SID_GE = "GE"; private static final int GE_SID = 9351; private static final String SID_AC = "AC"; private static final int AC_SID = 9371; private static final String SID_GL = "GL"; private static final int GL_SID = 9391; private static final String SID_EA = "EA"; private static final int EA_SID = 9441; private static final String SID_LA = "LA"; private static final int LA_SID = 9601; private static final String SID_RI = "RI"; private static final int RI_SID = 9612; private static final String SID_MP = "MP"; private static final int MP_SID = 9613; private static final String SID_RU = "RU"; private static final int RU_SID = 9614; private static final String SID_KC = "KC"; private static final int KC_SID = 9621; private static final String SID_AU = "AU"; private static final int AU_SID = 9631; private static final String SID_NE = "NE"; private static final int NE_SID = 9641; private static final String SID_BD = "BD"; private static final int BD_SID = 9651; private static final String SID_BA = "BA"; private static final int BA_SID = 9681; private static final String SID_AD = "AD"; private static final int AD_SID = 9691; private static final String SID_MK = "MK"; private static final int MK_SID = 9701; private static final String SID_UI = "UI"; private static final int UI_SID = 9712; private static final String SID_MR = "MR"; private static final int MR_SID = 9721; private static final String SID_CE = "CE"; private static final int CE_SID = 9722; private static final String SID_MJ = "MJ"; private static final int MJ_SID = 9731; private static final String SID_ST = "ST"; private static final int ST_SID = 9741; private static final String SID_LI = "LI"; private static final int LI_SID = 9742; private static final String SID_KE = "KE"; private static final int KE_SID = 9771; private static final String SID_JAMES_STR = "JAMES STR"; private static final int JAMES_STR_SID = 100001; private static final String SID_USBT = "USBT"; private static final int USBT_SID = 100002; private static final String SID_NI = "NI"; private static final int NI_SID = 100003; private static final String SID_PA = "PA"; private static final int PA_SID = 100004; private static final String SID_SCTH = "SCTH"; private static final int SCTH_SID = 100005; @Override public int getStopId(GStop gStop) { if (!Utils.isDigitsOnly(gStop.stop_id)) { if (SID_UN.equals(gStop.stop_id)) { return UN_SID; } else if (SID_EX.equals(gStop.stop_id)) { return EX_SID; } else if (SID_MI.equals(gStop.stop_id)) { return MI_SID; } else if (SID_LO.equals(gStop.stop_id)) { return LO_SID; } else if (SID_DA.equals(gStop.stop_id)) { return DA_SID; } else if (SID_SC.equals(gStop.stop_id)) { return SC_SID; } else if (SID_EG.equals(gStop.stop_id)) { return EG_SID; } else if (SID_GU.equals(gStop.stop_id)) { return GU_SID; } else if (SID_RO.equals(gStop.stop_id)) { return RO_SID; } else if (SID_PO.equals(gStop.stop_id)) { return PO_SID; } else if (SID_CL.equals(gStop.stop_id)) { return CL_SID; } else if (SID_OA.equals(gStop.stop_id)) { return OA_SID; } else if (SID_BO.equals(gStop.stop_id)) { return BO_SID; } else if (SID_AP.equals(gStop.stop_id)) { return AP_SID; } else if (SID_BU.equals(gStop.stop_id)) { return BU_SID; } else if (SID_AL.equals(gStop.stop_id)) { return AL_SID; } else if (SID_PIN.equals(gStop.stop_id)) { return PIN_SID; } else if (SID_AJ.equals(gStop.stop_id)) { return AJ_SID; } else if (SID_WH.equals(gStop.stop_id)) { return WH_SID; } else if (SID_OS.equals(gStop.stop_id)) { return OS_SID; } else if (SID_BL.equals(gStop.stop_id)) { return BL_SID; } else if (SID_KP.equals(gStop.stop_id)) { return KP_SID; } else if (SID_WE.equals(gStop.stop_id)) { return WE_SID; } else if (SID_ET.equals(gStop.stop_id)) { return ET_SID; } else if (SID_OR.equals(gStop.stop_id)) { return OR_SID; } else if (SID_OL.equals(gStop.stop_id)) { return OL_SID; } else if (SID_AG.equals(gStop.stop_id)) { return AG_SID; } else if (SID_DI.equals(gStop.stop_id)) { return DI_SID; } else if (SID_CO.equals(gStop.stop_id)) { return CO_SID; } else if (SID_ER.equals(gStop.stop_id)) { return ER_SID; } else if (SID_HA.equals(gStop.stop_id)) { return HA_SID; } else if (SID_YO.equals(gStop.stop_id)) { return YO_SID; } else if (SID_SR.equals(gStop.stop_id)) { return SR_SID; } else if (SID_ME.equals(gStop.stop_id)) { return ME_SID; } else if (SID_LS.equals(gStop.stop_id)) { return LS_SID; } else if (SID_ML.equals(gStop.stop_id)) { return ML_SID; } else if (SID_KI.equals(gStop.stop_id)) { return KI_SID; } else if (SID_MA.equals(gStop.stop_id)) { return MA_SID; } else if (SID_BE.equals(gStop.stop_id)) { return BE_SID; } else if (SID_BR.equals(gStop.stop_id)) { return BR_SID; } else if (SID_MO.equals(gStop.stop_id)) { return MO_SID; } else if (SID_GE.equals(gStop.stop_id)) { return GE_SID; } else if (SID_AC.equals(gStop.stop_id)) { return AC_SID; } else if (SID_GL.equals(gStop.stop_id)) { return GL_SID; } else if (SID_EA.equals(gStop.stop_id)) { return EA_SID; } else if (SID_LA.equals(gStop.stop_id)) { return LA_SID; } else if (SID_RI.equals(gStop.stop_id)) { return RI_SID; } else if (SID_MP.equals(gStop.stop_id)) { return MP_SID; } else if (SID_RU.equals(gStop.stop_id)) { return RU_SID; } else if (SID_KC.equals(gStop.stop_id)) { return KC_SID; } else if (SID_AU.equals(gStop.stop_id)) { return AU_SID; } else if (SID_NE.equals(gStop.stop_id)) { return NE_SID; } else if (SID_BD.equals(gStop.stop_id)) { return BD_SID; } else if (SID_BA.equals(gStop.stop_id)) { return BA_SID; } else if (SID_AD.equals(gStop.stop_id)) { return AD_SID; } else if (SID_MK.equals(gStop.stop_id)) { return MK_SID; } else if (SID_UI.equals(gStop.stop_id)) { return UI_SID; } else if (SID_MR.equals(gStop.stop_id)) { return MR_SID; } else if (SID_CE.equals(gStop.stop_id)) { return CE_SID; } else if (SID_MJ.equals(gStop.stop_id)) { return MJ_SID; } else if (SID_ST.equals(gStop.stop_id)) { return ST_SID; } else if (SID_LI.equals(gStop.stop_id)) { return LI_SID; } else if (SID_KE.equals(gStop.stop_id)) { return KE_SID; } else if (SID_JAMES_STR.equals(gStop.stop_id)) { return JAMES_STR_SID; } else if (SID_USBT.equals(gStop.stop_id)) { return USBT_SID; } else if (SID_NI.equals(gStop.stop_id)) { return NI_SID; } else if (SID_PA.equals(gStop.stop_id)) { return PA_SID; } else if (SID_SCTH.equals(gStop.stop_id)) { return SCTH_SID; } else { System.out.println("Unexpected stop ID " + gStop); System.exit(-1); return -1; } } return super.getStopId(gStop); } }
package dk.statsbiblioteket.newspaper.md5checker; import org.testng.Assert; import org.testng.annotations.Test; import dk.statsbiblioteket.medieplatform.autonomous.Batch; import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector; /** Test MD5 checker */ public class MD5CheckerComponentTest { @Test /** * Test checking checksums on two batches */ public void testDoWorkOnBatch() throws Exception { MD5CheckerComponent md5CheckerComponent = new MockupIteratorSuper(System.getProperties()); // Run on first batch with one wrong checksum ResultCollector result = new ResultCollector( md5CheckerComponent.getComponentName(), md5CheckerComponent.getComponentVersion()); Batch batch = new Batch("400022028241"); batch.setRoundTripNumber(1); md5CheckerComponent.doWorkOnBatch(batch, result); // Assert one failure with the expected report Assert.assertFalse(result.isSuccess(), result.toReport() + "\n"); String expected = "<result tool=\"" + md5CheckerComponent.getComponentName() + "\" xmlns=\"http://schemas.statsbiblioteket.dk/result/\">\n" + " <outcome>Failure</outcome>\n" + " <date>[date]</date>\n" + " <failures>\n" + " <failure>\n" + " <filereference>B400022028241-RT1/400022028241-14/1795-06-13-01/AdresseContoirsEfterretninger-1795-06-13-01-0006-brik.jp2/contents</filereference>\n" + " <type>checksum</type>\n" + " <component>MockupIteratorSuper</component>\n" + " <description>2F-O1: Expected checksum d41d8cd98f00b204e9800998ecf8427f, but was d41d8cd98f00b204e9800998ecf8427e</description>\n" + " </failure>\n" + " </failures>\n" + "</result>"; Assert.assertEquals( result.toReport() .replaceAll("<date>[^<]*</date>", "<date>[date]</date>"), expected); // Run on second batch with no wrong checksums result = new ResultCollector(md5CheckerComponent.getComponentName(), md5CheckerComponent.getComponentVersion()); batch = new Batch("400022028241"); batch.setRoundTripNumber(2); md5CheckerComponent.doWorkOnBatch(batch, result); // Assert no errors Assert.assertTrue(result.isSuccess(), result.toReport() + "\n"); } }
package org.alienlabs.hatchetharry.integrationTest; import java.util.concurrent.TimeUnit; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; public class FullAppTraversalTests { private static WebDriver chromeDriver1; private static WebDriver chromeDriver2; private static final String PORT = "8088"; private static final String HOST = "localhost"; private static final String SHOW_AND_OPEN_MOBILE_MENUBAR = "jQuery('#cssmenu').hide(); jQuery('.categories').hide(); jQuery('.dropdownmenu').show(); jQuery('.dropdownmenu:first').click();"; private static final String JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS = "window.scrollBy(0,100); jQuery('.w_content_container').scrollTop(200);"; private static final String JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_RESPONSIVE_MENU = "function elementInViewport(el) {\n" + " var top = el.offsetTop;\n" + " var left = el.offsetLeft;\n" + " var width = el.offsetWidth;\n" + " var height = el.offsetHeight;\n" + "\n" + " while(el.offsetParent) {\n" + " el = el.offsetParent;\n" + " top += el.offsetTop;\n" + " left += el.offsetLeft;\n" + " }\n" + "\n" + " return (\n" + " top > (window.pageYOffset + 50) &&\n" + " left > (window.pageXOffset + 50) &&\n" + " (top + height + 50) < (window.pageYOffset + window.innerHeight) &&\n" + " (left + width + 50) < (window.pageXOffset + window.innerWidth)\n" + " );\n" + "}\n" + "\n" + "var elementToLookFor = document.getElementById('revealTopLibraryCardLinkResponsive');\n" + "\n" + "for (var i = 0; i < 10000; i = i + 1) {\n" + " if (elementInViewport(elementToLookFor)) {\n" + " break;\n" + " } else {\n" + " window.scrollBy(0,5);\n}\n}"; private static final String JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_CARD = "function elementInViewport(el) {\n" + " var top = el.offsetTop;\n" + " var left = el.offsetLeft;\n" + " var width = el.offsetWidth;\n" + " var height = el.offsetHeight;\n" + "\n" + " while(el.offsetParent) {\n" + " el = el.offsetParent;\n" + " top += el.offsetTop;\n" + " left += el.offsetLeft;\n" + " }\n" + "\n" + " return (\n" + " top > (window.pageYOffset + 50) &&\n" + " left > (window.pageXOffset + 50) &&\n" + " (top + height + 50) < (window.pageYOffset + window.innerHeight) &&\n" + " (left + width + 50) < (window.pageXOffset + window.innerWidth)\n" + " );\n" + "}\n" + "\n" + "var elementToLookFor = jQuery(\"img[id^='tapHandleImage']\");\n" + "\n" + "for (var i = 0; i < 10000; i = i + 1) {\n" + " if (elementInViewport(elementToLookFor)) {\n" + " break;\n" + " } else {\n" + " window.scrollBy(0,5);\n}\n}"; @BeforeClass public static void setUpClass() { System.setProperty("webdriver.chrome.driver", "/home/nostromo/chromedriver"); final ChromeOptions options = new ChromeOptions(); final DesiredCapabilities capabilities = DesiredCapabilities.chrome(); capabilities.setCapability(ChromeOptions.CAPABILITY, options); FullAppTraversalTests.chromeDriver1 = new ChromeDriver(capabilities); FullAppTraversalTests.chromeDriver1.get(FullAppTraversalTests.HOST + ":" + FullAppTraversalTests.PORT + "/"); FullAppTraversalTests.chromeDriver2 = new ChromeDriver(capabilities); FullAppTraversalTests.chromeDriver2.get(FullAppTraversalTests.HOST + ":" + FullAppTraversalTests.PORT + "/"); } @AfterClass public static void tearDownClass() { FullAppTraversalTests.chromeDriver1.quit(); FullAppTraversalTests.chromeDriver2.quit(); } @Test public void testFullAppTraversal() throws InterruptedException { FullAppTraversalTests.chromeDriver1.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); FullAppTraversalTests.chromeDriver2.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // Create a game in Chrome 1 FullAppTraversalTests.waitForJQueryProcessing(FullAppTraversalTests.chromeDriver1, 60); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); FullAppTraversalTests.chromeDriver1.findElement(By.id("createGameLinkResponsive")).click(); Thread.sleep(5000); FullAppTraversalTests.chromeDriver1.findElement(By.id("name")).clear(); FullAppTraversalTests.chromeDriver1.findElement(By.id("name")).sendKeys("Zala"); new Select(FullAppTraversalTests.chromeDriver1.findElement(By.id("sideInput"))) .selectByVisibleText("infrared"); new Select(FullAppTraversalTests.chromeDriver1.findElement(By.id("decks"))) .selectByVisibleText("Aura Bant"); final String gameId = FullAppTraversalTests.chromeDriver1.findElement(By.id("gameId")) .getText(); FullAppTraversalTests.chromeDriver1.findElement(By.id("createSubmit")).click(); // Join a game in Chrome 2 FullAppTraversalTests.waitForJQueryProcessing(FullAppTraversalTests.chromeDriver2, 60); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); FullAppTraversalTests.chromeDriver2.findElement(By.id("joinGameLinkResponsive")).click(); Thread.sleep(5000); FullAppTraversalTests.chromeDriver2.findElement(By.id("name")).clear(); FullAppTraversalTests.chromeDriver2.findElement(By.id("name")).sendKeys("Marie"); new Select(FullAppTraversalTests.chromeDriver2.findElement(By.id("sideInput"))) .selectByVisibleText("ultraviolet"); new Select(FullAppTraversalTests.chromeDriver2.findElement(By.id("decks"))) .selectByVisibleText("Aura Bant"); FullAppTraversalTests.chromeDriver2.findElement(By.id("gameIdInput")).clear(); FullAppTraversalTests.chromeDriver2.findElement(By.id("gameIdInput")).sendKeys(gameId); FullAppTraversalTests.chromeDriver2.findElement(By.id("joinSubmit")).click(); // Assert that no card is present on battlefield Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".ui-draggable")).isEmpty()); Assert.assertTrue(FullAppTraversalTests.chromeDriver2.findElements( By.cssSelector(".ui-draggable")).isEmpty()); // Verify that the hands contains 7 cards Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".cross-link img")).size() == 7); Assert.assertTrue(FullAppTraversalTests.chromeDriver2.findElements( By.cssSelector(".cross-link img")).size() == 7); // Find first hand card name of Chrome1 String battlefieldCardName = FullAppTraversalTests.chromeDriver1 .findElements(By.cssSelector(".cross-link:nth-child(1) img")).get(0) .getAttribute("name"); // Play a card in Chrome1 FullAppTraversalTests.chromeDriver1.findElement(By.id("playCardLink0")).click(); // Verify that the hand contains only 6 cards, now Thread.sleep(10000); Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".cross-link img")).size() == 6); // Verify that card is present on the battlefield Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".ui-draggable")).size() == 1); Assert.assertTrue(FullAppTraversalTests.chromeDriver2.findElements( By.cssSelector(".ui-draggable")).size() == 1); // Verify the name of the card on the battlefield Assert.assertTrue(battlefieldCardName.equals(FullAppTraversalTests.chromeDriver1 .findElement(By.cssSelector(".ui-draggable")).getAttribute("name"))); Assert.assertTrue(battlefieldCardName.equals(FullAppTraversalTests.chromeDriver2 .findElement(By.cssSelector(".ui-draggable")).getAttribute("name"))); // Verify that the card is untapped Assert.assertFalse(FullAppTraversalTests.chromeDriver1 .findElements(By.cssSelector("img[id^='card']")).get(0).getAttribute("style") .contains("transform")); Assert.assertFalse(FullAppTraversalTests.chromeDriver2 .findElements(By.cssSelector("img[id^='card']")).get(0).getAttribute("style") .contains("transform")); // Tap card ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_CARD); FullAppTraversalTests.chromeDriver1 .findElement(By.cssSelector("img[id^='tapHandleImage']")).click(); Thread.sleep(10000); // Verify card is tapped Assert.assertTrue(FullAppTraversalTests.chromeDriver1 .findElements(By.cssSelector("img[id^='card']")).get(0).getAttribute("style") .contains("rotate(90deg)")); Assert.assertTrue(FullAppTraversalTests.chromeDriver2 .findElements(By.cssSelector("img[id^='card']")).get(0).getAttribute("style") .contains("rotate(90deg)")); // Assert that graveyard is not visible Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.id("graveyard-page-wrap")).isEmpty()); // Drag card to graveyard WebElement draggable = FullAppTraversalTests.chromeDriver1.findElement(By .cssSelector("img[id^='handleImage']")); WebElement to = FullAppTraversalTests.chromeDriver1.findElement(By.id("putToGraveyard")); new Actions(FullAppTraversalTests.chromeDriver1).dragAndDrop(draggable, to).build() .perform(); Thread.sleep(10000); // Assert graveyard is visible and contains one card Assert.assertFalse(FullAppTraversalTests.chromeDriver1.findElements( By.id("graveyard-page-wrap")).isEmpty()); Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".graveyard-cross-link")).size() == 1); // Verify name of the card in the graveyard Assert.assertTrue(battlefieldCardName.equals(FullAppTraversalTests.chromeDriver1 .findElements(By.cssSelector(".graveyard-cross-link:nth-child(1) img")).get(0) .getAttribute("name"))); // Play card from graveyard ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); Thread.sleep(1000); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_RESPONSIVE_MENU); FullAppTraversalTests.chromeDriver1.findElement( By.id("playCardFromGraveyardLinkResponsive")).click(); Thread.sleep(8000); // Verify the name of the card on the battlefield Assert.assertTrue(battlefieldCardName.equals(FullAppTraversalTests.chromeDriver1 .findElement(By.cssSelector(".ui-draggable")).getAttribute("name"))); Assert.assertTrue(battlefieldCardName.equals(FullAppTraversalTests.chromeDriver2 .findElement(By.cssSelector(".ui-draggable")).getAttribute("name"))); // Assert that the graveyard is visible and empty Assert.assertFalse(FullAppTraversalTests.chromeDriver1.findElements( By.id("graveyard-page-wrap")).isEmpty()); Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".graveyard-cross-link")).isEmpty()); // Drag card to hand draggable = FullAppTraversalTests.chromeDriver1.findElement(By .cssSelector("img[id^='handleImage']")); to = FullAppTraversalTests.chromeDriver1.findElement(By.id("putToHand")); new Actions(FullAppTraversalTests.chromeDriver1).dragAndDrop(draggable, to).build() .perform(); Thread.sleep(10000); // Assert that the hand contains 7 cards again Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".cross-link img")).size() == 7); // Reveal top card of library ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); Thread.sleep(1000); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_RESPONSIVE_MENU); FullAppTraversalTests.chromeDriver1 .findElement(By.id("revealTopLibraryCardLinkResponsive")).click(); Thread.sleep(8000); // Get top card name battlefieldCardName = FullAppTraversalTests.chromeDriver1.findElement( By.id("topLibraryCard")).getAttribute("name"); // Verify that the card name is the same in the second browser Assert.assertTrue(battlefieldCardName.equals(FullAppTraversalTests.chromeDriver2 .findElement(By.id("topLibraryCard")).getAttribute("name"))); // Click on the button "Do nothing" FullAppTraversalTests.chromeDriver1.findElement(By.id("doNothing")).click(); FullAppTraversalTests.chromeDriver2.findElement(By.id("doNothing")).click(); Thread.sleep(8000); // Assert that no card is present on battlefield Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".ui-draggable")).isEmpty()); Assert.assertTrue(FullAppTraversalTests.chromeDriver2.findElements( By.cssSelector(".ui-draggable")).isEmpty()); // Reveal again ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); FullAppTraversalTests.chromeDriver1 .findElement(By.id("revealTopLibraryCardLinkResponsive")).click(); Thread.sleep(8000); // Assert that the card is the same Assert.assertTrue(battlefieldCardName.equals(FullAppTraversalTests.chromeDriver1 .findElement(By.id("topLibraryCard")).getAttribute("name"))); Assert.assertTrue(battlefieldCardName.equals(FullAppTraversalTests.chromeDriver2 .findElement(By.id("topLibraryCard")).getAttribute("name"))); // Put to battlefield ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS); FullAppTraversalTests.chromeDriver1.findElement(By.id("putToBattlefieldFromModalWindow")) .click(); FullAppTraversalTests.chromeDriver2.findElement(By.id("doNothing")).click(); Thread.sleep(8000); // Verify that the card is present on the battlefield Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".ui-draggable")).size() == 1); Assert.assertTrue(FullAppTraversalTests.chromeDriver2.findElements( By.cssSelector(".ui-draggable")).size() == 1); // Assert that the card on the battlefield is the same Assert.assertTrue(battlefieldCardName.equals(FullAppTraversalTests.chromeDriver1 .findElement(By.cssSelector(".ui-draggable")).getAttribute("name"))); Assert.assertTrue(battlefieldCardName.equals(FullAppTraversalTests.chromeDriver2 .findElement(By.cssSelector(".ui-draggable")).getAttribute("name"))); // Reveal top card of library ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); FullAppTraversalTests.chromeDriver1 .findElement(By.id("revealTopLibraryCardLinkResponsive")).click(); Thread.sleep(8000); // Put to hand ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS); FullAppTraversalTests.chromeDriver1.findElement(By.id("putToHandFromModalWindow")).click(); FullAppTraversalTests.chromeDriver2.findElement(By.id("doNothing")).click(); Thread.sleep(8000); // Assert that the hand contains 8 cards Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".cross-link img")).size() == 8); // Verify that there is still one card on the battlefield Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".ui-draggable")).size() == 1); Assert.assertTrue(FullAppTraversalTests.chromeDriver2.findElements( By.cssSelector(".ui-draggable")).size() == 1); // Reveal again ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); FullAppTraversalTests.chromeDriver1 .findElement(By.id("revealTopLibraryCardLinkResponsive")).click(); Thread.sleep(8000); // Get top card name final String graveyardCardName = FullAppTraversalTests.chromeDriver1.findElement( By.id("topLibraryCard")).getAttribute("name"); // Put to graveyard ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS); FullAppTraversalTests.chromeDriver1.findElement(By.id("putToGraveyardFromModalWindow")) .click(); FullAppTraversalTests.chromeDriver2.findElement(By.id("doNothing")).click(); Thread.sleep(8000); // Assert graveyard is visible and contains one card Assert.assertFalse(FullAppTraversalTests.chromeDriver1.findElements( By.id("graveyard-page-wrap")).isEmpty()); Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".graveyard-cross-link")).size() == 1); // Verify name of the card in the graveyard Assert.assertTrue(graveyardCardName.equals(FullAppTraversalTests.chromeDriver1 .findElements(By.cssSelector(".graveyard-cross-link:nth-child(1) img")).get(0) .getAttribute("name"))); // Verify that there is still one card on the battlefield Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".ui-draggable")).size() == 1); Assert.assertTrue(FullAppTraversalTests.chromeDriver2.findElements( By.cssSelector(".ui-draggable")).size() == 1); // Verify the name of the card on the battlefield Assert.assertTrue(battlefieldCardName.equals(FullAppTraversalTests.chromeDriver1 .findElement(By.cssSelector(".ui-draggable")).getAttribute("name"))); Assert.assertTrue(battlefieldCardName.equals(FullAppTraversalTests.chromeDriver2 .findElement(By.cssSelector(".ui-draggable")).getAttribute("name"))); // Verify that the hands contains 7 cards Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".cross-link img")).size() == 8); Assert.assertTrue(FullAppTraversalTests.chromeDriver2.findElements( By.cssSelector(".cross-link img")).size() == 7); // Find first hand card name of Chrome1 final String activeHandCardName = FullAppTraversalTests.chromeDriver1 .findElements(By.cssSelector(".cross-link:nth-child(1) img")).get(0) .getAttribute("name"); // Put one card from hand to graveyard new Select(FullAppTraversalTests.chromeDriver1.findElement(By.id("putToZoneSelectForHand"))) .selectByVisibleText("Graveyard"); FullAppTraversalTests.chromeDriver1.findElement(By.id("moveToZoneSubmitHand")).click(); Thread.sleep(5000); // Verify that there is one more card in the graveyard Assert.assertFalse(FullAppTraversalTests.chromeDriver1.findElements( By.id("graveyard-page-wrap")).isEmpty()); Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".graveyard-cross-link")).size() == 2); // Get name of the current card in the hand Assert.assertEquals( activeHandCardName, FullAppTraversalTests.chromeDriver1 .findElements(By.cssSelector(".cross-link:nth-child(1) img")).get(0) .getAttribute("name")); // Put current card from hand to exile new Select(FullAppTraversalTests.chromeDriver1.findElement(By.id("putToZoneSelectForHand"))) .selectByVisibleText("Exile"); FullAppTraversalTests.chromeDriver1.findElement(By.id("moveToZoneSubmitHand")).click(); Thread.sleep(5000); // Verify that there is one more card in the exile and that it is // visible Assert.assertFalse(FullAppTraversalTests.chromeDriver1.findElements( By.id("exile-page-wrap")).isEmpty()); Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".exile-cross-link")).size() == 1); // Put current card in exile to graveyard new Select( FullAppTraversalTests.chromeDriver1.findElement(By.id("putToZoneSelectForExile"))) .selectByVisibleText("Graveyard"); FullAppTraversalTests.chromeDriver1.findElement(By.id("moveToZoneSubmitExile")).click(); Thread.sleep(5000); // Verify that there is one more card in the graveyard Assert.assertFalse(FullAppTraversalTests.chromeDriver1.findElements( By.id("graveyard-page-wrap")).isEmpty()); Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".graveyard-cross-link")).size() == 3); // Get name of the current card in the hand final String handCardName = FullAppTraversalTests.chromeDriver1 .findElements(By.cssSelector(".cross-link:nth-child(1) img")).get(0) .getAttribute("name"); // Put current card from hand to exile new Select(FullAppTraversalTests.chromeDriver1.findElement(By.id("putToZoneSelectForHand"))) .selectByVisibleText("Exile"); FullAppTraversalTests.chromeDriver1.findElement(By.id("moveToZoneSubmitHand")).click(); Thread.sleep(5000); // Verify that there is one more card in the exile Assert.assertFalse(FullAppTraversalTests.chromeDriver1.findElements( By.id("exile-page-wrap")).isEmpty()); Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".exile-cross-link")).size() == 2); // Get name of the current card in the exile final String exileCardName = FullAppTraversalTests.chromeDriver1 .findElements(By.cssSelector(".exile-cross-link:nth-child(1) img")).get(0) .getAttribute("name"); // Put card from exile to battlefield new Select( FullAppTraversalTests.chromeDriver1.findElement(By.id("putToZoneSelectForExile"))) .selectByVisibleText("Battlefield"); FullAppTraversalTests.chromeDriver1.findElement(By.id("moveToZoneSubmitExile")).click(); Thread.sleep(5000); // Verify that there are two cards on the battlefield Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".ui-draggable")).size() == 2); Assert.assertTrue(FullAppTraversalTests.chromeDriver2.findElements( By.cssSelector(".ui-draggable")).size() == 2); // Verify the name of the card on the battlefield Assert.assertTrue(exileCardName.equals(FullAppTraversalTests.chromeDriver1 .findElements(By.cssSelector(".ui-draggable")).get(1).getAttribute("name"))); Assert.assertTrue(exileCardName.equals(FullAppTraversalTests.chromeDriver2 .findElements(By.cssSelector(".ui-draggable")).get(1).getAttribute("name"))); } public static boolean waitForJQueryProcessing(final WebDriver driver, final int timeOutInSeconds) { boolean jQcondition = false; try { new WebDriverWait(driver, timeOutInSeconds) { }.until(new ExpectedCondition<Boolean>() { @Override public Boolean apply(final WebDriver driverObject) { return (Boolean)((JavascriptExecutor)driverObject) .executeScript("return jQuery.active == 0"); } }); jQcondition = (Boolean)((JavascriptExecutor)driver) .executeScript("return window.jQuery != undefined && jQuery.active === 0"); return jQcondition; } catch (final Exception e) { e.printStackTrace(); } return jQcondition; } }
package org.alienlabs.hatchetharry.integrationTest; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.TimeUnit; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; public class FullAppTraversalTests { private static WebDriver chromeDriver1; private static WebDriver chromeDriver2; private static final String PORT = "8088"; private static final String HOST = "localhost"; private static final String SHOW_AND_OPEN_MOBILE_MENUBAR = "jQuery('#cssmenu').hide(); jQuery('.categories').hide(); jQuery('.dropdownmenu').show(); jQuery('.dropdownmenu:first').click();"; private static final String JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS = "window.scrollBy(0,100); jQuery('.w_content_container').scrollTop(200);"; private static final String JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_RESPONSIVE_MENU = "function elementInViewport(el) {\n" + " var top = el.offsetTop;\n" + " var left = el.offsetLeft;\n" + " var width = el.offsetWidth;\n" + " var height = el.offsetHeight;\n" + "\n" + " while(el.offsetParent) {\n" + " el = el.offsetParent;\n" + " top += el.offsetTop;\n" + " left += el.offsetLeft;\n" + " }\n" + "\n" + " return (\n" + " top > (window.pageYOffset + 50) &&\n" + " left > (window.pageXOffset + 50) &&\n" + " (top + height + 50) < (window.pageYOffset + window.innerHeight) &&\n" + " (left + width + 50) < (window.pageXOffset + window.innerWidth)\n" + " );\n" + "}\n" + "\n" + "var elementToLookFor = document.getElementById('revealTopLibraryCardLinkResponsive');\n" + "\n" + "for (var i = 0; i < 10000; i = i + 1) {\n" + " if (elementInViewport(elementToLookFor)) {\n" + " break;\n" + " } else {\n" + " window.scrollBy(0,5);\n}\n}"; private static final String JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_CARD = "function elementInViewport(el) {\n" + " var top = el.offsetTop;\n" + " var left = el.offsetLeft;\n" + " var width = el.offsetWidth;\n" + " var height = el.offsetHeight;\n" + "\n" + " while(el.offsetParent) {\n" + " el = el.offsetParent;\n" + " top += el.offsetTop;\n" + " left += el.offsetLeft;\n" + " }\n" + "\n" + " return (\n" + " top > (window.pageYOffset + 50) &&\n" + " left > (window.pageXOffset + 50) &&\n" + " (top + height + 50) < (window.pageYOffset + window.innerHeight) &&\n" + " (left + width + 50) < (window.pageXOffset + window.innerWidth)\n" + " );\n" + "}\n" + "\n" + "var elementToLookFor = jQuery(\"img[id^='tapHandleImage']\");\n" + "\n" + "for (var i = 0; i < 10000; i = i + 1) {\n" + " if (elementInViewport(elementToLookFor)) {\n" + " break;\n" + " } else {\n" + " window.scrollBy(0,5);\n}\n}"; private static final String JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_PUT_TO_ZONE_SUMBIT_BUTTON_FOR_HAND = "function elementInViewport(el) {\n" + " var top = el.offsetTop;\n" + " var left = el.offsetLeft;\n" + " var width = el.offsetWidth;\n" + " var height = el.offsetHeight;\n" + "\n" + " while(el.offsetParent) {\n" + " el = el.offsetParent;\n" + " top += el.offsetTop;\n" + " left += el.offsetLeft;\n" + " }\n" + "\n" + " return (\n" + " top > (window.pageYOffset + 50) &&\n" + " left > (window.pageXOffset + 50) &&\n" + " (top + height + 50) < (window.pageYOffset + window.innerHeight) &&\n" + " (left + width + 50) < (window.pageXOffset + window.innerWidth)\n" + " );\n" + "}\n" + "\n" + "var elementToLookFor = jQuery(\"#moveToZoneSubmitHand\");\n" + "\n" + "for (var i = 0; i < 10000; i = i + 1) {\n" + " if (elementInViewport(elementToLookFor)) {\n" + " break;\n" + " } else {\n" + " window.scrollBy(0,5);\n}\n}"; @BeforeClass public static void setUpClass() throws InterruptedException, MalformedURLException { FullAppTraversalTests.chromeDriver1 = new RemoteWebDriver(new URL( FullAppTraversalTests.HOST + ":" + FullAppTraversalTests.PORT + "/"), DesiredCapabilities.chrome()); FullAppTraversalTests.chromeDriver2 = new RemoteWebDriver(new URL( FullAppTraversalTests.HOST + ":" + FullAppTraversalTests.PORT + "/"), DesiredCapabilities.chrome()); FullAppTraversalTests.chromeDriver1.manage().timeouts() .implicitlyWait(60, TimeUnit.SECONDS); FullAppTraversalTests.chromeDriver2.manage().timeouts() .implicitlyWait(60, TimeUnit.SECONDS); Thread.sleep(15000); } @AfterClass public static void tearDownClass() { FullAppTraversalTests.chromeDriver1.quit(); FullAppTraversalTests.chromeDriver2.quit(); } @Test public void testFullAppTraversal() throws InterruptedException { // Create a game in Chrome 1 FullAppTraversalTests.waitForJQueryProcessing(FullAppTraversalTests.chromeDriver1, 30); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); FullAppTraversalTests.chromeDriver1.findElement(By.id("createGameLinkResponsive")).click(); Thread.sleep(8000); FullAppTraversalTests.chromeDriver1.findElement(By.id("name")).clear(); FullAppTraversalTests.chromeDriver1.findElement(By.id("name")).sendKeys("Zala"); new Select(FullAppTraversalTests.chromeDriver1.findElement(By.id("sideInput"))) .selectByVisibleText("infrared"); new Select(FullAppTraversalTests.chromeDriver1.findElement(By.id("decks"))) .selectByVisibleText("Aura Bant"); final String gameId = FullAppTraversalTests.chromeDriver1.findElement(By.id("gameId")) .getText(); FullAppTraversalTests.chromeDriver1.findElement(By.id("createSubmit")).click(); Thread.sleep(8000); // Join a game in Chrome 2 FullAppTraversalTests.waitForJQueryProcessing(FullAppTraversalTests.chromeDriver2, 15); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); FullAppTraversalTests.chromeDriver2.findElement(By.id("joinGameLinkResponsive")).click(); Thread.sleep(8000); FullAppTraversalTests.chromeDriver2.findElement(By.id("name")).clear(); FullAppTraversalTests.chromeDriver2.findElement(By.id("name")).sendKeys("Marie"); new Select(FullAppTraversalTests.chromeDriver2.findElement(By.id("sideInput"))) .selectByVisibleText("ultraviolet"); new Select(FullAppTraversalTests.chromeDriver2.findElement(By.id("decks"))) .selectByVisibleText("Aura Bant"); FullAppTraversalTests.chromeDriver2.findElement(By.id("gameIdInput")).clear(); FullAppTraversalTests.chromeDriver2.findElement(By.id("gameIdInput")).sendKeys(gameId); FullAppTraversalTests.chromeDriver2.findElement(By.id("joinSubmit")).click(); // Assert that no card is present on battlefield // The Balduvian Horde is hidden but still there // And it contains TWO elements of class magicCard Thread.sleep(45000); Assert.assertEquals(2, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .size()); Assert.assertEquals(2, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .size()); // Verify that the hands contains 7 cards Assert.assertEquals(7, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".movers-row")) .size()); Assert.assertEquals(7, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".movers-row")) .size()); // Find first hand card name of Chrome1 final String battlefieldCardName = FullAppTraversalTests.chromeDriver1 .findElements(By.cssSelector(".cross-link:nth-child(1) img")).get(0) .getAttribute("name"); // Play a card in Chrome1 FullAppTraversalTests.chromeDriver1.findElement(By.id("playCardLink0")).click(); // Verify that the hand contains only 6 cards, now Thread.sleep(45000); Assert.assertEquals(6, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".movers-row")) .size()); Thread.sleep(15000); // Verify that card is present on the battlefield // Two HTML elements with class "magicCard" are created for each card Assert.assertEquals(4, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .size()); Assert.assertEquals(4, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .size()); // Verify the name of the card on the battlefield Assert.assertEquals( battlefieldCardName, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .get(2).getAttribute("name")); Assert.assertEquals( battlefieldCardName, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .get(2).getAttribute("name")); // Verify that the card is untapped Assert.assertFalse(FullAppTraversalTests.chromeDriver1 .findElements(By.cssSelector("img[id^='card']")).get(0).getAttribute("style") .contains("transform")); Assert.assertFalse(FullAppTraversalTests.chromeDriver2 .findElements(By.cssSelector("img[id^='card']")).get(0).getAttribute("style") .contains("transform")); // Tap card ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_CARD); FullAppTraversalTests.chromeDriver1 .findElement(By.cssSelector("img[id^='tapHandleImage']")).click(); Thread.sleep(15000); // Verify card is tapped Assert.assertTrue(FullAppTraversalTests.chromeDriver1 .findElements(By.cssSelector("img[id^='card']")).get(0).getAttribute("style") .contains("rotate(90deg)")); Assert.assertTrue(FullAppTraversalTests.chromeDriver2 .findElements(By.cssSelector("img[id^='card']")).get(0).getAttribute("style") .contains("rotate(90deg)")); // Assert that graveyard is not visible Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.id("graveyard-page-wrap")).isEmpty()); // Drag card to graveyard WebElement draggable = FullAppTraversalTests.chromeDriver1.findElement(By .cssSelector("img[id^='handleImage']")); WebElement to = FullAppTraversalTests.chromeDriver1.findElement(By.id("putToGraveyard")); new Actions(FullAppTraversalTests.chromeDriver1).dragAndDrop(draggable, to).build() .perform(); Thread.sleep(25000); // Assert graveyard is visible and contains one card Assert.assertFalse(FullAppTraversalTests.chromeDriver1.findElements( By.id("graveyard-page-wrap")).isEmpty()); Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".graveyard-cross-link")).size() == 1); // Verify name of the card in the graveyard Assert.assertTrue(battlefieldCardName.equals(FullAppTraversalTests.chromeDriver1 .findElements(By.cssSelector(".graveyard-cross-link:nth-child(1) img")).get(0) .getAttribute("name"))); // Play card from graveyard ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); Thread.sleep(10000); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_RESPONSIVE_MENU); FullAppTraversalTests.chromeDriver1.findElement( By.id("playCardFromGraveyardLinkResponsive")).click(); Thread.sleep(25000); // Verify the name of the card on the battlefield Assert.assertEquals( battlefieldCardName, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .get(2).getAttribute("name")); Assert.assertEquals( battlefieldCardName, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .get(2).getAttribute("name")); // Assert that the graveyard is visible and empty Assert.assertFalse(FullAppTraversalTests.chromeDriver1.findElements( By.id("graveyard-page-wrap")).isEmpty()); Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".graveyard-cross-link")).isEmpty()); // Drag card to hand draggable = FullAppTraversalTests.chromeDriver1.findElement(By .cssSelector("img[id^='handleImage']")); to = FullAppTraversalTests.chromeDriver1.findElement(By.id("putToHand")); new Actions(FullAppTraversalTests.chromeDriver1).dragAndDrop(draggable, to).build() .perform(); Thread.sleep(15000); // Assert that the hand contains 7 cards again Assert.assertEquals(7, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".movers-row")) .size()); // Reveal top card of library ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); Thread.sleep(8000); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_RESPONSIVE_MENU); FullAppTraversalTests.chromeDriver1 .findElement(By.id("revealTopLibraryCardLinkResponsive")).click(); Thread.sleep(8000); // Get top card name final String topCardName = FullAppTraversalTests.chromeDriver1.findElement( By.id("topLibraryCard")).getAttribute("name"); // Verify that the card name is the same in the second browser Assert.assertTrue(topCardName.equals(FullAppTraversalTests.chromeDriver2.findElement( By.id("topLibraryCard")).getAttribute("name"))); // Click on the button "Do nothing" FullAppTraversalTests.chromeDriver1.findElement(By.id("doNothing")).click(); FullAppTraversalTests.chromeDriver2.findElement(By.id("doNothing")).click(); Thread.sleep(8000); // Reveal again ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); FullAppTraversalTests.chromeDriver1 .findElement(By.id("revealTopLibraryCardLinkResponsive")).click(); Thread.sleep(15000); // Assert that the card is the same Assert.assertTrue(topCardName.equals(FullAppTraversalTests.chromeDriver1.findElement( By.id("topLibraryCard")).getAttribute("name"))); Assert.assertTrue(topCardName.equals(FullAppTraversalTests.chromeDriver2.findElement( By.id("topLibraryCard")).getAttribute("name"))); // Put to battlefield ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS); FullAppTraversalTests.chromeDriver1.findElement(By.id("putToBattlefieldFromModalWindow")) .click(); FullAppTraversalTests.chromeDriver2.findElement(By.id("doNothing")).click(); // Verify that the card is present on the battlefield Thread.sleep(25000); Assert.assertEquals(4, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .size()); Assert.assertEquals(4, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .size()); // Assert that the card on the battlefield is the same Assert.assertEquals( topCardName, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .get(2).getAttribute("name")); Assert.assertEquals( topCardName, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .get(2).getAttribute("name")); // Reveal top card of library ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); FullAppTraversalTests.chromeDriver1 .findElement(By.id("revealTopLibraryCardLinkResponsive")).click(); Thread.sleep(8000); // Put to hand ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS); FullAppTraversalTests.chromeDriver1.findElement(By.id("putToHandFromModalWindow")).click(); FullAppTraversalTests.chromeDriver2.findElement(By.id("doNothing")).click(); Thread.sleep(15000); // Assert that the hand contains 8 cards Assert.assertEquals(8, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".movers-row")) .size()); // Verify that there is still two cards on the battlefield Assert.assertEquals(4, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .size()); Assert.assertEquals(4, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .size()); // Reveal again ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.SHOW_AND_OPEN_MOBILE_MENUBAR); FullAppTraversalTests.chromeDriver1 .findElement(By.id("revealTopLibraryCardLinkResponsive")).click(); Thread.sleep(12000); // Get top card name final String graveyardCardName = FullAppTraversalTests.chromeDriver1.findElement( By.id("topLibraryCard")).getAttribute("name"); // Put to graveyard ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS); ((JavascriptExecutor)FullAppTraversalTests.chromeDriver2) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_MODAL_WINDOW_BUTTONS); FullAppTraversalTests.chromeDriver1.findElement(By.id("putToGraveyardFromModalWindow")) .click(); FullAppTraversalTests.chromeDriver2.findElement(By.id("doNothing")).click(); Thread.sleep(15000); // Assert graveyard is visible and contains one card Assert.assertFalse(FullAppTraversalTests.chromeDriver1.findElements( By.id("graveyard-page-wrap")).isEmpty()); Assert.assertTrue(FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".graveyard-cross-link")).size() == 1); // Verify name of the card in the graveyard Assert.assertTrue(graveyardCardName.equals(FullAppTraversalTests.chromeDriver1 .findElements(By.cssSelector(".graveyard-cross-link:nth-child(1) img")).get(0) .getAttribute("name"))); // Verify that there is still two cards on the battlefield Assert.assertEquals(4, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .size()); Assert.assertEquals(4, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .size()); // Verify the name of the card on the battlefield Assert.assertEquals( topCardName, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .get(2).getAttribute("name")); Assert.assertEquals( topCardName, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .get(2).getAttribute("name")); // Verify that the hands contains 8 cards Assert.assertEquals(8, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".movers-row")) .size()); Assert.assertEquals(7, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".movers-row")) .size()); // Put one card from hand to graveyard ((JavascriptExecutor)FullAppTraversalTests.chromeDriver1) .executeScript(FullAppTraversalTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_PUT_TO_ZONE_SUMBIT_BUTTON_FOR_HAND); new Select(FullAppTraversalTests.chromeDriver1.findElement(By.id("putToZoneSelectForHand"))) .selectByVisibleText("Graveyard"); FullAppTraversalTests.chromeDriver1.findElement(By.id("moveToZoneSubmitHand")).click(); Thread.sleep(15000); // Verify that there is one more card in the graveyard Assert.assertFalse(FullAppTraversalTests.chromeDriver1.findElements( By.id("graveyard-page-wrap")).isEmpty()); Assert.assertEquals( 2, FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".graveyard-cross-link")).size()); // Put current card from hand to exile new Select(FullAppTraversalTests.chromeDriver1.findElement(By.id("putToZoneSelectForHand"))) .selectByVisibleText("Exile"); FullAppTraversalTests.chromeDriver1.findElement(By.id("moveToZoneSubmitHand")).click(); Thread.sleep(15000); // Verify that there is one more card in the exile and that it is // visible Assert.assertFalse(FullAppTraversalTests.chromeDriver1.findElements( By.id("exile-page-wrap")).isEmpty()); Assert.assertEquals( 1, FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".exile-cross-link")).size()); // Put current card in exile to graveyard new Select( FullAppTraversalTests.chromeDriver1.findElement(By.id("putToZoneSelectForExile"))) .selectByVisibleText("Graveyard"); FullAppTraversalTests.chromeDriver1.findElement(By.id("moveToZoneSubmitExile")).click(); Thread.sleep(15000); // Verify that there is one more card in the graveyard Assert.assertFalse(FullAppTraversalTests.chromeDriver1.findElements( By.id("graveyard-page-wrap")).isEmpty()); Assert.assertEquals( 3, FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".graveyard-cross-link")).size()); // Get name of the current card in the hand final String handCardName = FullAppTraversalTests.chromeDriver1 .findElements(By.cssSelector(".cross-link:nth-child(1) img")).get(0) .getAttribute("name"); // Put current card from hand to exile new Select(FullAppTraversalTests.chromeDriver1.findElement(By.id("putToZoneSelectForHand"))) .selectByVisibleText("Exile"); FullAppTraversalTests.chromeDriver1.findElement(By.id("moveToZoneSubmitHand")).click(); Thread.sleep(15000); // Verify that there is one more card in the exile Assert.assertFalse(FullAppTraversalTests.chromeDriver1.findElements( By.id("exile-page-wrap")).isEmpty()); Assert.assertEquals( 1, FullAppTraversalTests.chromeDriver1.findElements( By.cssSelector(".exile-cross-link")).size()); // Get name of the current card in the exile final String exileCardName = FullAppTraversalTests.chromeDriver1 .findElements(By.cssSelector(".exile-cross-link:nth-child(1) img")).get(0) .getAttribute("name"); // Verify that active card in exile is same than card from hand Assert.assertEquals(handCardName, exileCardName); // Put card from exile to battlefield new Select( FullAppTraversalTests.chromeDriver1.findElement(By.id("putToZoneSelectForExile"))) .selectByVisibleText("Battlefield"); FullAppTraversalTests.chromeDriver1.findElement(By.id("moveToZoneSubmitExile")).click(); Thread.sleep(30000); // Verify that there are three cards on the battlefield Assert.assertEquals(6, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .size()); Assert.assertEquals(6, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .size()); // Verify the name of the card on the battlefield Assert.assertEquals( exileCardName, FullAppTraversalTests.chromeDriver1.findElements(By.cssSelector(".magicCard")) .get(4).getAttribute("name")); Assert.assertEquals( exileCardName, FullAppTraversalTests.chromeDriver2.findElements(By.cssSelector(".magicCard")) .get(4).getAttribute("name")); } public static boolean waitForJQueryProcessing(final WebDriver driver, final int timeOutInSeconds) { boolean jQcondition = false; try { new WebDriverWait(driver, timeOutInSeconds) { }.until(new ExpectedCondition<Boolean>() { @Override public Boolean apply(final WebDriver driverObject) { return (Boolean)((JavascriptExecutor)driverObject) .executeScript("return jQuery.active == 0"); } }); jQcondition = (Boolean)((JavascriptExecutor)driver) .executeScript("return window.jQuery != undefined && jQuery.active === 0"); return jQcondition; } catch (final Exception e) { e.printStackTrace(); } return jQcondition; } }
package org.alienlabs.hatchetharry.integrationTest; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.webapp.WebAppContext; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class VerifyClientSideTests { private static final Logger LOGGER = LoggerFactory.getLogger(VerifyClientSideTests.class); private static final String PORT = "8088"; private static final String HOST = "localhost"; private static final Server server = new Server(); private static final String QUNIT_FAILED_TESTS = "0"; private static final String QUNIT_PASSED_TESTS = "6"; private static final String QUNIT_TOTAL_TESTS = "6"; private static final String MISTLETOE_FAILED_TESTS = "Errors/Failures: 0"; private static final String MISTLETOE_TOTAL_TESTS = "Total tests: 2"; private static WebDriver firefoxDriver1; private static WebDriver firefoxDriver2; private static final String JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_RUN_BUTTON = "function elementInViewport(el) {\n" + " var top = el.offsetTop;\n" + " var left = el.offsetLeft;\n" + " var width = el.offsetWidth;\n" + " var height = el.offsetHeight;\n" + "\n" + " while(el.offsetParent) {\n" + " el = el.offsetParent;\n" + " top += el.offsetTop;\n" + " left += el.offsetLeft;\n" + " }\n" + "\n" + " return (\n" + " top > (window.pageYOffset + 50) &&\n" + " left > (window.pageXOffset + 5) &&\n" + " (top + height + 50) < (window.pageYOffset + window.innerHeight) &&\n" + " (left + width + 50) < (window.pageXOffset + window.innerWidth)\n" + " );\n" + "}\n" + "\n" + "var elementToLookFor = document.getElementById('runMistletoe');\n" + "\n" + "for (var i = 0; i < 10000; i = i + 1) {\n" + " if (elementInViewport(elementToLookFor)) {\n" + " break;\n" + " } else {\n" + " window.scrollBy(0,1);\n}\n}"; private static final String SCROLL_DOWN = "window.scrollBy(0,50);"; @BeforeClass public static void setUpClass() throws Exception { VerifyClientSideTests.LOGGER .info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>> STARTING EMBEDDED JETTY SERVER"); final ServerConnector http = new ServerConnector(VerifyClientSideTests.server); http.setHost(VerifyClientSideTests.HOST); http.setPort(Integer.parseInt(VerifyClientSideTests.PORT)); http.setIdleTimeout(30000); VerifyClientSideTests.server.addConnector(http); final WebAppContext webapp = new WebAppContext(); webapp.setContextPath("/"); webapp.setWar("src/main/webapp"); VerifyClientSideTests.server.setHandler(webapp); VerifyClientSideTests.server.start(); VerifyClientSideTests.LOGGER .info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SUCCESSFULLY STARTED EMBEDDED JETTY SERVER"); VerifyClientSideTests.firefoxDriver1 = new FirefoxDriver(); VerifyClientSideTests.firefoxDriver2 = new FirefoxDriver(); Thread.sleep(15000); VerifyClientSideTests.firefoxDriver1.get("http://" + VerifyClientSideTests.HOST + ":" + VerifyClientSideTests.PORT + "/"); VerifyClientSideTests.firefoxDriver2.get("http://" + VerifyClientSideTests.HOST + ":" + VerifyClientSideTests.PORT + "/"); Thread.sleep(30000); } @Test public void testQunit() { final String passed1 = VerifyClientSideTests.firefoxDriver1.findElement(By.id("passed")) .getText(); final String total1 = VerifyClientSideTests.firefoxDriver1.findElement(By.id("total")) .getText(); final String failed1 = VerifyClientSideTests.firefoxDriver1.findElement(By.id("failed")) .getText(); Assert.assertEquals(VerifyClientSideTests.QUNIT_PASSED_TESTS, passed1); Assert.assertEquals(VerifyClientSideTests.QUNIT_TOTAL_TESTS, total1); Assert.assertEquals(VerifyClientSideTests.QUNIT_FAILED_TESTS, failed1); } @Test public void testMistletoe() throws InterruptedException { ((JavascriptExecutor)VerifyClientSideTests.firefoxDriver1) .executeScript(VerifyClientSideTests.JAVA_SCRIPT_TO_CENTER_VIEWPORT_AROUND_RUN_BUTTON); VerifyClientSideTests.firefoxDriver1.findElement(By.id("runMistletoe")).click(); Thread.sleep(75000); ((JavascriptExecutor)VerifyClientSideTests.firefoxDriver1) .executeScript(VerifyClientSideTests.SCROLL_DOWN); final String chromeTotal = VerifyClientSideTests.firefoxDriver1.findElement( By.id("runsSummary")).getText(); final String chromeFailed = VerifyClientSideTests.firefoxDriver1.findElement( By.id("errorsSummary")).getText(); Assert.assertEquals(VerifyClientSideTests.MISTLETOE_TOTAL_TESTS, chromeTotal); Assert.assertEquals(VerifyClientSideTests.MISTLETOE_FAILED_TESTS, chromeFailed); } @AfterClass public static void tearDownClass() throws Exception { if (null != VerifyClientSideTests.firefoxDriver1) { VerifyClientSideTests.firefoxDriver1.quit(); } if (null != VerifyClientSideTests.firefoxDriver2) { VerifyClientSideTests.firefoxDriver2.quit(); } VerifyClientSideTests.LOGGER .info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>> STOPPING EMBEDDED JETTY SERVER"); VerifyClientSideTests.server.stop(); VerifyClientSideTests.server.join(); Thread.sleep(30000); } }
package org.cru.godtools.tests; import com.google.common.collect.ImmutableSet; import org.cru.godtools.api.packages.GodToolsPackageService; import org.cru.godtools.api.translations.DraftTranslationUpdateProcess; import org.cru.godtools.api.translations.GodToolsTranslationService; import org.cru.godtools.api.translations.NewTranslationProcess; import org.cru.godtools.domain.TestClockImpl; import org.cru.godtools.domain.images.ImageService; import org.cru.godtools.domain.images.ReferencedImageService; import org.cru.godtools.domain.languages.LanguageService; import org.cru.godtools.domain.packages.PackageService; import org.cru.godtools.domain.packages.PackageStructureService; import org.cru.godtools.domain.packages.PageStructureService; import org.cru.godtools.domain.packages.TranslationElementService; import org.cru.godtools.domain.translations.TranslationService; import org.cru.godtools.translate.client.onesky.FileClient; import org.cru.godtools.translate.client.onesky.OneSkyDataService; import org.cru.godtools.translate.client.onesky.OneSkyTranslationDownload; import org.cru.godtools.translate.client.onesky.OneSkyTranslationUpload; import org.cru.godtools.translate.client.onesky.TranslationClient; public class GodToolsPackageServiceTestClassCollection { static ImmutableSet<Class<?>> classSet = ImmutableSet.of(GodToolsTranslationService.class, ImageService.class, GodToolsPackageService.class, ReferencedImageService.class, PackageService.class, TranslationService.class, LanguageService.class, PackageStructureService.class, PageStructureService.class, TranslationElementService.class, NewTranslationProcess.class, DraftTranslationUpdateProcess.class, OneSkyTranslationDownload.class, OneSkyTranslationUpload.class, FileClient.class, TranslationClient.class, TestClockImpl.class, OneSkyDataService.class); public static Class<?>[] getClasses() { return classSet.toArray(new Class<?>[classSet.size()]); } }
package org.opendaylight.bgpcep.tcpmd5.nio; import java.io.IOException; import java.net.SocketOption; import java.nio.channels.NetworkChannel; import java.util.Set; import org.opendaylight.bgpcep.tcpmd5.KeyAccess; import org.opendaylight.bgpcep.tcpmd5.KeyAccessFactory; import org.opendaylight.bgpcep.tcpmd5.KeyMapping; import org.opendaylight.bgpcep.tcpmd5.MD5SocketOptions; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; /** * Channel option wrapper which unifies the underlying NetworkChannel with * the TCP MD5 Signature option if the channel is supported by the JNI library. */ final class MD5ChannelOptions { private static final Set<SocketOption<?>> MD5_OPTIONS = ImmutableSet.<SocketOption<?>>of(MD5SocketOptions.TCP_MD5SIG); private final NetworkChannel ch; private final KeyAccess access; private MD5ChannelOptions(final NetworkChannel ch, final KeyAccess access) { this.ch = Preconditions.checkNotNull(ch); this.access = access; } static MD5ChannelOptions create(final KeyAccessFactory keyAccessFactory, final NetworkChannel ch) { final KeyAccess access = keyAccessFactory.getKeyAccess(Preconditions.checkNotNull(ch)); return new MD5ChannelOptions(ch, access); } @SuppressWarnings("unchecked") public <T> T getOption(final SocketOption<T> name) throws IOException { if (access != null && name.equals(MD5SocketOptions.TCP_MD5SIG)) { return (T)access.getKeys(); } return ch.getOption(name); } public <T> void setOption(final SocketOption<T> name, final T value) throws IOException { if (access != null && name.equals(MD5SocketOptions.TCP_MD5SIG)) { access.setKeys((KeyMapping)value); } else { ch.setOption(name, value); } } public Set<SocketOption<?>> supportedOptions() { if (access != null) { return Sets.union(MD5_OPTIONS, ch.supportedOptions()); } else { return ch.supportedOptions(); } } }
package org.restheart.test.plugins.interceptors; import io.undertow.server.HttpServerExchange; import java.util.Map; import org.bson.BsonDocument; import org.bson.BsonValue; import org.restheart.handlers.exchange.BsonRequest; import org.restheart.handlers.exchange.BsonResponse; import org.restheart.plugins.InjectConfiguration; import org.restheart.plugins.InterceptPoint; import org.restheart.plugins.Interceptor; import org.restheart.plugins.RegisterPlugin; import org.restheart.utils.JsonUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Andrea Di Cesare {@literal <andrea@softinstigate.com>} */ @RegisterPlugin( name = "snooper", description = "An example hook that logs request and response info", enabledByDefault = false, interceptPoint = InterceptPoint.RESPONSE_ASYNC) @SuppressWarnings("deprecation") public class SnooperHook implements Interceptor { private static final Logger LOGGER = LoggerFactory.getLogger(SnooperHook.class); @InjectConfiguration public void init(Map<String, Object> conf) { LOGGER.info("Configuration args {}", conf); } /** * * @param exchange */ @Override public void handle(HttpServerExchange exchange) throws Exception { var request = BsonRequest.wrap(exchange); var response = BsonResponse.wrap(exchange); LOGGER.info("Request {} {} {}", request.getMethod(), exchange.getRequestURI(), exchange.getStatusCode()); if (response.getDbOperationResult() != null) { BsonValue newId = response .getDbOperationResult() .getNewId(); BsonDocument newData = response .getDbOperationResult() .getNewData(); BsonDocument oldData = response .getDbOperationResult() .getOldData(); LOGGER.info("**** New id ****\n{}", newId == null ? null : newId); LOGGER.info("**** New data ****\n{}", newData == null ? null : newData.toJson()); LOGGER.info("**** Old data ****\n{}", oldData == null ? null : oldData.toJson()); } BsonValue responseContent = response.getContent(); if (responseContent != null) { LOGGER.info("*** Response content ****\n{}", JsonUtils.toJson(responseContent)); } } @Override public boolean resolve(HttpServerExchange exchange) { return true; } }
package fredboat.command.fun; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.async.Callback; import com.mashape.unirest.http.exceptions.UnirestException; import fredboat.commandmeta.abs.Command; import fredboat.util.CacheUtil; import net.dv8tion.jda.core.MessageBuilder; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.TextChannel; import java.io.File; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class E6Command extends Command { private static final String BASE_URL = "https: @Override public void onInvoke(Guild guild, TextChannel channel, Member invoker, Message message, String[] args) { try{ StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(BASE_URL); stringBuilder.append(args[1]); stringBuilder.append("&limit=1"); String finalString = stringBuilder.toString(); channel.sendMessage(finalString); //channel.sendMessage(finalString).queue(); //File tmp = CacheUtil.getImageFromURL(finalString); //channel.sendFile(tmp, null).queue(); } } }
package com.sometrik.framework; import java.io.IOException; import java.io.InputStream; import com.sometrik.framework.NativeCommand.Selector; import android.content.res.AssetManager; import android.content.res.ColorStateList; import android.graphics.Bitmap.Config; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.GradientDrawable; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.animation.Animation; import android.view.animation.RotateAnimation; import android.widget.Button; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; public class FWButton extends Button implements NativeCommandHandler { private FrameWork frame; private Animation animation = null; private ViewStyleManager normalStyle, activeStyle, selectedStyle; private ViewStyleManager currentStyle; private boolean isSelected = false; public FWButton(FrameWork frameWork) { super(frameWork); this.frame = frameWork; BitmapCache bitmapCache = frameWork.bitmapCache; final float scale = getContext().getResources().getDisplayMetrics().density; this.normalStyle = currentStyle = new ViewStyleManager(bitmapCache, scale, true); this.activeStyle = new ViewStyleManager(bitmapCache, scale, false); this.selectedStyle = new ViewStyleManager(bitmapCache, scale, false); final FWButton button = this; setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { if (!FrameWork.transitionAnimation) { frame.intChangedEvent(System.currentTimeMillis() / 1000.0, getElementId(), 1, 0); if (animation != null) button.startAnimation(animation); } } }); setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { button.currentStyle = button.activeStyle; button.currentStyle.apply(button); } else if (event.getAction() == MotionEvent.ACTION_UP) { button.currentStyle = isSelected ? button.selectedStyle : button.normalStyle; button.currentStyle.apply(button); } return false; } }); } @Override public void addChild(View view) { System.out.println("FWButton couldn't handle command"); } @Override public void addOption(int optionId, String text) { System.out.println("FWButton couldn't handle command"); } @Override public void setValue(String v) { setText(v); } @Override public void setValue(int v) { boolean b = v != 0; if (b != isSelected) { isSelected = b; if (isSelected) currentStyle = selectedStyle; else currentStyle = normalStyle; currentStyle.apply(this); } } @Override public int getElementId() { return getId(); } @Override public void setStyle(Selector selector, String key, String value) { if (selector == Selector.NORMAL) { normalStyle.setStyle(key, value); if (normalStyle == currentStyle) normalStyle.apply(this); } else if (selector == Selector.ACTIVE) { activeStyle.setStyle(key, value); if (activeStyle == currentStyle) activeStyle.apply(this); } else if (selector == Selector.SELECTED) { selectedStyle.setStyle(key, value); if (selectedStyle == currentStyle) selectedStyle.apply(this); } if (key.equals("animation")) { if (value.equals("rotate")) { RotateAnimation r = new RotateAnimation(-5f, 5f,50,50); r.setDuration(100); r.setRepeatCount(10); r.setRepeatMode(RotateAnimation.REVERSE); animation = r; } } } @Override public void setError(boolean hasError, String errorText) { } @Override public void onScreenOrientationChange(boolean isLandscape) { // TODO Auto-generated method stub } @Override public void addData(String text, int row, int column, int sheet) { System.out.println("FWButton couldn't handle command"); } @Override public void setViewVisibility(boolean visibility) { if (visibility){ this.setVisibility(VISIBLE); } else { this.setVisibility(INVISIBLE); } } @Override public void clear() { System.out.println("couldn't handle command"); } @Override public void flush() { // TODO Auto-generated method stub } @Override public void addColumn(String text, int columnType) { // TODO Auto-generated method stub } @Override public void reshape(int value, int size) { // TODO Auto-generated method stub } @Override public void setImage(byte[] bytes, int width, int height, Config config) { // TODO Auto-generated method stub } @Override public void reshape(int size) { // TODO Auto-generated method stub } @Override public void deinitialize() { // TODO Auto-generated method stub } }
package com.sometrik.framework; import java.io.IOException; import java.io.InputStream; import com.sometrik.framework.NativeCommand.Selector; import android.content.res.AssetManager; import android.content.res.ColorStateList; import android.graphics.Bitmap.Config; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.GradientDrawable; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.animation.Animation; import android.view.animation.RotateAnimation; import android.widget.Button; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; public class FWButton extends Button implements NativeCommandHandler { FrameWork frame; BitmapDrawable leftDraw; BitmapDrawable rightDraw; BitmapDrawable bottomDraw; BitmapDrawable topDraw; Animation animation = null; ViewStyleManager normalStyle, activeStyle, currentStyle; public FWButton(FrameWork frameWork) { super(frameWork); this.frame = frameWork; final float scale = getContext().getResources().getDisplayMetrics().density; this.normalStyle = currentStyle = new ViewStyleManager(scale, true); this.activeStyle = new ViewStyleManager(scale, false); final FWButton button = this; setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { if (!FrameWork.transitionAnimation) { frame.intChangedEvent(System.currentTimeMillis() / 1000.0, getElementId(), 1, 0); if (animation != null) button.startAnimation(animation); } } }); setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { button.currentStyle = button.activeStyle; button.currentStyle.apply(button); } else if (event.getAction() == MotionEvent.ACTION_UP) { button.currentStyle = button.normalStyle; button.currentStyle.apply(button); } return false; } }); } @Override public void addChild(View view) { System.out.println("FWButton couldn't handle command"); } @Override public void addOption(int optionId, String text) { System.out.println("FWButton couldn't handle command"); } @Override public void setValue(String v) { setText(v); } @Override public void setValue(int v) { System.out.println("FWButton couldn't handle command"); } @Override public int getElementId() { return getId(); } @Override public void setStyle(Selector selector, String key, String value) { if (selector == Selector.NORMAL) { normalStyle.setStyle(key, value); if (normalStyle == currentStyle) normalStyle.apply(this); } else if (selector == Selector.ACTIVE) { activeStyle.setStyle(key, value); if (activeStyle == currentStyle) activeStyle.apply(this); } if (key.equals("icon-left") || key.equals("icon-right") || key.equals("icon-top") || key.equals("icon-bottom")){ AssetManager mgr = frame.getAssets(); try { InputStream stream = mgr.open(value); BitmapDrawable draw = new BitmapDrawable(stream); this.setGravity(Gravity.CENTER); if (key.equals("icon-right")){ rightDraw = draw; } else if (key.equals("icon-top")){ topDraw = draw; } else if (key.equals("icon-bottom")){ bottomDraw = draw; } else if (key.equals("icon-left")){ leftDraw = draw; } this.setCompoundDrawablesWithIntrinsicBounds(leftDraw, topDraw, rightDraw, bottomDraw); } catch (IOException e) { System.out.println("no picture found: " + value); e.printStackTrace(); } } else if (key.equals("animation")) { if (value.equals("rotate")) { RotateAnimation r = new RotateAnimation(-5f, 5f,50,50); r.setDuration(100); r.setRepeatCount(10); r.setRepeatMode(RotateAnimation.REVERSE); animation = r; } } } @Override public void setError(boolean hasError, String errorText) { } @Override public void onScreenOrientationChange(boolean isLandscape) { // TODO Auto-generated method stub } @Override public void addData(String text, int row, int column, int sheet) { System.out.println("FWButton couldn't handle command"); } @Override public void setViewVisibility(boolean visibility) { if (visibility){ this.setVisibility(VISIBLE); } else { this.setVisibility(INVISIBLE); } } @Override public void clear() { System.out.println("couldn't handle command"); } @Override public void flush() { // TODO Auto-generated method stub } @Override public void addColumn(String text, int columnType) { // TODO Auto-generated method stub } @Override public void reshape(int value, int size) { // TODO Auto-generated method stub } @Override public void setImage(byte[] bytes, int width, int height, Config config) { // TODO Auto-generated method stub } @Override public void reshape(int size) { // TODO Auto-generated method stub } @Override public void deinitialize() { // TODO Auto-generated method stub } }
package oap.io; import com.google.common.io.ByteStreams; import com.google.common.io.CountingInputStream; import oap.util.Stream; import oap.util.Strings; import oap.util.Try; import java.io.*; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.zip.*; public class IoStreams { public static final int DEFAULT_BUFFER = 8192; public static Stream<String> lines( URL url ) { return lines( url, Encoding.PLAIN, p -> { } ); } public static Stream<String> lines( URL url, Consumer<Integer> progressCallback ) { return lines( url, Encoding.PLAIN, progressCallback ); } public static Stream<String> lines( URL url, Encoding encoding, Consumer<Integer> progressCallback ) { try { URLConnection connection = url.openConnection(); InputStream stream = connection.getInputStream(); return lines( stream, connection.getContentLengthLong(), encoding, progressCallback ) .onClose( Try.run( stream::close ) ); } catch( IOException e ) { throw new UncheckedIOException( e ); } } public static Stream<String> lines( Path path ) { return lines( path, Encoding.PLAIN, p -> { } ); } public static Stream<String> lines( Path path, Encoding encoding ) { return lines( path, encoding, p -> { } ); } public static Stream<String> lines( Path path, Encoding encoding, Consumer<Integer> progressCallback ) { InputStream stream = in( path, Encoding.PLAIN ); return lines( stream, path.toFile().length(), encoding, progressCallback ) .onClose( Try.run( stream::close ) ); } private static Stream<String> lines( InputStream stream, long size, Encoding encoding, Consumer<Integer> progressCallback ) { long percent = size / 100; AtomicInteger lastReport = new AtomicInteger(); CountingInputStream counting = new CountingInputStream( stream ); return lines( in( counting, encoding ) ) .map( l -> { if( percent > 0 && counting.getCount() / percent > lastReport.get() ) { lastReport.set( ( int ) ( counting.getCount() / percent ) ); progressCallback.accept( lastReport.get() ); } return l; } ); } public static Stream<String> lines( InputStream stream ) { return Stream.of( new BufferedReader( new InputStreamReader( stream, StandardCharsets.UTF_8 ) ).lines() ); } public static void write( Path path, Encoding encoding, String value ) { path.toAbsolutePath().getParent().toFile().mkdirs(); try( OutputStream out = out( path, encoding ) ) { out.write( Strings.toByteArray( value ) ); } catch( IOException e ) { throw new UncheckedIOException( e ); } } public static void write( Path path, Encoding encoding, InputStream in ) { path.toAbsolutePath().getParent().toFile().mkdirs(); try( OutputStream out = out( path, encoding ) ) { ByteStreams.copy( in, out ); } catch( IOException e ) { throw new UncheckedIOException( e ); } } public static OutputStream out( Path path, Encoding encoding ) { return out( path, encoding, DEFAULT_BUFFER ); } public static OutputStream out( Path path, Encoding encoding, int bufferSize ) { return out( path, encoding, bufferSize, false ); } public static OutputStream out( Path path, Encoding encoding, boolean append ) { return out( path, encoding, DEFAULT_BUFFER, append ); } public static OutputStream out( Path path, Encoding encoding, int bufferSize, boolean append ) { return out( path, encoding, bufferSize, append, false, false ); } public static OutputStream out( Path path, Encoding encoding, int bufferSize, boolean append, boolean safe, boolean removeEmptyIfSafe ) { assert ( !removeEmptyIfSafe || safe ); path.toAbsolutePath().getParent().toFile().mkdirs(); try { OutputStream fos = new BufferedOutputStream( safe ? new SafeFileOutputStream( path, append, removeEmptyIfSafe ) : new FileOutputStream( path.toFile(), append ), bufferSize ); switch( encoding ) { case GZIP: return new GZIPOutputStream( fos ); case ZIP: if( append ) throw new IllegalArgumentException( "cannot append zip file" ); ZipOutputStream zip = new ZipOutputStream( fos ); zip.putNextEntry( new ZipEntry( path.getFileName().toString() ) ); return zip; default: return fos; } } catch( IOException e ) { throw new UncheckedIOException( e ); } } public static InputStream in( Path path, Encoding encoding ) { try { return in( new BufferedInputStream( new FileInputStream( path.toFile() ) ), encoding ); } catch( FileNotFoundException e ) { throw new UncheckedIOException( e ); } } public static InputStream in( InputStream stream, Encoding encoding ) { try { switch( encoding ) { case GZIP: return new GZIPInputStream( stream ); case ZIP: ZipInputStream zip = new ZipInputStream( stream ); if( zip.getNextEntry() == null ) throw new IllegalArgumentException( "zip stream contains no entries" ); return zip; default: return stream; } } catch( IOException e ) { throw new UncheckedIOException( e ); } } public enum Encoding { PLAIN, ZIP, GZIP } }
package com.restfb.types; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import com.restfb.Facebook; import com.restfb.util.DateUtils; import com.restfb.util.ReflectionUtils; public class User extends NamedFacebookType { @Facebook("first_name") private String firstName; @Facebook("last_name") private String lastName; @Facebook private String link; @Facebook private String about; @Facebook("relationship_status") private String relationshipStatus; @Facebook private String religion; @Facebook private String website; @Facebook private String birthday; @Facebook private String email; @Facebook private String picture; @Facebook private Integer timezone; @Facebook private Boolean verified; @Facebook private String gender; @Facebook private String political; @Facebook private NamedFacebookType hometown; @Facebook private NamedFacebookType location; @Facebook("updated_time") private String updatedTime; @Facebook(value = "interested_in", contains = String.class) private List<String> interestedIn = new ArrayList<String>(); @Facebook(value = "meeting_for", contains = String.class) private List<String> meetingFor = new ArrayList<String>(); @Facebook(contains = Work.class) private List<Work> work = new ArrayList<Work>(); @Facebook(contains = Education.class) private List<Education> education = new ArrayList<Education>(); public static class Work { // Facebook month-year only date format. // Example: 2007-03 private static final String FACEBOOK_MONTH_YEAR_DATE_FORMAT = "yyyy-MM"; @Facebook NamedFacebookType employer; @Facebook NamedFacebookType location; @Facebook NamedFacebookType position; @Facebook("start_date") private String startDate; @Facebook("end_date") private String endDate; protected Date toMonthYearDate(String date) throws IllegalArgumentException { if (date == null) return null; try { return new SimpleDateFormat(FACEBOOK_MONTH_YEAR_DATE_FORMAT) .parse(date); } catch (ParseException e) { throw new IllegalArgumentException( "Unable to parse date '" + date + "' using format string '" + FACEBOOK_MONTH_YEAR_DATE_FORMAT + "'", e); } } /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return ReflectionUtils.hashCode(this); } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object that) { return ReflectionUtils.equals(this, that); } /** * @see java.lang.Object#toString() */ @Override public String toString() { return ReflectionUtils.toString(this); } /** * The employer for this job. * * @return The employer for this job. */ public NamedFacebookType getEmployer() { return employer; } /** * The location of this job. * * @return The location of this job. */ public NamedFacebookType getLocation() { return location; } /** * Position held at this job. * * @return Position held at this job. */ public NamedFacebookType getPosition() { return position; } /** * Date this job was started. * * @return Date this job was started. */ public Date getStartDate() { return toMonthYearDate(startDate); } /** * Date this job ended. * * @return Date this job ended. */ public Date getEndDate() { return toMonthYearDate(endDate); } } public static class Education { @Facebook NamedFacebookType school; @Facebook NamedFacebookType year; @Facebook NamedFacebookType degree; @Facebook(value = "concentration", contains = NamedFacebookType.class) private List<NamedFacebookType> concentration = new ArrayList<NamedFacebookType>(); /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return ReflectionUtils.hashCode(this); } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object that) { return ReflectionUtils.equals(this, that); } /** * @see java.lang.Object#toString() */ @Override public String toString() { return ReflectionUtils.toString(this); } /** * The school name and ID. * * @return The school name and ID. */ public NamedFacebookType getSchool() { return school; } /** * Graduation year. * * @return Graduation year. */ public NamedFacebookType getYear() { return year; } /** * Degree acquired. * * @return Degree acquired. */ public NamedFacebookType getDegree() { return degree; } /** * Concentrations/minors. * * @return Concentrations/minors. */ public List<NamedFacebookType> getConcentration() { return Collections.unmodifiableList(concentration); } } /** * The user's first name. * * @return The user's first name. */ public String getFirstName() { return firstName; } /** * The user's last name. * * @return The user's last name. */ public String getLastName() { return lastName; } /** * A link to the user's profile. * * @return A link to the user's profile. */ public String getLink() { return link; } /** * The user's blurb that appears under their profile picture. * * @return The user's blurb that appears under their profile picture. */ public String getAbout() { return about; } /** * The user's relationship status. * * @return The user's relationship status. */ public String getRelationshipStatus() { return relationshipStatus; } /** * The user's birthday. * * @return The user's birthday. */ public Date getBirthday() { return DateUtils.toDateFromShortFormat(birthday); } /** * The user's religion. * * @return The user's religion. */ public String getReligion() { return religion; } /** * A link to the user's personal website. * * @return A link to the user's personal website. */ public String getWebsite() { return website; } /** * The proxied or contact email address granted by the user. * * @return The proxied or contact email address granted by the user. */ public String getEmail() { return email; } /** * The user's profile picture URL. * * @return The user's profile picture URL. */ public String getPicture() { return picture; } /** * The user's timezone offset. * * @return The user's timezone offset. */ public Integer getTimezone() { return timezone; } /** * Is the user verified? * * @return User verification status. */ public Boolean getVerified() { return verified; } /** * Date the user's profile was updated. * * @return Date the user's profile was updated. */ public Date getUpdatedTime() { return DateUtils.toDateFromLongFormat(updatedTime); } /** * The user's gender. * * @return The user's gender. */ public String getGender() { return gender; } /** * The user's political affiliation. * * @return The user's political affiliation. */ public String getPolitical() { return political; } /** * The user's hometown. * * @return The user's hometown. */ public NamedFacebookType getHometown() { return hometown; } /** * The user's current location. * * @return The user's current location. */ public NamedFacebookType getLocation() { return location; } /** * The user's interests. * * @return The user's interests. */ public List<String> getInterestedIn() { return Collections.unmodifiableList(interestedIn); } /** * What genders the user is interested in meeting. * * @return What genders the user is interested in meeting. */ public List<String> getMeetingFor() { return Collections.unmodifiableList(meetingFor); } /** * A list of the work history from the user's profile * * @return A list of the work history from the user's profile */ public List<Work> getWork() { return Collections.unmodifiableList(work); } /** * A list of the education history from the user's profile * * @return A list of the education history from the user's profile */ public List<Education> getEducation() { return Collections.unmodifiableList(education); } }
package mazemaker; import java.net.URL; import java.util.List; import java.util.ResourceBundle; import javafx.animation.Animation; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Application; import javafx.beans.binding.DoubleBinding; import javafx.beans.property.IntegerProperty; import javafx.collections.FXCollections; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ColorPicker; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.Slider; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.paint.Color; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import javafx.stage.Stage; import javafx.util.Duration; import mazemaker.io.*; import mazemaker.maze.*; import mazemaker.maze.generators.*; import mazemaker.maze.solvers.*; public class MazeMaker extends Application implements Initializable{ private static final int FRAMEDELAY = 100; private static final String BACKSTEP = "Backtrace"; private static final String BRANCHINGBS = "Branching Backtrace"; private static final String COINFLIP = "Random Binary Tree"; private static final String KRUSKAL = "Randomized Kruskal's"; private static final String PRIM = "Randomized Prim's"; private static final String BLANK = "Blank Maze"; private static final String RIGHTHAND = "Right Hand Rule"; private static final String LEFTHAND = "Left hand Rule"; private static final String RANDOMTURNS = "Random Turns"; private final Alert help = new Alert(AlertType.INFORMATION); private final Alert about = new Alert(AlertType.INFORMATION); private final ImageView pencilImage = new ImageView( new Image(getClass().getResourceAsStream("resources/pencil.png"))); private final ImageView cursorImage = new ImageView( new Image(getClass().getResourceAsStream("resources/pointer.png"))); private final Tooltip pencilTooltip = new Tooltip("Switch to Draw Mode)"); private final Tooltip cursorTooltip = new Tooltip("Switch to Cursor Mode"); @FXML private Button modeButton; @FXML private Label animLabel; @FXML private CheckBox showUnvisitedBox; @FXML private Slider speedSlider; @FXML private TextField rowsField; @FXML private TextField colsField; @FXML private ComboBox genCombo; @FXML private Slider biasSlider; @FXML private ComboBox solverCombo; @FXML private TextField cellField; @FXML private TextField wallField; @FXML private ColorPicker cellColor; @FXML private ColorPicker visitedColor; @FXML private ColorPicker wallColor; @FXML private ColorPicker spriteColor; @FXML private ColorPicker goalColor; @FXML private ComboBox spriteCombo; @FXML private ScrollPane scrollPane; private MazeView mazeview; private Timeline playback; private GifWriter gifWriter; private Thread currentTask; private List<Datum[]> steps; private int step; @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("MazeMaker.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("MazeMaker"); stage.show(); } @Override public void initialize(URL url, ResourceBundle rb) { playback = new Timeline(new KeyFrame(new Duration(FRAMEDELAY), f -> { if (step == steps.size()) stopPlayback(); if (gifWriter != null) gifWriter.snapshot(); mazeview.draw(steps.get(step++), getSprite()); })); playback.rateProperty().bind(new DoubleBinding(){ {super.bind(speedSlider.valueProperty());} @Override protected double computeValue() { // log scale with ticks at 0.01, 0.1, 1, 10, 100 x return Math.pow(10, speedSlider.getValue()); } }); playback.setCycleCount(Animation.INDEFINITE); modeButton.setGraphic(pencilImage); modeButton.setTooltip(pencilTooltip); initDialog(help, "Help", parse(IO.readFile("help.text"))); initDialog(about, "About", parse(IO.readFile("about.text"))); initNumField(rowsField, 1, 20, 500, null); initNumField(colsField, 1, 20, 500, null); initComboBox(genCombo, new String[]{ BACKSTEP, BRANCHINGBS, COINFLIP, KRUSKAL, PRIM, BLANK}); initComboBox(solverCombo, new String[]{ RIGHTHAND, LEFTHAND, RANDOMTURNS}); initComboBox(spriteCombo, MazeView.getSpriteTypes()); mazeview = new MazeView(); initNumField(cellField, 1, 20, 100, mazeview.cellSize); initNumField(wallField, 1, 2, 25, mazeview.wallThickness); cellColor.setValue(Color.WHITE); wallColor.setValue(Color.BLACK); goalColor.setValue(Color.GRAY); spriteColor.setValue(Color.BLUE); visitedColor.setValue(Color.PINK); mazeview.cellColor.bind(cellColor.valueProperty()); mazeview.wallColor.bind(wallColor.valueProperty()); mazeview.goalColor.bind(goalColor.valueProperty()); mazeview.spriteColor.bind(spriteColor.valueProperty()); mazeview.visitedColor.bind(visitedColor.valueProperty()); mazeview.showUnvisited.bind(showUnvisitedBox.selectedProperty()); scrollPane.setContent(mazeview); } private TextFlow parse(List<String> lines) { Text[] parsedSegments = new Text[lines.size()]; for (int i = 0 ; i < lines.size() ; i++) { parsedSegments[i] = new Text(lines.get(i).substring(1) + "\n"); switch (lines.get(i).charAt(0)) { case ' parsedSegments[i].setStyle("-fx-font-size: 20px;"); break; case '$': parsedSegments[i].setStyle("-fx-font-size: 16px;"); break; default: parsedSegments[i].setStyle("-fx-font-size: 12px; -fx-line-spacing: 4px;"); break; } } return new TextFlow(parsedSegments); } private void initDialog(Alert dialog, String title, TextFlow content) { dialog.setTitle(title); dialog.setHeaderText(null); dialog.setGraphic(null); dialog.getDialogPane().setStyle("-fx-max-width: 500px;"); dialog.getDialogPane().setContent(content); } private void initNumField(TextField field, int min, int initial, int max, IntegerProperty tie) { field.setText(Integer.toString(initial)); field.textProperty().addListener((observable, oldValue, newValue) -> { try { int newVal = Integer.parseInt(newValue); if (!(min <= newVal)) field.setText(Integer.toString(min)); else if (!(newVal <= max)) field.setText(Integer.toString(max)); } catch (NumberFormatException e) { field.setText(oldValue); } if (tie != null) tie.set(Integer.parseInt(field.getText())); }); if (tie != null) tie.set(initial); } private void initComboBox(ComboBox comboBox, String... values) { comboBox.setItems(FXCollections.observableArrayList(values)); comboBox.setValue(comboBox.getItems().get(0)); } public static void main(String[] args) { launch(args); } /* GUI ACTIONS */ public void openMaze() { playback.stop(); step = 0; mazeview.setMaze(MazeIO.openMaze()); } public void saveMaze() { MazeIO.saveMaze(mazeview.getMaze()); } public void export() { IO.saveToPNG(mazeview); } public void mode() { if (mazeview.getMode() == MazeView.SELECT_MODE) { mazeview.setMode(MazeView.PENCIL_MODE); modeButton.setGraphic(cursorImage); modeButton.setTooltip(cursorTooltip); } else { mazeview.setMode(MazeView.SELECT_MODE); modeButton.setGraphic(pencilImage); modeButton.setTooltip(pencilTooltip); } } public void generate() { playback.stop(); step = 0; mazeview.setMaze(new Maze(getMazeWidth(), getMazeHeight())); runActor(makeActor(getGenerator())); } public void solve() { runActor(makeActor(getSolver())); } public void pausePlayback() { playback.stop(); } public void playPlayback() { if (playback.getStatus() == Animation.Status.STOPPED) { mazeview.setShowAll(false); mazeview.redraw(); } playback.play(); } public void stopPlayback() { playback.stop(); step = 0; mazeview.setShowAll(true); mazeview.clear(); mazeview.redraw(); if (currentTask != null) currentTask.interrupt(); if (gifWriter != null) { gifWriter.close(); gifWriter = null; } } public void record() { stopPlayback(); gifWriter = new GifWriter(mazeview, (int)(playback.getRate() * FRAMEDELAY)); if (!gifWriter.init()) gifWriter = null; } public void help() { help.showAndWait(); } public void about() { about.showAndWait(); } /* ACTOR LOGIC */ private void setAnimation(List<Datum[]> steps) { mazeview.redraw(); this.steps = steps; step = 0; } private void runActor(MazeActor actor) { stopPlayback(); if (actor == null) return; animLabel.textProperty().bind(actor.messageProperty()); actor.setOnSucceeded(e -> setAnimation(actor.getValue())); currentTask = new Thread(actor); currentTask.start(); } private MazeActor makeActor(String name) { Maze maze = mazeview.getMaze(); switch (name) { case MazeMaker.BACKSTEP: return new Backstep(name, maze, getHBias(), getVBias()); case MazeMaker.BRANCHINGBS: return new BranchingBackstep(name, maze, getHBias(), getVBias(), 10); case MazeMaker.COINFLIP: return new RandomBinaryTree(name, maze, getHBias(), getVBias()); case MazeMaker.KRUSKAL: return new Kruskal(name, maze); case MazeMaker.PRIM: return new Prim(name, maze); case MazeMaker.BLANK: return null; case MazeMaker.RIGHTHAND: return new WallFollower(name, maze, true); case MazeMaker.LEFTHAND: return new WallFollower(name, maze, false); case MazeMaker.RANDOMTURNS: return new RandomTurns(name, maze); default: animLabel.setText("error"); return null; } } /* GUI GETTERS */ private int getMazeWidth() { return Integer.parseInt(colsField.getText()); } private int getMazeHeight() { return Integer.parseInt(rowsField.getText()); } private int getHBias() { return (int)biasSlider.getValue(); } private int getVBias() { return (int)(biasSlider.getMax() + biasSlider.getMin() - biasSlider.getValue()); } private String getGenerator() { return (String)genCombo.getValue(); } private String getSolver() { return (String)solverCombo.getValue(); } private String getSprite() { return (String)spriteCombo.getValue(); } }
package com.almasb.fxgl.app; import com.almasb.fxgl.core.EngineService; import com.almasb.fxgl.core.concurrent.Async; import com.almasb.fxgl.core.concurrent.IOTask; import com.almasb.fxgl.core.reflect.ReflectionUtils; import com.almasb.fxgl.core.serialization.Bundle; import com.almasb.fxgl.core.util.Platform; import com.almasb.fxgl.dsl.FXGL; import com.almasb.fxgl.generated.BuildProperties; import com.almasb.fxgl.profile.DataFile; import com.almasb.fxgl.profile.SaveLoadHandler; import com.almasb.fxgl.ui.FontType; import com.almasb.sslogger.*; import javafx.application.Application; import javafx.concurrent.Task; import javafx.stage.Stage; import java.util.HashMap; import java.util.Map; import java.util.ResourceBundle; /** * To use FXGL, extend this class and implement necessary methods. * The initialization process can be seen below (irrelevant phases are omitted): * * <ol> * <li>Instance fields of YOUR subclass of GameApplication</li> * <li>initSettings()</li> * <li>Services configuration (after this you can safely call any FXGL.* methods)</li> * Executed on JavaFX UI thread: * <li>initInput()</li> * <li>onPreInit()</li> * NOT executed on JavaFX UI thread: * <li>initGameVars()</li> * <li>initGame()</li> * <li>initPhysics()</li> * <li>initUI()</li> * Start of main game loop execution on JavaFX UI thread * </ol> * * Unless explicitly stated, methods are not thread-safe and must be * executed on the JavaFX Application (UI) Thread. * By default all callbacks are executed on the JavaFX Application (UI) Thread. * * Note: do NOT make any FXGL calls within your APP constructor or to initialize * APP fields during declaration, make these calls in initGame(). * * @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com) */ public abstract class GameApplication { private static final Logger log = Logger.get(GameApplication.class); public static void launch(String[] args) { try { var instance = newInstance(); launch(instance, args); } catch (Exception e) { printErrorAndExit(e); } } public static void launch(Class<? extends GameApplication> appClass, String[] args) { try { var instance = ReflectionUtils.newInstance(appClass); launch(instance, args); } catch (Exception e) { printErrorAndExit(e); } } public static void customLaunch(GameApplication app, Stage stage) { try { var settings = app.takeUserSettings(); app.initLogger(settings); FXGLApplication.customLaunchFX(app, settings, stage); } catch (Exception e) { printErrorAndExit(e); } } private static void launch(GameApplication app, String[] args) { var settings = app.takeUserSettings(); app.initLogger(settings); if (settings.isLinux()) { System.setProperty("quantum.multithreaded", "false"); } FXGLApplication.launchFX(app, settings, args); } private static GameApplication newInstance() { var appClass = ReflectionUtils.getCallingClass(GameApplication.class, "launch"); return ReflectionUtils.newInstance(appClass); } private static void printErrorAndExit(Exception e) { System.out.println("Error during launch:"); e.printStackTrace(); System.out.println("Application will now exit"); System.exit(-1); } private ReadOnlyGameSettings takeUserSettings() { var localSettings = new GameSettings(); initSettings(localSettings); var platform = Platform.get(); // if user set platform as browser, we keep it that way if (localSettings.getRuntimeInfo().getPlatform().isBrowser()) { platform = Platform.BROWSER; } var runtimeInfo = new RuntimeInfo(platform, BuildProperties.VERSION, BuildProperties.BUILD); localSettings.setRuntimeInfo(runtimeInfo); localSettings.setExperimentalNative(localSettings.isExperimentalNative() || platform.isMobile()); return localSettings.toReadOnly(); } private void initLogger(ReadOnlyGameSettings settings) { Logger.configure(new LoggerConfig()); // we write all logs to file but adjust console log level based on app mode if (settings.isDesktop()) { Logger.addOutput(new FileOutput("FXGL"), LoggerLevel.DEBUG); } Logger.addOutput(new ConsoleOutput(), settings.getApplicationMode().getLoggerLevel()); log.debug("Logger initialized"); log.debug("Logging settings\n" + settings); } /** * Initialize app settings. * * @param settings app settings */ protected abstract void initSettings(GameSettings settings); /** * Called once per application lifetime, just before initGame(). */ protected void onPreInit() {} /** * Initialize input, i.e. bind key presses, bind mouse buttons. * <pre> * Example: * * Input input = getInput(); * input.addAction(new UserAction("Move Left") { * protected void onAction() { * playerControl.moveLeft(); * } * }, KeyCode.A); * </pre> */ protected void initInput() {} /** * Can be overridden to provide global variables. * * @param vars map containing CVars (global variables) */ protected void initGameVars(Map<String, Object> vars) {} /** * Initialize game objects. */ protected void initGame() {} /** * Initialize collision handlers, physics properties. */ protected void initPhysics() {} /** * Initialize UI objects. */ protected void initUI() {} /** * Called every frame _only_ in Play state. * * @param tpf time per frame */ protected void onUpdate(double tpf) {} public static final class FXGLApplication extends Application { public static GameApplication app; private static ReadOnlyGameSettings settings; private static Engine engine; private MainWindow mainWindow; /** * This is the main entry point as run by the JavaFX platform. */ @Override public void start(Stage stage) { // any exception on the JavaFX thread will be caught and reported Thread.setDefaultUncaughtExceptionHandler((thread, e) -> handleFatalError(e)); log.debug("Initializing FXGL"); engine = new Engine(settings); // after this call, all FXGL.* calls (apart from those accessing services) are valid FXGL.inject$fxgl(engine, app, this); var startupScene = settings.getSceneFactory().newStartup(); // get window up ASAP mainWindow = new MainWindow(stage, startupScene, settings); mainWindow.show(); // TODO: possibly a better way exists of doing below engine.getEnvironmentVars$fxgl().put("settings", settings); engine.getEnvironmentVars$fxgl().put("mainWindow", mainWindow); // start initialization of services on a background thread // then start the loop on the JavaFX thread var task = IOTask.ofVoid(() -> { engine.initServices(); postServicesInit(); }) .onSuccess(n -> engine.startLoop()) .onFailure(e -> handleFatalError(e)) .toJavaFXTask(); Async.INSTANCE.execute(task); } private void postServicesInit() { initPauseResumeHandler(); initSaveLoadHandler(); initAndLoadLocalization(); initAndRegisterFontFactories(); // onGameUpdate is only updated in Game Scene FXGL.getGameScene().addListener(tpf -> engine.onGameUpdate(tpf)); } private void initPauseResumeHandler() { if (!settings.isMobile()) { mainWindow.iconifiedProperty().addListener((obs, o, isMinimized) -> { if (isMinimized) { engine.pauseLoop(); } else { engine.resumeLoop(); } }); } } private void initSaveLoadHandler() { FXGL.getSaveLoadService().addHandler(new SaveLoadHandler() { @Override public void onSave(DataFile data) { var bundle = new Bundle("FXGLServices"); engine.write(bundle); } @Override public void onLoad(DataFile data) { var bundle = data.getBundle("FXGLServices"); engine.read(bundle); } }); } private void initAndLoadLocalization() { log.debug("Loading localizations"); settings.getSupportedLanguages().forEach(lang -> { var bundle = FXGL.getAssetLoader().loadResourceBundle("languages/" + lang.getName().toLowerCase() + ".properties"); FXGL.getLocalizationService().addLanguageData(lang, bundle); }); FXGL.getLocalizationService().selectedLanguageProperty().bind(settings.getLanguage()); } private void initAndRegisterFontFactories() { log.debug("Registering font factories with UI factory"); var uiFactory = FXGL.getUIFactoryService(); uiFactory.registerFontFactory(FontType.UI, FXGL.getAssetLoader().loadFont(settings.getFontUI())); uiFactory.registerFontFactory(FontType.GAME, FXGL.getAssetLoader().loadFont(settings.getFontGame())); uiFactory.registerFontFactory(FontType.MONO, FXGL.getAssetLoader().loadFont(settings.getFontMono())); uiFactory.registerFontFactory(FontType.TEXT, FXGL.getAssetLoader().loadFont(settings.getFontText())); } private boolean isError = false; private void handleFatalError(Throwable error) { if (isError) { // just ignore to avoid spamming dialogs return; } isError = true; // stop main loop from running as we cannot continue engine.stopLoop(); log.fatal("Uncaught Exception:", error); log.fatal("Application will now exit"); if (mainWindow != null) { mainWindow.showFatalError(error, this::exitFXGL); } else { exitFXGL(); } } public void exitFXGL() { log.debug("Exiting FXGL"); if (engine != null && !isError) engine.stopLoopAndExitServices(); log.debug("Shutting down background threads"); Async.INSTANCE.shutdownNow(); log.debug("Closing logger and exiting JavaFX"); Logger.close(); javafx.application.Platform.exit(); } static void launchFX(GameApplication app, ReadOnlyGameSettings settings, String[] args) { FXGLApplication.app = app; FXGLApplication.settings = settings; launch(args); } static void customLaunchFX(GameApplication app, ReadOnlyGameSettings settings, Stage stage) { FXGLApplication.app = app; FXGLApplication.settings = settings; new FXGLApplication().start(stage); } } public static class GameApplicationService extends EngineService { private GameApplication app = FXGLApplication.app; @Override public void onMainLoopStarting() { // these things need to be called early before the main loop // so that menus can correctly display input controls, etc. app.initInput(); app.onPreInit(); } @Override public void onGameUpdate(double tpf) { app.onUpdate(tpf); } } /** * * Clears previous game. * * Initializes game, physics and UI. * * This task is rerun every time the game application is restarted. */ public static class InitAppTask extends Task<Void> { private GameApplication app = FXGLApplication.app; @Override protected Void call() throws Exception { var start = System.nanoTime(); log.debug("Initializing game"); updateMessage("Initializing game"); initGame(); app.initPhysics(); app.initUI(); FXGLApplication.engine.onGameReady(FXGL.getWorldProperties()); log.infof("Game initialization took: %.3f sec", (System.nanoTime() - start) / 1000000000.0); return null; } private void initGame() { var vars = new HashMap<String, Object>(); app.initGameVars(vars); vars.forEach((name, value) -> FXGL.getWorldProperties().setValue(name, value) ); app.initGame(); } @Override protected void failed() { throw new RuntimeException("Initialization failed", getException()); } } }