lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
lgpl-2.1
6267986ae6fd9aa86521384684e57b9d209cfaa2
0
xtremexp/UT4Converter
package org.xtx.ut4converter.t3d; import org.xtx.ut4converter.MapConverter; import org.xtx.ut4converter.export.UTPackageExtractor; import org.xtx.ut4converter.ucore.UPackageRessource; public class T3DMusicEvent extends T3DActor { private UPackageRessource song; private MTran transition = MTran.MTRAN_Fade; /** * How fast music transition is done */ enum MTran { MTRAN_None, MTRAN_Instant, MTRAN_Segue, MTRAN_Fade, MTRAN_FastFade, MTRAN_SlowFade } public T3DMusicEvent(MapConverter mc, String t3dClass) { super(mc, t3dClass); registerSimpleProperty("bAffectAllPlayers", Boolean.class, Boolean.TRUE); registerSimpleProperty("bOnceOnly", Boolean.class, Boolean.FALSE); registerSimpleProperty("bSilence", Boolean.class, Boolean.FALSE); registerSimpleProperty("CdTrack", Short.class, 255); registerSimpleProperty("SongSection", Short.class, 0); } @Override public boolean analyseT3DData(String line) { if (line.startsWith("Song=")) { this.song = mapConverter.getUPackageRessource(line.split("\'")[1], T3DRessource.Type.MUSIC); } else if (line.startsWith("Transition=")) { this.transition = MTran.valueOf(T3DUtils.getString(line)); } else { return super.analyseT3DData(line); } return true; } @Override public void convert() { if(song != null) { song.export(UTPackageExtractor.getExtractor(mapConverter, song)); } super.convert(); } @Override public String toString() { sbf.append(IDT).append("Begin Actor Class=MusicEvent_C \n"); sbf.append(IDT).append("\tBegin Object Class=AudioComponent Name=\"LevelMusic\"\n"); sbf.append(IDT).append("\tEnd Object\n"); sbf.append(IDT).append("\tBegin Object Name=\"LevelMusic\"\n"); writeLocRotAndScale(); sbf.append(IDT).append("\tEnd Object\n"); if(song != null){ sbf.append(IDT).append("\tSong=SoundCue'").append(song.getConvertedName(mapConverter)).append("'\n"); // duplicate property because in most case won't know the song because of "section" property // TODO maybe modify to add _<songSection> to Song property ?? (this would mean convert .s3m/.xm, and extract // wave by section sbf.append(IDT).append("\tSongOriginal=\"").append(song.getFullName()).append("\"\n"); } if(transition != null){ sbf.append(IDT).append("\tTransition=NewEnumerator").append(transition.ordinal()).append("\n"); } writeSimpleProperties(); sbf.append(IDT).append("\tLevelMusic=LevelMusic\n"); sbf.append(IDT).append("\tRootComponent=LevelMusic\n"); writeEndActor(); return super.toString(); } }
src/main/java/org/xtx/ut4converter/t3d/T3DMusicEvent.java
package org.xtx.ut4converter.t3d; import org.xtx.ut4converter.MapConverter; import org.xtx.ut4converter.export.UTPackageExtractor; import org.xtx.ut4converter.ucore.UPackageRessource; public class T3DMusicEvent extends T3DActor { private Boolean bAffectAllPlayers = Boolean.TRUE; private Boolean bOnceOnly; private Boolean bSilence; private Short cdTrack; private UPackageRessource song; private Short songSection; private MTran transition = MTran.MTRAN_Fade; /** * How fast music transition is done */ enum MTran { MTRAN_None, MTRAN_Instant, MTRAN_Segue, MTRAN_Fade, MTRAN_FastFade, MTRAN_SlowFade } public T3DMusicEvent(MapConverter mc, String t3dClass) { super(mc, t3dClass); } @Override public boolean analyseT3DData(String line) { if (line.startsWith("bAffectAllPlayers=")) { this.bAffectAllPlayers = T3DUtils.getBoolean(line); } else if (line.startsWith("bOnceOnly=")) { this.bOnceOnly = T3DUtils.getBoolean(line); } else if (line.startsWith("bSilence=")) { this.bSilence = T3DUtils.getBoolean(line); } else if (line.startsWith("CdTrack=")) { this.cdTrack = T3DUtils.getShort(line); } else if (line.startsWith("SongSection=")) { this.songSection = T3DUtils.getShort(line); } else if (line.startsWith("Song=")) { this.song = mapConverter.getUPackageRessource(line.split("\'")[1], T3DRessource.Type.MUSIC); } else if (line.startsWith("Transition=")) { this.transition = MTran.valueOf(T3DUtils.getString(line)); } else { return super.analyseT3DData(line); } return true; } @Override public void convert() { if(song != null) { song.export(UTPackageExtractor.getExtractor(mapConverter, song)); } super.convert(); } @Override public String toString() { sbf.append(IDT).append("Begin Actor Class=MusicEvent_C \n"); sbf.append(IDT).append("\tBegin Object Class=SceneComponent Name=\"DefaultSceneRoot\"\n"); sbf.append(IDT).append("\tEnd Object\n"); sbf.append(IDT).append("\tBegin Object Name=\"DefaultSceneRoot\"\n"); writeLocRotAndScale(); sbf.append(IDT).append("\tEnd Object\n"); sbf.append(IDT).append("\tDefaultSceneRoot=DefaultSceneRoot\n"); if(bAffectAllPlayers != null){ sbf.append(IDT).append("\tbAffectAllPlayers=").append(bAffectAllPlayers).append("\n"); } if(bOnceOnly != null){ sbf.append(IDT).append("\tbOnceOnly=").append(bOnceOnly).append("\n"); } if(bSilence != null){ sbf.append(IDT).append("\tbSilence=").append(bSilence).append("\n"); } if(cdTrack != null){ sbf.append(IDT).append("\tCdTrack=").append(cdTrack).append("\n"); } if(song != null){ sbf.append(IDT).append("\tSong=SoundCue'").append(song.getConvertedName(mapConverter)).append("'\n"); // duplicate property because in most case won't know the song because of "section" property // TODO maybe modify to add _<songSection> to Song property ?? (this would mean convert .s3m/.xm, and extract // wave by section sbf.append(IDT).append("\tSongOriginal=\"").append(song.getFullName()).append("\"\n"); } if(songSection != null){ sbf.append(IDT).append("\tSongSection=").append(songSection).append("\n"); } if(transition != null){ sbf.append(IDT).append("\tTransition=NewEnumerator").append(transition.ordinal()).append("\n"); } sbf.append(IDT).append("\tRootComponent=DefaultSceneRoot\n"); writeEndActor(); return super.toString(); } }
Music event fix bad root component + refactors
src/main/java/org/xtx/ut4converter/t3d/T3DMusicEvent.java
Music event fix bad root component + refactors
<ide><path>rc/main/java/org/xtx/ut4converter/t3d/T3DMusicEvent.java <ide> <ide> public class T3DMusicEvent extends T3DActor { <ide> <del> private Boolean bAffectAllPlayers = Boolean.TRUE; <del> <del> private Boolean bOnceOnly; <del> <del> private Boolean bSilence; <del> <del> private Short cdTrack; <del> <ide> private UPackageRessource song; <del> <del> private Short songSection; <ide> <ide> private MTran transition = MTran.MTRAN_Fade; <ide> <ide> <ide> public T3DMusicEvent(MapConverter mc, String t3dClass) { <ide> super(mc, t3dClass); <add> <add> registerSimpleProperty("bAffectAllPlayers", Boolean.class, Boolean.TRUE); <add> registerSimpleProperty("bOnceOnly", Boolean.class, Boolean.FALSE); <add> registerSimpleProperty("bSilence", Boolean.class, Boolean.FALSE); <add> registerSimpleProperty("CdTrack", Short.class, 255); <add> registerSimpleProperty("SongSection", Short.class, 0); <ide> } <ide> <ide> @Override <ide> public boolean analyseT3DData(String line) { <del> if (line.startsWith("bAffectAllPlayers=")) { <del> this.bAffectAllPlayers = T3DUtils.getBoolean(line); <del> } <del> else if (line.startsWith("bOnceOnly=")) { <del> this.bOnceOnly = T3DUtils.getBoolean(line); <del> } <del> else if (line.startsWith("bSilence=")) { <del> this.bSilence = T3DUtils.getBoolean(line); <del> } <del> else if (line.startsWith("CdTrack=")) { <del> this.cdTrack = T3DUtils.getShort(line); <del> } <del> else if (line.startsWith("SongSection=")) { <del> this.songSection = T3DUtils.getShort(line); <del> } <del> else if (line.startsWith("Song=")) { <add> if (line.startsWith("Song=")) { <ide> this.song = mapConverter.getUPackageRessource(line.split("\'")[1], T3DRessource.Type.MUSIC); <ide> } <ide> else if (line.startsWith("Transition=")) { <ide> <ide> sbf.append(IDT).append("Begin Actor Class=MusicEvent_C \n"); <ide> <del> sbf.append(IDT).append("\tBegin Object Class=SceneComponent Name=\"DefaultSceneRoot\"\n"); <add> sbf.append(IDT).append("\tBegin Object Class=AudioComponent Name=\"LevelMusic\"\n"); <ide> sbf.append(IDT).append("\tEnd Object\n"); <ide> <del> sbf.append(IDT).append("\tBegin Object Name=\"DefaultSceneRoot\"\n"); <add> sbf.append(IDT).append("\tBegin Object Name=\"LevelMusic\"\n"); <ide> writeLocRotAndScale(); <ide> sbf.append(IDT).append("\tEnd Object\n"); <ide> <del> sbf.append(IDT).append("\tDefaultSceneRoot=DefaultSceneRoot\n"); <del> <del> <del> if(bAffectAllPlayers != null){ <del> sbf.append(IDT).append("\tbAffectAllPlayers=").append(bAffectAllPlayers).append("\n"); <del> } <del> <del> if(bOnceOnly != null){ <del> sbf.append(IDT).append("\tbOnceOnly=").append(bOnceOnly).append("\n"); <del> } <del> <del> if(bSilence != null){ <del> sbf.append(IDT).append("\tbSilence=").append(bSilence).append("\n"); <del> } <del> <del> if(cdTrack != null){ <del> sbf.append(IDT).append("\tCdTrack=").append(cdTrack).append("\n"); <del> } <ide> <ide> if(song != null){ <ide> sbf.append(IDT).append("\tSong=SoundCue'").append(song.getConvertedName(mapConverter)).append("'\n"); <ide> sbf.append(IDT).append("\tSongOriginal=\"").append(song.getFullName()).append("\"\n"); <ide> } <ide> <del> if(songSection != null){ <del> sbf.append(IDT).append("\tSongSection=").append(songSection).append("\n"); <del> } <del> <ide> if(transition != null){ <ide> sbf.append(IDT).append("\tTransition=NewEnumerator").append(transition.ordinal()).append("\n"); <ide> } <ide> <del> sbf.append(IDT).append("\tRootComponent=DefaultSceneRoot\n"); <add> writeSimpleProperties(); <add> <add> sbf.append(IDT).append("\tLevelMusic=LevelMusic\n"); <add> sbf.append(IDT).append("\tRootComponent=LevelMusic\n"); <ide> <ide> writeEndActor(); <ide>
Java
lgpl-2.1
16e81eb12173ec497a53d6c6332113b5cbfbb820
0
ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 2.1 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *****************************************************************/ package jade.core.messaging; //#MIDP_EXCLUDE_FILE import java.io.FileWriter; import java.io.PrintWriter; import java.io.IOException; import java.util.Date; import jade.core.ServiceFinder; import jade.core.VerticalCommand; import jade.core.GenericCommand; import jade.core.Service; import jade.core.BaseService; import jade.core.ServiceException; import jade.core.Filter; import jade.core.Node; import jade.core.AgentContainer; import jade.core.MainContainer; import jade.core.CaseInsensitiveString; import jade.core.AID; import jade.core.ContainerID; import jade.core.Profile; import jade.core.Specifier; import jade.core.ProfileException; import jade.core.IMTPException; import jade.core.NotFoundException; import jade.core.UnreachableException; import jade.domain.FIPAAgentManagement.InternalError; import jade.domain.FIPAAgentManagement.Envelope; import jade.domain.FIPAAgentManagement.ReceivedObject; import jade.security.Authority; import jade.security.AgentPrincipal; import jade.security.PrivilegedExceptionAction; import jade.security.AuthException; import jade.lang.acl.ACLMessage; import jade.lang.acl.ACLCodec; import jade.lang.acl.StringACLCodec; import jade.mtp.MTP; import jade.mtp.MTPDescriptor; import jade.mtp.MTPException; import jade.mtp.InChannel; import jade.mtp.TransportAddress; import jade.util.leap.Iterator; import jade.util.leap.Map; import jade.util.leap.HashMap; import jade.util.leap.List; /** The JADE service to manage the message passing subsystem installed on the platform. @author Giovanni Rimassa - FRAMeTech s.r.l. */ public class MessagingService extends BaseService implements MessageManager.Channel { public static class UnknownACLEncodingException extends NotFoundException { UnknownACLEncodingException(String msg) { super(msg); } } // End of UnknownACLEncodingException class public static final String MAIN_SLICE = "Main-Container"; public MessagingService(AgentContainer ac, Profile p) throws ProfileException { super(p); myContainer = ac; cachedSlices = new HashMap(); // Initialize its own ID String platformID = myContainer.getPlatformID(); accID = "fipa-mts://" + platformID + "/acc"; myMessageManager = new MessageManager(); myMessageManager.initialize(p, this); // Create a local slice localSlice = new ServiceComponent(); } public String getName() { return MessagingSlice.NAME; } public Class getHorizontalInterface() { return MessagingSlice.class; } public Slice getLocalSlice() { return localSlice; } public Filter getCommandFilter() { return localSlice; } /** Inner mix-in class for this service: this class receives commands through its <code>Filter</code> interface and serves them, coordinating with remote parts of this service through the <code>Slice</code> interface (that extends the <code>Service.Slice</code> interface). */ private class ServiceComponent implements Filter, MessagingSlice { public Iterator getAddresses() { return routes.getAddresses(); } // Entry point for the ACL message dispatching process public void deliverNow(ACLMessage msg, AID receiverID) throws UnreachableException, NotFoundException { try { MainContainer impl = myContainer.getMain(); if(impl != null) { while(true) { // Directly use the GADT on the main container ContainerID cid = impl.getContainerID(receiverID); MessagingSlice targetSlice = (MessagingSlice)getSlice(cid.getName()); try { targetSlice.dispatchLocally(msg, receiverID); return; // Message dispatched } catch(NotFoundException nfe) { // The agent was found in he GADT, but not in the target LADT => try again } } } else { // Try first with the cached <AgentID;Container ID> pairs MessagingSlice cachedSlice = (MessagingSlice)cachedSlices.get(receiverID); if(cachedSlice != null) { // Cache hit :-) try { System.out.println("--- Cache Hit for AID [" + receiverID.getLocalName() + "] ---"); cachedSlice.dispatchLocally(msg, receiverID); } catch(IMTPException imtpe) { cachedSlices.remove(receiverID); // Eliminate stale cache entry deliverUntilOK(msg, receiverID); } catch(NotFoundException nfe) { cachedSlices.remove(receiverID); // Eliminate stale cache entry deliverUntilOK(msg, receiverID); } } else { // Cache miss :-( System.out.println("--- Cache Miss for AID [" + receiverID.getLocalName() + "] ---"); deliverUntilOK(msg, receiverID); } } } catch(IMTPException imtpe) { throw new UnreachableException("Unreachable network node", imtpe); } catch(ServiceException se) { throw new UnreachableException("Unreachable service slice:", se); } } private void deliverUntilOK(ACLMessage msg, AID receiverID) throws IMTPException, NotFoundException, ServiceException { boolean ok = false; do { MessagingSlice mainSlice = (MessagingSlice)getSlice(MAIN_SLICE); ContainerID cid = mainSlice.getAgentLocation(receiverID); MessagingSlice targetSlice = (MessagingSlice)getSlice(cid.getName()); try { targetSlice.dispatchLocally(msg, receiverID); System.out.println("--- New Container for AID " + receiverID.getLocalName() + " is " + cid.getName() + " ---"); // On successful message dispatch, put the slice into the slice cache cachedSlices.put(receiverID, targetSlice); ok = true; } catch(NotFoundException nfe) { ok = false; // Stale proxy again, maybe the receiver is running around. Try again... } } while(!ok); } // Implementation of the Filter interface public void accept(VerticalCommand cmd) { // FIXME: Should set the exception somehow... try { String name = cmd.getName(); if(name.equals(SEND_MESSAGE)) { handleSendMessage(cmd); } if(name.equals(INSTALL_MTP)) { Object result = handleInstallMTP(cmd); cmd.setReturnValue(result); } else if(name.equals(UNINSTALL_MTP)) { handleUninstallMTP(cmd); } else if(name.equals(SET_PLATFORM_ADDRESSES)) { handleSetPlatformAddresses(cmd); } } catch(AuthException ae) { cmd.setReturnValue(ae); } catch(IMTPException imtpe) { imtpe.printStackTrace(); } catch(NotFoundException nfe) { nfe.printStackTrace(); } catch(ServiceException se) { se.printStackTrace(); } catch(MTPException mtpe) { mtpe.printStackTrace(); } } public void setBlocking(boolean newState) { // Do nothing. Blocking and Skipping not supported } public boolean isBlocking() { return false; // Blocking and Skipping not implemented } public void setSkipping(boolean newState) { // Do nothing. Blocking and Skipping not supported } public boolean isSkipping() { return false; // Blocking and Skipping not implemented } // Implementation of the Service.Slice interface public Service getService() { return MessagingService.this; } public Node getNode() throws ServiceException { try { return MessagingService.this.getLocalNode(); } catch(IMTPException imtpe) { throw new ServiceException("Problem in contacting the IMTP Manager", imtpe); } } public void serve(VerticalCommand cmd) { try { String cmdName = cmd.getName(); Object[] params = cmd.getParams(); if(cmdName.equals(H_DISPATCHLOCALLY)) { ACLMessage msg = (ACLMessage)params[0]; AID receiverID = (AID)params[1]; dispatchLocally(msg, receiverID); } else if(cmdName.equals(H_ROUTEOUT)) { ACLMessage msg = (ACLMessage)params[0]; AID receiverID = (AID)params[1]; String address = (String)params[2]; routeOut(msg, receiverID, address); } else if(cmdName.equals(H_GETAGENTLOCATION)) { AID agentID = (AID)params[0]; cmd.setReturnValue(getAgentLocation(agentID)); } else if(cmdName.equals(H_INSTALLMTP)) { String address = (String)params[0]; String className = (String)params[1]; cmd.setReturnValue(installMTP(address, className)); } else if(cmdName.equals(H_UNINSTALLMTP)) { String address = (String)params[0]; uninstallMTP(address); } else if(cmdName.equals(H_NEWMTP)) { MTPDescriptor mtp = (MTPDescriptor)params[0]; ContainerID cid = (ContainerID)params[1]; newMTP(mtp, cid); } else if(cmdName.equals(H_DEADMTP)) { MTPDescriptor mtp = (MTPDescriptor)params[0]; ContainerID cid = (ContainerID)params[1]; deadMTP(mtp, cid); } else if(cmdName.equals(H_ADDROUTE)) { MTPDescriptor mtp = (MTPDescriptor)params[0]; String sliceName = (String)params[1]; addRoute(mtp, sliceName); } else if(cmdName.equals(H_REMOVEROUTE)) { MTPDescriptor mtp = (MTPDescriptor)params[0]; String sliceName = (String)params[1]; removeRoute(mtp, sliceName); } } catch(Throwable t) { cmd.setReturnValue(t); } } // Implementation of the service-specific horizontal interface MessagingSlice public void dispatchLocally(ACLMessage msg, AID receiverID) throws IMTPException, NotFoundException { boolean found = myContainer.postMessageToLocalAgent(msg, receiverID); if(!found) { throw new NotFoundException("Messaging service slice failed to find " + receiverID); } } public void routeOut(ACLMessage msg, AID receiverID, String address) throws IMTPException, MTPException { RoutingTable.OutPort out = routes.lookup(address); if(out != null) out.route(msg, receiverID, address); else throw new MTPException("No suitable route found for address " + address + "."); } public ContainerID getAgentLocation(AID agentID) throws IMTPException, NotFoundException { MainContainer impl = myContainer.getMain(); if(impl != null) { return impl.getContainerID(agentID); } else { // Do nothing for now, but could also have a local GADT copy, thus enabling e.g. Main Container replication return null; } } public MTPDescriptor installMTP(String address, String className) throws IMTPException, ServiceException, MTPException { try { // Create the MTP Class c = Class.forName(className); MTP proto = (MTP)c.newInstance(); InChannel.Dispatcher dispatcher = new InChannel.Dispatcher() { public void dispatchMessage(Envelope env, byte[] payload) { // To avoid message loops, make sure that the ID of this ACC does // not appear in a previous 'received' stamp ReceivedObject[] stamps = env.getStamps(); for(int i = 0; i < stamps.length; i++) { String id = stamps[i].getBy(); if(CaseInsensitiveString.equalsIgnoreCase(id, accID)) { System.out.println("ERROR: Message loop detected !!!"); System.out.println("Route is: "); for(int j = 0; j < stamps.length; j++) System.out.println("[" + j + "]" + stamps[j].getBy()); System.out.println("Message dispatch aborted."); return; } } // Put a 'received-object' stamp in the envelope ReceivedObject ro = new ReceivedObject(); ro.setBy(accID); ro.setDate(new Date()); env.setReceived(ro); // Decode the message, according to the 'acl-representation' slot String aclRepresentation = env.getAclRepresentation(); // Default to String representation if(aclRepresentation == null) aclRepresentation = StringACLCodec.NAME; ACLCodec codec = (ACLCodec)messageEncodings.get(aclRepresentation.toLowerCase()); if(codec == null) { System.out.println("Unknown ACL codec: " + aclRepresentation); return; } try { ACLMessage msg = codec.decode(payload); msg.setEnvelope(env); // If the 'sender' AID has no addresses, replace it with the // 'from' envelope slot AID sender = msg.getSender(); if(sender == null) { System.out.println("ERROR: Trying to dispatch a message with a null sender."); System.out.println("Aborting send operation..."); return; } Iterator itSender = sender.getAllAddresses(); if(!itSender.hasNext()) msg.setSender(env.getFrom()); Iterator it = env.getAllIntendedReceiver(); // If no 'intended-receiver' is present, use the 'to' slot (but // this should not happen). if(!it.hasNext()) it = env.getAllTo(); while(it.hasNext()) { AID receiver = (AID)it.next(); boolean found = myContainer.postMessageToLocalAgent(msg, receiver); if(!found) { myMessageManager.deliver(msg, receiver); } } } catch(ACLCodec.CodecException ce) { ce.printStackTrace(); } } }; if(address == null) { // Let the MTP choose the address TransportAddress ta = proto.activate(dispatcher); address = proto.addrToStr(ta); } else { // Convert the given string into a TransportAddress object and use it TransportAddress ta = proto.strToAddr(address); proto.activate(dispatcher, ta); } routes.addLocalMTP(address, proto); MTPDescriptor result = new MTPDescriptor(proto.getName(), new String[] {address}, proto.getSupportedProtocols()); MessagingSlice mainSlice = (MessagingSlice)getSlice(MAIN_SLICE); mainSlice.newMTP(result, myContainer.getID()); return result; } catch(ClassNotFoundException cnfe) { throw new MTPException("ERROR: The class " + className + " for the " + address + " MTP was not found"); } catch(InstantiationException ie) { throw new MTPException("The class " + className + " raised InstantiationException (see nested exception)", ie); } catch(IllegalAccessException iae) { throw new MTPException("The class " + className + " raised IllegalAccessException (see nested exception)", iae); } } public void uninstallMTP(String address) throws IMTPException, ServiceException, NotFoundException, MTPException { MTP proto = routes.removeLocalMTP(address); if(proto != null) { TransportAddress ta = proto.strToAddr(address); proto.deactivate(ta); MTPDescriptor desc = new MTPDescriptor(proto.getName(), new String[] {address}, proto.getSupportedProtocols()); MessagingSlice mainSlice = (MessagingSlice)getSlice(MAIN_SLICE); mainSlice.deadMTP(desc, myContainer.getID()); } else { throw new MTPException("No such address was found on this container: " + address); } } public void newMTP(MTPDescriptor mtp, ContainerID cid) throws IMTPException, ServiceException { MainContainer impl = myContainer.getMain(); if(impl != null) { // Update the routing tables of all the other slices Slice[] slices = getAllSlices(); for(int i = 0; i < slices.length; i++) { try { MessagingSlice slice = (MessagingSlice)slices[i]; String sliceName = slice.getNode().getName(); if(!sliceName.equals(cid.getName())) { slice.addRoute(mtp, cid.getName()); } } catch(Throwable t) { // Re-throw allowed exceptions if(t instanceof IMTPException) { throw (IMTPException)t; } if(t instanceof ServiceException) { throw (ServiceException)t; } System.out.println("### addRoute() threw " + t.getClass().getName() + " ###"); } } impl.newMTP(mtp, cid); } else { // Do nothing for now, but could also route the command to the main slice, thus enabling e.g. AMS replication } } public void deadMTP(MTPDescriptor mtp, ContainerID cid) throws IMTPException, ServiceException { MainContainer impl = myContainer.getMain(); if(impl != null) { // Update the routing tables of all the other slices Slice[] slices = getAllSlices(); for(int i = 0; i < slices.length; i++) { try { MessagingSlice slice = (MessagingSlice)slices[i]; String sliceName = slice.getNode().getName(); if(!sliceName.equals(cid.getName())) { slice.removeRoute(mtp, cid.getName()); } } catch(Throwable t) { // Re-throw allowed exceptions if(t instanceof IMTPException) { throw (IMTPException)t; } if(t instanceof ServiceException) { throw (ServiceException)t; } System.out.println("### removeRoute() threw " + t.getClass().getName() + " ###"); } } impl.deadMTP(mtp, cid); } else { // Do nothing for now, but could also route the command to the main slice, thus enabling e.g. AMS replication } } public void addRoute(MTPDescriptor mtp, String sliceName) throws IMTPException, ServiceException { MessagingSlice slice = (MessagingSlice)getSlice(sliceName); routes.addRemoteMTP(mtp, sliceName, slice); String[] addresses = mtp.getAddresses(); for(int i = 0; i < addresses.length; i++) { myContainer.addAddressToLocalAgents(addresses[i]); } } public void removeRoute(MTPDescriptor mtp, String sliceName) throws IMTPException, ServiceException { MessagingSlice slice = (MessagingSlice)getSlice(sliceName); routes.removeRemoteMTP(mtp, sliceName, slice); String[] addresses = mtp.getAddresses(); for(int i = 0; i < addresses.length; i++) { myContainer.removeAddressFromLocalAgents(addresses[i]); } } private RoutingTable routes = new RoutingTable(MessagingService.this); } // End of ServiceComponent class /** Activates the ACL codecs and MTPs as specified in the given <code>Profile</code> instance. @param myProfile The <code>Profile</code> instance containing the list of ACL codecs and MTPs to activate on this node. **/ public void activateProfile(Profile myProfile) { try { // Activate the default ACL String codec anyway ACLCodec stringCodec = new StringACLCodec(); messageEncodings.put(stringCodec.getName().toLowerCase(), stringCodec); // Codecs List l = myProfile.getSpecifiers(Profile.ACLCODECS); Iterator codecs = l.iterator(); while (codecs.hasNext()) { Specifier spec = (Specifier) codecs.next(); String className = spec.getClassName(); try{ Class c = Class.forName(className); ACLCodec codec = (ACLCodec)c.newInstance(); messageEncodings.put(codec.getName().toLowerCase(), codec); System.out.println("Installed "+ codec.getName()+ " ACLCodec implemented by " + className + "\n"); // FIXME: notify the AMS of the new Codec to update the APDescritption. } catch(ClassNotFoundException cnfe){ throw new jade.lang.acl.ACLCodec.CodecException("ERROR: The class " +className +" for the ACLCodec not found.", cnfe); } catch(InstantiationException ie) { throw new jade.lang.acl.ACLCodec.CodecException("The class " + className + " raised InstantiationException (see NestedException)", ie); } catch(IllegalAccessException iae) { throw new jade.lang.acl.ACLCodec.CodecException("The class " + className + " raised IllegalAccessException (see nested exception)", iae); } } // MTPs l = myProfile.getSpecifiers(Profile.MTPS); String fileName = myProfile.getParameter(Profile.FILE_DIR, "") + "MTPs-" + myContainer.getID().getName() + ".txt"; PrintWriter f = new PrintWriter(new FileWriter(fileName)); Iterator mtps = l.iterator(); while (mtps.hasNext()) { Specifier spec = (Specifier) mtps.next(); String className = spec.getClassName(); String addressURL = null; Object[] args = spec.getArgs(); if (args != null && args.length > 0) { addressURL = args[0].toString(); if(addressURL.equals("")) { addressURL = null; } } MTPDescriptor mtp = localSlice.installMTP(addressURL, className); String[] mtpAddrs = mtp.getAddresses(); f.println(mtpAddrs[0]); System.out.println(mtpAddrs[0]); } f.close(); } catch (ProfileException pe1) { System.out.println("Error reading MTPs/Codecs"); pe1.printStackTrace(); } catch(ServiceException se) { System.out.println("Error installing local MTPs"); se.printStackTrace(); } catch(jade.lang.acl.ACLCodec.CodecException ce) { System.out.println("Error installing ACL Codec"); ce.printStackTrace(); } catch(MTPException me) { System.out.println("Error installing MTP"); me.printStackTrace(); } catch(IOException ioe) { System.out.println("Error writing platform address"); ioe.printStackTrace(); } catch(IMTPException imtpe) { // Should never happen as this is a local call imtpe.printStackTrace(); } } public void deliverNow(ACLMessage msg, AID receiverID) throws UnreachableException { try { if(myContainer.livesHere(receiverID)) { localSlice.deliverNow(msg, receiverID); } else { // Dispatch it through the ACC Iterator addresses = receiverID.getAllAddresses(); while(addresses.hasNext()) { String address = (String)addresses.next(); try { forwardMessage(msg, receiverID, address); return; } catch(MTPException mtpe) { System.out.println("Bad address [" + address + "]: trying the next one..."); } } notifyFailureToSender(msg, receiverID, new InternalError("No valid address contained within the AID " + receiverID.getName())); } } catch(NotFoundException nfe) { // The receiver does not exist --> Send a FAILURE message notifyFailureToSender(msg, receiverID, new InternalError("Agent not found: " + nfe.getMessage())); } } private void forwardMessage(ACLMessage msg, AID receiver, String address) throws MTPException { AID aid = msg.getSender(); if(aid == null) { System.out.println("ERROR: null message sender. Aborting message dispatch..."); return; } // if has no address set, then adds the addresses of this platform if(!aid.getAllAddresses().hasNext()) addPlatformAddresses(aid); Iterator it1 = msg.getAllReceiver(); while(it1.hasNext()) { AID id = (AID)it1.next(); if(!id.getAllAddresses().hasNext()) addPlatformAddresses(id); } Iterator it2 = msg.getAllReplyTo(); while(it2.hasNext()) { AID id = (AID)it2.next(); if(!id.getAllAddresses().hasNext()) addPlatformAddresses(id); } try { localSlice.routeOut(msg, receiver, address); } catch(IMTPException imtpe) { throw new MTPException("Error during message routing", imtpe); } } /** * This method is used internally by the platform in order * to notify the sender of a message that a failure was reported by * the Message Transport Service. * Package scoped as it can be called by the MessageManager */ public void notifyFailureToSender(ACLMessage msg, AID receiver, InternalError ie) { //if (the sender is not the AMS and the performative is not FAILURE) if ( (msg.getSender()==null) || ((msg.getSender().equals(myContainer.getAMS())) && (msg.getPerformative()==ACLMessage.FAILURE))) // sanity check to avoid infinte loops return; // else send back a failure message final ACLMessage failure = msg.createReply(); failure.setPerformative(ACLMessage.FAILURE); //System.err.println(failure.toString()); final AID theAMS = myContainer.getAMS(); failure.setSender(theAMS); // FIXME: the content is not completely correct, but that should // also avoid creating wrong content // FIXME: the content should include the indication about the // receiver to wich dispatching failed. String content = "( (action " + msg.getSender().toString(); content = content + " ACLMessage ) " + ie.getMessage() + ")"; failure.setContent(content); try { Authority authority = myContainer.getAuthority(); authority.doPrivileged(new PrivilegedExceptionAction() { public Object run() { try { // FIXME: Having a custom code path to send failure notifications would be better... GenericCommand cmd = new GenericCommand(MessagingSlice.SEND_MESSAGE, MessagingSlice.NAME, ""); cmd.addParam(failure); cmd.addParam(theAMS); handleSendMessage(cmd); } catch (AuthException ae) { // it does not have permission to notify the failure // it never happens if the policy file gives // enough permission to the jade.jar System.out.println( ae.getMessage() ); } return null; // nothing to return } }); } catch(Exception e) { // should be never thrown e.printStackTrace(); } } // Vertical command handler methods private void handleSendMessage(VerticalCommand cmd) throws AuthException { Object[] params = cmd.getParams(); ACLMessage msg = (ACLMessage)params[0]; AID sender = (AID)params[1]; // Set the sender unless already set try { if (msg.getSender().getName().length() < 1) msg.setSender(sender); } catch (NullPointerException e) { msg.setSender(sender); } // --- This code could go into a Security Service, intercepting the message sending... AgentPrincipal target1 = myContainer.getAgentPrincipal(msg.getSender()); Authority authority = myContainer.getAuthority(); authority.checkAction(Authority.AGENT_SEND_AS, target1, null); // --- End of security code AuthException lastException = null; // 26-Mar-2001. The receivers set into the Envelope of the message, // if present, must have precedence over those set into the ACLMessage. // If no :intended-receiver parameter is present in the Envelope, // then the :to parameter // is used to generate :intended-receiver field. // // create an Iterator with all the receivers to which the message must be // delivered Iterator it = msg.getAllIntendedReceiver(); while (it.hasNext()) { AID dest = (AID)it.next(); try { AgentPrincipal target2 = myContainer.getAgentPrincipal(dest); authority.checkAction(Authority.AGENT_SEND_TO, target2, null); ACLMessage copy = (ACLMessage)msg.clone(); boolean found = myContainer.postMessageToLocalAgent(copy, dest); if(!found) { myMessageManager.deliver(copy, dest); } } catch (AuthException ae) { lastException = ae; notifyFailureToSender(msg, dest, new InternalError(ae.getMessage())); } } if(lastException != null) throw lastException; } private MTPDescriptor handleInstallMTP(VerticalCommand cmd) throws IMTPException, ServiceException, NotFoundException, MTPException { Object[] params = cmd.getParams(); String address = (String)params[0]; ContainerID cid = (ContainerID)params[1]; String className = (String)params[2]; MessagingSlice targetSlice = (MessagingSlice)getSlice(cid.getName()); return targetSlice.installMTP(address, className); } private void handleUninstallMTP(VerticalCommand cmd) throws IMTPException, ServiceException, NotFoundException, MTPException { Object[] params = cmd.getParams(); String address = (String)params[0]; ContainerID cid = (ContainerID)params[1]; MessagingSlice targetSlice = (MessagingSlice)getSlice(cid.getName()); targetSlice.uninstallMTP(address); } private void handleSetPlatformAddresses(VerticalCommand cmd) { Object[] params = cmd.getParams(); AID id = (AID)params[0]; id.clearAllAddresses(); addPlatformAddresses(id); } public void prepareEnvelope(ACLMessage msg, AID receiver) { Envelope env = msg.getEnvelope(); if(env == null) { msg.setDefaultEnvelope(); env = msg.getEnvelope(); } // 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()); // If no ACL representation is found, then default to String // representation String rep = env.getAclRepresentation(); if(rep == null) env.setAclRepresentation(StringACLCodec.NAME); // 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); String comments = env.getComments(); if(comments == null) env.setComments(""); Long payloadLength = env.getPayloadLength(); if(payloadLength == null) env.setPayloadLength(new Long(-1)); String payloadEncoding = env.getPayloadEncoding(); if(payloadEncoding == null) env.setPayloadEncoding(""); } public byte[] encodeMessage(ACLMessage msg) throws NotFoundException { Envelope env = msg.getEnvelope(); String enc = env.getAclRepresentation(); if(enc != null) { // A Codec was selected ACLCodec codec =(ACLCodec)messageEncodings.get(enc.toLowerCase()); if(codec!=null) { // Supported Codec // FIXME: should verifY that the recevivers supports this Codec return codec.encode(msg); } else { // Unsupported Codec //FIXME: find the best according to the supported, the MTP (and the receivers Codec) throw new 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 UnknownACLEncodingException("No ACL encoding set."); } } /* * This method is called before preparing the Envelope of an outgoing message. * It checks for all the AIDs present in the message and adds the addresses, if not present **/ private void addPlatformAddresses(AID id) { Iterator it = localSlice.getAddresses(); while(it.hasNext()) { String addr = (String)it.next(); id.addAddresses(addr); } } // The concrete agent container, providing access to LADT, etc. private AgentContainer myContainer; // The local slice for this service private ServiceComponent localSlice; // The cached AID -> MessagingSlice associations private Map cachedSlices; // The table of the locally installed ACL message encodings private Map messageEncodings = new HashMap(); // The platform ID, to be used in inter-platform dispatching private String accID; // The component managing asynchronous message delivery and retries private MessageManager myMessageManager; }
src/jade/core/messaging/MessagingService.java
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 2.1 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *****************************************************************/ package jade.core.messaging; import java.io.FileWriter; import java.io.PrintWriter; import java.io.IOException; import java.util.Date; import jade.core.ServiceFinder; import jade.core.VerticalCommand; import jade.core.GenericCommand; import jade.core.Service; import jade.core.BaseService; import jade.core.ServiceException; import jade.core.Filter; import jade.core.Node; import jade.core.AgentContainerImpl; import jade.core.MainContainerImpl; import jade.core.CaseInsensitiveString; import jade.core.AID; import jade.core.ContainerID; import jade.core.Profile; import jade.core.Specifier; import jade.core.ProfileException; import jade.core.IMTPException; import jade.core.NotFoundException; import jade.core.UnreachableException; import jade.domain.FIPAAgentManagement.InternalError; import jade.domain.FIPAAgentManagement.Envelope; import jade.domain.FIPAAgentManagement.ReceivedObject; import jade.security.Authority; import jade.security.AgentPrincipal; import jade.security.PrivilegedExceptionAction; import jade.security.AuthException; import jade.lang.acl.ACLMessage; import jade.lang.acl.ACLCodec; import jade.lang.acl.StringACLCodec; import jade.mtp.MTP; import jade.mtp.MTPDescriptor; import jade.mtp.MTPException; import jade.mtp.InChannel; import jade.mtp.TransportAddress; import jade.util.leap.Iterator; import jade.util.leap.Map; import jade.util.leap.HashMap; import jade.util.leap.List; /** The JADE service to manage the message passing subsystem installed on the platform. @author Giovanni Rimassa - FRAMeTech s.r.l. */ public class MessagingService extends BaseService implements MessageManager.Channel { public static class UnknownACLEncodingException extends NotFoundException { UnknownACLEncodingException(String msg) { super(msg); } } // End of UnknownACLEncodingException class /** The name of this service. */ public static final String NAME = "jade.core.messaging.Messaging"; /** This command name represents the action of sending an ACL message from an agent to another. */ public static final String SEND_MESSAGE = "Send-Message"; /** This command name represents the <code>install-mtp</code> action. */ public static final String INSTALL_MTP = "Install-MTP"; /** This command name represents the <code>uninstall-mtp</code> action. */ public static final String UNINSTALL_MTP = "Uninstall-MTP"; /** This command name represents the <code>set-platform-addresses</code> action. */ public static final String SET_PLATFORM_ADDRESSES = "Set-Platform-Addresses"; public static final String MAIN_SLICE = "Main-Container"; public MessagingService(AgentContainerImpl ac, Profile p) throws ProfileException { super(p); myContainer = ac; cachedSlices = new HashMap(); // Initialize its own ID String platformID = myContainer.getPlatformID(); accID = "fipa-mts://" + platformID + "/acc"; myMessageManager = new MessageManager(); myMessageManager.initialize(p, this); // Create a local slice localSlice = new ServiceComponent(); } public String getName() { return NAME; } public Class getHorizontalInterface() { return MessagingSlice.class; } public Slice getLocalSlice() { return localSlice; } public Filter getCommandFilter() { return localSlice; } /** Inner mix-in class for this service: this class receives commands through its <code>Filter</code> interface and serves them, coordinating with remote parts of this service through the <code>Slice</code> interface (that extends the <code>Service.Slice</code> interface). */ private class ServiceComponent implements Filter, MessagingSlice { public Iterator getAddresses() { return routes.getAddresses(); } // Entry point for the ACL message dispatching process public void deliverNow(ACLMessage msg, AID receiverID) throws UnreachableException, NotFoundException { try { MainContainerImpl impl = myContainer.getMain(); if(impl != null) { while(true) { // Directly use the GADT on the main container ContainerID cid = impl.getContainerID(receiverID); MessagingSlice targetSlice = (MessagingSlice)getSlice(cid.getName()); try { targetSlice.dispatchLocally(msg, receiverID); return; // Message dispatched } catch(NotFoundException nfe) { // The agent was found in he GADT, but not in the target LADT => try again } } } else { // Try first with the cached <AgentID;Container ID> pairs MessagingSlice cachedSlice = (MessagingSlice)cachedSlices.get(receiverID); if(cachedSlice != null) { // Cache hit :-) try { System.out.println("--- Cache Hit for AID [" + receiverID.getLocalName() + "] ---"); cachedSlice.dispatchLocally(msg, receiverID); } catch(IMTPException imtpe) { cachedSlices.remove(receiverID); // Eliminate stale cache entry deliverUntilOK(msg, receiverID); } catch(NotFoundException nfe) { cachedSlices.remove(receiverID); // Eliminate stale cache entry deliverUntilOK(msg, receiverID); } } else { // Cache miss :-( System.out.println("--- Cache Miss for AID [" + receiverID.getLocalName() + "] ---"); deliverUntilOK(msg, receiverID); } } } catch(IMTPException imtpe) { throw new UnreachableException("Unreachable network node", imtpe); } catch(ServiceException se) { throw new UnreachableException("Unreachable service slice:", se); } } private void deliverUntilOK(ACLMessage msg, AID receiverID) throws IMTPException, NotFoundException, ServiceException { boolean ok = false; do { MessagingSlice mainSlice = (MessagingSlice)getSlice(MAIN_SLICE); ContainerID cid = mainSlice.getAgentLocation(receiverID); MessagingSlice targetSlice = (MessagingSlice)getSlice(cid.getName()); try { targetSlice.dispatchLocally(msg, receiverID); System.out.println("--- New Container for AID " + receiverID.getLocalName() + " is " + cid.getName() + " ---"); // On successful message dispatch, put the slice into the slice cache cachedSlices.put(receiverID, targetSlice); ok = true; } catch(NotFoundException nfe) { ok = false; // Stale proxy again, maybe the receiver is running around. Try again... } } while(!ok); } // Implementation of the Filter interface public void accept(VerticalCommand cmd) { // FIXME: Should set the exception somehow... try { String name = cmd.getName(); if(name.equals(SEND_MESSAGE)) { handleSendMessage(cmd); } if(name.equals(INSTALL_MTP)) { Object result = handleInstallMTP(cmd); cmd.setReturnValue(result); } else if(name.equals(UNINSTALL_MTP)) { handleUninstallMTP(cmd); } else if(name.equals(SET_PLATFORM_ADDRESSES)) { handleSetPlatformAddresses(cmd); } } catch(AuthException ae) { cmd.setReturnValue(ae); } catch(IMTPException imtpe) { imtpe.printStackTrace(); } catch(NotFoundException nfe) { nfe.printStackTrace(); } catch(ServiceException se) { se.printStackTrace(); } catch(MTPException mtpe) { mtpe.printStackTrace(); } } public void setBlocking(boolean newState) { // Do nothing. Blocking and Skipping not supported } public boolean isBlocking() { return false; // Blocking and Skipping not implemented } public void setSkipping(boolean newState) { // Do nothing. Blocking and Skipping not supported } public boolean isSkipping() { return false; // Blocking and Skipping not implemented } // Implementation of the Service.Slice interface public Service getService() { return MessagingService.this; } public Node getNode() throws ServiceException { try { return MessagingService.this.getLocalNode(); } catch(IMTPException imtpe) { throw new ServiceException("Problem in contacting the IMTP Manager", imtpe); } } public void serve(VerticalCommand cmd) { try { String cmdName = cmd.getName(); Object[] params = cmd.getParams(); if(cmdName.equals(H_DISPATCHLOCALLY)) { ACLMessage msg = (ACLMessage)params[0]; AID receiverID = (AID)params[1]; dispatchLocally(msg, receiverID); } else if(cmdName.equals(H_ROUTEOUT)) { ACLMessage msg = (ACLMessage)params[0]; AID receiverID = (AID)params[1]; String address = (String)params[2]; routeOut(msg, receiverID, address); } else if(cmdName.equals(H_GETAGENTLOCATION)) { AID agentID = (AID)params[0]; cmd.setReturnValue(getAgentLocation(agentID)); } else if(cmdName.equals(H_INSTALLMTP)) { String address = (String)params[0]; String className = (String)params[1]; cmd.setReturnValue(installMTP(address, className)); } else if(cmdName.equals(H_UNINSTALLMTP)) { String address = (String)params[0]; uninstallMTP(address); } else if(cmdName.equals(H_NEWMTP)) { MTPDescriptor mtp = (MTPDescriptor)params[0]; ContainerID cid = (ContainerID)params[1]; newMTP(mtp, cid); } else if(cmdName.equals(H_DEADMTP)) { MTPDescriptor mtp = (MTPDescriptor)params[0]; ContainerID cid = (ContainerID)params[1]; deadMTP(mtp, cid); } else if(cmdName.equals(H_ADDROUTE)) { MTPDescriptor mtp = (MTPDescriptor)params[0]; String sliceName = (String)params[1]; addRoute(mtp, sliceName); } else if(cmdName.equals(H_REMOVEROUTE)) { MTPDescriptor mtp = (MTPDescriptor)params[0]; String sliceName = (String)params[1]; removeRoute(mtp, sliceName); } } catch(Throwable t) { cmd.setReturnValue(t); } } // Implementation of the service-specific horizontal interface MessagingSlice public void dispatchLocally(ACLMessage msg, AID receiverID) throws IMTPException, NotFoundException { boolean found = myContainer.postMessageToLocalAgent(msg, receiverID); if(!found) { throw new NotFoundException("Messaging service slice failed to find " + receiverID); } } public void routeOut(ACLMessage msg, AID receiverID, String address) throws IMTPException, MTPException { RoutingTable.OutPort out = routes.lookup(address); if(out != null) out.route(msg, receiverID, address); else throw new MTPException("No suitable route found for address " + address + "."); } public ContainerID getAgentLocation(AID agentID) throws IMTPException, NotFoundException { MainContainerImpl impl = myContainer.getMain(); if(impl != null) { return impl.getContainerID(agentID); } else { // Do nothing for now, but could also have a local GADT copy, thus enabling e.g. Main Container replication return null; } } public MTPDescriptor installMTP(String address, String className) throws IMTPException, ServiceException, MTPException { try { // Create the MTP Class c = Class.forName(className); MTP proto = (MTP)c.newInstance(); InChannel.Dispatcher dispatcher = new InChannel.Dispatcher() { public void dispatchMessage(Envelope env, byte[] payload) { // To avoid message loops, make sure that the ID of this ACC does // not appear in a previous 'received' stamp ReceivedObject[] stamps = env.getStamps(); for(int i = 0; i < stamps.length; i++) { String id = stamps[i].getBy(); if(CaseInsensitiveString.equalsIgnoreCase(id, accID)) { System.out.println("ERROR: Message loop detected !!!"); System.out.println("Route is: "); for(int j = 0; j < stamps.length; j++) System.out.println("[" + j + "]" + stamps[j].getBy()); System.out.println("Message dispatch aborted."); return; } } // Put a 'received-object' stamp in the envelope ReceivedObject ro = new ReceivedObject(); ro.setBy(accID); ro.setDate(new Date()); env.setReceived(ro); // Decode the message, according to the 'acl-representation' slot String aclRepresentation = env.getAclRepresentation(); // Default to String representation if(aclRepresentation == null) aclRepresentation = StringACLCodec.NAME; ACLCodec codec = (ACLCodec)messageEncodings.get(aclRepresentation.toLowerCase()); if(codec == null) { System.out.println("Unknown ACL codec: " + aclRepresentation); return; } try { ACLMessage msg = codec.decode(payload); msg.setEnvelope(env); // If the 'sender' AID has no addresses, replace it with the // 'from' envelope slot AID sender = msg.getSender(); if(sender == null) { System.out.println("ERROR: Trying to dispatch a message with a null sender."); System.out.println("Aborting send operation..."); return; } Iterator itSender = sender.getAllAddresses(); if(!itSender.hasNext()) msg.setSender(env.getFrom()); Iterator it = env.getAllIntendedReceiver(); // If no 'intended-receiver' is present, use the 'to' slot (but // this should not happen). if(!it.hasNext()) it = env.getAllTo(); while(it.hasNext()) { AID receiver = (AID)it.next(); boolean found = myContainer.postMessageToLocalAgent(msg, receiver); if(!found) { myMessageManager.deliver(msg, receiver); } } } catch(ACLCodec.CodecException ce) { ce.printStackTrace(); } } }; if(address == null) { // Let the MTP choose the address TransportAddress ta = proto.activate(dispatcher); address = proto.addrToStr(ta); } else { // Convert the given string into a TransportAddress object and use it TransportAddress ta = proto.strToAddr(address); proto.activate(dispatcher, ta); } routes.addLocalMTP(address, proto); MTPDescriptor result = new MTPDescriptor(proto.getName(), new String[] {address}, proto.getSupportedProtocols()); MessagingSlice mainSlice = (MessagingSlice)getSlice(MAIN_SLICE); mainSlice.newMTP(result, myContainer.getID()); return result; } catch(ClassNotFoundException cnfe) { throw new MTPException("ERROR: The class " + className + " for the " + address + " MTP was not found"); } catch(InstantiationException ie) { throw new MTPException("The class " + className + " raised InstantiationException (see nested exception)", ie); } catch(IllegalAccessException iae) { throw new MTPException("The class " + className + " raised IllegalAccessException (see nested exception)", iae); } } public void uninstallMTP(String address) throws IMTPException, ServiceException, NotFoundException, MTPException { MTP proto = routes.removeLocalMTP(address); if(proto != null) { TransportAddress ta = proto.strToAddr(address); proto.deactivate(ta); MTPDescriptor desc = new MTPDescriptor(proto.getName(), new String[] {address}, proto.getSupportedProtocols()); MessagingSlice mainSlice = (MessagingSlice)getSlice(MAIN_SLICE); mainSlice.deadMTP(desc, myContainer.getID()); } else { throw new MTPException("No such address was found on this container: " + address); } } public void newMTP(MTPDescriptor mtp, ContainerID cid) throws IMTPException, ServiceException { MainContainerImpl impl = myContainer.getMain(); if(impl != null) { // Update the routing tables of all the other slices Slice[] slices = getAllSlices(); for(int i = 0; i < slices.length; i++) { try { MessagingSlice slice = (MessagingSlice)slices[i]; String sliceName = slice.getNode().getName(); if(!sliceName.equals(cid.getName())) { slice.addRoute(mtp, cid.getName()); } } catch(Throwable t) { // Re-throw allowed exceptions if(t instanceof IMTPException) { throw (IMTPException)t; } if(t instanceof ServiceException) { throw (ServiceException)t; } System.out.println("### addRoute() threw " + t.getClass().getName() + " ###"); } } impl.newMTP(mtp, cid); } else { // Do nothing for now, but could also route the command to the main slice, thus enabling e.g. AMS replication } } public void deadMTP(MTPDescriptor mtp, ContainerID cid) throws IMTPException, ServiceException { MainContainerImpl impl = myContainer.getMain(); if(impl != null) { // Update the routing tables of all the other slices Slice[] slices = getAllSlices(); for(int i = 0; i < slices.length; i++) { try { MessagingSlice slice = (MessagingSlice)slices[i]; String sliceName = slice.getNode().getName(); if(!sliceName.equals(cid.getName())) { slice.removeRoute(mtp, cid.getName()); } } catch(Throwable t) { // Re-throw allowed exceptions if(t instanceof IMTPException) { throw (IMTPException)t; } if(t instanceof ServiceException) { throw (ServiceException)t; } System.out.println("### removeRoute() threw " + t.getClass().getName() + " ###"); } } impl.deadMTP(mtp, cid); } else { // Do nothing for now, but could also route the command to the main slice, thus enabling e.g. AMS replication } } public void addRoute(MTPDescriptor mtp, String sliceName) throws IMTPException, ServiceException { MessagingSlice slice = (MessagingSlice)getSlice(sliceName); routes.addRemoteMTP(mtp, sliceName, slice); String[] addresses = mtp.getAddresses(); for(int i = 0; i < addresses.length; i++) { myContainer.addAddressToLocalAgents(addresses[i]); } } public void removeRoute(MTPDescriptor mtp, String sliceName) throws IMTPException, ServiceException { MessagingSlice slice = (MessagingSlice)getSlice(sliceName); routes.removeRemoteMTP(mtp, sliceName, slice); String[] addresses = mtp.getAddresses(); for(int i = 0; i < addresses.length; i++) { myContainer.removeAddressFromLocalAgents(addresses[i]); } } private RoutingTable routes = new RoutingTable(MessagingService.this); } // End of ServiceComponent class /** Activates the ACL codecs and MTPs as specified in the given <code>Profile</code> instance. @param myProfile The <code>Profile</code> instance containing the list of ACL codecs and MTPs to activate on this node. **/ public void activateProfile(Profile myProfile) { try { // Activate the default ACL String codec anyway ACLCodec stringCodec = new StringACLCodec(); messageEncodings.put(stringCodec.getName().toLowerCase(), stringCodec); // Codecs List l = myProfile.getSpecifiers(Profile.ACLCODECS); Iterator codecs = l.iterator(); while (codecs.hasNext()) { Specifier spec = (Specifier) codecs.next(); String className = spec.getClassName(); try{ Class c = Class.forName(className); ACLCodec codec = (ACLCodec)c.newInstance(); messageEncodings.put(codec.getName().toLowerCase(), codec); System.out.println("Installed "+ codec.getName()+ " ACLCodec implemented by " + className + "\n"); // FIXME: notify the AMS of the new Codec to update the APDescritption. } catch(ClassNotFoundException cnfe){ throw new jade.lang.acl.ACLCodec.CodecException("ERROR: The class " +className +" for the ACLCodec not found.", cnfe); } catch(InstantiationException ie) { throw new jade.lang.acl.ACLCodec.CodecException("The class " + className + " raised InstantiationException (see NestedException)", ie); } catch(IllegalAccessException iae) { throw new jade.lang.acl.ACLCodec.CodecException("The class " + className + " raised IllegalAccessException (see nested exception)", iae); } } // MTPs l = myProfile.getSpecifiers(Profile.MTPS); String fileName = myProfile.getParameter(Profile.FILE_DIR, "") + "MTPs-" + myContainer.getID().getName() + ".txt"; PrintWriter f = new PrintWriter(new FileWriter(fileName)); Iterator mtps = l.iterator(); while (mtps.hasNext()) { Specifier spec = (Specifier) mtps.next(); String className = spec.getClassName(); String addressURL = null; Object[] args = spec.getArgs(); if (args != null && args.length > 0) { addressURL = args[0].toString(); if(addressURL.equals("")) { addressURL = null; } } MTPDescriptor mtp = localSlice.installMTP(addressURL, className); String[] mtpAddrs = mtp.getAddresses(); f.println(mtpAddrs[0]); System.out.println(mtpAddrs[0]); } f.close(); } catch (ProfileException pe1) { System.out.println("Error reading MTPs/Codecs"); pe1.printStackTrace(); } catch(ServiceException se) { System.out.println("Error installing local MTPs"); se.printStackTrace(); } catch(jade.lang.acl.ACLCodec.CodecException ce) { System.out.println("Error installing ACL Codec"); ce.printStackTrace(); } catch(MTPException me) { System.out.println("Error installing MTP"); me.printStackTrace(); } catch(IOException ioe) { System.out.println("Error writing platform address"); ioe.printStackTrace(); } catch(IMTPException imtpe) { // Should never happen as this is a local call imtpe.printStackTrace(); } } public void deliverNow(ACLMessage msg, AID receiverID) throws UnreachableException { try { if(myContainer.livesHere(receiverID)) { localSlice.deliverNow(msg, receiverID); } else { // Dispatch it through the ACC Iterator addresses = receiverID.getAllAddresses(); while(addresses.hasNext()) { String address = (String)addresses.next(); try { forwardMessage(msg, receiverID, address); return; } catch(MTPException mtpe) { System.out.println("Bad address [" + address + "]: trying the next one..."); } } notifyFailureToSender(msg, receiverID, new InternalError("No valid address contained within the AID " + receiverID.getName())); } } catch(NotFoundException nfe) { // The receiver does not exist --> Send a FAILURE message notifyFailureToSender(msg, receiverID, new InternalError("Agent not found: " + nfe.getMessage())); } } private void forwardMessage(ACLMessage msg, AID receiver, String address) throws MTPException { AID aid = msg.getSender(); if(aid == null) { System.out.println("ERROR: null message sender. Aborting message dispatch..."); return; } // if has no address set, then adds the addresses of this platform if(!aid.getAllAddresses().hasNext()) addPlatformAddresses(aid); Iterator it1 = msg.getAllReceiver(); while(it1.hasNext()) { AID id = (AID)it1.next(); if(!id.getAllAddresses().hasNext()) addPlatformAddresses(id); } Iterator it2 = msg.getAllReplyTo(); while(it2.hasNext()) { AID id = (AID)it2.next(); if(!id.getAllAddresses().hasNext()) addPlatformAddresses(id); } try { localSlice.routeOut(msg, receiver, address); } catch(IMTPException imtpe) { throw new MTPException("Error during message routing", imtpe); } } /** * This method is used internally by the platform in order * to notify the sender of a message that a failure was reported by * the Message Transport Service. * Package scoped as it can be called by the MessageManager */ public void notifyFailureToSender(ACLMessage msg, AID receiver, InternalError ie) { //if (the sender is not the AMS and the performative is not FAILURE) if ( (msg.getSender()==null) || ((msg.getSender().equals(myContainer.getAMS())) && (msg.getPerformative()==ACLMessage.FAILURE))) // sanity check to avoid infinte loops return; // else send back a failure message final ACLMessage failure = msg.createReply(); failure.setPerformative(ACLMessage.FAILURE); //System.err.println(failure.toString()); final AID theAMS = myContainer.getAMS(); failure.setSender(theAMS); // FIXME: the content is not completely correct, but that should // also avoid creating wrong content // FIXME: the content should include the indication about the // receiver to wich dispatching failed. String content = "( (action " + msg.getSender().toString(); content = content + " ACLMessage ) " + ie.getMessage() + ")"; failure.setContent(content); try { Authority authority = myContainer.getAuthority(); authority.doPrivileged(new PrivilegedExceptionAction() { public Object run() { try { // FIXME: Having a custom code path for send failure notifications would be better... GenericCommand cmd = new GenericCommand(SEND_MESSAGE, NAME, ""); cmd.addParam(failure); cmd.addParam(theAMS); handleSendMessage(cmd); } catch (AuthException ae) { // it does not have permission to notify the failure // it never happens if the policy file gives // enough permission to the jade.jar System.out.println( ae.getMessage() ); } return null; // nothing to return } }); } catch(Exception e) { // should be never thrown e.printStackTrace(); } } // Vertical command handler methods private void handleSendMessage(VerticalCommand cmd) throws AuthException { Object[] params = cmd.getParams(); ACLMessage msg = (ACLMessage)params[0]; AID sender = (AID)params[1]; // Set the sender unless already set try { if (msg.getSender().getName().length() < 1) msg.setSender(sender); } catch (NullPointerException e) { msg.setSender(sender); } // --- This code could go into a Security Service, intercepting the message sending... AgentPrincipal target1 = myContainer.getAgentPrincipal(msg.getSender()); Authority authority = myContainer.getAuthority(); authority.checkAction(Authority.AGENT_SEND_AS, target1, null); // --- End of security code AuthException lastException = null; // 26-Mar-2001. The receivers set into the Envelope of the message, // if present, must have precedence over those set into the ACLMessage. // If no :intended-receiver parameter is present in the Envelope, // then the :to parameter // is used to generate :intended-receiver field. // // create an Iterator with all the receivers to which the message must be // delivered Iterator it = msg.getAllIntendedReceiver(); while (it.hasNext()) { AID dest = (AID)it.next(); try { AgentPrincipal target2 = myContainer.getAgentPrincipal(dest); authority.checkAction(Authority.AGENT_SEND_TO, target2, null); ACLMessage copy = (ACLMessage)msg.clone(); boolean found = myContainer.postMessageToLocalAgent(copy, dest); if(!found) { myMessageManager.deliver(copy, dest); } } catch (AuthException ae) { lastException = ae; notifyFailureToSender(msg, dest, new InternalError(ae.getMessage())); } } if(lastException != null) throw lastException; } private MTPDescriptor handleInstallMTP(VerticalCommand cmd) throws IMTPException, ServiceException, NotFoundException, MTPException { Object[] params = cmd.getParams(); String address = (String)params[0]; ContainerID cid = (ContainerID)params[1]; String className = (String)params[2]; MessagingSlice targetSlice = (MessagingSlice)getSlice(cid.getName()); return targetSlice.installMTP(address, className); } private void handleUninstallMTP(VerticalCommand cmd) throws IMTPException, ServiceException, NotFoundException, MTPException { Object[] params = cmd.getParams(); String address = (String)params[0]; ContainerID cid = (ContainerID)params[1]; MessagingSlice targetSlice = (MessagingSlice)getSlice(cid.getName()); targetSlice.uninstallMTP(address); } private void handleSetPlatformAddresses(VerticalCommand cmd) { Object[] params = cmd.getParams(); AID id = (AID)params[0]; id.clearAllAddresses(); addPlatformAddresses(id); } public void prepareEnvelope(ACLMessage msg, AID receiver) { Envelope env = msg.getEnvelope(); if(env == null) { msg.setDefaultEnvelope(); env = msg.getEnvelope(); } // 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()); // If no ACL representation is found, then default to String // representation String rep = env.getAclRepresentation(); if(rep == null) env.setAclRepresentation(StringACLCodec.NAME); // 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); String comments = env.getComments(); if(comments == null) env.setComments(""); Long payloadLength = env.getPayloadLength(); if(payloadLength == null) env.setPayloadLength(new Long(-1)); String payloadEncoding = env.getPayloadEncoding(); if(payloadEncoding == null) env.setPayloadEncoding(""); } public byte[] encodeMessage(ACLMessage msg) throws NotFoundException { Envelope env = msg.getEnvelope(); String enc = env.getAclRepresentation(); if(enc != null) { // A Codec was selected ACLCodec codec =(ACLCodec)messageEncodings.get(enc.toLowerCase()); if(codec!=null) { // Supported Codec // FIXME: should verifY that the recevivers supports this Codec return codec.encode(msg); } else { // Unsupported Codec //FIXME: find the best according to the supported, the MTP (and the receivers Codec) throw new 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 UnknownACLEncodingException("No ACL encoding set."); } } /* * This method is called before preparing the Envelope of an outgoing message. * It checks for all the AIDs present in the message and adds the addresses, if not present **/ private void addPlatformAddresses(AID id) { Iterator it = localSlice.getAddresses(); while(it.hasNext()) { String addr = (String)it.next(); id.addAddresses(addr); } } // The concrete agent container, providing access to LADT, etc. private AgentContainerImpl myContainer; // The local slice for this service private ServiceComponent localSlice; // The cached AID -> MessagingSlice associations private Map cachedSlices; // The table of the locally installed ACL message encodings private Map messageEncodings = new HashMap(); // The platform ID, to be used in inter-platform dispatching private String accID; // The component managing asynchronous message delivery and retries private MessageManager myMessageManager; }
Moved the names of the vertical commands to the MessagingSlice interface. Enabled porting to MIDP.
src/jade/core/messaging/MessagingService.java
Moved the names of the vertical commands to the MessagingSlice interface. Enabled porting to MIDP.
<ide><path>rc/jade/core/messaging/MessagingService.java <ide> <ide> package jade.core.messaging; <ide> <add>//#MIDP_EXCLUDE_FILE <ide> <ide> import java.io.FileWriter; <ide> import java.io.PrintWriter; <ide> import jade.core.Filter; <ide> import jade.core.Node; <ide> <del>import jade.core.AgentContainerImpl; <del>import jade.core.MainContainerImpl; <add>import jade.core.AgentContainer; <add>import jade.core.MainContainer; <ide> import jade.core.CaseInsensitiveString; <ide> import jade.core.AID; <ide> import jade.core.ContainerID; <ide> <ide> import jade.lang.acl.ACLMessage; <ide> import jade.lang.acl.ACLCodec; <add> <ide> import jade.lang.acl.StringACLCodec; <ide> <ide> import jade.mtp.MTP; <ide> } <ide> } // End of UnknownACLEncodingException class <ide> <del> /** <del> The name of this service. <del> */ <del> public static final String NAME = "jade.core.messaging.Messaging"; <del> <del> /** <del> This command name represents the action of sending an ACL <del> message from an agent to another. <del> */ <del> public static final String SEND_MESSAGE = "Send-Message"; <del> <del> /** <del> This command name represents the <code>install-mtp</code> <del> action. <del> */ <del> public static final String INSTALL_MTP = "Install-MTP"; <del> <del> /** <del> This command name represents the <code>uninstall-mtp</code> <del> action. <del> */ <del> public static final String UNINSTALL_MTP = "Uninstall-MTP"; <del> <del> /** <del> This command name represents the <code>set-platform-addresses</code> <del> action. <del> */ <del> public static final String SET_PLATFORM_ADDRESSES = "Set-Platform-Addresses"; <del> <ide> <ide> public static final String MAIN_SLICE = "Main-Container"; <ide> <ide> <del> public MessagingService(AgentContainerImpl ac, Profile p) throws ProfileException { <add> public MessagingService(AgentContainer ac, Profile p) throws ProfileException { <ide> super(p); <ide> <ide> myContainer = ac; <ide> } <ide> <ide> public String getName() { <del> return NAME; <add> return MessagingSlice.NAME; <ide> } <ide> <ide> public Class getHorizontalInterface() { <ide> // Entry point for the ACL message dispatching process <ide> public void deliverNow(ACLMessage msg, AID receiverID) throws UnreachableException, NotFoundException { <ide> try { <del> MainContainerImpl impl = myContainer.getMain(); <add> MainContainer impl = myContainer.getMain(); <ide> if(impl != null) { <ide> while(true) { <ide> // Directly use the GADT on the main container <ide> } <ide> <ide> public ContainerID getAgentLocation(AID agentID) throws IMTPException, NotFoundException { <del> MainContainerImpl impl = myContainer.getMain(); <add> MainContainer impl = myContainer.getMain(); <ide> if(impl != null) { <ide> return impl.getContainerID(agentID); <ide> } <ide> } <ide> <ide> public void newMTP(MTPDescriptor mtp, ContainerID cid) throws IMTPException, ServiceException { <del> MainContainerImpl impl = myContainer.getMain(); <add> MainContainer impl = myContainer.getMain(); <ide> <ide> if(impl != null) { <ide> <ide> } <ide> <ide> public void deadMTP(MTPDescriptor mtp, ContainerID cid) throws IMTPException, ServiceException { <del> MainContainerImpl impl = myContainer.getMain(); <add> MainContainer impl = myContainer.getMain(); <ide> <ide> if(impl != null) { <ide> <ide> the list of ACL codecs and MTPs to activate on this node. <ide> **/ <ide> public void activateProfile(Profile myProfile) { <add> <ide> try { <ide> <ide> // Activate the default ACL String codec anyway <ide> authority.doPrivileged(new PrivilegedExceptionAction() { <ide> public Object run() { <ide> try { <del> // FIXME: Having a custom code path for send failure notifications would be better... <del> GenericCommand cmd = new GenericCommand(SEND_MESSAGE, NAME, ""); <add> // FIXME: Having a custom code path to send failure notifications would be better... <add> GenericCommand cmd = new GenericCommand(MessagingSlice.SEND_MESSAGE, MessagingSlice.NAME, ""); <ide> cmd.addParam(failure); <ide> cmd.addParam(theAMS); <ide> handleSendMessage(cmd); <ide> <ide> <ide> // The concrete agent container, providing access to LADT, etc. <del> private AgentContainerImpl myContainer; <add> private AgentContainer myContainer; <ide> <ide> // The local slice for this service <ide> private ServiceComponent localSlice; <ide> private MessageManager myMessageManager; <ide> <ide> <del> <del> <ide> }
Java
apache-2.0
17ea1c4d93c7f6575b8cce8f226a79d4914f5791
0
winningsix/hive,wisgood/hive,WANdisco/hive,wisgood/hive,wisgood/hive,WANdisco/amplab-hive,asonipsl/hive,WANdisco/amplab-hive,asonipsl/hive,winningsix/hive,WANdisco/amplab-hive,WANdisco/hive,WANdisco/amplab-hive,winningsix/hive,winningsix/hive,asonipsl/hive,asonipsl/hive,WANdisco/amplab-hive,WANdisco/hive,WANdisco/hive,wisgood/hive,WANdisco/amplab-hive,winningsix/hive,wisgood/hive,wisgood/hive,WANdisco/hive,WANdisco/hive,asonipsl/hive,asonipsl/hive,asonipsl/hive,winningsix/hive,winningsix/hive,winningsix/hive,WANdisco/hive,wisgood/hive,WANdisco/amplab-hive,WANdisco/hive,WANdisco/amplab-hive,asonipsl/hive,wisgood/hive
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.hbase; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.mapred.TableOutputFormat; import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil; import org.apache.hadoop.hbase.security.User; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hive.hbase.HBaseSerDe.ColumnMapping; import org.apache.hadoop.hive.metastore.HiveMetaHook; import org.apache.hadoop.hive.metastore.MetaStoreUtils; import org.apache.hadoop.hive.metastore.api.MetaException; import org.apache.hadoop.hive.metastore.api.Table; import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants; import org.apache.hadoop.hive.ql.index.IndexPredicateAnalyzer; import org.apache.hadoop.hive.ql.index.IndexSearchCondition; import org.apache.hadoop.hive.ql.metadata.DefaultStorageHandler; import org.apache.hadoop.hive.ql.metadata.HiveStoragePredicateHandler; import org.apache.hadoop.hive.ql.plan.ExprNodeDesc; import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc; import org.apache.hadoop.hive.ql.plan.TableDesc; import org.apache.hadoop.hive.serde2.Deserializer; import org.apache.hadoop.hive.serde2.SerDe; import org.apache.hadoop.hive.serde2.SerDeException; import org.apache.hadoop.mapred.InputFormat; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.OutputFormat; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.util.StringUtils; /** * HBaseStorageHandler provides a HiveStorageHandler implementation for * HBase. */ public class HBaseStorageHandler extends DefaultStorageHandler implements HiveMetaHook, HiveStoragePredicateHandler { final static public String DEFAULT_PREFIX = "default."; //Check if the configure job properties is called from input // or output for setting asymmetric properties private boolean configureInputJobProps = true; private Configuration jobConf; private Configuration hbaseConf; private HBaseAdmin admin; private HBaseAdmin getHBaseAdmin() throws MetaException { try { if (admin == null) { admin = new HBaseAdmin(hbaseConf); } return admin; } catch (IOException ioe) { throw new MetaException(StringUtils.stringifyException(ioe)); } } private String getHBaseTableName(Table tbl) { // Give preference to TBLPROPERTIES over SERDEPROPERTIES // (really we should only use TBLPROPERTIES, so this is just // for backwards compatibility with the original specs). String tableName = tbl.getParameters().get(HBaseSerDe.HBASE_TABLE_NAME); if (tableName == null) { //convert to lower case in case we are getting from serde tableName = tbl.getSd().getSerdeInfo().getParameters().get( HBaseSerDe.HBASE_TABLE_NAME); //standardize to lower case if (tableName != null) { tableName = tableName.toLowerCase(); } } if (tableName == null) { tableName = (tbl.getDbName() + "." + tbl.getTableName()).toLowerCase(); if (tableName.startsWith(DEFAULT_PREFIX)) { tableName = tableName.substring(DEFAULT_PREFIX.length()); } } return tableName; } @Override public void preDropTable(Table table) throws MetaException { // nothing to do } @Override public void rollbackDropTable(Table table) throws MetaException { // nothing to do } @Override public void commitDropTable( Table tbl, boolean deleteData) throws MetaException { try { String tableName = getHBaseTableName(tbl); boolean isExternal = MetaStoreUtils.isExternalTable(tbl); if (deleteData && !isExternal) { if (getHBaseAdmin().isTableEnabled(tableName)) { getHBaseAdmin().disableTable(tableName); } getHBaseAdmin().deleteTable(tableName); } } catch (IOException ie) { throw new MetaException(StringUtils.stringifyException(ie)); } } @Override public void preCreateTable(Table tbl) throws MetaException { boolean isExternal = MetaStoreUtils.isExternalTable(tbl); // We'd like to move this to HiveMetaStore for any non-native table, but // first we need to support storing NULL for location on a table if (tbl.getSd().getLocation() != null) { throw new MetaException("LOCATION may not be specified for HBase."); } try { String tableName = getHBaseTableName(tbl); Map<String, String> serdeParam = tbl.getSd().getSerdeInfo().getParameters(); String hbaseColumnsMapping = serdeParam.get(HBaseSerDe.HBASE_COLUMNS_MAPPING); List<ColumnMapping> columnsMapping = null; columnsMapping = HBaseSerDe.parseColumnsMapping(hbaseColumnsMapping); HTableDescriptor tableDesc; if (!getHBaseAdmin().tableExists(tableName)) { // if it is not an external table then create one if (!isExternal) { // Create the column descriptors tableDesc = new HTableDescriptor(tableName); Set<String> uniqueColumnFamilies = new HashSet<String>(); for (ColumnMapping colMap : columnsMapping) { if (!colMap.hbaseRowKey) { uniqueColumnFamilies.add(colMap.familyName); } } for (String columnFamily : uniqueColumnFamilies) { tableDesc.addFamily(new HColumnDescriptor(Bytes.toBytes(columnFamily))); } getHBaseAdmin().createTable(tableDesc); } else { // an external table throw new MetaException("HBase table " + tableName + " doesn't exist while the table is declared as an external table."); } } else { if (!isExternal) { throw new MetaException("Table " + tableName + " already exists" + " within HBase; use CREATE EXTERNAL TABLE instead to" + " register it in Hive."); } // make sure the schema mapping is right tableDesc = getHBaseAdmin().getTableDescriptor(Bytes.toBytes(tableName)); for (int i = 0; i < columnsMapping.size(); i++) { ColumnMapping colMap = columnsMapping.get(i); if (colMap.hbaseRowKey) { continue; } if (!tableDesc.hasFamily(colMap.familyNameBytes)) { throw new MetaException("Column Family " + colMap.familyName + " is not defined in hbase table " + tableName); } } } // ensure the table is online new HTable(hbaseConf, tableDesc.getName()); } catch (Exception se) { throw new MetaException(StringUtils.stringifyException(se)); } } @Override public void rollbackCreateTable(Table table) throws MetaException { boolean isExternal = MetaStoreUtils.isExternalTable(table); String tableName = getHBaseTableName(table); try { if (!isExternal && getHBaseAdmin().tableExists(tableName)) { // we have created an HBase table, so we delete it to roll back; if (getHBaseAdmin().isTableEnabled(tableName)) { getHBaseAdmin().disableTable(tableName); } getHBaseAdmin().deleteTable(tableName); } } catch (IOException ie) { throw new MetaException(StringUtils.stringifyException(ie)); } } @Override public void commitCreateTable(Table table) throws MetaException { // nothing to do } @Override public Configuration getConf() { return hbaseConf; } public Configuration getJobConf() { return jobConf; } @Override public void setConf(Configuration conf) { jobConf = conf; hbaseConf = HBaseConfiguration.create(conf); } @Override public Class<? extends InputFormat> getInputFormatClass() { return HiveHBaseTableInputFormat.class; } @Override public Class<? extends OutputFormat> getOutputFormatClass() { return org.apache.hadoop.hive.hbase.HiveHBaseTableOutputFormat.class; } @Override public Class<? extends SerDe> getSerDeClass() { return HBaseSerDe.class; } @Override public HiveMetaHook getMetaHook() { return this; } @Override public void configureInputJobProperties( TableDesc tableDesc, Map<String, String> jobProperties) { //Input this.configureInputJobProps = true; configureTableJobProperties(tableDesc, jobProperties); } @Override public void configureOutputJobProperties( TableDesc tableDesc, Map<String, String> jobProperties) { //Output this.configureInputJobProps = false; configureTableJobProperties(tableDesc, jobProperties); } @Override public void configureTableJobProperties( TableDesc tableDesc, Map<String, String> jobProperties) { Properties tableProperties = tableDesc.getProperties(); jobProperties.put( HBaseSerDe.HBASE_COLUMNS_MAPPING, tableProperties.getProperty(HBaseSerDe.HBASE_COLUMNS_MAPPING)); jobProperties.put(HBaseSerDe.HBASE_COLUMNS_REGEX_MATCHING, tableProperties.getProperty(HBaseSerDe.HBASE_COLUMNS_REGEX_MATCHING, "true")); jobProperties.put(HBaseSerDe.HBASE_TABLE_DEFAULT_STORAGE_TYPE, tableProperties.getProperty(HBaseSerDe.HBASE_TABLE_DEFAULT_STORAGE_TYPE,"string")); String scanCache = tableProperties.getProperty(HBaseSerDe.HBASE_SCAN_CACHE); if (scanCache != null) { jobProperties.put(HBaseSerDe.HBASE_SCAN_CACHE, scanCache); } String scanCacheBlocks = tableProperties.getProperty(HBaseSerDe.HBASE_SCAN_CACHEBLOCKS); if (scanCacheBlocks != null) { jobProperties.put(HBaseSerDe.HBASE_SCAN_CACHEBLOCKS, scanCacheBlocks); } String scanBatch = tableProperties.getProperty(HBaseSerDe.HBASE_SCAN_BATCH); if (scanBatch != null) { jobProperties.put(HBaseSerDe.HBASE_SCAN_BATCH, scanBatch); } String tableName = tableProperties.getProperty(HBaseSerDe.HBASE_TABLE_NAME); if (tableName == null) { tableName = tableProperties.getProperty(hive_metastoreConstants.META_TABLE_NAME); tableName = tableName.toLowerCase(); if (tableName.startsWith(DEFAULT_PREFIX)) { tableName = tableName.substring(DEFAULT_PREFIX.length()); } } jobProperties.put(HBaseSerDe.HBASE_TABLE_NAME, tableName); Configuration jobConf = getJobConf(); addHBaseResources(jobConf, jobProperties); // do this for reconciling HBaseStorageHandler for use in HCatalog // check to see if this an input job or an outputjob if (this.configureInputJobProps) { for (String k : jobProperties.keySet()) { jobConf.set(k, jobProperties.get(k)); } try { addHBaseDelegationToken(jobConf); }//try catch (IOException e) { throw new IllegalStateException("Error while configuring input job properties", e); } //input job properties } else { jobProperties.put(TableOutputFormat.OUTPUT_TABLE, tableName); } // output job properties } /** * Utility method to add hbase-default.xml and hbase-site.xml properties to a new map * if they are not already present in the jobConf. * @param jobConf Job configuration * @param newJobProperties Map to which new properties should be added */ private void addHBaseResources(Configuration jobConf, Map<String, String> newJobProperties) { Configuration conf = new Configuration(false); HBaseConfiguration.addHbaseResources(conf); for (Entry<String, String> entry : conf) { if (jobConf.get(entry.getKey()) == null) { newJobProperties.put(entry.getKey(), entry.getValue()); } } } private void addHBaseDelegationToken(Configuration conf) throws IOException { if (User.isHBaseSecurityEnabled(conf)) { try { User.getCurrent().obtainAuthTokenForJob(conf,new Job(conf)); } catch (InterruptedException e) { throw new IOException("Error while obtaining hbase delegation token", e); } } } @Override public void configureJobConf(TableDesc tableDesc, JobConf jobConf) { try { TableMapReduceUtil.addDependencyJars(jobConf); org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil.addDependencyJars(jobConf, HBaseStorageHandler.class, org.apache.hadoop.hbase.HBaseConfiguration.class); } catch (IOException e) { throw new RuntimeException(e); } } @Override public DecomposedPredicate decomposePredicate( JobConf jobConf, Deserializer deserializer, ExprNodeDesc predicate) { String columnNameProperty = jobConf.get( org.apache.hadoop.hive.serde.serdeConstants.LIST_COLUMNS); List<String> columnNames = Arrays.asList(columnNameProperty.split(",")); HBaseSerDe hbaseSerde = (HBaseSerDe) deserializer; int keyColPos = hbaseSerde.getKeyColumnOffset(); String keyColType = jobConf.get(org.apache.hadoop.hive.serde.serdeConstants.LIST_COLUMN_TYPES). split(",")[keyColPos]; IndexPredicateAnalyzer analyzer = HiveHBaseTableInputFormat.newIndexPredicateAnalyzer(columnNames.get(keyColPos), keyColType, hbaseSerde.getStorageFormatOfCol(keyColPos).get(0)); List<IndexSearchCondition> searchConditions = new ArrayList<IndexSearchCondition>(); ExprNodeGenericFuncDesc residualPredicate = (ExprNodeGenericFuncDesc)analyzer.analyzePredicate(predicate, searchConditions); int scSize = searchConditions.size(); if (scSize < 1 || 2 < scSize) { // Either there was nothing which could be pushed down (size = 0), // there were complex predicates which we don't support yet. // Currently supported are one of the form: // 1. key < 20 (size = 1) // 2. key = 20 (size = 1) // 3. key < 20 and key > 10 (size = 2) return null; } if (scSize == 2 && (searchConditions.get(0).getComparisonOp() .equals("org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPEqual") || searchConditions.get(1).getComparisonOp() .equals("org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPEqual"))) { // If one of the predicates is =, then any other predicate with it is illegal. return null; } DecomposedPredicate decomposedPredicate = new DecomposedPredicate(); decomposedPredicate.pushedPredicate = analyzer.translateSearchConditions( searchConditions); decomposedPredicate.residualPredicate = residualPredicate; return decomposedPredicate; } }
hbase-handler/src/java/org/apache/hadoop/hive/hbase/HBaseStorageHandler.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.hbase; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.mapred.TableOutputFormat; import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil; import org.apache.hadoop.hbase.security.User; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hive.hbase.HBaseSerDe.ColumnMapping; import org.apache.hadoop.hive.metastore.HiveMetaHook; import org.apache.hadoop.hive.metastore.MetaStoreUtils; import org.apache.hadoop.hive.metastore.api.MetaException; import org.apache.hadoop.hive.metastore.api.Table; import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants; import org.apache.hadoop.hive.ql.index.IndexPredicateAnalyzer; import org.apache.hadoop.hive.ql.index.IndexSearchCondition; import org.apache.hadoop.hive.ql.metadata.DefaultStorageHandler; import org.apache.hadoop.hive.ql.metadata.HiveStoragePredicateHandler; import org.apache.hadoop.hive.ql.plan.ExprNodeDesc; import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc; import org.apache.hadoop.hive.ql.plan.TableDesc; import org.apache.hadoop.hive.serde2.Deserializer; import org.apache.hadoop.hive.serde2.SerDe; import org.apache.hadoop.hive.serde2.SerDeException; import org.apache.hadoop.mapred.InputFormat; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.OutputFormat; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.util.StringUtils; /** * HBaseStorageHandler provides a HiveStorageHandler implementation for * HBase. */ public class HBaseStorageHandler extends DefaultStorageHandler implements HiveMetaHook, HiveStoragePredicateHandler { final static public String DEFAULT_PREFIX = "default."; //Check if the configure job properties is called from input // or output for setting asymmetric properties private boolean configureInputJobProps = true; private Configuration jobConf; private Configuration hbaseConf; private HBaseAdmin admin; private HBaseAdmin getHBaseAdmin() throws MetaException { try { if (admin == null) { admin = new HBaseAdmin(hbaseConf); } return admin; } catch (IOException ioe) { throw new MetaException(StringUtils.stringifyException(ioe)); } } private String getHBaseTableName(Table tbl) { // Give preference to TBLPROPERTIES over SERDEPROPERTIES // (really we should only use TBLPROPERTIES, so this is just // for backwards compatibility with the original specs). String tableName = tbl.getParameters().get(HBaseSerDe.HBASE_TABLE_NAME); if (tableName == null) { //convert to lower case in case we are getting from serde tableName = tbl.getSd().getSerdeInfo().getParameters().get( HBaseSerDe.HBASE_TABLE_NAME); //standardize to lower case if (tableName != null) { tableName = tableName.toLowerCase(); } } if (tableName == null) { tableName = (tbl.getDbName() + "." + tbl.getTableName()).toLowerCase(); if (tableName.startsWith(DEFAULT_PREFIX)) { tableName = tableName.substring(DEFAULT_PREFIX.length()); } } return tableName; } @Override public void preDropTable(Table table) throws MetaException { // nothing to do } @Override public void rollbackDropTable(Table table) throws MetaException { // nothing to do } @Override public void commitDropTable( Table tbl, boolean deleteData) throws MetaException { try { String tableName = getHBaseTableName(tbl); boolean isExternal = MetaStoreUtils.isExternalTable(tbl); if (deleteData && !isExternal) { if (getHBaseAdmin().isTableEnabled(tableName)) { getHBaseAdmin().disableTable(tableName); } getHBaseAdmin().deleteTable(tableName); } } catch (IOException ie) { throw new MetaException(StringUtils.stringifyException(ie)); } } @Override public void preCreateTable(Table tbl) throws MetaException { boolean isExternal = MetaStoreUtils.isExternalTable(tbl); // We'd like to move this to HiveMetaStore for any non-native table, but // first we need to support storing NULL for location on a table if (tbl.getSd().getLocation() != null) { throw new MetaException("LOCATION may not be specified for HBase."); } try { String tableName = getHBaseTableName(tbl); Map<String, String> serdeParam = tbl.getSd().getSerdeInfo().getParameters(); String hbaseColumnsMapping = serdeParam.get(HBaseSerDe.HBASE_COLUMNS_MAPPING); List<ColumnMapping> columnsMapping = null; columnsMapping = HBaseSerDe.parseColumnsMapping(hbaseColumnsMapping); HTableDescriptor tableDesc; if (!getHBaseAdmin().tableExists(tableName)) { // if it is not an external table then create one if (!isExternal) { // Create the column descriptors tableDesc = new HTableDescriptor(tableName); Set<String> uniqueColumnFamilies = new HashSet<String>(); for (ColumnMapping colMap : columnsMapping) { if (!colMap.hbaseRowKey) { uniqueColumnFamilies.add(colMap.familyName); } } for (String columnFamily : uniqueColumnFamilies) { tableDesc.addFamily(new HColumnDescriptor(Bytes.toBytes(columnFamily))); } getHBaseAdmin().createTable(tableDesc); } else { // an external table throw new MetaException("HBase table " + tableName + " doesn't exist while the table is declared as an external table."); } } else { if (!isExternal) { throw new MetaException("Table " + tableName + " already exists" + " within HBase; use CREATE EXTERNAL TABLE instead to" + " register it in Hive."); } // make sure the schema mapping is right tableDesc = getHBaseAdmin().getTableDescriptor(Bytes.toBytes(tableName)); for (int i = 0; i < columnsMapping.size(); i++) { ColumnMapping colMap = columnsMapping.get(i); if (colMap.hbaseRowKey) { continue; } if (!tableDesc.hasFamily(colMap.familyNameBytes)) { throw new MetaException("Column Family " + colMap.familyName + " is not defined in hbase table " + tableName); } } } // ensure the table is online new HTable(hbaseConf, tableDesc.getName()); } catch (Exception se) { throw new MetaException(StringUtils.stringifyException(se)); } } @Override public void rollbackCreateTable(Table table) throws MetaException { boolean isExternal = MetaStoreUtils.isExternalTable(table); String tableName = getHBaseTableName(table); try { if (!isExternal && getHBaseAdmin().tableExists(tableName)) { // we have created an HBase table, so we delete it to roll back; if (getHBaseAdmin().isTableEnabled(tableName)) { getHBaseAdmin().disableTable(tableName); } getHBaseAdmin().deleteTable(tableName); } } catch (IOException ie) { throw new MetaException(StringUtils.stringifyException(ie)); } } @Override public void commitCreateTable(Table table) throws MetaException { // nothing to do } @Override public Configuration getConf() { return hbaseConf; } public Configuration getJobConf() { return jobConf; } @Override public void setConf(Configuration conf) { jobConf = conf; hbaseConf = HBaseConfiguration.create(conf); } @Override public Class<? extends InputFormat> getInputFormatClass() { return HiveHBaseTableInputFormat.class; } @Override public Class<? extends OutputFormat> getOutputFormatClass() { return org.apache.hadoop.hive.hbase.HiveHBaseTableOutputFormat.class; } @Override public Class<? extends SerDe> getSerDeClass() { return HBaseSerDe.class; } @Override public HiveMetaHook getMetaHook() { return this; } @Override public void configureInputJobProperties( TableDesc tableDesc, Map<String, String> jobProperties) { //Input this.configureInputJobProps = true; configureTableJobProperties(tableDesc, jobProperties); } @Override public void configureOutputJobProperties( TableDesc tableDesc, Map<String, String> jobProperties) { //Output this.configureInputJobProps = false; configureTableJobProperties(tableDesc, jobProperties); } @Override public void configureTableJobProperties( TableDesc tableDesc, Map<String, String> jobProperties) { Properties tableProperties = tableDesc.getProperties(); jobProperties.put( HBaseSerDe.HBASE_COLUMNS_MAPPING, tableProperties.getProperty(HBaseSerDe.HBASE_COLUMNS_MAPPING)); jobProperties.put(HBaseSerDe.HBASE_COLUMNS_REGEX_MATCHING, tableProperties.getProperty(HBaseSerDe.HBASE_COLUMNS_REGEX_MATCHING, "true")); jobProperties.put(HBaseSerDe.HBASE_TABLE_DEFAULT_STORAGE_TYPE, tableProperties.getProperty(HBaseSerDe.HBASE_TABLE_DEFAULT_STORAGE_TYPE,"string")); String scanCache = tableProperties.getProperty(HBaseSerDe.HBASE_SCAN_CACHE); if (scanCache != null) { jobProperties.put(HBaseSerDe.HBASE_SCAN_CACHE, scanCache); } String scanCacheBlocks = tableProperties.getProperty(HBaseSerDe.HBASE_SCAN_CACHEBLOCKS); if (scanCacheBlocks != null) { jobProperties.put(HBaseSerDe.HBASE_SCAN_CACHEBLOCKS, scanCacheBlocks); } String scanBatch = tableProperties.getProperty(HBaseSerDe.HBASE_SCAN_BATCH); if (scanBatch != null) { jobProperties.put(HBaseSerDe.HBASE_SCAN_BATCH, scanBatch); } String tableName = tableProperties.getProperty(HBaseSerDe.HBASE_TABLE_NAME); if (tableName == null) { tableName = tableProperties.getProperty(hive_metastoreConstants.META_TABLE_NAME); tableName = tableName.toLowerCase(); if (tableName.startsWith(DEFAULT_PREFIX)) { tableName = tableName.substring(DEFAULT_PREFIX.length()); } } jobProperties.put(HBaseSerDe.HBASE_TABLE_NAME, tableName); Configuration jobConf = getJobConf(); addHBaseResources(jobConf, jobProperties); // do this for reconciling HBaseStorageHandler for use in HCatalog // check to see if this an input job or an outputjob if (this.configureInputJobProps) { try { HBaseConfiguration.addHbaseResources(jobConf); addHBaseDelegationToken(jobConf); }//try catch (IOException e) { throw new IllegalStateException("Error while configuring input job properties", e); } //input job properties } else { Configuration copyOfConf = new Configuration(jobConf); HBaseConfiguration.addHbaseResources(copyOfConf); jobProperties.put(TableOutputFormat.OUTPUT_TABLE, tableName); } // output job properties } /** * Utility method to add hbase-default.xml and hbase-site.xml properties to a new map * if they are not already present in the jobConf. * @param jobConf Job configuration * @param newJobProperties Map to which new properties should be added */ private void addHBaseResources(Configuration jobConf, Map<String, String> newJobProperties) { Configuration conf = new Configuration(false); HBaseConfiguration.addHbaseResources(conf); for (Entry<String, String> entry : conf) { if (jobConf.get(entry.getKey()) == null) { newJobProperties.put(entry.getKey(), entry.getValue()); } } } private void addHBaseDelegationToken(Configuration conf) throws IOException { if (User.isHBaseSecurityEnabled(conf)) { try { User.getCurrent().obtainAuthTokenForJob(conf,new Job(conf)); } catch (InterruptedException e) { throw new IOException("Error while obtaining hbase delegation token", e); } } } @Override public void configureJobConf(TableDesc tableDesc, JobConf jobConf) { try { TableMapReduceUtil.addDependencyJars(jobConf); org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil.addDependencyJars(jobConf, HBaseStorageHandler.class, org.apache.hadoop.hbase.HBaseConfiguration.class); } catch (IOException e) { throw new RuntimeException(e); } } @Override public DecomposedPredicate decomposePredicate( JobConf jobConf, Deserializer deserializer, ExprNodeDesc predicate) { String columnNameProperty = jobConf.get( org.apache.hadoop.hive.serde.serdeConstants.LIST_COLUMNS); List<String> columnNames = Arrays.asList(columnNameProperty.split(",")); HBaseSerDe hbaseSerde = (HBaseSerDe) deserializer; int keyColPos = hbaseSerde.getKeyColumnOffset(); String keyColType = jobConf.get(org.apache.hadoop.hive.serde.serdeConstants.LIST_COLUMN_TYPES). split(",")[keyColPos]; IndexPredicateAnalyzer analyzer = HiveHBaseTableInputFormat.newIndexPredicateAnalyzer(columnNames.get(keyColPos), keyColType, hbaseSerde.getStorageFormatOfCol(keyColPos).get(0)); List<IndexSearchCondition> searchConditions = new ArrayList<IndexSearchCondition>(); ExprNodeGenericFuncDesc residualPredicate = (ExprNodeGenericFuncDesc)analyzer.analyzePredicate(predicate, searchConditions); int scSize = searchConditions.size(); if (scSize < 1 || 2 < scSize) { // Either there was nothing which could be pushed down (size = 0), // there were complex predicates which we don't support yet. // Currently supported are one of the form: // 1. key < 20 (size = 1) // 2. key = 20 (size = 1) // 3. key < 20 and key > 10 (size = 2) return null; } if (scSize == 2 && (searchConditions.get(0).getComparisonOp() .equals("org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPEqual") || searchConditions.get(1).getComparisonOp() .equals("org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPEqual"))) { // If one of the predicates is =, then any other predicate with it is illegal. return null; } DecomposedPredicate decomposedPredicate = new DecomposedPredicate(); decomposedPredicate.pushedPredicate = analyzer.translateSearchConditions( searchConditions); decomposedPredicate.residualPredicate = residualPredicate; return decomposedPredicate; } }
HIVE-6115 - Remove redundant code in HiveHBaseStorageHandler (Brock reviewed by Xuefu and Sushanth) git-svn-id: c2303eb81cb646bce052f55f7f0d14f181a5956c@1557731 13f79535-47bb-0310-9956-ffa450edef68
hbase-handler/src/java/org/apache/hadoop/hive/hbase/HBaseStorageHandler.java
HIVE-6115 - Remove redundant code in HiveHBaseStorageHandler (Brock reviewed by Xuefu and Sushanth)
<ide><path>base-handler/src/java/org/apache/hadoop/hive/hbase/HBaseStorageHandler.java <ide> // do this for reconciling HBaseStorageHandler for use in HCatalog <ide> // check to see if this an input job or an outputjob <ide> if (this.configureInputJobProps) { <add> for (String k : jobProperties.keySet()) { <add> jobConf.set(k, jobProperties.get(k)); <add> } <ide> try { <del> HBaseConfiguration.addHbaseResources(jobConf); <ide> addHBaseDelegationToken(jobConf); <ide> }//try <ide> catch (IOException e) { <ide> } //input job properties <ide> } <ide> else { <del> Configuration copyOfConf = new Configuration(jobConf); <del> HBaseConfiguration.addHbaseResources(copyOfConf); <ide> jobProperties.put(TableOutputFormat.OUTPUT_TABLE, tableName); <ide> } // output job properties <ide> }
Java
apache-2.0
d92316a7237dc58ee2db27898d92503d66c62358
0
kalaspuffar/pdfbox,apache/pdfbox,kalaspuffar/pdfbox,apache/pdfbox
/***************************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ****************************************************************************/ package org.apache.pdfbox.preflight.utils; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSDocument; import org.apache.pdfbox.cos.COSFloat; import org.apache.pdfbox.cos.COSInteger; import org.apache.pdfbox.cos.COSObject; import org.apache.pdfbox.cos.COSStream; import org.apache.pdfbox.cos.COSString; import org.apache.pdfbox.io.RandomAccess; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.persistence.util.COSObjectKey; import org.junit.Test; public class TestCOSUtils { @Test public void testIsInteger() { try { COSObject co = new COSObject(COSInteger.get(10)); co.setGenerationNumber(COSInteger.ZERO); co.setObjectNumber(COSInteger.get(10)); assertFalse(COSUtils.isInteger(co, new IOCOSDocument())); COSDocument doc = new COSDocument(); addToXref(doc, new COSObjectKey(co), 1000); COSUtils.isInteger(co, doc); doc.close(); } catch (IOException e) { fail(e.getMessage()); } } @Test public void testIsFloat() { try { COSObject co = new COSObject(new COSFloat(10.0f)); co.setGenerationNumber(COSInteger.ZERO); co.setObjectNumber(COSInteger.get(10)); assertFalse(COSUtils.isFloat(co, new IOCOSDocument())); COSDocument doc = new COSDocument(); addToXref(doc, new COSObjectKey(co), 1000); COSUtils.isFloat(co, doc); doc.close(); } catch (IOException e) { fail(e.getMessage()); } } @Test public void testIsString() { try { COSObject co = new COSObject(new COSString("")); co.setGenerationNumber(COSInteger.ZERO); co.setObjectNumber(COSInteger.get(10)); assertFalse(COSUtils.isString(co, new IOCOSDocument())); COSDocument doc = new COSDocument(); addToXref(doc, new COSObjectKey(co), 1000); COSUtils.isString(co, doc); doc.close(); } catch (IOException e) { fail(e.getMessage()); } } @Test public void testIsStream() { try { COSObject co = new COSObject(new COSStream(null)); co.setGenerationNumber(COSInteger.ZERO); co.setObjectNumber(COSInteger.get(10)); assertFalse(COSUtils.isStream(co, new IOCOSDocument())); COSDocument doc = new COSDocument(); addToXref(doc, new COSObjectKey(co), 1000); COSUtils.isStream(co, doc); doc.close(); } catch (IOException e) { fail(e.getMessage()); } } @Test public void testIsDictionary() { try { COSObject co = new COSObject(new COSDictionary()); co.setGenerationNumber(COSInteger.ZERO); co.setObjectNumber(COSInteger.get(10)); assertFalse(COSUtils.isDictionary(co, new IOCOSDocument())); COSDocument doc = new COSDocument(); addToXref(doc, new COSObjectKey(co), 1000); COSUtils.isDictionary(co, doc); doc.close(); } catch (IOException e) { fail(e.getMessage()); } } @Test public void testIsArray() { try { COSObject co = new COSObject(new COSArray()); co.setGenerationNumber(COSInteger.ZERO); co.setObjectNumber(COSInteger.get(10)); assertFalse(COSUtils.isArray(co, new IOCOSDocument())); COSDocument doc = new COSDocument(); addToXref(doc, new COSObjectKey(co), 1000); COSUtils.isArray(co, doc); doc.close(); } catch (IOException e) { fail(e.getMessage()); } } @Test public void testCloseCOSDocumentNull() { COSUtils.closeDocumentQuietly((COSDocument) null); } @Test public void testClosePDDocumentNull() { COSUtils.closeDocumentQuietly((PDDocument) null); } @Test public void testCloseCOSDocumentIO() { try { COSUtils.closeDocumentQuietly(new IOCOSDocument()); } catch (IOException e) { fail(e.getMessage()); } } protected void addToXref(COSDocument doc, COSObjectKey key, long value) { Map<COSObjectKey, Long> xrefTable = new HashMap<COSObjectKey, Long>(1); xrefTable.put(key, value); doc.addXRefTable(xrefTable); } /** * Class used to check the catch block in COSUtils methods */ private class IOCOSDocument extends COSDocument { IOCOSDocument() throws IOException { super(); } IOCOSDocument(File scratchDir) throws IOException { super(scratchDir); } IOCOSDocument(RandomAccess file) { super(file); } @Override public void close() throws IOException { super.close(); throw new IOException("Exception for code coverage"); } @Override public COSObject getObjectFromPool(COSObjectKey key) throws IOException { super.close(); throw new IOException("Exception for code coverage"); } } }
preflight/src/test/java/org/apache/pdfbox/preflight/utils/TestCOSUtils.java
/***************************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ****************************************************************************/ package org.apache.pdfbox.preflight.utils; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSDocument; import org.apache.pdfbox.cos.COSFloat; import org.apache.pdfbox.cos.COSInteger; import org.apache.pdfbox.cos.COSObject; import org.apache.pdfbox.cos.COSStream; import org.apache.pdfbox.cos.COSString; import org.apache.pdfbox.io.RandomAccess; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.persistence.util.COSObjectKey; import org.apache.pdfbox.preflight.utils.COSUtils; import org.junit.Test; public class TestCOSUtils { @Test public void testIsInteger() { try { COSObject co = new COSObject(new COSInteger(10)); co.setGenerationNumber(COSInteger.ZERO); co.setObjectNumber(new COSInteger(10)); assertFalse(COSUtils.isInteger(co, new IOCOSDocument())); COSDocument doc = new COSDocument(); addToXref(doc, new COSObjectKey(co), 1000); COSUtils.isInteger(co, doc); doc.close(); } catch (IOException e) { fail(e.getMessage()); } } @Test public void testIsFloat() { try { COSObject co = new COSObject(new COSFloat(10.0f)); co.setGenerationNumber(COSInteger.ZERO); co.setObjectNumber(new COSInteger(10)); assertFalse(COSUtils.isFloat(co, new IOCOSDocument())); COSDocument doc = new COSDocument(); addToXref(doc, new COSObjectKey(co), 1000); COSUtils.isFloat(co, doc); doc.close(); } catch (IOException e) { fail(e.getMessage()); } } @Test public void testIsString() { try { COSObject co = new COSObject(new COSString("")); co.setGenerationNumber(COSInteger.ZERO); co.setObjectNumber(new COSInteger(10)); assertFalse(COSUtils.isString(co, new IOCOSDocument())); COSDocument doc = new COSDocument(); addToXref(doc, new COSObjectKey(co), 1000); COSUtils.isString(co, doc); doc.close(); } catch (IOException e) { fail(e.getMessage()); } } @Test public void testIsStream() { try { COSObject co = new COSObject(new COSStream(null)); co.setGenerationNumber(COSInteger.ZERO); co.setObjectNumber(new COSInteger(10)); assertFalse(COSUtils.isStream(co, new IOCOSDocument())); COSDocument doc = new COSDocument(); addToXref(doc, new COSObjectKey(co), 1000); COSUtils.isStream(co, doc); doc.close(); } catch (IOException e) { fail(e.getMessage()); } } @Test public void testIsDictionary() { try { COSObject co = new COSObject(new COSDictionary()); co.setGenerationNumber(COSInteger.ZERO); co.setObjectNumber(new COSInteger(10)); assertFalse(COSUtils.isDictionary(co, new IOCOSDocument())); COSDocument doc = new COSDocument(); addToXref(doc, new COSObjectKey(co), 1000); COSUtils.isDictionary(co, doc); doc.close(); } catch (IOException e) { fail(e.getMessage()); } } @Test public void testIsArray() { try { COSObject co = new COSObject(new COSArray()); co.setGenerationNumber(COSInteger.ZERO); co.setObjectNumber(new COSInteger(10)); assertFalse(COSUtils.isArray(co, new IOCOSDocument())); COSDocument doc = new COSDocument(); addToXref(doc, new COSObjectKey(co), 1000); COSUtils.isArray(co, doc); doc.close(); } catch (IOException e) { fail(e.getMessage()); } } @Test public void testCloseCOSDocumentNull() { COSUtils.closeDocumentQuietly((COSDocument) null); } @Test public void testClosePDDocumentNull() { COSUtils.closeDocumentQuietly((PDDocument) null); } @Test public void testCloseCOSDocumentIO() { try { COSUtils.closeDocumentQuietly(new IOCOSDocument()); } catch (IOException e) { fail(e.getMessage()); } } protected void addToXref(COSDocument doc, COSObjectKey key, long value) { Map<COSObjectKey, Long> xrefTable = new HashMap<COSObjectKey, Long>(1); xrefTable.put(key, value); doc.addXRefTable(xrefTable); } /** * Class used to check the catch block in COSUtils methods */ private class IOCOSDocument extends COSDocument { IOCOSDocument() throws IOException { super(); } IOCOSDocument(File scratchDir) throws IOException { super(scratchDir); } IOCOSDocument(RandomAccess file) { super(file); } @Override public void close() throws IOException { super.close(); throw new IOException("Exception for code coverage"); } @Override public COSObject getObjectFromPool(COSObjectKey key) throws IOException { super.close(); throw new IOException("Exception for code coverage"); } } }
PDFBOX-2002: replaced deprecated COSInteger constructors git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1583212 13f79535-47bb-0310-9956-ffa450edef68
preflight/src/test/java/org/apache/pdfbox/preflight/utils/TestCOSUtils.java
PDFBOX-2002: replaced deprecated COSInteger constructors
<ide><path>reflight/src/test/java/org/apache/pdfbox/preflight/utils/TestCOSUtils.java <ide> import org.apache.pdfbox.io.RandomAccess; <ide> import org.apache.pdfbox.pdmodel.PDDocument; <ide> import org.apache.pdfbox.persistence.util.COSObjectKey; <del>import org.apache.pdfbox.preflight.utils.COSUtils; <ide> import org.junit.Test; <ide> <ide> public class TestCOSUtils <ide> { <ide> try <ide> { <del> COSObject co = new COSObject(new COSInteger(10)); <del> co.setGenerationNumber(COSInteger.ZERO); <del> co.setObjectNumber(new COSInteger(10)); <add> COSObject co = new COSObject(COSInteger.get(10)); <add> co.setGenerationNumber(COSInteger.ZERO); <add> co.setObjectNumber(COSInteger.get(10)); <ide> <ide> assertFalse(COSUtils.isInteger(co, new IOCOSDocument())); <ide> <ide> { <ide> COSObject co = new COSObject(new COSFloat(10.0f)); <ide> co.setGenerationNumber(COSInteger.ZERO); <del> co.setObjectNumber(new COSInteger(10)); <add> co.setObjectNumber(COSInteger.get(10)); <ide> <ide> assertFalse(COSUtils.isFloat(co, new IOCOSDocument())); <ide> <ide> { <ide> COSObject co = new COSObject(new COSString("")); <ide> co.setGenerationNumber(COSInteger.ZERO); <del> co.setObjectNumber(new COSInteger(10)); <add> co.setObjectNumber(COSInteger.get(10)); <ide> <ide> assertFalse(COSUtils.isString(co, new IOCOSDocument())); <ide> <ide> { <ide> COSObject co = new COSObject(new COSStream(null)); <ide> co.setGenerationNumber(COSInteger.ZERO); <del> co.setObjectNumber(new COSInteger(10)); <add> co.setObjectNumber(COSInteger.get(10)); <ide> <ide> assertFalse(COSUtils.isStream(co, new IOCOSDocument())); <ide> <ide> { <ide> COSObject co = new COSObject(new COSDictionary()); <ide> co.setGenerationNumber(COSInteger.ZERO); <del> co.setObjectNumber(new COSInteger(10)); <add> co.setObjectNumber(COSInteger.get(10)); <ide> <ide> assertFalse(COSUtils.isDictionary(co, new IOCOSDocument())); <ide> <ide> { <ide> COSObject co = new COSObject(new COSArray()); <ide> co.setGenerationNumber(COSInteger.ZERO); <del> co.setObjectNumber(new COSInteger(10)); <add> co.setObjectNumber(COSInteger.get(10)); <ide> <ide> assertFalse(COSUtils.isArray(co, new IOCOSDocument())); <ide>
JavaScript
bsd-3-clause
072ba496964fca14abc29b6738cc1dce535fd36e
0
yahoo/ypromise
YUI.add('promise-tests', function (Y) { var Assert = Y.Assert, ArrayAssert = Y.Test.ArrayAssert, Case = Y.Test.Case, Promise = Y.Promise, isPromise = Promise.isPromise; /** Takes a promise and a callback. Calls the callback or fails the test if the promise was rejected. **/ Case.prototype.success = function (promise, callback) { var test = this; promise.then(function (value) { test.resume(function () { callback.call(this, value); }); }, function (reason) { test.resume(function () { Assert.fail('Promise rejected instead of fulfilled'); }); }); test.wait(); }; /** Takes a promise and a callback. Calls the callback or fails the test if the promise was fulfilled. **/ Case.prototype.failure = function (promise, callback) { var test = this; promise.then(function (value) { test.resume(function () { Assert.fail('Promise fulfilled instead of rejected'); }); }, function (reason) { test.resume(function () { callback.call(this, reason); }); }); test.wait(); }; function wait(ms) { return new Promise(function (resolve) { setTimeout(function () { resolve(ms); }, ms); }); } function rejectedAfter(ms) { return new Promise(function (resolve, reject) { setTimeout(function () { reject(ms); }, ms); }); } // -- Suite -------------------------------------------------------------------- var suite = new Y.Test.Suite({ name: 'Promise tests' }); // -- Lifecycle ---------------------------------------------------------------- suite.add(new Y.Test.Case({ name: 'Basic promise behavior', _should: { error: { 'calling Promise as a function should throw': true } }, 'calling Promise as a function should throw': function () { Promise(function () {}); }, 'promise.then returns a promise': function () { var promise = new Promise(function (resolve) { resolve(5); }); Assert.isInstanceOf(Promise, promise.then(), 'promise.then returns a promise'); }, 'fulfilling more than once should not change the promise value': function () { var promise = new Promise(function (resolve) { resolve(true); resolve(5); }); this.success(promise, function (value) { Assert.areSame(true, value, 'value should remain the same'); }); }, 'rejecting more than once should not change the rejection reason': function () { var promise = new Promise(function (resolve, reject) { reject(new Error('foo')); reject(new Error('bar')); }); this.failure(promise, function (reason) { Assert.areEqual('foo', reason.message, 'reason should remain the same'); }); }, 'correct value for "this" inside the promise init function': function () { var promiseB = new Promise(function () { Assert.isUndefined(this, '"this" should be undefined'); }); }, 'errors thrown inside the init function should turn into rejections': function () { var reason = new Error('Some reason'), promise; promise = new Promise(function () { throw reason; }); this.failure(promise, function (result) { Assert.areSame(reason, result, 'Promise should be rejected to the thrown error'); }); }, 'callbacks passed to then should be called asynchronously': function () { var changed = false; var promise = new Promise(function (resolve) { resolve(); }).then(function () { changed = true; }); Assert.areEqual(false, changed, 'callback should not modify local variable in this turn of the event loop'); } })); suite.add(new Y.Test.Case({ name: 'Behavior of the then() callbacks', _should: { ignore: { '`this` inside a callback must be undefined in strict mode': (function () { 'use strict'; return typeof this !== 'undefined'; }()), '`this` inside a callback must be the global object': (function () { return typeof this === 'undefined'; }()) } }, 'throwing inside a callback should turn into a rejection': function () { var error = new Error('Arbitrary error'); var promise = new Promise(function (resolve) { resolve(5); }).then(function (value) { throw error; }); this.failure(promise, function (reason) { Assert.areSame(error, reason, 'thrown error should become the rejection reason'); }); }, 'returning a promise from a callback should link both promises': function () { var promise = new Promise(function (resolve) { resolve('placeholder'); }).then(function () { return new Promise(function (resolve) { resolve(5); }); }); this.success(promise, function (value) { Assert.areEqual(5, value, 'new value should be the value from the returned promise'); }); }, // This test is run only when not in strict mode '`this` inside a callback must be the global object': function () { var test = this, fulfilled, rejected, fulfilledThis, rejectedThis; fulfilled = new Promise(function (resolve) { resolve('value'); }); rejected = new Promise(function (resolve, reject) { reject('reason'); }); fulfilled.then(function () { fulfilledThis = this; rejected.then(null, function () { rejectedThis = this; test.resume(function () { Assert.areSame(Y.config.global, fulfilledThis, 'when not in strict mode `this` in the success callback must be the global object'); Assert.areSame(Y.config.global, rejectedThis, 'when not in strict mode `this` in the failure callback must be the global object'); }); }); }); test.wait(); }, // This test is run only in strict mode '`this` inside a callback must be undefined in strict mode': function () { 'use strict'; var test = this, fulfilled, rejected, fulfilledThis, rejectedThis; fulfilled = new Promise(function (resolve) { resolve('value'); }); rejected = new Promise(function (resolve, reject) { reject('reason'); }); fulfilled.then(function () { fulfilledThis = this; rejected.then(null, function () { rejectedThis = this; test.resume(function () { Assert.isUndefined(fulfilledThis, 'in strict mode `this` in the success callback must be undefined'); Assert.isUndefined(rejectedThis, 'in strict mode `this` in the failure callback must be undefined'); }); }); }); test.wait(); } })); suite.add(new Y.Test.Case({ name: 'control flow with catch()', 'promises have a catch() method': function () { var promise = new Promise(function () {}); Assert.isFunction(promise['catch'], 'promises should have a `catch` method'); }, 'catch(fn) does nothing to resolved promises': function () { var value = {foo:'bar'}, resolved = new Promise(function (resolve) { resolve(value); }), next; next = resolved['catch'](function (err) { return err; }); Assert.isObject(next, 'catch() should return an object'); Assert.isTrue(Promise.isPromise(next), 'catch() should return a promise'); this.success(next, function (val) { Assert.areSame(value, val, 'promise fulfilled value should remain the same') }); }, 'catch(fn) is equivalent to then(undefined, fn)': function () { var reason = new Error('some error'), rejected = new Promise(function (resolve, reject) { reject(reason); }), next; next = rejected['catch'](function (err) { return err; }); this.success(next, function (value) { Assert.areSame(reason, value, 'returning an error in catch() should cause the next promise to be fulfilled'); }); } })); suite.add(new Y.Test.Case({ name: 'Promise detection with Promise.isPromise', _should: { ignore: { 'detect object with getters that throw': !Object.create } }, 'detecting YUI promises': function () { Assert.isTrue(isPromise(new Promise(function () {})), 'a YUI promise should be identified as a promise'); }, 'detecting pseudo promises': function () { Assert.isTrue(isPromise({ then: function () { return 5; } }), 'a pseudo promise should be identified as a promise'); }, 'failing for values and almost promises': function () { // truthy values Assert.isFalse(isPromise(5), 'numbers should not be identified as promises'); Assert.isFalse(isPromise('foo'), 'strings should not be identified as promises'); Assert.isFalse(isPromise(true), 'true booleans should not be identified as promises'); Assert.isFalse(isPromise({}), 'objects should not be identified as promises'); // false values Assert.isFalse(isPromise(0), 'zero should not be identified as a promise'); Assert.isFalse(isPromise(''), 'empty strings should not be identified as promises'); Assert.isFalse(isPromise(false), 'false booleans should not be identified as promises'); Assert.isFalse(isPromise(null), 'null should not be identified as a promise'); Assert.isFalse(isPromise(undefined), 'undefined should not be identified as a promise'); // almost promises Assert.isFalse(isPromise({ then: 5 }), 'almost promises should not be identified as promises'); }, 'detect object with getters that throw': function () { var nonPromise = Object.create(null, { then: { get: function () { throw new Error('isPromise did not catch an exception thrown by the getter of the `then` property'); } } }); Assert.isFalse(isPromise(nonPromise), 'an object with a `then` property that throws should not be identified as a promise'); } })); suite.add(new Y.Test.Case({ name: 'Promise factories tests', 'Promise constructor has the correct methods': function () { Assert.isFunction(Promise.reject, 'Promise.reject should be a function'); Assert.isFunction(Promise.resolve, 'Promise.resolve should be a function'); }, 'Promise.reject() returns an rejected promise': function () { var value = new Error('foo'), promise = Promise.reject(value); Assert.isTrue(isPromise(promise), 'Promise.reject() should return a promise'); this.failure(promise, function next(rejected, result) { Assert.areSame(value, result, 'Promise.reject() should respect the passed value'); }); }, 'Promise.reject() should wrap fulfilled promises': function () { var value = new Promise(function (resolve) { resolve('foo'); }), promise = Promise.reject(value); this.failure(promise, function (rejected, result) { Assert.areSame(value, result, 'Promise.reject() should wrap fulfilled promises'); }); }, 'Promise.reject() should wrap rejected promises': function () { var value = new Promise(function (resolve, reject) { reject('foo'); }), promise = Promise.reject(value); this.failure(promise, function (result) { Assert.areSame(value, result, 'Promise.reject() should wrap rejected promises'); }); }, 'Promise.reject() should preserve the constructor when using inheritance': function () { function Subpromise() { Subpromise.superclass.constructor.apply(this, arguments); } Y.extend(Subpromise, Promise, null, {reject: Promise.reject}); var promise = Subpromise.reject('foo'); var test = this; Assert.isInstanceOf(Subpromise, promise, 'rejected promise should be an instance of the subclass'); this.failure(promise, function (reason) { Assert.areSame('foo', reason, 'subpromise should have the correct rejection reason'); }); }, 'Promise.resolve() is fulfilled when passed a regular value': function () { var value = {}, promise = Promise.resolve(value); this.success(promise, function (result) { Assert.areSame(value, result, 'resolved promise should respect the value passed to it'); }); }, 'Promise.resolve() adopts the state of an fulfilled promise': function () { var value = {}, fulfilled = Promise.resolve(value), promise = Promise.resolve(fulfilled); this.success(promise, function (result) { Assert.areSame(value, result, 'resolved promise should take the value of the provided promise'); }); }, 'Promise.resolve() adopts the state of a rejected promise': function () { var value = {}, fulfilled = Promise.reject(value), promise = Promise.resolve(fulfilled); this.failure(promise, function (rejected, result) { Assert.areSame(value, result, 'resolved promise should take the value of the provided promise'); }); }, 'Promise.resolve() should preserve the constructor when using inheritance': function () { function Subpromise() { Subpromise.superclass.constructor.apply(this, arguments); } Y.extend(Subpromise, Promise, null, {resolve: Promise.resolve}); var promise = Subpromise.resolve('foo'); Assert.isInstanceOf(Subpromise, promise, 'resolved promise should be an instance of the subclass'); this.success(promise, function (value) { Assert.areSame('foo', value, 'subpromise should have the correct fulfilled value'); }); } })); suite.add(new Y.Test.Case({ name: 'Promise.all() tests', 'Promise.all() should return a promise': function () { var somePromise = new Promise(function () {}); Assert.isInstanceOf(Promise, Promise.all([5]), 'when passed a value, Promise.all() should return a promise'); Assert.isInstanceOf(Promise, Promise.all([new Promise(function () {})]), 'when passed a promise, Promise.all() should return a promise'); Assert.isInstanceOf(Promise, Promise.all([]), 'with an empty list Promise.all() should still return a promise'); Assert.areNotSame(somePromise, Promise.all([somePromise]), 'when passed a promise, Promise.all() should return a new promise'); }, 'a non array argument should turn into a rejected promise': function () { this.failure(Promise.all('foo'), function (error) { Assert.isInstanceOf(TypeError, error, 'rejection reason should be a TypeError'); }); }, 'order of promises should be preserved': function () { var promise = Promise.all([wait(20), wait(10), wait(15)]); this.success(promise, function (result) { ArrayAssert.itemsAreSame([20, 10, 15], result, 'order of returned values should be the same as the parameter list'); }); }, 'values should be wrapped in a promise': function () { var obj = { hello: 'world' }, promise = Promise.all(['foo', 5, obj]); this.success(promise, function (result) { ArrayAssert.itemsAreSame(['foo', 5, obj], result, 'values passed to Promise.all() should be wrapped in promises, not ignored'); }); }, 'correct handling of function parameters': function () { function testFn() {} this.success(Promise.all([testFn]), function (values) { Assert.isFunction(values[0], 'promise value should be a function'); Assert.areSame(testFn, values[0], 'promise value should be the passed function'); }); }, 'Promise.all() should fail as fast as possible': function () { var promise = Promise.all([rejectedAfter(20), rejectedAfter(10), rejectedAfter(15)]); this.failure(promise, function (reason) { Assert.areEqual(10, reason, 'reason should be the one from the first promise to be rejected'); }); } })); suite.add(new Y.Test.Case({ name: 'Promise.race() tests', 'a non array argument should turn into a rejected promise': function () { this.failure(Promise.race('foo'), function (error) { Assert.isInstanceOf(TypeError, error, 'rejection reason should be a TypeError'); }); }, 'Promise.race() should fulfill when passed a fulfilled promise': function () { this.success(Promise.race([wait(10)]), function (result) { Assert.areEqual(10, result, 'Promise.race() should fulfill when passed a fulfilled promise'); }); }, 'Promise.race() should reject when passed a rejected promise': function () { this.failure(Promise.race([rejectedAfter(10)]), function (result) { Assert.areEqual(10, result, 'Promise.race() should reject when passed a rejected promise'); }); }, 'Promise.race() should fulfill to the value of the first promise to be fulfilled': function () { var promise = Promise.race([wait(10), wait(100)]); this.success(promise, function (result) { Assert.areEqual(10, result, 'Promise.race() should fulfill to the value of the first promise to be fulfilled'); }); }, 'Promise.race() should reject with the reason of the first promise to be rejected': function () { var promise = Promise.race([rejectedAfter(10), rejectedAfter(100)]); this.failure(promise, function (result) { Assert.areEqual(10, result, 'Promise.race() should reject with the reason of the first promise to be rejected'); }); } })); suite.add(new Y.Test.Case({ name: 'Promise.cast() tests', 'a promise should not be modified': function () { var promise = Promise.resolve(), wrapped = Promise.cast(promise); Assert.isTrue(Promise.isPromise(promise), 'Promise.cast should always return a promise'); Assert.areSame(promise, wrapped, 'Promise.cast should not modify a promise'); }, 'values should be wrapped in a promise': function () { // truthy values Assert.isInstanceOf(Promise, Promise.cast(5), 'numbers should be wrapped in a promise'); Assert.isInstanceOf(Promise, Promise.cast('foo'), 'strings should be wrapped in a promise'); Assert.isInstanceOf(Promise, Promise.cast(true), 'booleans should be wrapped in a promise'); Assert.isInstanceOf(Promise, Promise.cast(function () {}), 'functions should be wrapped in a promise'); Assert.isInstanceOf(Promise, Promise.cast({}), 'objects should be wrapped in a promise'); // falsy values Assert.isInstanceOf(Promise, Promise.cast(0), 'zero should be wrapped in a promise'); Assert.isInstanceOf(Promise, Promise.cast(''), 'empty strings should be wrapped in a promise'); Assert.isInstanceOf(Promise, Promise.cast(false), 'false should be wrapped in a promise'); Assert.isInstanceOf(Promise, Promise.cast(null), 'null should be wrapped in a promise'); Assert.isInstanceOf(Promise, Promise.cast(undefined), 'undefined should be wrapped in a promise'); Assert.isInstanceOf(Promise, Promise.cast(), 'undefined (empty parameters) should be wrapped in a promise'); // almost promises Assert.isInstanceOf(Promise, Promise.cast({then: 5}), 'promise-like objects should be wrapped in a promise'); } })); Y.Test.Runner.add(suite); }, '@VERSION@', { requires: [ 'promise', 'test' ] });
tests/unit/assets/promise-tests.js
YUI.add('promise-tests', function (Y) { var Assert = Y.Assert, ArrayAssert = Y.Test.ArrayAssert, Promise = Y.Promise, isPromise = Promise.isPromise; /** Takes a promise and a callback. Calls the callback with a boolean parameter indicating if the promise is fulfilled and the value as the next parameter **/ function isFulfilled(promise, next) { promise.then(function (x) { next(true, x); }, function (e) { next(false, e); }); } /** Takes a promise and a callback. Calls the callback with a boolean parameter indicating if the promise is rejected and the reason as the next parameter **/ function isRejected(promise, next) { promise.then(function (x) { next(false, x); }, function (e) { next(true, e); }); } function wait(ms) { return new Promise(function (resolve) { setTimeout(function () { resolve(ms); }, ms); }); } function rejectedAfter(ms) { return new Promise(function (resolve, reject) { setTimeout(function () { reject(ms); }, ms); }); } // -- Suite -------------------------------------------------------------------- var suite = new Y.Test.Suite({ name: 'Promise tests' }); // -- Lifecycle ---------------------------------------------------------------- suite.add(new Y.Test.Case({ name: 'Basic promise behavior', _should: { error: { 'calling Promise as a function should throw': true } }, 'calling Promise as a function should throw': function () { Promise(function () {}); }, 'promise.then returns a promise': function () { var promise = new Promise(function (resolve) { resolve(5); }); Assert.isInstanceOf(Promise, promise.then(), 'promise.then returns a promise'); }, 'fulfilling more than once should not change the promise value': function () { var test = this; new Promise(function (resolve) { resolve(true); resolve(5); }).then(function (value) { test.resume(function () { Assert.areSame(true, value, 'value should remain the same'); }); }); test.wait(100); }, 'rejecting more than once should not change the rejection reason': function () { var test = this; new Promise(function (resolve, reject) { reject(new Error('foo')); reject(new Error('bar')); }).then(null, function (reason) { test.resume(function () { Assert.areEqual('foo', reason.message, 'reason should remain the same'); }); }); test.wait(100); }, 'correct value for "this" inside the promise init function': function () { var promiseB = new Promise(function () { Assert.isUndefined(this, '"this" should be undefined'); }); }, 'errors thrown inside the init function should turn into rejections': function () { var test = this, reason = new Error('Some reason'), promise; promise = new Promise(function () { throw reason; }); isRejected(promise, function (rejected, result) { test.resume(function () { Assert.isTrue(rejected, 'Promise should be rejected'); Assert.areSame(reason, result, 'Promise should be rejected to the thrown error'); }); }); test.wait(); }, 'callbacks passed to then should be called asynchronously': function () { var test = this; var foo = false; new Promise(function (resolve) { resolve(); }).then(function () { foo = true; test.resume(); }); Assert.areEqual(false, foo, 'callback should not modify local variable in this turn of the event loop'); test.wait(); } })); suite.add(new Y.Test.Case({ name: 'Behavior of the then() callbacks', _should: { ignore: { '|this| inside a callback must be undefined in strict mode': (function () { 'use strict'; return typeof this !== 'undefined'; }()), '|this| inside a callback must be the global object': (function () { return typeof this === 'undefined'; }()) } }, 'throwing inside a callback should turn into a rejection': function () { var test = this, error = new Error('Arbitrary error'); new Promise(function (resolve) { resolve(5); }).then(function (value) { throw error; }).then(null, function (reason) { test.resume(function () { Assert.areSame(error, reason, 'thrown error should become the rejection reason'); }); }); test.wait(50); }, 'returning a promise from a callback should link both promises': function () { var test = this; new Promise(function (resolve) { resolve('placeholder'); }).then(function () { return new Promise(function (resolve) { resolve(5); }); }).then(function (value) { test.resume(function () { Assert.areEqual(5, value, 'new value should be the value from the returned promise'); }); }); test.wait(100); }, // This test is run only when not in strict mode '|this| inside a callback must be the global object': function () { var test = this, fulfilled, rejected, fulfilledThis, rejectedThis; fulfilled = new Promise(function (resolve) { resolve('value'); }); rejected = new Promise(function (resolve, reject) { reject('reason'); }); fulfilled.then(function () { fulfilledThis = this; rejected.then(null, function () { rejectedThis = this; test.resume(function () { Assert.areSame(Y.config.global, fulfilledThis, 'when not in strict mode |this| in the success callback must be the global object'); Assert.areSame(Y.config.global, rejectedThis, 'when not in strict mode |this| in the failure callback must be the global object'); }); }); }); test.wait(300); }, // This test is run only in strict mode '|this| inside a callback must be undefined in strict mode': function () { 'use strict'; var test = this, fulfilled, rejected, fulfilledThis, rejectedThis; fulfilled = new Promise(function (resolve) { resolve('value'); }); rejected = new Promise(function (resolve, reject) { reject('reason'); }); fulfilled.then(function () { fulfilledThis = this; rejected.then(null, function () { rejectedThis = this; test.resume(function () { Assert.isUndefined(fulfilledThis, 'in strict mode |this| in the success callback must be undefined'); Assert.isUndefined(rejectedThis, 'in strict mode |this| in the failure callback must be undefined'); }); }); }); test.wait(300); } })); suite.add(new Y.Test.Case({ name: 'control flow with catch()', 'promises have a catch() method': function () { var promise = new Promise(function () {}); Assert.isFunction(promise['catch'], 'promises should have a `catch` method'); }, 'catch(fn) does nothing to resolved promises': function () { var value = {foo:'bar'}, resolved = new Promise(function (resolve) { resolve(value); }), next, test = this; next = resolved['catch'](function (err) { return err; }); Assert.isObject(next, 'catch() should return an object'); Assert.isTrue(Promise.isPromise(next), 'catch() should return a promise'); isFulfilled(next, function (fulfilled, val) { test.resume(function () { Assert.isTrue(fulfilled, 'promise should still be fulfilled'); Assert.areSame(value, val, 'promise fulfilled value should remain the same') }); }); test.wait(); }, 'catch(fn) is equivalent to then(undefined, fn)': function () { var reason = new Error('some error'), rejected = new Promise(function (resolve, reject) { reject(reason); }), next, test = this; next = rejected['catch'](function (err) { return err; }); isFulfilled(next, function (fulfilled, value) { test.resume(function () { Assert.isTrue(fulfilled, 'promise should now be fulfilled'); Assert.areSame(reason, value, 'returning an error in catch() should cause the next promise to be fulfilled'); }); }); test.wait(); } })); suite.add(new Y.Test.Case({ name: 'Promise detection with Promise.isPromise', _should: { ignore: { 'detect object with getters that throw': !Object.create } }, 'detecting YUI promises': function () { Assert.isTrue(isPromise(new Promise(function () {})), 'a YUI promise should be identified as a promise'); }, 'detecting pseudo promises': function () { Assert.isTrue(isPromise({ then: function () { return 5; } }), 'a pseudo promise should be identified as a promise'); }, 'failing for values and almost promises': function () { // truthy values Assert.isFalse(isPromise(5), 'numbers should not be identified as promises'); Assert.isFalse(isPromise('foo'), 'strings should not be identified as promises'); Assert.isFalse(isPromise(true), 'true booleans should not be identified as promises'); Assert.isFalse(isPromise({}), 'objects should not be identified as promises'); // false values Assert.isFalse(isPromise(0), 'zero should not be identified as a promise'); Assert.isFalse(isPromise(''), 'empty strings should not be identified as promises'); Assert.isFalse(isPromise(false), 'false booleans should not be identified as promises'); Assert.isFalse(isPromise(null), 'null should not be identified as a promise'); Assert.isFalse(isPromise(undefined), 'undefined should not be identified as a promise'); // almost promises Assert.isFalse(isPromise({ then: 5 }), 'almost promises should not be identified as promises'); }, 'detect object with getters that throw': function () { var nonPromise = Object.create(null, { then: { get: function () { throw new Error('isPromise did not catch an exception thrown by the getter of the `then` property'); } } }); Assert.isFalse(isPromise(nonPromise), 'an object with a `then` property that throws should not be identified as a promise'); } })); suite.add(new Y.Test.Case({ name: 'Promise factories tests', 'Promise constructor has the correct methods': function () { Assert.isFunction(Promise.reject, 'Promise.reject should be a function'); Assert.isFunction(Promise.resolve, 'Promise.resolve should be a function'); }, 'Promise.reject() returns an rejected promise': function () { var test = this, value = new Error('foo'), promise = Promise.reject(value); Assert.isTrue(isPromise(promise), 'Promise.reject() should return a promise'); isRejected(promise, function next(rejected, result) { test.resume(function () { Assert.isTrue(rejected, 'promise should be rejected, not fulfilled'); Assert.areSame(value, result, 'Promise.reject() should respect the passed value'); }); }); test.wait(); }, 'Promise.reject() should wrap fulfilled promises': function () { var test = this, value = new Promise(function (resolve) { resolve('foo'); }), promise = Promise.reject(value); isRejected(promise, function (rejected, result) { test.resume(function () { Assert.isTrue(rejected, 'promise should be rejected, not fulfilled'); Assert.areSame(value, result, 'Promise.reject() should wrap fulfilled promises'); }); }); test.wait(); }, 'Promise.reject() should wrap rejected promises': function () { var test = this, value = new Promise(function (resolve, reject) { reject('foo'); }), promise = Promise.reject(value); isRejected(promise, function (rejected, result) { test.resume(function () { Assert.isTrue(rejected, 'promise should be rejected, not fulfilled'); Assert.areSame(value, result, 'Promise.reject() should wrap rejected promises'); }); }); test.wait(); }, 'Promise.reject() should preserve the constructor when using inheritance': function () { function Subpromise() { Subpromise.superclass.constructor.apply(this, arguments); } Y.extend(Subpromise, Promise, null, {reject: Promise.reject}); var promise = Subpromise.reject('foo'); var test = this; Assert.isInstanceOf(Subpromise, promise, 'rejected promise should be an instance of the subclass'); isRejected(promise, function (rejected, reason) { test.resume(function () { Assert.isTrue(rejected, 'subpromise should be rejected'); Assert.areSame('foo', reason, 'subpromise should have the correct rejection reason'); }); }); test.wait(); }, 'Promise.resolve() is fulfilled when passed a regular value': function () { var test = this, value = {}, promise = Promise.resolve(value); isFulfilled(promise, function (fulfilled, result) { test.resume(function () { Assert.isTrue(fulfilled, 'resolved promise should be fulfilled'); Assert.areSame(value, result, 'resolved promise should respect the value passed to it'); }); }); test.wait(); }, 'Promise.resolve() adopts the state of an fulfilled promise': function () { var test = this, value = {}, fulfilled = Promise.resolve(value), promise = Promise.resolve(fulfilled); isFulfilled(promise, function (fulfilled, result) { test.resume(function () { Assert.isTrue(fulfilled, 'resolved promise should be fulfilled'); Assert.areSame(value, result, 'resolved promise should take the value of the provided promise'); }); }); test.wait(); }, 'Promise.resolve() adopts the state of a rejected promise': function () { var test = this, value = {}, fulfilled = Promise.reject(value), promise = Promise.resolve(fulfilled); isRejected(promise, function (rejected, result) { test.resume(function () { Assert.isTrue(rejected, 'resolved promise should be rejected'); Assert.areSame(value, result, 'resolved promise should take the value of the provided promise'); }); }); test.wait(); }, 'Promise.resolve() should preserve the constructor when using inheritance': function () { function Subpromise() { Subpromise.superclass.constructor.apply(this, arguments); } Y.extend(Subpromise, Promise, null, {resolve: Promise.resolve}); var promise = Subpromise.resolve('foo'); var test = this; Assert.isInstanceOf(Subpromise, promise, 'resolved promise should be an instance of the subclass'); isFulfilled(promise, function (fulfilled, value) { test.resume(function () { Assert.isTrue(fulfilled, 'subpromise should be fulfilled'); Assert.areSame('foo', value, 'subpromise should have the correct fulfilled value'); }); }); test.wait(); } })); suite.add(new Y.Test.Case({ name: 'Promise.all() tests', 'Promise.all() should return a promise': function () { var somePromise = new Promise(function () {}); Assert.isInstanceOf(Promise, Promise.all([5]), 'when passed a value, Promise.all() should return a promise'); Assert.isInstanceOf(Promise, Promise.all([new Promise(function () {})]), 'when passed a promise, Promise.all() should return a promise'); Assert.isInstanceOf(Promise, Promise.all([]), 'with an empty list Promise.all() should still return a promise'); Assert.areNotSame(somePromise, Promise.all([somePromise]), 'when passed a promise, Promise.all() should return a new promise'); }, 'a non array argument should turn into a rejected promise': function () { var test = this; isRejected(Promise.all('foo'), function (rejected, error) { test.resume(function () { Assert.isTrue(rejected, 'wrong argument for all() should return a rejected promise'); Assert.isInstanceOf(TypeError, error, 'rejection reason should be a TypeError'); }); }); test.wait(); }, 'order of promises should be preserved': function () { var test = this, promise = Promise.all([wait(20), wait(10), wait(15)]); isFulfilled(promise, function (fulfilled, result) { test.resume(function () { Assert.isTrue(fulfilled, 'promise should be fulfilled'); ArrayAssert.itemsAreSame([20, 10, 15], result, 'order of returned values should be the same as the parameter list'); }); }); test.wait(); }, 'values should be wrapped in a promise': function () { var test = this, obj = { hello: 'world' }, promise = Promise.all(['foo', 5, obj]); isFulfilled(promise, function (fulfilled, result) { test.resume(function () { Assert.isTrue(fulfilled, 'promise should be fulfilled'); ArrayAssert.itemsAreSame(['foo', 5, obj], result, 'values passed to Promise.all() should be wrapped in promises, not ignored'); }); }); test.wait(); }, 'correct handling of function parameters': function () { var test = this, promise; function testFn() {} promise = Promise.all([testFn]); isFulfilled(promise, function (fulfilled, values) { test.resume(function () { Assert.isTrue(fulfilled, 'promise should be fulfilled'); Assert.isFunction(values[0], 'promise value should be a function'); Assert.areSame(testFn, values[0], 'promise value should be the passed function'); }); }); test.wait(); }, 'Promise.all() should fail as fast as possible': function () { var test = this, promise; promise = Promise.all([rejectedAfter(20), rejectedAfter(10), rejectedAfter(15)]); isRejected(promise, function (rejected, reason) { test.resume(function () { Assert.isTrue(rejected, 'promise should be rejected'); Assert.areEqual(10, reason, 'reason should be the one from the first promise to be rejected'); }); }); test.wait(); } })); suite.add(new Y.Test.Case({ name: 'Promise.race() tests', 'a non array argument should turn into a rejected promise': function () { var test = this; isRejected(Promise.race('foo'), function (rejected, error) { test.resume(function () { Assert.isTrue(rejected, 'wrong argument for all() should return a rejected promise'); Assert.isInstanceOf(TypeError, error, 'rejection reason should be a TypeError'); }); }); test.wait(); }, 'Promise.race() should fulfill when passed a fulfilled promise': function () { var test = this, promise = Promise.race([wait(10)]); isFulfilled(promise, function (fulfilled, result) { test.resume(function () { Assert.isTrue(fulfilled, 'promise should be fulfilled'); Assert.areEqual(10, result, 'Promise.race() should fulfill when passed a fulfilled promise'); }); }); test.wait(); }, 'Promise.race() should reject when passed a rejected promise': function () { var test = this, promise = Promise.race([rejectedAfter(10)]); isRejected(promise, function (rejected, result) { test.resume(function () { Assert.isTrue(rejected, 'promise should be rejected'); Assert.areEqual(10, result, 'Promise.race() should reject when passed a rejected promise'); }); }); test.wait(); }, 'Promise.race() should fulfill to the value of the first promise to be fulfilled': function () { var test = this, promise = Promise.race([wait(10), wait(100)]); isFulfilled(promise, function (fulfilled, result) { test.resume(function () { Assert.isTrue(fulfilled, 'promise should be fulfilled'); Assert.areEqual(10, result, 'Promise.race() should fulfill to the value of the first promise to be fulfilled'); }); }); test.wait(); }, 'Promise.race() should reject with the reason of the first promise to be rejected': function () { var test = this, promise = Promise.race([rejectedAfter(10), rejectedAfter(100)]); isRejected(promise, function (rejected, result) { test.resume(function () { Assert.isTrue(rejected, 'promise should be rejected'); Assert.areEqual(10, result, 'Promise.race() should reject with the reason of the first promise to be rejected'); }); }); test.wait(); } })); suite.add(new Y.Test.Case({ name: 'Promise.cast() tests', 'a promise should not be modified': function () { var promise = Promise.resolve(), wrapped = Promise.cast(promise); Assert.isTrue(Promise.isPromise(promise), 'Promise.cast should always return a promise'); Assert.areSame(promise, wrapped, 'Promise.cast should not modify a promise'); }, 'values should be wrapped in a promise': function () { // truthy values Assert.isInstanceOf(Promise, Promise.cast(5), 'numbers should be wrapped in a promise'); Assert.isInstanceOf(Promise, Promise.cast('foo'), 'strings should be wrapped in a promise'); Assert.isInstanceOf(Promise, Promise.cast(true), 'booleans should be wrapped in a promise'); Assert.isInstanceOf(Promise, Promise.cast(function () {}), 'functions should be wrapped in a promise'); Assert.isInstanceOf(Promise, Promise.cast({}), 'objects should be wrapped in a promise'); // falsy values Assert.isInstanceOf(Promise, Promise.cast(0), 'zero should be wrapped in a promise'); Assert.isInstanceOf(Promise, Promise.cast(''), 'empty strings should be wrapped in a promise'); Assert.isInstanceOf(Promise, Promise.cast(false), 'false should be wrapped in a promise'); Assert.isInstanceOf(Promise, Promise.cast(null), 'null should be wrapped in a promise'); Assert.isInstanceOf(Promise, Promise.cast(undefined), 'undefined should be wrapped in a promise'); Assert.isInstanceOf(Promise, Promise.cast(), 'undefined (empty parameters) should be wrapped in a promise'); // almost promises Assert.isInstanceOf(Promise, Promise.cast({then: 5}), 'promise-like objects should be wrapped in a promise'); } })); Y.Test.Runner.add(suite); }, '@VERSION@', { requires: [ 'promise', 'test' ] });
Add testCase.success() and testCase.failure()
tests/unit/assets/promise-tests.js
Add testCase.success() and testCase.failure()
<ide><path>ests/unit/assets/promise-tests.js <ide> <ide> var Assert = Y.Assert, <ide> ArrayAssert = Y.Test.ArrayAssert, <add> Case = Y.Test.Case, <ide> Promise = Y.Promise, <ide> isPromise = Promise.isPromise; <ide> <ide> /** <del> Takes a promise and a callback. Calls the callback with a boolean parameter <del> indicating if the promise is fulfilled and the value as the next parameter <add> Takes a promise and a callback. Calls the callback or fails the test if the <add> promise was rejected. <ide> **/ <del> function isFulfilled(promise, next) { <del> promise.then(function (x) { <del> next(true, x); <del> }, function (e) { <del> next(false, e); <add> Case.prototype.success = function (promise, callback) { <add> var test = this; <add> <add> promise.then(function (value) { <add> test.resume(function () { <add> callback.call(this, value); <add> }); <add> }, function (reason) { <add> test.resume(function () { <add> Assert.fail('Promise rejected instead of fulfilled'); <add> }); <ide> }); <del> } <add> <add> test.wait(); <add> }; <ide> <ide> /** <del> Takes a promise and a callback. Calls the callback with a boolean parameter <del> indicating if the promise is rejected and the reason as the next parameter <add> Takes a promise and a callback. Calls the callback or fails the test if the <add> promise was fulfilled. <ide> **/ <del> function isRejected(promise, next) { <del> promise.then(function (x) { <del> next(false, x); <del> }, function (e) { <del> next(true, e); <add> Case.prototype.failure = function (promise, callback) { <add> var test = this; <add> <add> promise.then(function (value) { <add> test.resume(function () { <add> Assert.fail('Promise fulfilled instead of rejected'); <add> }); <add> }, function (reason) { <add> test.resume(function () { <add> callback.call(this, reason); <add> }); <ide> }); <del> } <add> <add> test.wait(); <add> }; <ide> <ide> function wait(ms) { <ide> return new Promise(function (resolve) { <ide> }, <ide> <ide> 'fulfilling more than once should not change the promise value': function () { <del> var test = this; <del> <del> new Promise(function (resolve) { <add> var promise = new Promise(function (resolve) { <ide> resolve(true); <ide> resolve(5); <del> }).then(function (value) { <del> test.resume(function () { <del> Assert.areSame(true, value, 'value should remain the same'); <del> }); <del> }); <del> <del> test.wait(100); <add> }); <add> <add> this.success(promise, function (value) { <add> Assert.areSame(true, value, 'value should remain the same'); <add> }); <ide> }, <ide> <ide> 'rejecting more than once should not change the rejection reason': function () { <del> var test = this; <del> <del> new Promise(function (resolve, reject) { <add> var promise = new Promise(function (resolve, reject) { <ide> reject(new Error('foo')); <ide> reject(new Error('bar')); <del> }).then(null, function (reason) { <del> test.resume(function () { <del> Assert.areEqual('foo', reason.message, 'reason should remain the same'); <del> }); <del> }); <del> <del> test.wait(100); <add> }); <add> <add> this.failure(promise, function (reason) { <add> Assert.areEqual('foo', reason.message, 'reason should remain the same'); <add> }); <ide> }, <ide> <ide> 'correct value for "this" inside the promise init function': function () { <ide> }, <ide> <ide> 'errors thrown inside the init function should turn into rejections': function () { <del> var test = this, <del> reason = new Error('Some reason'), <add> var reason = new Error('Some reason'), <ide> promise; <ide> <ide> promise = new Promise(function () { <ide> throw reason; <ide> }); <ide> <del> isRejected(promise, function (rejected, result) { <del> test.resume(function () { <del> Assert.isTrue(rejected, 'Promise should be rejected'); <del> Assert.areSame(reason, result, 'Promise should be rejected to the thrown error'); <del> }); <del> }); <del> <del> test.wait(); <add> this.failure(promise, function (result) { <add> Assert.areSame(reason, result, 'Promise should be rejected to the thrown error'); <add> }); <ide> }, <ide> <ide> 'callbacks passed to then should be called asynchronously': function () { <del> var test = this; <del> <del> var foo = false; <del> <del> new Promise(function (resolve) { <add> var changed = false; <add> <add> var promise = new Promise(function (resolve) { <ide> resolve(); <ide> }).then(function () { <del> foo = true; <del> test.resume(); <del> }); <del> <del> Assert.areEqual(false, foo, 'callback should not modify local variable in this turn of the event loop'); <del> <del> test.wait(); <add> changed = true; <add> }); <add> <add> Assert.areEqual(false, changed, 'callback should not modify local variable in this turn of the event loop'); <ide> } <ide> <ide> })); <ide> <ide> _should: { <ide> ignore: { <del> '|this| inside a callback must be undefined in strict mode': (function () { <add> '`this` inside a callback must be undefined in strict mode': (function () { <ide> 'use strict'; <ide> return typeof this !== 'undefined'; <ide> }()), <del> '|this| inside a callback must be the global object': (function () { <add> '`this` inside a callback must be the global object': (function () { <ide> return typeof this === 'undefined'; <ide> }()) <ide> } <ide> }, <ide> <ide> 'throwing inside a callback should turn into a rejection': function () { <del> var test = this, <del> error = new Error('Arbitrary error'); <del> <del> new Promise(function (resolve) { <add> var error = new Error('Arbitrary error'); <add> <add> var promise = new Promise(function (resolve) { <ide> resolve(5); <ide> }).then(function (value) { <ide> throw error; <del> }).then(null, function (reason) { <del> test.resume(function () { <del> Assert.areSame(error, reason, 'thrown error should become the rejection reason'); <del> }); <del> }); <del> <del> test.wait(50); <add> }); <add> <add> this.failure(promise, function (reason) { <add> Assert.areSame(error, reason, 'thrown error should become the rejection reason'); <add> }); <ide> }, <ide> <ide> 'returning a promise from a callback should link both promises': function () { <del> var test = this; <del> <del> new Promise(function (resolve) { <add> var promise = new Promise(function (resolve) { <ide> resolve('placeholder'); <ide> }).then(function () { <ide> return new Promise(function (resolve) { <ide> resolve(5); <ide> }); <del> }).then(function (value) { <del> test.resume(function () { <del> Assert.areEqual(5, value, 'new value should be the value from the returned promise'); <del> }); <del> }); <del> <del> test.wait(100); <add> }); <add> <add> this.success(promise, function (value) { <add> Assert.areEqual(5, value, 'new value should be the value from the returned promise'); <add> }); <ide> }, <ide> <ide> // This test is run only when not in strict mode <del> '|this| inside a callback must be the global object': function () { <add> '`this` inside a callback must be the global object': function () { <ide> var test = this, <ide> fulfilled, rejected, <ide> fulfilledThis, rejectedThis; <ide> rejected.then(null, function () { <ide> rejectedThis = this; <ide> test.resume(function () { <del> Assert.areSame(Y.config.global, fulfilledThis, 'when not in strict mode |this| in the success callback must be the global object'); <del> Assert.areSame(Y.config.global, rejectedThis, 'when not in strict mode |this| in the failure callback must be the global object'); <add> Assert.areSame(Y.config.global, fulfilledThis, 'when not in strict mode `this` in the success callback must be the global object'); <add> Assert.areSame(Y.config.global, rejectedThis, 'when not in strict mode `this` in the failure callback must be the global object'); <ide> }); <ide> }); <ide> }); <ide> <del> test.wait(300); <add> test.wait(); <ide> }, <ide> <ide> // This test is run only in strict mode <del> '|this| inside a callback must be undefined in strict mode': function () { <add> '`this` inside a callback must be undefined in strict mode': function () { <ide> 'use strict'; <ide> <ide> var test = this, <ide> rejected.then(null, function () { <ide> rejectedThis = this; <ide> test.resume(function () { <del> Assert.isUndefined(fulfilledThis, 'in strict mode |this| in the success callback must be undefined'); <del> Assert.isUndefined(rejectedThis, 'in strict mode |this| in the failure callback must be undefined'); <add> Assert.isUndefined(fulfilledThis, 'in strict mode `this` in the success callback must be undefined'); <add> Assert.isUndefined(rejectedThis, 'in strict mode `this` in the failure callback must be undefined'); <ide> }); <ide> }); <ide> }); <ide> <del> test.wait(300); <add> test.wait(); <ide> } <ide> })); <ide> <ide> resolved = new Promise(function (resolve) { <ide> resolve(value); <ide> }), <del> next, <del> test = this; <add> next; <ide> <ide> next = resolved['catch'](function (err) { <ide> return err; <ide> Assert.isObject(next, 'catch() should return an object'); <ide> Assert.isTrue(Promise.isPromise(next), 'catch() should return a promise'); <ide> <del> isFulfilled(next, function (fulfilled, val) { <del> test.resume(function () { <del> Assert.isTrue(fulfilled, 'promise should still be fulfilled'); <del> Assert.areSame(value, val, 'promise fulfilled value should remain the same') <del> }); <del> }); <del> <del> test.wait(); <add> this.success(next, function (val) { <add> Assert.areSame(value, val, 'promise fulfilled value should remain the same') <add> }); <ide> }, <ide> <ide> 'catch(fn) is equivalent to then(undefined, fn)': function () { <ide> rejected = new Promise(function (resolve, reject) { <ide> reject(reason); <ide> }), <del> next, test = this; <add> next; <ide> <ide> next = rejected['catch'](function (err) { <ide> return err; <ide> }); <ide> <del> isFulfilled(next, function (fulfilled, value) { <del> test.resume(function () { <del> Assert.isTrue(fulfilled, 'promise should now be fulfilled'); <del> Assert.areSame(reason, value, 'returning an error in catch() should cause the next promise to be fulfilled'); <del> }); <del> }); <del> <del> test.wait(); <add> this.success(next, function (value) { <add> Assert.areSame(reason, value, 'returning an error in catch() should cause the next promise to be fulfilled'); <add> }); <ide> } <ide> })); <ide> <ide> }, <ide> <ide> 'Promise.reject() returns an rejected promise': function () { <del> var test = this, <del> value = new Error('foo'), <add> var value = new Error('foo'), <ide> promise = Promise.reject(value); <ide> <ide> Assert.isTrue(isPromise(promise), 'Promise.reject() should return a promise'); <ide> <del> isRejected(promise, function next(rejected, result) { <del> test.resume(function () { <del> Assert.isTrue(rejected, 'promise should be rejected, not fulfilled'); <del> Assert.areSame(value, result, 'Promise.reject() should respect the passed value'); <del> }); <del> }); <del> <del> test.wait(); <add> this.failure(promise, function next(rejected, result) { <add> Assert.areSame(value, result, 'Promise.reject() should respect the passed value'); <add> }); <ide> }, <ide> <ide> 'Promise.reject() should wrap fulfilled promises': function () { <del> var test = this, <del> value = new Promise(function (resolve) { <add> var value = new Promise(function (resolve) { <ide> resolve('foo'); <ide> }), <ide> promise = Promise.reject(value); <ide> <del> isRejected(promise, function (rejected, result) { <del> test.resume(function () { <del> Assert.isTrue(rejected, 'promise should be rejected, not fulfilled'); <del> Assert.areSame(value, result, 'Promise.reject() should wrap fulfilled promises'); <del> }); <del> }); <del> <del> test.wait(); <add> this.failure(promise, function (rejected, result) { <add> Assert.areSame(value, result, 'Promise.reject() should wrap fulfilled promises'); <add> }); <ide> }, <ide> <ide> 'Promise.reject() should wrap rejected promises': function () { <del> var test = this, <del> value = new Promise(function (resolve, reject) { <add> var value = new Promise(function (resolve, reject) { <ide> reject('foo'); <ide> }), <ide> promise = Promise.reject(value); <ide> <del> isRejected(promise, function (rejected, result) { <del> test.resume(function () { <del> Assert.isTrue(rejected, 'promise should be rejected, not fulfilled'); <del> Assert.areSame(value, result, 'Promise.reject() should wrap rejected promises'); <del> }); <del> }); <del> <del> test.wait(); <add> this.failure(promise, function (result) { <add> Assert.areSame(value, result, 'Promise.reject() should wrap rejected promises'); <add> }); <ide> }, <ide> <ide> 'Promise.reject() should preserve the constructor when using inheritance': function () { <ide> <ide> Assert.isInstanceOf(Subpromise, promise, 'rejected promise should be an instance of the subclass'); <ide> <del> isRejected(promise, function (rejected, reason) { <del> test.resume(function () { <del> Assert.isTrue(rejected, 'subpromise should be rejected'); <del> Assert.areSame('foo', reason, 'subpromise should have the correct rejection reason'); <del> }); <del> }); <del> <del> test.wait(); <add> this.failure(promise, function (reason) { <add> Assert.areSame('foo', reason, 'subpromise should have the correct rejection reason'); <add> }); <ide> }, <ide> <ide> 'Promise.resolve() is fulfilled when passed a regular value': function () { <del> var test = this, <del> value = {}, <add> var value = {}, <ide> promise = Promise.resolve(value); <ide> <del> isFulfilled(promise, function (fulfilled, result) { <del> test.resume(function () { <del> Assert.isTrue(fulfilled, 'resolved promise should be fulfilled'); <del> Assert.areSame(value, result, 'resolved promise should respect the value passed to it'); <del> }); <del> }); <del> <del> test.wait(); <add> this.success(promise, function (result) { <add> Assert.areSame(value, result, 'resolved promise should respect the value passed to it'); <add> }); <ide> }, <ide> <ide> 'Promise.resolve() adopts the state of an fulfilled promise': function () { <del> var test = this, <del> value = {}, <add> var value = {}, <ide> fulfilled = Promise.resolve(value), <ide> promise = Promise.resolve(fulfilled); <ide> <del> isFulfilled(promise, function (fulfilled, result) { <del> test.resume(function () { <del> Assert.isTrue(fulfilled, 'resolved promise should be fulfilled'); <del> Assert.areSame(value, result, 'resolved promise should take the value of the provided promise'); <del> }); <del> }); <del> <del> test.wait(); <add> this.success(promise, function (result) { <add> Assert.areSame(value, result, 'resolved promise should take the value of the provided promise'); <add> }); <ide> }, <ide> <ide> 'Promise.resolve() adopts the state of a rejected promise': function () { <del> var test = this, <del> value = {}, <add> var value = {}, <ide> fulfilled = Promise.reject(value), <ide> promise = Promise.resolve(fulfilled); <ide> <del> isRejected(promise, function (rejected, result) { <del> test.resume(function () { <del> Assert.isTrue(rejected, 'resolved promise should be rejected'); <del> Assert.areSame(value, result, 'resolved promise should take the value of the provided promise'); <del> }); <del> }); <del> <del> test.wait(); <add> this.failure(promise, function (rejected, result) { <add> Assert.areSame(value, result, 'resolved promise should take the value of the provided promise'); <add> }); <ide> }, <ide> <ide> 'Promise.resolve() should preserve the constructor when using inheritance': function () { <ide> Y.extend(Subpromise, Promise, null, {resolve: Promise.resolve}); <ide> <ide> var promise = Subpromise.resolve('foo'); <del> var test = this; <ide> <ide> Assert.isInstanceOf(Subpromise, promise, 'resolved promise should be an instance of the subclass'); <ide> <del> isFulfilled(promise, function (fulfilled, value) { <del> test.resume(function () { <del> Assert.isTrue(fulfilled, 'subpromise should be fulfilled'); <del> Assert.areSame('foo', value, 'subpromise should have the correct fulfilled value'); <del> }); <del> }); <del> <del> test.wait(); <add> this.success(promise, function (value) { <add> Assert.areSame('foo', value, 'subpromise should have the correct fulfilled value'); <add> }); <ide> } <ide> })); <ide> <ide> }, <ide> <ide> 'a non array argument should turn into a rejected promise': function () { <del> var test = this; <del> <del> isRejected(Promise.all('foo'), function (rejected, error) { <del> test.resume(function () { <del> Assert.isTrue(rejected, 'wrong argument for all() should return a rejected promise'); <del> Assert.isInstanceOf(TypeError, error, 'rejection reason should be a TypeError'); <del> }); <del> }); <del> <del> test.wait(); <add> this.failure(Promise.all('foo'), function (error) { <add> Assert.isInstanceOf(TypeError, error, 'rejection reason should be a TypeError'); <add> }); <ide> }, <ide> <ide> 'order of promises should be preserved': function () { <del> var test = this, <del> promise = Promise.all([wait(20), wait(10), wait(15)]); <del> <del> isFulfilled(promise, function (fulfilled, result) { <del> test.resume(function () { <del> Assert.isTrue(fulfilled, 'promise should be fulfilled'); <del> ArrayAssert.itemsAreSame([20, 10, 15], result, 'order of returned values should be the same as the parameter list'); <del> }); <del> }); <del> <del> test.wait(); <add> var promise = Promise.all([wait(20), wait(10), wait(15)]); <add> <add> this.success(promise, function (result) { <add> ArrayAssert.itemsAreSame([20, 10, 15], result, 'order of returned values should be the same as the parameter list'); <add> }); <ide> }, <ide> <ide> 'values should be wrapped in a promise': function () { <del> var test = this, <del> obj = { <add> var obj = { <ide> hello: 'world' <ide> }, <ide> promise = Promise.all(['foo', 5, obj]); <ide> <del> isFulfilled(promise, function (fulfilled, result) { <del> test.resume(function () { <del> Assert.isTrue(fulfilled, 'promise should be fulfilled'); <del> ArrayAssert.itemsAreSame(['foo', 5, obj], result, 'values passed to Promise.all() should be wrapped in promises, not ignored'); <del> }); <del> }); <del> <del> test.wait(); <add> this.success(promise, function (result) { <add> ArrayAssert.itemsAreSame(['foo', 5, obj], result, 'values passed to Promise.all() should be wrapped in promises, not ignored'); <add> }); <ide> }, <ide> <ide> 'correct handling of function parameters': function () { <del> var test = this, promise; <del> <ide> function testFn() {} <ide> <del> promise = Promise.all([testFn]); <del> <del> isFulfilled(promise, function (fulfilled, values) { <del> test.resume(function () { <del> Assert.isTrue(fulfilled, 'promise should be fulfilled'); <del> Assert.isFunction(values[0], 'promise value should be a function'); <del> Assert.areSame(testFn, values[0], 'promise value should be the passed function'); <del> }); <del> }); <del> <del> test.wait(); <add> this.success(Promise.all([testFn]), function (values) { <add> Assert.isFunction(values[0], 'promise value should be a function'); <add> Assert.areSame(testFn, values[0], 'promise value should be the passed function'); <add> }); <ide> }, <ide> <ide> 'Promise.all() should fail as fast as possible': function () { <del> var test = this, promise; <del> <del> promise = Promise.all([rejectedAfter(20), rejectedAfter(10), rejectedAfter(15)]); <del> <del> isRejected(promise, function (rejected, reason) { <del> test.resume(function () { <del> Assert.isTrue(rejected, 'promise should be rejected'); <del> Assert.areEqual(10, reason, 'reason should be the one from the first promise to be rejected'); <del> }); <del> }); <del> <del> test.wait(); <add> var promise = Promise.all([rejectedAfter(20), rejectedAfter(10), rejectedAfter(15)]); <add> <add> this.failure(promise, function (reason) { <add> Assert.areEqual(10, reason, 'reason should be the one from the first promise to be rejected'); <add> }); <ide> } <ide> <ide> })); <ide> name: 'Promise.race() tests', <ide> <ide> 'a non array argument should turn into a rejected promise': function () { <del> var test = this; <del> <del> isRejected(Promise.race('foo'), function (rejected, error) { <del> test.resume(function () { <del> Assert.isTrue(rejected, 'wrong argument for all() should return a rejected promise'); <del> Assert.isInstanceOf(TypeError, error, 'rejection reason should be a TypeError'); <del> }); <del> }); <del> <del> test.wait(); <add> this.failure(Promise.race('foo'), function (error) { <add> Assert.isInstanceOf(TypeError, error, 'rejection reason should be a TypeError'); <add> }); <ide> }, <ide> <ide> 'Promise.race() should fulfill when passed a fulfilled promise': function () { <del> var test = this, <del> promise = Promise.race([wait(10)]); <del> <del> isFulfilled(promise, function (fulfilled, result) { <del> test.resume(function () { <del> Assert.isTrue(fulfilled, 'promise should be fulfilled'); <del> Assert.areEqual(10, result, 'Promise.race() should fulfill when passed a fulfilled promise'); <del> }); <del> }); <del> <del> test.wait(); <add> this.success(Promise.race([wait(10)]), function (result) { <add> Assert.areEqual(10, result, 'Promise.race() should fulfill when passed a fulfilled promise'); <add> }); <ide> }, <ide> <ide> 'Promise.race() should reject when passed a rejected promise': function () { <del> var test = this, <del> promise = Promise.race([rejectedAfter(10)]); <del> <del> isRejected(promise, function (rejected, result) { <del> test.resume(function () { <del> Assert.isTrue(rejected, 'promise should be rejected'); <del> Assert.areEqual(10, result, 'Promise.race() should reject when passed a rejected promise'); <del> }); <del> }); <del> <del> test.wait(); <add> this.failure(Promise.race([rejectedAfter(10)]), function (result) { <add> Assert.areEqual(10, result, 'Promise.race() should reject when passed a rejected promise'); <add> }); <ide> }, <ide> <ide> 'Promise.race() should fulfill to the value of the first promise to be fulfilled': function () { <del> var test = this, <del> promise = Promise.race([wait(10), wait(100)]); <del> <del> isFulfilled(promise, function (fulfilled, result) { <del> test.resume(function () { <del> Assert.isTrue(fulfilled, 'promise should be fulfilled'); <del> Assert.areEqual(10, result, 'Promise.race() should fulfill to the value of the first promise to be fulfilled'); <del> }); <del> }); <del> <del> test.wait(); <add> var promise = Promise.race([wait(10), wait(100)]); <add> <add> this.success(promise, function (result) { <add> Assert.areEqual(10, result, 'Promise.race() should fulfill to the value of the first promise to be fulfilled'); <add> }); <ide> }, <ide> <ide> 'Promise.race() should reject with the reason of the first promise to be rejected': function () { <del> var test = this, <del> promise = Promise.race([rejectedAfter(10), rejectedAfter(100)]); <del> <del> isRejected(promise, function (rejected, result) { <del> test.resume(function () { <del> Assert.isTrue(rejected, 'promise should be rejected'); <del> Assert.areEqual(10, result, 'Promise.race() should reject with the reason of the first promise to be rejected'); <del> }); <del> }); <del> <del> test.wait(); <add> var promise = Promise.race([rejectedAfter(10), rejectedAfter(100)]); <add> <add> this.failure(promise, function (result) { <add> Assert.areEqual(10, result, 'Promise.race() should reject with the reason of the first promise to be rejected'); <add> }); <ide> } <ide> })); <ide>
Java
apache-2.0
46e6b23974fec9fc15877ef4e33aa78d14ff22fa
0
lorisdanto/symbolicautomata,lorisdanto/symbolicautomata
package correction; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import automata.Move; import automata.sfa.SFA; import automata.sfa.SFAInputMove; import theory.characters.CharPred; import theory.intervals.UnaryCharIntervalSolver; public class StringCorrection { // save computed p, l, v, f values for later use private static HashMap<String, Pair> pStorage = null; private static HashMap<String, Boolean> lStorage = null; private static HashMap<String, Pair> vStorage = null; private static HashMap<String, Pair> fStorage = null; // let -1 represent positive infinity private static final int INFINITY = -1; /** * Find the string which is accepted by given FSA and has lowest edit * distance to the input string * * @param inpSFA * given symbolic finite automata * @param inpStr * input string * @return result string that is accepted by SFA */ public static String getCorrectString(SFA<CharPred, Character> inpSFA, String inpStr) { Pair p = getCorrectPair(inpSFA, inpStr); LinkedList<CharPred> l = p.charSet; UnaryCharIntervalSolver ba = new UnaryCharIntervalSolver(); return ba.stringOfListOfCharPred(l); } /** * Find the lowest edit distance from input string to a string that is * accepted by given FSA * * @param inpSFA * given symbolic finite automata * @param inpStr * input string * @return result edit distance */ public static int computeEditDistance(SFA<CharPred, Character> inpSFA, String inpStr) { Pair p = getCorrectPair(inpSFA, inpStr); return p.editDistance; } /** * Find the lowest edit distance from input string to a string that is * accepted by given FSA * * @param inpSFA * given symbolic finite automata * @param inpStr * input string * @return result string represented by a linked list of char predicates */ public static LinkedList<CharPred> getCorrectCharPredList(SFA<CharPred, Character> inpSFA, String inpStr) { Pair p = getCorrectPair(inpSFA, inpStr); return p.charSet; } /** * Find the string which is accepted by given FSA and has lowest edit * distance to the input string * * @param inpSFA * given symbolic finite automata * @param inpStr * input string * @return result string represented by a linked list of char predicates */ private static Pair getCorrectPair(SFA<CharPred, Character> inpSFA, String inpStr) { pStorage = new HashMap<String, Pair>(); lStorage = new HashMap<String, Boolean>(); fStorage = new HashMap<String, Pair>(); vStorage = new HashMap<String, Pair>(); Pair p = new Pair(INFINITY, null); for (Integer i : inpSFA.getFinalStates()) { Pair termF = F(inpStr.length(), i, inpSFA, inpStr); if (lt(termF.editDistance, p.editDistance)) { p.editDistance = termF.editDistance; p.charSet = termF.charSet; } } return p; } /** * F refers to the lowest number of edit operations needed to force FSA to * goal state, given the first j characters of the input string * * @param j * number of first characters of input string * @param S * goal state * @param templ * given SFA * @param inpStr * input string * @return lowest number of edit operations and corresponding string segment */ private static Pair F(int j, int S, SFA<CharPred, Character> templ, String inpStr) { String lookUp = String.format("%d,%d", j, S); if (fStorage.containsKey(lookUp)) { return fStorage.get(lookUp); } if (j == 0) { if (S == templ.getInitialState()) { Pair result = new Pair(0, new LinkedList<CharPred>()); fStorage.put(lookUp, result); return result; } else { Pair result = new Pair(INFINITY, new LinkedList<CharPred>()); fStorage.put(lookUp, result); return result; } } Pair minCost = new Pair(INFINITY, new LinkedList<CharPred>()); for (Integer i : templ.getStates()) { Pair termF = F(j - 1, i, templ, inpStr); Pair termV = V(i, S, inpStr.charAt(j - 1), templ); int newCost = add(termF.editDistance, termV.editDistance); if (lt(newCost, minCost.editDistance)) { minCost.editDistance = newCost; LinkedList<CharPred> l = new LinkedList<CharPred>(); l.addAll(termF.charSet); l.addAll(termV.charSet); minCost.charSet = l; } } fStorage.put(lookUp, minCost); return minCost; } /** * V refers to the lowest number of edit operations needed to change * character c into a string beta which will force the FSA from state T to * state S * * @param T * origin state * @param S * destination state * @param c * a single character * @param templ * given SFA * @return lowest number of edit operations and corresponding string beta */ private static Pair V(int T, int S, Character c, SFA<CharPred, Character> templ) { String lookUp = String.format("%d,%d,%c", T, S, c); if (vStorage.containsKey(lookUp)) { return vStorage.get(lookUp); } Pair pResult = P(templ.stateCount() - 1, T, S, templ); Pair p = new Pair(pResult.editDistance, (LinkedList<CharPred>) pResult.charSet.clone()); if (p.editDistance == 0) { if (T == S) { Collection<Move<CharPred, Character>> arcs = templ.getMovesFrom(T); for (Move<CharPred, Character> q : arcs) { if (q.to == S) { SFAInputMove<CharPred, Character> curr = (SFAInputMove<CharPred, Character>) q; if (curr.guard.isSatisfiedBy(c)) { LinkedList<CharPred> l = new LinkedList<>(); l.add(new CharPred(c)); Pair temp = new Pair(0, l); vStorage.put(lookUp, temp); return temp; } } } } Pair temp = new Pair(1, new LinkedList<CharPred>()); vStorage.put(lookUp, temp); return temp; } else { Pair term = p; boolean lRes = L(templ.stateCount() - 1, T, S, c, templ); if (lRes) { for (int j = 0; j < term.charSet.size(); j++) { if (term.charSet.get(j).isSatisfiedBy(c)) { term.charSet.set(j, new CharPred(c)); break; } } } int i = lRes ? 1 : 0; term.editDistance = sub(term.editDistance, i); vStorage.put(lookUp, term); return term; } } /** * P refers to the length of the shortest string which force the FSA from * state T to state S, passing only through states numbered k or less * * @param k * max state passed * @param T * origin state * @param S * destination state * @param templ * given SFA * @return edit distance P and corresponding string segment */ private static Pair P(int k, int T, int S, SFA<CharPred, Character> templ) { String lookUp = String.format("%d,%d,%d", k, T, S); if (pStorage.containsKey(lookUp)) { return pStorage.get(lookUp); } if (T == S) { Pair res = new Pair(0, new LinkedList<CharPred>()); pStorage.put(lookUp, res); return res; } if (k == 0) { Collection<Move<CharPred, Character>> arcs = templ.getMovesFrom(T); for (Move<CharPred, Character> q : arcs) { if (q.to == S) { SFAInputMove<CharPred, Character> curr = (SFAInputMove<CharPred, Character>) q; LinkedList<CharPred> l = new LinkedList<CharPred>(); l.add(curr.guard); Pair res = new Pair(1, l); pStorage.put(lookUp, res); return res; } } return new Pair(INFINITY, new LinkedList<CharPred>()); } Pair term1 = P(k - 1, T, S, templ); Pair term2 = P(k - 1, T, k, templ); Pair term3 = P(k - 1, k, S, templ); Pair result; if (le(term1.editDistance, add(term2.editDistance, term3.editDistance))) { result = new Pair(term1.editDistance, term1.charSet); } else { LinkedList<CharPred> l = new LinkedList<CharPred>(); l.addAll(term2.charSet); l.addAll(term3.charSet); result = new Pair(add(term2.editDistance, term3.editDistance), l); } pStorage.put(lookUp, result); return result; } /** * L indicates whether or not character c is accepted by some arc along a * path of shortest length from T to S, passing only through states numbered * k or less * * @param k * max state passed * @param T * origin state * @param S * destination state * @param c * a single character * @param templ * given SFA * @return truth of indicator L */ private static boolean L(int k, int T, int S, Character c, SFA<CharPred, Character> templ) { String lookUp = String.format("%d,%d,%d,%c", k, T, S, c); if (lStorage.containsKey(lookUp)) { return lStorage.get(lookUp); } if (k == 0) { Collection<Move<CharPred, Character>> arcs = templ.getMovesFrom(T); for (Move<CharPred, Character> q : arcs) { if (q.to == S) { SFAInputMove<CharPred, Character> curr = (SFAInputMove<CharPred, Character>) q; if (curr.guard.isSatisfiedBy(c)) { lStorage.put(lookUp, true); return true; } } } lStorage.put(lookUp, false); return false; } boolean result; Pair term1 = P(k - 1, T, S, templ); Pair term2 = P(k - 1, T, k, templ); Pair term3 = P(k - 1, k, S, templ); if (gt(term1.editDistance, add(term2.editDistance, term3.editDistance))) { result = L(k - 1, T, k, c, templ) || L(k - 1, k, S, c, templ); } else if (eq(term1.editDistance, add(term2.editDistance, term3.editDistance))) { result = L(k - 1, T, k, c, templ) || L(k - 1, k, S, c, templ) || L(k - 1, T, S, c, templ); } else { result = L(k - 1, T, S, c, templ); } lStorage.put(lookUp, result); return result; } /** * wrapper functions to deal with infinity calculation and comparison */ private static int add(int a, int b) { if (a == INFINITY || b == INFINITY) { return INFINITY; } else { return a + b; } } private static int sub(int a, int b) { if (a == INFINITY && b != INFINITY) return INFINITY; else return a - b; } private static boolean lt(int a, int b) { if (a == INFINITY) a = Integer.MAX_VALUE; if (b == INFINITY) b = Integer.MAX_VALUE; return a < b; } private static boolean gt(int a, int b) { if (a == INFINITY) a = Integer.MAX_VALUE; if (b == INFINITY) b = Integer.MAX_VALUE; return a > b; } private static boolean eq(int a, int b) { return a == b; } private static boolean le(int a, int b) { if (a == INFINITY) a = Integer.MAX_VALUE; if (b == INFINITY) b = Integer.MAX_VALUE; return a <= b; } } /** * This is a wrapper class. It contains a double variable representing edit * distance and a linked list representing a string segment */ class Pair { protected int editDistance; protected LinkedList<CharPred> charSet; protected Pair(int i, LinkedList<CharPred> s) { editDistance = i; charSet = s; } }
SVPAlib/src/correction/StringCorrection.java
package correction; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import automata.Move; import automata.sfa.SFA; import automata.sfa.SFAInputMove; import theory.characters.CharPred; public class StringCorrection { private static SFA<CharPred, Character> templ = null; private static Collection<Integer> goalStates = null; private static Collection<Integer> allStates = null; private static String w = null; private static int numStates; private static HashMap<String, Pair> pStore = null; private static HashMap<String, Boolean> lStore = null; public static LinkedList<CharPred> getCorrectString(SFA<CharPred, Character> inpSFA, String inpStr) { w = inpStr; templ = inpSFA; numStates = inpSFA.stateCount(); goalStates = inpSFA.getFinalStates(); allStates = inpSFA.getStates(); pStore = new HashMap<String, Pair>(); lStore = new HashMap<String, Boolean>(); double minDist = Double.POSITIVE_INFINITY; LinkedList<CharPred> resultStr = null; for (Integer i : goalStates) { Pair termF = F(w.length(), i); if (termF.editDistance < minDist) { minDist = termF.editDistance; resultStr = termF.charSet; } } return resultStr; } public static int computeEditDistance(SFA<CharPred, Character> inpSFA, String inpStr) { w = inpStr; templ = inpSFA; numStates = inpSFA.stateCount(); goalStates = inpSFA.getFinalStates(); allStates = inpSFA.getStates(); pStore = new HashMap<String, Pair>(); lStore = new HashMap<String, Boolean>(); double minDist = Double.POSITIVE_INFINITY; for (Integer i : goalStates) { Pair termF = F(w.length(), i); if (termF.editDistance < minDist) { minDist = termF.editDistance; } } return (int)minDist; } private static Pair F(int j, int S) { if (j == 0) { if (S == templ.getInitialState()) { return new Pair(0.0, new LinkedList<CharPred>()); } else { return new Pair(Double.POSITIVE_INFINITY, new LinkedList<CharPred>()); } } Pair minCost = new Pair(Double.POSITIVE_INFINITY, new LinkedList<CharPred>()); for (Integer i : allStates) { Pair termF = F(j - 1, i); Pair termV = V(i, S, w.charAt(j - 1)); double newCost = termF.editDistance + termV.editDistance; if (newCost < minCost.editDistance) { minCost.editDistance = newCost; LinkedList<CharPred> l = new LinkedList<CharPred>(); l.addAll(termF.charSet); l.addAll(termV.charSet); minCost.charSet = l; } } return minCost; } private static Pair V(int T, int S, Character c) { Pair p = P(numStates - 1, T, S); if (p.editDistance == 0) { if (T == S) { Collection<Move<CharPred, Character>> arcs = templ.getMovesFrom(T); for (Move<CharPred, Character> q : arcs) { if (q.to == S) { SFAInputMove<CharPred, Character> curr = (SFAInputMove<CharPred, Character>) q; if (curr.guard.isSatisfiedBy(c)) { LinkedList<CharPred> l = new LinkedList<>(); l.add(new CharPred(c)); return new Pair(0.0, l); } } } return new Pair(1.0, new LinkedList<CharPred>()); } else { return new Pair(1.0, new LinkedList<CharPred>()); } } else { Pair term = p; if (L(numStates - 1, T, S, c)) { for (int j = 0; j < term.charSet.size(); j++) { if (term.charSet.get(j).isSatisfiedBy(c)) { term.charSet.set(j, new CharPred(c)); break; } } } int i = L(numStates - 1, T, S, c) ? 1 : 0; term.editDistance -= i; return term; } } private static Pair P(int k, int T, int S) { String lookUp = String.format("%d$%d$%d", k, T, S); // if (pStore.containsKey(lookUp)) { // return pStore.get(lookUp); // } if (T == S) return new Pair(0.0, new LinkedList<CharPred>()); if (k == 0) { Collection<Move<CharPred, Character>> arcs = templ.getMovesFrom(T); for (Move<CharPred, Character> q : arcs) { if (q.to == S) { SFAInputMove<CharPred, Character> curr = (SFAInputMove<CharPred, Character>) q; LinkedList<CharPred> l = new LinkedList<CharPred>(); l.add(curr.guard); Pair res = new Pair(1.0, l); // pStore.put(lookUp, res); return res; } } return new Pair(Double.POSITIVE_INFINITY, new LinkedList<CharPred>()); } Pair term1 = P(k - 1, T, S); Pair term2 = P(k - 1, T, k); Pair term3 = P(k - 1, k, S); Pair result; if (term1.editDistance <= term2.editDistance + term3.editDistance) { result = term1; } else { LinkedList<CharPred> l = new LinkedList<CharPred>(); l.addAll(term2.charSet); l.addAll(term3.charSet); result = new Pair(term2.editDistance + term3.editDistance, l); } // pStore.put(lookUp, result); return result; } /** * L indicates whether or not character c is accepted by some arc * along a path of shortest length from T to S, passing only through * states numbered k or less * * @param k max state involved * @param T origin state * @param S destination state * @param c a single character */ private static boolean L(int k, int T, int S, Character c) { String lookUp = String.format("%d$%d$%d$%c", k, T, S, c); // if (lStore.containsKey(lookUp)) { // return lStore.get(lookUp); // } if (k == 0) { Collection<Move<CharPred, Character>> arcs = templ.getMovesFrom(T); for (Move<CharPred, Character> q : arcs) { if (q.to == S) { SFAInputMove<CharPred, Character> curr = (SFAInputMove<CharPred, Character>) q; if (curr.guard.isSatisfiedBy(c)) { lStore.put(lookUp, true); return true; } } } lStore.put(lookUp, false); return false; } boolean result; Pair term1 = P(k - 1, T, S); Pair term2 = P(k - 1, T, k); Pair term3 = P(k - 1, k, S); if (term1.editDistance > term2.editDistance + term3.editDistance) { result = L(k - 1, T, k, c) || L(k - 1, k, S, c); } else if (term1.editDistance == term2.editDistance + term3.editDistance) { result = L(k - 1, T, k, c) || L(k - 1, k, S, c) || L(k - 1, T, S, c); } else { result = L(k - 1, T, S, c); } lStore.put(lookUp, result); return result; } } /** * This is a wrapper class. It contains a double variable representing * edit distance and a linked list representing a string segment */ class Pair { protected double editDistance; protected LinkedList<CharPred> charSet; protected Pair(double i, LinkedList<CharPred> s) { editDistance = i; charSet = s; } }
Many major changes change double edit distances to int add wrapper functions to deal with infinity change public interface use hashmap to store recursive results add comments
SVPAlib/src/correction/StringCorrection.java
Many major changes
<ide><path>VPAlib/src/correction/StringCorrection.java <ide> import automata.sfa.SFA; <ide> import automata.sfa.SFAInputMove; <ide> import theory.characters.CharPred; <add>import theory.intervals.UnaryCharIntervalSolver; <ide> <ide> public class StringCorrection { <del> private static SFA<CharPred, Character> templ = null; <del> private static Collection<Integer> goalStates = null; <del> private static Collection<Integer> allStates = null; <del> private static String w = null; <del> private static int numStates; <del> private static HashMap<String, Pair> pStore = null; <del> private static HashMap<String, Boolean> lStore = null; <del> <del> public static LinkedList<CharPred> getCorrectString(SFA<CharPred, Character> inpSFA, String inpStr) { <del> w = inpStr; <del> templ = inpSFA; <del> numStates = inpSFA.stateCount(); <del> goalStates = inpSFA.getFinalStates(); <del> allStates = inpSFA.getStates(); <del> pStore = new HashMap<String, Pair>(); <del> lStore = new HashMap<String, Boolean>(); <del> <del> double minDist = Double.POSITIVE_INFINITY; <del> LinkedList<CharPred> resultStr = null; <del> for (Integer i : goalStates) { <del> Pair termF = F(w.length(), i); <del> if (termF.editDistance < minDist) { <del> minDist = termF.editDistance; <del> resultStr = termF.charSet; <del> } <del> } <del> return resultStr; <del> } <del> <add> // save computed p, l, v, f values for later use <add> private static HashMap<String, Pair> pStorage = null; <add> private static HashMap<String, Boolean> lStorage = null; <add> private static HashMap<String, Pair> vStorage = null; <add> private static HashMap<String, Pair> fStorage = null; <add> // let -1 represent positive infinity <add> private static final int INFINITY = -1; <add> <add> /** <add> * Find the string which is accepted by given FSA and has lowest edit <add> * distance to the input string <add> * <add> * @param inpSFA <add> * given symbolic finite automata <add> * @param inpStr <add> * input string <add> * @return result string that is accepted by SFA <add> */ <add> public static String getCorrectString(SFA<CharPred, Character> inpSFA, String inpStr) { <add> Pair p = getCorrectPair(inpSFA, inpStr); <add> LinkedList<CharPred> l = p.charSet; <add> UnaryCharIntervalSolver ba = new UnaryCharIntervalSolver(); <add> return ba.stringOfListOfCharPred(l); <add> } <add> <add> /** <add> * Find the lowest edit distance from input string to a string that is <add> * accepted by given FSA <add> * <add> * @param inpSFA <add> * given symbolic finite automata <add> * @param inpStr <add> * input string <add> * @return result edit distance <add> */ <ide> public static int computeEditDistance(SFA<CharPred, Character> inpSFA, String inpStr) { <del> w = inpStr; <del> templ = inpSFA; <del> numStates = inpSFA.stateCount(); <del> goalStates = inpSFA.getFinalStates(); <del> allStates = inpSFA.getStates(); <del> pStore = new HashMap<String, Pair>(); <del> lStore = new HashMap<String, Boolean>(); <del> <del> double minDist = Double.POSITIVE_INFINITY; <del> for (Integer i : goalStates) { <del> Pair termF = F(w.length(), i); <del> if (termF.editDistance < minDist) { <del> minDist = termF.editDistance; <del> } <del> } <del> return (int)minDist; <del> } <del> <del> private static Pair F(int j, int S) { <add> Pair p = getCorrectPair(inpSFA, inpStr); <add> return p.editDistance; <add> } <add> <add> /** <add> * Find the lowest edit distance from input string to a string that is <add> * accepted by given FSA <add> * <add> * @param inpSFA <add> * given symbolic finite automata <add> * @param inpStr <add> * input string <add> * @return result string represented by a linked list of char predicates <add> */ <add> public static LinkedList<CharPred> getCorrectCharPredList(SFA<CharPred, Character> inpSFA, String inpStr) { <add> Pair p = getCorrectPair(inpSFA, inpStr); <add> return p.charSet; <add> } <add> <add> /** <add> * Find the string which is accepted by given FSA and has lowest edit <add> * distance to the input string <add> * <add> * @param inpSFA <add> * given symbolic finite automata <add> * @param inpStr <add> * input string <add> * @return result string represented by a linked list of char predicates <add> */ <add> private static Pair getCorrectPair(SFA<CharPred, Character> inpSFA, String inpStr) { <add> pStorage = new HashMap<String, Pair>(); <add> lStorage = new HashMap<String, Boolean>(); <add> fStorage = new HashMap<String, Pair>(); <add> vStorage = new HashMap<String, Pair>(); <add> Pair p = new Pair(INFINITY, null); <add> for (Integer i : inpSFA.getFinalStates()) { <add> Pair termF = F(inpStr.length(), i, inpSFA, inpStr); <add> if (lt(termF.editDistance, p.editDistance)) { <add> p.editDistance = termF.editDistance; <add> p.charSet = termF.charSet; <add> } <add> } <add> return p; <add> } <add> <add> /** <add> * F refers to the lowest number of edit operations needed to force FSA to <add> * goal state, given the first j characters of the input string <add> * <add> * @param j <add> * number of first characters of input string <add> * @param S <add> * goal state <add> * @param templ <add> * given SFA <add> * @param inpStr <add> * input string <add> * @return lowest number of edit operations and corresponding string segment <add> */ <add> private static Pair F(int j, int S, SFA<CharPred, Character> templ, String inpStr) { <add> String lookUp = String.format("%d,%d", j, S); <add> if (fStorage.containsKey(lookUp)) { <add> return fStorage.get(lookUp); <add> } <ide> if (j == 0) { <ide> if (S == templ.getInitialState()) { <del> return new Pair(0.0, new LinkedList<CharPred>()); <add> Pair result = new Pair(0, new LinkedList<CharPred>()); <add> fStorage.put(lookUp, result); <add> return result; <ide> } else { <del> return new Pair(Double.POSITIVE_INFINITY, new LinkedList<CharPred>()); <del> } <del> } <del> Pair minCost = new Pair(Double.POSITIVE_INFINITY, new LinkedList<CharPred>()); <del> for (Integer i : allStates) { <del> Pair termF = F(j - 1, i); <del> Pair termV = V(i, S, w.charAt(j - 1)); <del> double newCost = termF.editDistance + termV.editDistance; <del> if (newCost < minCost.editDistance) { <add> Pair result = new Pair(INFINITY, new LinkedList<CharPred>()); <add> fStorage.put(lookUp, result); <add> return result; <add> } <add> } <add> Pair minCost = new Pair(INFINITY, new LinkedList<CharPred>()); <add> for (Integer i : templ.getStates()) { <add> Pair termF = F(j - 1, i, templ, inpStr); <add> Pair termV = V(i, S, inpStr.charAt(j - 1), templ); <add> int newCost = add(termF.editDistance, termV.editDistance); <add> if (lt(newCost, minCost.editDistance)) { <ide> minCost.editDistance = newCost; <ide> LinkedList<CharPred> l = new LinkedList<CharPred>(); <ide> l.addAll(termF.charSet); <ide> minCost.charSet = l; <ide> } <ide> } <add> fStorage.put(lookUp, minCost); <ide> return minCost; <ide> } <ide> <del> private static Pair V(int T, int S, Character c) { <del> Pair p = P(numStates - 1, T, S); <add> /** <add> * V refers to the lowest number of edit operations needed to change <add> * character c into a string beta which will force the FSA from state T to <add> * state S <add> * <add> * @param T <add> * origin state <add> * @param S <add> * destination state <add> * @param c <add> * a single character <add> * @param templ <add> * given SFA <add> * @return lowest number of edit operations and corresponding string beta <add> */ <add> private static Pair V(int T, int S, Character c, SFA<CharPred, Character> templ) { <add> String lookUp = String.format("%d,%d,%c", T, S, c); <add> if (vStorage.containsKey(lookUp)) { <add> return vStorage.get(lookUp); <add> } <add> Pair pResult = P(templ.stateCount() - 1, T, S, templ); <add> Pair p = new Pair(pResult.editDistance, (LinkedList<CharPred>) pResult.charSet.clone()); <ide> if (p.editDistance == 0) { <ide> if (T == S) { <ide> Collection<Move<CharPred, Character>> arcs = templ.getMovesFrom(T); <ide> if (curr.guard.isSatisfiedBy(c)) { <ide> LinkedList<CharPred> l = new LinkedList<>(); <ide> l.add(new CharPred(c)); <del> return new Pair(0.0, l); <add> Pair temp = new Pair(0, l); <add> vStorage.put(lookUp, temp); <add> return temp; <ide> } <ide> } <ide> } <del> return new Pair(1.0, new LinkedList<CharPred>()); <del> } else { <del> return new Pair(1.0, new LinkedList<CharPred>()); <del> } <add> } <add> Pair temp = new Pair(1, new LinkedList<CharPred>()); <add> vStorage.put(lookUp, temp); <add> return temp; <ide> } else { <del> <ide> Pair term = p; <del> if (L(numStates - 1, T, S, c)) { <add> boolean lRes = L(templ.stateCount() - 1, T, S, c, templ); <add> if (lRes) { <ide> for (int j = 0; j < term.charSet.size(); j++) { <ide> if (term.charSet.get(j).isSatisfiedBy(c)) { <ide> term.charSet.set(j, new CharPred(c)); <ide> } <ide> } <ide> } <del> int i = L(numStates - 1, T, S, c) ? 1 : 0; <del> term.editDistance -= i; <add> int i = lRes ? 1 : 0; <add> term.editDistance = sub(term.editDistance, i); <add> vStorage.put(lookUp, term); <ide> return term; <ide> } <ide> } <ide> <del> private static Pair P(int k, int T, int S) { <del> String lookUp = String.format("%d$%d$%d", k, T, S); <del> // if (pStore.containsKey(lookUp)) { <del> // return pStore.get(lookUp); <del> // } <del> if (T == S) <del> return new Pair(0.0, new LinkedList<CharPred>()); <add> /** <add> * P refers to the length of the shortest string which force the FSA from <add> * state T to state S, passing only through states numbered k or less <add> * <add> * @param k <add> * max state passed <add> * @param T <add> * origin state <add> * @param S <add> * destination state <add> * @param templ <add> * given SFA <add> * @return edit distance P and corresponding string segment <add> */ <add> private static Pair P(int k, int T, int S, SFA<CharPred, Character> templ) { <add> String lookUp = String.format("%d,%d,%d", k, T, S); <add> if (pStorage.containsKey(lookUp)) { <add> return pStorage.get(lookUp); <add> } <add> if (T == S) { <add> Pair res = new Pair(0, new LinkedList<CharPred>()); <add> pStorage.put(lookUp, res); <add> return res; <add> } <add> <ide> if (k == 0) { <ide> Collection<Move<CharPred, Character>> arcs = templ.getMovesFrom(T); <ide> for (Move<CharPred, Character> q : arcs) { <ide> SFAInputMove<CharPred, Character> curr = (SFAInputMove<CharPred, Character>) q; <ide> LinkedList<CharPred> l = new LinkedList<CharPred>(); <ide> l.add(curr.guard); <del> Pair res = new Pair(1.0, l); <del> // pStore.put(lookUp, res); <add> Pair res = new Pair(1, l); <add> pStorage.put(lookUp, res); <ide> return res; <ide> } <ide> } <del> return new Pair(Double.POSITIVE_INFINITY, new LinkedList<CharPred>()); <del> } <del> Pair term1 = P(k - 1, T, S); <del> Pair term2 = P(k - 1, T, k); <del> Pair term3 = P(k - 1, k, S); <add> return new Pair(INFINITY, new LinkedList<CharPred>()); <add> } <add> Pair term1 = P(k - 1, T, S, templ); <add> Pair term2 = P(k - 1, T, k, templ); <add> Pair term3 = P(k - 1, k, S, templ); <ide> Pair result; <del> if (term1.editDistance <= term2.editDistance + term3.editDistance) { <del> result = term1; <add> if (le(term1.editDistance, add(term2.editDistance, term3.editDistance))) { <add> result = new Pair(term1.editDistance, term1.charSet); <ide> } else { <ide> LinkedList<CharPred> l = new LinkedList<CharPred>(); <ide> l.addAll(term2.charSet); <ide> l.addAll(term3.charSet); <del> result = new Pair(term2.editDistance + term3.editDistance, l); <del> } <del> // pStore.put(lookUp, result); <add> result = new Pair(add(term2.editDistance, term3.editDistance), l); <add> } <add> pStorage.put(lookUp, result); <ide> return result; <ide> } <ide> <ide> /** <del> * L indicates whether or not character c is accepted by some arc <del> * along a path of shortest length from T to S, passing only through <del> * states numbered k or less <del> * <del> * @param k max state involved <del> * @param T origin state <del> * @param S destination state <del> * @param c a single character <del> */ <del> private static boolean L(int k, int T, int S, Character c) { <del> String lookUp = String.format("%d$%d$%d$%c", k, T, S, c); <del> // if (lStore.containsKey(lookUp)) { <del> // return lStore.get(lookUp); <del> // } <add> * L indicates whether or not character c is accepted by some arc along a <add> * path of shortest length from T to S, passing only through states numbered <add> * k or less <add> * <add> * @param k <add> * max state passed <add> * @param T <add> * origin state <add> * @param S <add> * destination state <add> * @param c <add> * a single character <add> * @param templ <add> * given SFA <add> * @return truth of indicator L <add> */ <add> private static boolean L(int k, int T, int S, Character c, SFA<CharPred, Character> templ) { <add> String lookUp = String.format("%d,%d,%d,%c", k, T, S, c); <add> if (lStorage.containsKey(lookUp)) { <add> return lStorage.get(lookUp); <add> } <ide> if (k == 0) { <ide> Collection<Move<CharPred, Character>> arcs = templ.getMovesFrom(T); <ide> for (Move<CharPred, Character> q : arcs) { <ide> if (q.to == S) { <ide> SFAInputMove<CharPred, Character> curr = (SFAInputMove<CharPred, Character>) q; <ide> if (curr.guard.isSatisfiedBy(c)) { <del> lStore.put(lookUp, true); <add> lStorage.put(lookUp, true); <ide> return true; <ide> } <ide> } <ide> } <del> lStore.put(lookUp, false); <add> lStorage.put(lookUp, false); <ide> return false; <ide> } <ide> boolean result; <del> Pair term1 = P(k - 1, T, S); <del> Pair term2 = P(k - 1, T, k); <del> Pair term3 = P(k - 1, k, S); <del> if (term1.editDistance > term2.editDistance + term3.editDistance) { <del> result = L(k - 1, T, k, c) || L(k - 1, k, S, c); <del> } else if (term1.editDistance == term2.editDistance + term3.editDistance) { <del> result = L(k - 1, T, k, c) || L(k - 1, k, S, c) || L(k - 1, T, S, c); <add> Pair term1 = P(k - 1, T, S, templ); <add> Pair term2 = P(k - 1, T, k, templ); <add> Pair term3 = P(k - 1, k, S, templ); <add> if (gt(term1.editDistance, add(term2.editDistance, term3.editDistance))) { <add> result = L(k - 1, T, k, c, templ) || L(k - 1, k, S, c, templ); <add> } else if (eq(term1.editDistance, add(term2.editDistance, term3.editDistance))) { <add> result = L(k - 1, T, k, c, templ) || L(k - 1, k, S, c, templ) || L(k - 1, T, S, c, templ); <ide> } else { <del> result = L(k - 1, T, S, c); <del> } <del> lStore.put(lookUp, result); <add> result = L(k - 1, T, S, c, templ); <add> } <add> lStorage.put(lookUp, result); <ide> return result; <ide> } <ide> <add> /** <add> * wrapper functions to deal with infinity calculation and comparison <add> */ <add> private static int add(int a, int b) { <add> if (a == INFINITY || b == INFINITY) { <add> return INFINITY; <add> } else { <add> return a + b; <add> } <add> } <add> <add> private static int sub(int a, int b) { <add> if (a == INFINITY && b != INFINITY) <add> return INFINITY; <add> else <add> return a - b; <add> } <add> <add> private static boolean lt(int a, int b) { <add> if (a == INFINITY) <add> a = Integer.MAX_VALUE; <add> if (b == INFINITY) <add> b = Integer.MAX_VALUE; <add> return a < b; <add> } <add> <add> private static boolean gt(int a, int b) { <add> if (a == INFINITY) <add> a = Integer.MAX_VALUE; <add> if (b == INFINITY) <add> b = Integer.MAX_VALUE; <add> return a > b; <add> } <add> <add> private static boolean eq(int a, int b) { <add> return a == b; <add> } <add> <add> private static boolean le(int a, int b) { <add> if (a == INFINITY) <add> a = Integer.MAX_VALUE; <add> if (b == INFINITY) <add> b = Integer.MAX_VALUE; <add> return a <= b; <add> } <add> <ide> } <ide> <del> <ide> /** <del> * This is a wrapper class. It contains a double variable representing <del> * edit distance and a linked list representing a string segment <add> * This is a wrapper class. It contains a double variable representing edit <add> * distance and a linked list representing a string segment <ide> */ <ide> class Pair { <del> protected double editDistance; <add> protected int editDistance; <ide> protected LinkedList<CharPred> charSet; <ide> <del> protected Pair(double i, LinkedList<CharPred> s) { <add> protected Pair(int i, LinkedList<CharPred> s) { <ide> editDistance = i; <ide> charSet = s; <ide> }
Java
apache-2.0
16a221a3934fca0ab5f4cf7a7bd06b316f39914d
0
Ravmouse/vvasilyev,Ravmouse/vvasilyev,Ravmouse/vvasilyev
package ru.job4j.h2http; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletConfig; import java.io.IOException; import java.io.PrintWriter; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; /** * Сервлет. */ public class UserServlet extends HttpServlet { //Presentation /** * Ссылка на класс ValidateService, где данные проверяются. */ private final ValidateService logic = ValidateService.getInstance(); /** * Хэш-отображение с экземплярами классов, реализующих интерфейс Consumer, которые получаются после * выполнения соответствующих методов. */ private final Map<String, Consumer<HttpServletRequest>> actionFunc = new HashMap<>(); /** * @param servletConfig servletConfig. */ @Override public void init(ServletConfig servletConfig) { actionFunc.put("add", addUser()); actionFunc.put("update", updateUser()); actionFunc.put("delete", deleteUser()); } /** * @param req запрос. * @param res ответ. * @throws IOException исключение. */ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter writer = new PrintWriter(res.getOutputStream()); if (req.getAttribute("text") == null) { writer.append(Arrays.toString(logic.findAll())); } else { writer.append(req.getAttribute("text").toString()); } writer.flush(); } /** * @param req запрос. * @param res ответ. * @throws IOException исключение. */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException { final String text; res.setContentType("text/html"); final String key = req.getParameter("action"); try { actionFunc.get(key).accept(req); } catch (VersionUserException | NotExistedUserException e) { //Пробрасывается исключение. text = e.getMessage(); //Получается сообщение из исключения. req.setAttribute("text", text); //Устанавливается аттрибут в запросе. doGet(req, res); //Вызывается doGet(), чтобы отправить ответ клиенту return; //с сообщением исключения. } text = Arrays.toString(logic.findAll()); //Если искл. не было, то находим всех User'ов. req.setAttribute("text", text); //Устанавливаем аттрибут в запросе, doGet(req, res); //который направляем в doGet(). } /** * Добавление нового User'а. * Все параметры запроса направляются в Логику, где создается новый User. * @return экземпляр анонимного класса, реализующего функц.интерфейс Consumer с методом accept(). */ private Consumer<HttpServletRequest> addUser() { return new Consumer<HttpServletRequest>() { @Override public void accept(HttpServletRequest request) { final List<String> list = parseRequest(request); logic.add(list.get(0), list.get(1), list.get(2), list.get(3), list.get(4)); } }; } /** * Обновление существующего User'а. * Все параметры запроса направляются в Логику, где обновляется существующий User. * @return экземпляр анонимного класса, реализующего функц.интерфейс Consumer с методом accept(). * @throws VersionUserException если 1-ый поток уже обновил значение User. * @throws NotExistedUserException если User'а с таким id не существует. */ private Consumer<HttpServletRequest> updateUser() throws VersionUserException, NotExistedUserException { return request -> logic.update(parseRequest(request)); } /** * Удаление существующего User'а. Из запроса достаточно получить только id User'а. * @return экземпляр анонимного класса, реализующего функц.интерфейс Consumer с методом accept(). * @throws VersionUserException если 1-ый поток уже обновил значение User. * @throws NotExistedUserException если User'а с таким id не существует. */ private Consumer<HttpServletRequest> deleteUser() throws VersionUserException, NotExistedUserException { return request -> logic.delete(request.getParameter("id")); } /** * @param request запрос. * @return список параметров из запроса. */ private List<String> parseRequest(HttpServletRequest request) { List<String> list = new ArrayList<>(); String decodedString = null; try { //Декодирование, чтобы был символ @, а не %40. decodedString = URLDecoder.decode(request.getParameter("email"), "UTF-8"); } catch (IOException io) { io.printStackTrace(); } list.add(request.getParameter("id")); list.add(request.getParameter("name")); list.add(request.getParameter("login")); list.add(decodedString); list.add(request.getParameter("createDate")); return list; } }
chapter_008/src/main/java/ru/job4j/h2http/UserServlet.java
package ru.job4j.h2http; import ru.job4j.h4waitnotifynotifyall.t3lock.SimpleLock; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletConfig; import java.io.IOException; import java.io.PrintWriter; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; /** * Сервлет. */ public class UserServlet extends HttpServlet { //Presentation /** * Ссылка на класс ValidateService, где данные проверяются. */ private final ValidateService logic = ValidateService.getInstance(); /** * Хэш-отображение с экземплярами классов, реализующих интерфейс Consumer, которые получаются после * выполнения соответствующих методов. */ private final Map<String, Consumer<HttpServletRequest>> actionFunc = new HashMap<>(); /** * Строка для вывода клиенту в GET-запросе. */ private String text; private SimpleLock lock = new SimpleLock(); /** * @param servletConfig servletConfig. */ @Override public void init(ServletConfig servletConfig) { actionFunc.put("add", addUser()); actionFunc.put("update", updateUser()); actionFunc.put("delete", deleteUser()); } /** * @param req запрос. * @param res ответ. * @throws IOException исключение. */ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter writer = new PrintWriter(res.getOutputStream()); writer.append(text); writer.flush(); } /** * @param req запрос. * @param res ответ. * @throws IOException исключение. */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException { res.setContentType("text/html"); String key = req.getParameter("action"); try { actionFunc.get(key).accept(req); } catch (VersionUserException | NotExistedUserException e) { //Пробрасывается исключение. try { lock.lock(); //Если поток дошел сюда первым, то он "захватывает" lock первым. } catch (InterruptedException exp) { exp.printStackTrace(); } text = e.getMessage(); //Получается сообщение из исключения. doGet(req, res); //Вызывается doGet(), чтобы отправить ответ клиенту с сообщением исключения. text = Arrays.toString(logic.findAll()); //Если после POST-запроса клиент сделает GET-запрос, то нужно lock.unlock(); //"Отпускает" lock. return; //снова отобразить список User'ов. } try { lock.lock(); //Если первый поток - это тот, который не выкидывает искл., то } catch (InterruptedException e) { //он "захватывает" lock первым. e.printStackTrace(); } text = Arrays.toString(logic.findAll()); //Если искл. не было, то сюда записываем всех User'ов и отображаем doGet(req, res); //в doGet(). lock.unlock(); //"Отпускает" lock. } /** * Добавление нового User'а. * Все параметры запроса направляются в Логику, где создается новый User. * @return экземпляр анонимного класса, реализующего функц.интерфейс Consumer с методом accept(). */ private Consumer<HttpServletRequest> addUser() { return new Consumer<HttpServletRequest>() { @Override public void accept(HttpServletRequest request) { final List<String> list = parseRequest(request); logic.add(list.get(0), list.get(1), list.get(2), list.get(3), list.get(4)); } }; } /** * Обновление существующего User'а. * Все параметры запроса направляются в Логику, где обновляется существующий User. * @return экземпляр анонимного класса, реализующего функц.интерфейс Consumer с методом accept(). * @throws VersionUserException если 1-ый поток уже обновил значение User. * @throws NotExistedUserException если User'а с таким id не существует. */ private Consumer<HttpServletRequest> updateUser() throws VersionUserException, NotExistedUserException { return request -> logic.update(parseRequest(request)); } /** * Удаление существующего User'а. Из запроса достаточно получить только id User'а. * @return экземпляр анонимного класса, реализующего функц.интерфейс Consumer с методом accept(). * @throws VersionUserException если 1-ый поток уже обновил значение User. * @throws NotExistedUserException если User'а с таким id не существует. */ private Consumer<HttpServletRequest> deleteUser() throws VersionUserException, NotExistedUserException { return request -> logic.delete(request.getParameter("id")); } /** * @param request запрос. * @return список параметров из запроса. */ private List<String> parseRequest(HttpServletRequest request) { List<String> list = new ArrayList<>(); String decodedString = null; try { //Декодирование, чтобы был символ @, а не %40. decodedString = URLDecoder.decode(request.getParameter("email"), "UTF-8"); } catch (IOException io) { io.printStackTrace(); } list.add(request.getParameter("id")); list.add(request.getParameter("name")); list.add(request.getParameter("login")); list.add(decodedString); list.add(request.getParameter("createDate")); return list; } }
2.1. Crud servlet, Web app architecture [#2512] (исправления).
chapter_008/src/main/java/ru/job4j/h2http/UserServlet.java
2.1. Crud servlet, Web app architecture [#2512] (исправления).
<ide><path>hapter_008/src/main/java/ru/job4j/h2http/UserServlet.java <ide> package ru.job4j.h2http; <ide> <del>import ru.job4j.h4waitnotifynotifyall.t3lock.SimpleLock; <ide> import javax.servlet.http.HttpServlet; <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.servlet.http.HttpServletResponse; <ide> * выполнения соответствующих методов. <ide> */ <ide> private final Map<String, Consumer<HttpServletRequest>> actionFunc = new HashMap<>(); <del> /** <del> * Строка для вывода клиенту в GET-запросе. <del> */ <del> private String text; <del> private SimpleLock lock = new SimpleLock(); <ide> <ide> /** <ide> * @param servletConfig servletConfig. <ide> public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { <ide> res.setContentType("text/html"); <ide> PrintWriter writer = new PrintWriter(res.getOutputStream()); <del> writer.append(text); <add> if (req.getAttribute("text") == null) { <add> writer.append(Arrays.toString(logic.findAll())); <add> } else { <add> writer.append(req.getAttribute("text").toString()); <add> } <ide> writer.flush(); <ide> } <ide> <ide> */ <ide> @Override <ide> public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException { <add> final String text; <ide> res.setContentType("text/html"); <del> String key = req.getParameter("action"); <add> final String key = req.getParameter("action"); <ide> try { <ide> actionFunc.get(key).accept(req); <ide> } catch (VersionUserException | NotExistedUserException e) { //Пробрасывается исключение. <del> try { <del> lock.lock(); //Если поток дошел сюда первым, то он "захватывает" lock первым. <del> } catch (InterruptedException exp) { <del> exp.printStackTrace(); <del> } <del> text = e.getMessage(); //Получается сообщение из исключения. <del> doGet(req, res); //Вызывается doGet(), чтобы отправить ответ клиенту с сообщением исключения. <del> text = Arrays.toString(logic.findAll()); //Если после POST-запроса клиент сделает GET-запрос, то нужно <del> lock.unlock(); //"Отпускает" lock. <del> return; //снова отобразить список User'ов. <add> text = e.getMessage(); //Получается сообщение из исключения. <add> req.setAttribute("text", text); //Устанавливается аттрибут в запросе. <add> doGet(req, res); //Вызывается doGet(), чтобы отправить ответ клиенту <add> return; //с сообщением исключения. <ide> } <del> try { <del> lock.lock(); //Если первый поток - это тот, который не выкидывает искл., то <del> } catch (InterruptedException e) { //он "захватывает" lock первым. <del> e.printStackTrace(); <del> } <del> text = Arrays.toString(logic.findAll()); //Если искл. не было, то сюда записываем всех User'ов и отображаем <del> doGet(req, res); //в doGet(). <del> lock.unlock(); //"Отпускает" lock. <add> text = Arrays.toString(logic.findAll()); //Если искл. не было, то находим всех User'ов. <add> req.setAttribute("text", text); //Устанавливаем аттрибут в запросе, <add> doGet(req, res); //который направляем в doGet(). <ide> } <ide> <ide> /**
JavaScript
mit
3e30b1fde73b9a9822634b95d4865740eb71bc47
0
ioBroker/ioBroker.influxdb
/* jshint -W097 */// jshint strict:false /*jslint node: true */ /*jshint expr: true*/ var expect = require('chai').expect; var setup = require(__dirname + '/lib/setup'); var objects = null; var states = null; var onStateChanged = null; var onObjectChanged = null; var sendToID = 1; var adapterShortName = setup.adapterName.substring(setup.adapterName.indexOf('.')+1); var now; function checkConnectionOfAdapter(cb, counter) { counter = counter || 0; console.log('Try check #' + counter); if (counter > 30) { if (cb) cb('Cannot check connection'); return; } console.log('Checking alive key for key : ' + adapterShortName); states.getState('system.adapter.' + adapterShortName + '.0.alive', function (err, state) { if (err) console.error(err); if (state && state.val) { if (cb) cb(); } else { setTimeout(function () { checkConnectionOfAdapter(cb, counter + 1); }, 1000); } }); } function checkValueOfState(id, value, cb, counter) { counter = counter || 0; if (counter > 20) { if (cb) cb('Cannot check value Of State ' + id); return; } states.getState(id, function (err, state) { if (err) console.error(err); if (value === null && !state) { if (cb) cb(); } else if (state && (value === undefined || state.val === value)) { if (cb) cb(); } else { setTimeout(function () { checkValueOfState(id, value, cb, counter + 1); }, 500); } }); } function sendTo(target, command, message, callback) { onStateChanged = function (id, state) { if (id === 'messagebox.system.adapter.test.0') { callback(state.message); } }; states.pushMessage('system.adapter.' + target, { command: command, message: message, from: 'system.adapter.test.0', callback: { message: message, id: sendToID++, ack: false, time: (new Date()).getTime() } }); } describe('Test ' + adapterShortName + ' adapter', function() { before('Test ' + adapterShortName + ' adapter: Start js-controller', function (_done) { this.timeout(600000); // because of first install from npm setup.setupController(function () { var config = setup.getAdapterConfig(); // enable adapter config.common.enabled = true; config.common.loglevel = 'debug'; //config.native.dbtype = 'sqlite'; setup.setAdapterConfig(config.common, config.native); setup.startController(true, function(id, obj) {}, function (id, state) { if (onStateChanged) onStateChanged(id, state); }, function (_objects, _states) { objects = _objects; states = _states; _done(); }); }); }); it('Test ' + adapterShortName + ' adapter: Check if adapter started', function (done) { this.timeout(60000); checkConnectionOfAdapter(function (res) { if (res) console.log(res); expect(res).not.to.be.equal('Cannot check connection'); objects.setObject('system.adapter.test.0', { common: { }, type: 'instance' }, function () { states.subscribeMessage('system.adapter.test.0'); sendTo('influxdb.0', 'enableHistory', { id: 'system.adapter.influxdb.0.memRss', options: { changesOnly: true, debounce: 0, retention: 31536000, seriesBufferMax: 0, changesMinDelta: 0.5, storageType: 'Number' } }, function (result) { expect(result.error).to.be.undefined; expect(result.success).to.be.true; sendTo('influxdb.0', 'enableHistory', { id: 'system.adapter.influxdb.0.memHeapTotal', options: { changesOnly: true, debounce: 0, retention: 31536000, storageType: 'String' } }, function (result) { expect(result.error).to.be.undefined; expect(result.success).to.be.true; sendTo('influxdb.0', 'enableHistory', { id: 'system.adapter.influxdb.0.uptime', options: { changesOnly: false, debounce: 0, retention: 31536000, storageType: 'Boolean' } }, function (result) { expect(result.error).to.be.undefined; expect(result.success).to.be.true; sendTo('influxdb.0', 'enableHistory', { id: 'system.adapter.influxdb.0.memHeapUsed', options: { changesOnly: false, debounce: 0, retention: 31536000, } }, function (result) { expect(result.error).to.be.undefined; expect(result.success).to.be.true; // wait till adapter receives the new settings setTimeout(function () { done(); }, 10000); }); }); }); }); }); }); }); it('Test ' + adapterShortName + ': Write string value for memHeapUsed into DB to force a type conflict', function (done) { this.timeout(5000); now = new Date().getTime(); states.setState('system.adapter.influxdb.0.memHeapUsed', {val: 'Blubb', ts: now - 20000, from: 'test.0'}, function (err) { if (err) { console.log(err); } done(); }); }); it('Test ' + adapterShortName + ': Check Enabled Points after Enable', function (done) { this.timeout(5000); sendTo('influxdb.0', 'getEnabledDPs', {}, function (result) { console.log(JSON.stringify(result)); expect(Object.keys(result).length).to.be.equal(4); expect(result['system.adapter.influxdb.0.memRss'].enabled).to.be.true; done(); }); }); it('Test ' + adapterShortName + ': Write values into DB', function (done) { this.timeout(25000); now = new Date().getTime(); states.setState('system.adapter.influxdb.0.memRss', {val: true, ts: now - 20000, from: 'test.0'}, function (err) { if (err) { console.log(err); } setTimeout(function () { states.setState('system.adapter.influxdb.0.memRss', {val: 2, ts: now - 10000, from: 'test.0'}, function (err) { if (err) { console.log(err); } setTimeout(function () { states.setState('system.adapter.influxdb.0.memRss', {val: 2, ts: now - 5000, from: 'test.0'}, function (err) { if (err) { console.log(err); } setTimeout(function () { states.setState('system.adapter.influxdb.0.memRss', {val: 2.2, ts: now - 4000, from: 'test.0'}, function (err) { if (err) { console.log(err); } setTimeout(function () { states.setState('system.adapter.influxdb.0.memRss', {val: '2.5', ts: now - 3000, from: 'test.0'}, function (err) { if (err) { console.log(err); } setTimeout(function () { states.setState('system.adapter.influxdb.0.memRss', {val: 3, ts: now - 1000, from: 'test.0'}, function (err) { if (err) { console.log(err); } setTimeout(function () { states.setState('system.adapter.influxdb.0.memRss', {val: 'Test', ts: now - 500, from: 'test.0'}, function (err) { if (err) { console.log(err); } setTimeout(done, 1000); }); }, 100); }); }, 100); }); }, 100); }); }, 100); }); }, 100); }); }, 100); }); }); it('Test ' + adapterShortName + ': Read values from DB using query', function (done) { this.timeout(10000); sendTo('influxdb.0', 'query', 'SELECT * FROM "system.adapter.influxdb.0.memRss"', function (result) { console.log(JSON.stringify(result.result, null, 2)); expect(result.result[0].length).to.be.at.least(4); var found = 0; for (var i = 0; i < result.result[0].length; i++) { if (result.result[0][i].value >= 1 && result.result[0][i].value <= 3) found ++; } expect(found).to.be.equal(4); done(); }); }); it('Test ' + adapterShortName + ': Read values from DB using GetHistory', function (done) { this.timeout(10000); sendTo('influxdb.0', 'getHistory', { id: 'system.adapter.influxdb.0.memRss', options: { start: now - 30000, count: 50, aggregate: 'none' } }, function (result) { console.log(JSON.stringify(result.result, null, 2)); expect(result.result.length).to.be.at.least(4); var found = 0; for (var i = 0; i < result.result.length; i++) { if (result.result[i].val >= 1 && result.result[i].val <= 3) found ++; } expect(found).to.be.equal(4); sendTo('influxdb.0', 'getHistory', { id: 'system.adapter.influxdb.0.memRss', options: { start: now - 15000, count: 2, aggregate: 'none' } }, function (result) { console.log(JSON.stringify(result.result, null, 2)); expect(result.result.length).to.be.at.least(2); var found = 0; for (var i = 0; i < result.result.length; i++) { if (result.result[i].val >= 2 && result.result[i].val < 3) found ++; } expect(found).to.be.equal(2); done(); }); }); }); it('Test ' + adapterShortName + ': Check Datapoint Types', function (done) { this.timeout(65000); setTimeout(function() { sendTo('influxdb.0', 'query', 'SHOW FIELD KEYS FROM "system.adapter.influxdb.0.memRss"', function (result) { console.log('result: ' + JSON.stringify(result.result, null, 2)); var found = false; for (var i = 0; i < result.result[0].length; i++) { if (result.result[0][i].fieldKey === 'value') { found = true; expect(result.result[0][i].fieldType).to.be.equal('float'); break; } } expect(found).to.be.true; sendTo('influxdb.0', 'query', 'SHOW FIELD KEYS FROM "system.adapter.influxdb.0.memHeapTotal"', function (result2) { console.log('result2: ' + JSON.stringify(result2.result, null, 2)); var found = false; for (var i = 0; i < result2.result[0].length; i++) { if (result2.result[0][i].fieldKey === 'value') { found = true; expect(result2.result[0][i].fieldType).to.be.equal('string'); break; } } expect(found).to.be.true; sendTo('influxdb.0', 'query', 'SHOW FIELD KEYS FROM "system.adapter.influxdb.0.uptime"', function (result3) { console.log('result3: ' + JSON.stringify(result3.result, null, 2)); var found = false; for (var i = 0; i < result3.result[0].length; i++) { if (result3.result[0][i].fieldKey === 'value') { found = true; expect(result3.result[0][i].fieldType).to.be.equal('boolean'); break; } } expect(found).to.be.true; setTimeout(function () { done(); }, 3000); }); }); }); }, 60000); }); it('Test ' + adapterShortName + ': Disable Datapoint again', function (done) { this.timeout(5000); sendTo('influxdb.0', 'disableHistory', { id: 'system.adapter.influxdb.0.memRss', }, function (result) { expect(result.error).to.be.undefined; expect(result.success).to.be.true; done(); }); }); it('Test ' + adapterShortName + ': Check Enabled Points after Disable', function (done) { this.timeout(5000); sendTo('influxdb.0', 'getEnabledDPs', {}, function (result) { console.log(JSON.stringify(result)); expect(Object.keys(result).length).to.be.equal(3); done(); }); }); it('Test ' + adapterShortName + ': Check that storageType is set now for memHeapUsed', function (done) { this.timeout(5000); objects.getObject('system.adapter.influxdb.0.memHeapUsed', function(err, obj) { expect(obj.common.custom['influxdb.0'].storageType).to.be.equal('String'); expect(err).to.be.null; done(); }); }); after('Test ' + adapterShortName + ' adapter: Stop js-controller', function (done) { this.timeout(10000); setup.stopController(function (normalTerminated) { console.log('Adapter normal terminated: ' + normalTerminated); done(); }); }); });
test/testAdapter.js
/* jshint -W097 */// jshint strict:false /*jslint node: true */ /*jshint expr: true*/ var expect = require('chai').expect; var setup = require(__dirname + '/lib/setup'); var objects = null; var states = null; var onStateChanged = null; var onObjectChanged = null; var sendToID = 1; var adapterShortName = setup.adapterName.substring(setup.adapterName.indexOf('.')+1); var now; function checkConnectionOfAdapter(cb, counter) { counter = counter || 0; console.log('Try check #' + counter); if (counter > 30) { if (cb) cb('Cannot check connection'); return; } console.log('Checking alive key for key : ' + adapterShortName); states.getState('system.adapter.' + adapterShortName + '.0.alive', function (err, state) { if (err) console.error(err); if (state && state.val) { if (cb) cb(); } else { setTimeout(function () { checkConnectionOfAdapter(cb, counter + 1); }, 1000); } }); } function checkValueOfState(id, value, cb, counter) { counter = counter || 0; if (counter > 20) { if (cb) cb('Cannot check value Of State ' + id); return; } states.getState(id, function (err, state) { if (err) console.error(err); if (value === null && !state) { if (cb) cb(); } else if (state && (value === undefined || state.val === value)) { if (cb) cb(); } else { setTimeout(function () { checkValueOfState(id, value, cb, counter + 1); }, 500); } }); } function sendTo(target, command, message, callback) { onStateChanged = function (id, state) { if (id === 'messagebox.system.adapter.test.0') { callback(state.message); } }; states.pushMessage('system.adapter.' + target, { command: command, message: message, from: 'system.adapter.test.0', callback: { message: message, id: sendToID++, ack: false, time: (new Date()).getTime() } }); } describe('Test ' + adapterShortName + ' adapter', function() { before('Test ' + adapterShortName + ' adapter: Start js-controller', function (_done) { this.timeout(600000); // because of first install from npm setup.setupController(function () { var config = setup.getAdapterConfig(); // enable adapter config.common.enabled = true; config.common.loglevel = 'debug'; //config.native.dbtype = 'sqlite'; setup.setAdapterConfig(config.common, config.native); setup.startController(true, function(id, obj) {}, function (id, state) { if (onStateChanged) onStateChanged(id, state); }, function (_objects, _states) { objects = _objects; states = _states; _done(); }); }); }); it('Test ' + adapterShortName + ' adapter: Check if adapter started', function (done) { this.timeout(60000); checkConnectionOfAdapter(function (res) { if (res) console.log(res); expect(res).not.to.be.equal('Cannot check connection'); objects.setObject('system.adapter.test.0', { common: { }, type: 'instance' }, function () { states.subscribeMessage('system.adapter.test.0'); sendTo('influxdb.0', 'enableHistory', { id: 'system.adapter.influxdb.0.memRss', options: { changesOnly: true, debounce: 0, retention: 31536000, seriesBufferMax: 0, changesMinDelta: 0.5, storageType: 'Number' } }, function (result) { expect(result.error).to.be.undefined; expect(result.success).to.be.true; sendTo('influxdb.0', 'enableHistory', { id: 'system.adapter.influxdb.0.memHeapTotal', options: { changesOnly: true, debounce: 0, retention: 31536000, storageType: 'String' } }, function (result) { expect(result.error).to.be.undefined; expect(result.success).to.be.true; sendTo('influxdb.0', 'enableHistory', { id: 'system.adapter.influxdb.0.uptime', options: { changesOnly: false, debounce: 0, retention: 31536000, storageType: 'Boolean' } }, function (result) { expect(result.error).to.be.undefined; expect(result.success).to.be.true; sendTo('influxdb.0', 'enableHistory', { id: 'system.adapter.influxdb.0.memHeapUsed', options: { changesOnly: false, debounce: 0, retention: 31536000, } }, function (result) { expect(result.error).to.be.undefined; expect(result.success).to.be.true; // wait till adapter receives the new settings setTimeout(function () { done(); }, 10000); }); }); }); }); }); }); }); it('Test ' + adapterShortName + ': Write string value for memHeapUsed into DB to force a type conflict', function (done) { this.timeout(5000); now = new Date().getTime(); states.setState('system.adapter.influxdb.0.memHeapUsed', {val: 'Blubb', ts: now - 20000, from: 'test.0'}, function (err) { if (err) { console.log(err); } done(); }); }); it('Test ' + adapterShortName + ': Check Enabled Points after Enable', function (done) { this.timeout(5000); sendTo('influxdb.0', 'getEnabledDPs', {}, function (result) { console.log(JSON.stringify(result)); expect(Object.keys(result).length).to.be.equal(4); expect(result['system.adapter.influxdb.0.memRss'].enabled).to.be.true; done(); }); }); it('Test ' + adapterShortName + ': Write values into DB', function (done) { this.timeout(25000); now = new Date().getTime(); states.setState('system.adapter.influxdb.0.memRss', {val: true, ts: now - 20000, from: 'test.0'}, function (err) { if (err) { console.log(err); } setTimeout(function () { states.setState('system.adapter.influxdb.0.memRss', {val: 2, ts: now - 10000, from: 'test.0'}, function (err) { if (err) { console.log(err); } setTimeout(function () { states.setState('system.adapter.influxdb.0.memRss', {val: 2, ts: now - 5000, from: 'test.0'}, function (err) { if (err) { console.log(err); } setTimeout(function () { states.setState('system.adapter.influxdb.0.memRss', {val: 2.2, ts: now - 4000, from: 'test.0'}, function (err) { if (err) { console.log(err); } setTimeout(function () { states.setState('system.adapter.influxdb.0.memRss', {val: '2.5', ts: now - 3000, from: 'test.0'}, function (err) { if (err) { console.log(err); } setTimeout(function () { states.setState('system.adapter.influxdb.0.memRss', {val: 3, ts: now - 1000, from: 'test.0'}, function (err) { if (err) { console.log(err); } setTimeout(function () { states.setState('system.adapter.influxdb.0.memRss', {val: 'Test', ts: now - 500, from: 'test.0'}, function (err) { if (err) { console.log(err); } setTimeout(done, 1000); }); }, 100); }); }, 100); }); }, 100); }); }, 100); }); }, 100); }); }, 100); }); }); it('Test ' + adapterShortName + ': Read values from DB using query', function (done) { this.timeout(10000); sendTo('influxdb.0', 'query', 'SELECT * FROM "system.adapter.influxdb.0.memRss"', function (result) { console.log(JSON.stringify(result.result, null, 2)); expect(result.result[0].length).to.be.at.least(4); var found = 0; for (var i = 0; i < result.result[0].length; i++) { if (result.result[0][i].value >= 1 && result.result[0][i].value <= 3) found ++; } expect(found).to.be.equal(4); done(); }); }); it('Test ' + adapterShortName + ': Read values from DB using GetHistory', function (done) { this.timeout(10000); sendTo('influxdb.0', 'getHistory', { id: 'system.adapter.influxdb.0.memRss', options: { start: now - 30000, count: 50, aggregate: 'none' } }, function (result) { console.log(JSON.stringify(result.result, null, 2)); expect(result.result.length).to.be.at.least(4); var found = 0; for (var i = 0; i < result.result.length; i++) { if (result.result[i].val >= 1 && result.result[i].val <= 3) found ++; } expect(found).to.be.equal(4); sendTo('influxdb.0', 'getHistory', { id: 'system.adapter.influxdb.0.memRss', options: { start: now - 15000, count: 2, aggregate: 'none' } }, function (result) { console.log(JSON.stringify(result.result, null, 2)); expect(result.result.length).to.be.at.least(2); var found = 0; for (var i = 0; i < result.result.length; i++) { if (result.result[i].val >= 2 && result.result[i].val < 3) found ++; } expect(found).to.be.equal(2); done(); }); }); }); it('Test ' + adapterShortName + ': Check Datapoint Types', function (done) { this.timeout(65000); setTimeout(function() { sendTo('influxdb.0', 'query', 'SHOW FIELD KEYS FROM "system.adapter.influxdb.0.memRss"', function (result) { console.log('result: ' + JSON.stringify(result.result, null, 2)); var found = false; for (var i = 0; i < result.result[0].length; i++) { if (result.result[0][i].fieldKey === 'value') { found = true; expect(result.result[0][i].fieldType).to.be.equal('float'); break; } } expect(found).to.be.true; sendTo('influxdb.0', 'query', 'SHOW FIELD KEYS FROM "system.adapter.influxdb.0.memHeapTotal"', function (result2) { console.log('result2: ' + JSON.stringify(result2.result, null, 2)); var found = false; for (var i = 0; i < result2.result[0].length; i++) { if (result2.result[0][i].fieldKey === 'value') { found = true; expect(result2.result[0][i].fieldType).to.be.equal('string'); break; } } expect(found).to.be.true; sendTo('influxdb.0', 'query', 'SHOW FIELD KEYS FROM "system.adapter.influxdb.0.uptime"', function (result3) { console.log('result3: ' + JSON.stringify(result3.result, null, 2)); var found = false; for (var i = 0; i < result3.result[0].length; i++) { if (result3.result[0][i].fieldKey === 'value') { found = true; expect(result3.result[0][i].fieldType).to.be.equal('boolean'); break; } } expect(found).to.be.true; setTimeout(function () { done(); }, 3000); }); }); }); }, 60000); }); it('Test ' + adapterShortName + ': Disable Datapoint again', function (done) { this.timeout(5000); sendTo('influxdb.0', 'disableHistory', { id: 'system.adapter.influxdb.0.memRss', }, function (result) { expect(result.error).to.be.undefined; expect(result.success).to.be.true; done(); }); }); it('Test ' + adapterShortName + ': Check Enabled Points after Disable', function (done) { this.timeout(5000); sendTo('influxdb.0', 'getEnabledDPs', {}, function (result) { console.log(JSON.stringify(result)); expect(Object.keys(result).length).to.be.equal(3); done(); }); }); it('Test ' + adapterShortName + ': Check that storageType is set now for memHeapUsed', function (done) { this.timeout(5000); objects.getObject('system.adapter.influxdb.0.memHeapUsed', function(err, obj) { expect(obj.common.custom['influxdb.0'].storageType).to.be.equal('Number'); expect(err).to.be.null; done(); }); }); after('Test ' + adapterShortName + ' adapter: Stop js-controller', function (done) { this.timeout(10000); setup.stopController(function (normalTerminated) { console.log('Adapter normal terminated: ' + normalTerminated); done(); }); }); });
fix testing
test/testAdapter.js
fix testing
<ide><path>est/testAdapter.js <ide> this.timeout(5000); <ide> <ide> objects.getObject('system.adapter.influxdb.0.memHeapUsed', function(err, obj) { <del> expect(obj.common.custom['influxdb.0'].storageType).to.be.equal('Number'); <add> expect(obj.common.custom['influxdb.0'].storageType).to.be.equal('String'); <ide> expect(err).to.be.null; <ide> done(); <ide> });
Java
agpl-3.0
6d874785ab10974ed9e8118575ecb8ca76f3c33c
0
patricklam/JudoDB,patricklam/JudoDB
package ca.patricklam.judodb.client; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.HashMap; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsonUtils; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.FormElement; import com.google.gwt.dom.client.Style.Display; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.i18n.client.NumberFormat; import com.google.gwt.safehtml.client.SafeHtmlTemplates; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.Hidden; import com.google.gwt.user.client.ui.InlineLabel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.ValueBoxBase; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; public class ClientWidget extends Composite { interface MyUiBinder extends UiBinder<Widget, ClientWidget> {} public static MyUiBinder uiBinder = GWT.create(MyUiBinder.class); private final JudoDB jdb; @UiField DivElement cid; @UiField HTMLPanel clientMain; @UiField TextBox nom; @UiField TextBox prenom; @UiField TextBox ddn_display; @UiField Hidden ddn; @UiField TextBox sexe; @UiField Anchor copysib; @UiField TextBox adresse; @UiField TextBox ville; @UiField TextBox codePostal; @UiField TextBox tel; @UiField TextBox courriel; @UiField TextBox affiliation; @UiField TextBox grade; @UiField Anchor showgrades; @UiField TextBox date_grade; @UiField TextBox carte_resident; @UiField TextBox nom_recu_impot; @UiField TextBox tel_contact_urgence; @UiField ListBox date_inscription; @UiField InlineLabel semaines; @UiField Anchor inscrire; @UiField Anchor modifier; @UiField Anchor desinscrire; @UiField TextBox saisons; @UiField CheckBox prorata; @UiField CheckBox verification; @UiField TextBox categorie; @UiField TextBox categorieFrais; @UiField ListBox cours; @UiField ListBox no_sessions; @UiField ListBox escompte; @UiField TextBox cas_special_note; @UiField TextBox cas_special_pct; @UiField TextBox escompteFrais; @UiField CheckBox sans_affiliation; @UiField CheckBox affiliation_initiation; @UiField CheckBox affiliation_ecole; @UiField TextBox affiliationFrais; @UiField ListBox produit; @UiField CheckBox resident; @UiField CheckBox paypal; @UiField TextBox suppFrais; @UiField CheckBox solde; @UiField TextBox frais; @UiField Hidden grades_encoded; @UiField Hidden grade_dates_encoded; @UiField Hidden date_inscription_encoded; @UiField Hidden saisons_encoded; @UiField Hidden prorata_encoded; @UiField Hidden verification_encoded; @UiField Hidden categorieFrais_encoded; @UiField Hidden cours_encoded; @UiField Hidden no_sessions_encoded; @UiField Hidden escompte_encoded; @UiField Hidden cas_special_note_encoded; @UiField Hidden cas_special_pct_encoded; @UiField Hidden escompteFrais_encoded; @UiField Hidden sans_affiliation_encoded; @UiField Hidden affiliation_initiation_encoded; @UiField Hidden affiliation_ecole_encoded; @UiField Hidden affiliationFrais_encoded; @UiField Hidden judogi_encoded; @UiField Hidden resident_encoded; @UiField Hidden paypal_encoded; @UiField Hidden suppFrais_encoded; @UiField Hidden solde_encoded; @UiField Hidden frais_encoded; @UiField Hidden club_id_encoded; @UiField Hidden guid_on_form; @UiField Hidden sid; @UiField Hidden deleted; @UiField Button saveClientButton; @UiField Button saveAndReturnClientButton; @UiField Button deleteClientButton; @UiField Button discardClientButton; @UiField HTMLPanel blurb; @UiField HTMLPanel gradeHistory; @UiField Grid gradeTable; @UiField Anchor saveGrades; @UiField Anchor annulerGrades; @UiField ListBox dropDownUserClubs; private final FormElement clientform; private static final String PULL_ONE_CLIENT_URL = JudoDB.BASE_URL + "pull_one_client.php"; private static final String PUSH_ONE_CLIENT_URL = JudoDB.BASE_URL + "push_one_client.php"; private static final String CONFIRM_PUSH_URL = JudoDB.BASE_URL + "confirm_push.php"; private int pushTries; public interface BlurbTemplate extends SafeHtmlTemplates { @Template ("<p>Je {0} certifie que les informations inscrites sur ce formulaire sont véridiques. "+ "En adhèrant au {3}, j'accepte tous les risques d'accident liés à la pratique du "+ "judo qui pourraient survenir dans les locaux ou lors d'activités extérieurs organisées par le Club. "+ "J'accepte de respecter les règlements du Club en tout temps y compris lors des déplacements.</p>"+ "<h4>Politique de remboursement</h4>"+ "<p>Aucun remboursement ne sera accordé sans présentation d'un certificat médical du participant. "+ "Seuls les frais de cours correspondant à la période restante sont remboursables. "+ "En cas d'annulation par le participant, un crédit pourra être émis par le Club, "+ "pour les frais de cours correspondant à la période restante.</p>"+ "<p>Signature {1}: <span style='float:right'>Date: _________</span></p>"+ "<p>Signature résponsable du club: <span style='float:right'>Date: {2}</span></p>") SafeHtml blurb(String nom, String membreOuParent, String today, String clubName); } private static final BlurbTemplate BLURB = GWT.create(BlurbTemplate.class); private ClubPrix[] clubPrix; /** A list of cours as retrieved from the server. * Must stay in synch with the ListBox field cours. */ private List<CoursSummary> backingCours = new ArrayList<CoursSummary>(); private List<EscompteSummary> escompteSummaries = new ArrayList<EscompteSummary>(); private List<ProduitSummary> produitSummaries = new ArrayList<ProduitSummary>(); private ClientData cd; private String guid; private int currentServiceNumber; public int getCurrentServiceNumber() { return currentServiceNumber; } private String sibid; private List<ChangeHandler> onPopulated = new ArrayList<ChangeHandler>(); private ClubListHandler clubListHandler; public ClientWidget(int cid, JudoDB jdb) { this.jdb = jdb; initWidget(uiBinder.createAndBindUi(this)); clientform = FormElement.as(clientMain.getElementById("clientform")); clientform.setAction(PUSH_ONE_CLIENT_URL); deleted.setValue(""); clubListHandler = new ClubListHandler(); dropDownUserClubs.setSelectedIndex(jdb.selectedClub); dropDownUserClubs.addChangeHandler(clubListHandler); no_sessions.addItem("1"); no_sessions.addItem("2"); gradeHistory.setVisible(false); prorata.setValue(true); categorie.setReadOnly(true); saisons.setReadOnly(true); categorieFrais.setReadOnly(true); categorieFrais.setAlignment(ValueBoxBase.TextAlignment.RIGHT); cas_special_pct.setAlignment(ValueBoxBase.TextAlignment.RIGHT); escompteFrais.setReadOnly(true); escompteFrais.setAlignment(ValueBoxBase.TextAlignment.RIGHT); affiliationFrais.setReadOnly(true); affiliationFrais.setAlignment(ValueBoxBase.TextAlignment.RIGHT); suppFrais.setReadOnly(true); suppFrais.setAlignment(ValueBoxBase.TextAlignment.RIGHT); frais.setReadOnly(true); frais.setAlignment(ValueBoxBase.TextAlignment.RIGHT); ((Element)cas_special_note.getElement().getParentNode()).getStyle().setDisplay(Display.NONE); ((Element)cas_special_pct.getElement().getParentNode()).getStyle().setDisplay(Display.NONE); no_sessions.setItemSelected(1, true); if (cid == -1 && jdb.getSelectedClubID() == null) { jdb.setStatus("Veuillez selectionner un club pour le client."); new Timer() { public void run() { ClientWidget.this.jdb.popMode(); } }.schedule(1000); return; } inscrire.addClickHandler(inscrireClickHandler); modifier.addClickHandler(modifierClickHandler); desinscrire.addClickHandler(desinscrireClickHandler); showgrades.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { gradeHistory.setVisible(true); } ; }); saveGrades.addClickHandler(saveGradesHandler); annulerGrades.addClickHandler(annulerGradesHandler); adresse.addChangeHandler(updateCopySibHandler); ville.addChangeHandler(updateCopySibHandler); codePostal.addChangeHandler(updateCopySibHandler); tel.addChangeHandler(updateCopySibHandler); tel_contact_urgence.addChangeHandler(updateCopySibHandler); courriel.addChangeHandler(updateCopySibHandler); ddn_display.addChangeHandler(recomputeHandler); grade.addChangeHandler(directGradeChangeHandler); date_grade.addChangeHandler(directGradeDateChangeHandler); grade.addChangeHandler(recomputeHandler); date_inscription.addChangeHandler(changeSaisonHandler); prorata.addValueChangeHandler(recomputeValueHandler); no_sessions.addChangeHandler(recomputeHandler); escompte.addChangeHandler(changeEscompteHandler); cas_special_pct.addChangeHandler(clearEscompteAmtAndRecomputeHandler); escompteFrais.addChangeHandler(clearEscomptePctAndRecomputeHandler); sans_affiliation.addValueChangeHandler(recomputeValueHandler); affiliation_initiation.addValueChangeHandler(recomputeValueHandler); affiliation_ecole.addValueChangeHandler(recomputeValueHandler); produit.addChangeHandler(recomputeHandler); resident.addValueChangeHandler(recomputeValueHandler); paypal.addValueChangeHandler(recomputeValueHandler); saveAndReturnClientButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { pushClientDataToServer(true); } }); saveClientButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { pushClientDataToServer(false); } }); discardClientButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { ClientWidget.this.jdb.clearStatus(); ClientWidget.this.jdb.popMode(); } }); deleteClientButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { pushDeleteToServer(); } }); copysib.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { copysib(); } }); jdb.populateClubList(false, dropDownUserClubs); jdb.pleaseWait(); if (cid != -1) retrieveClient(cid); else { this.cd = JavaScriptObject.createObject().cast(); this.cd.setID(null); this.cd.setNom(""); addNewService(); ClubSummary cs = jdb.getClubSummaryByID(jdb.getSelectedClubID()); cd.makeDefault(cs); currentServiceNumber = this.cd.getMostRecentServiceNumber(); JsArray<GradeData> ga = JavaScriptObject.createArray().cast(); GradeData gd = JavaScriptObject.createObject().cast(); gd.setGrade("Blanche"); gd.setDateGrade(Constants.DB_DATE_FORMAT.format(new Date())); ga.set(0, gd); this.cd.setGrades(ga); loadClientData(); jdb.clearStatus(); } retrieveSessions(); retrieveClubPrix(); retrieveCours(); retrieveEscomptes(); retrieveProduits(); } private void addNewService() { ServiceData sd = ServiceData.newServiceData(); sd.inscrireAujourdhui(); sd.setClubID(jdb.getSelectedClubID()); JsArray<ServiceData> sa = cd.getServices(); if (sa == null) { sa = JavaScriptObject.createArray().cast(); cd.setServices(sa); } sa.push(sd); } private void loadEscomptes(JsArray<EscompteSummary> escompteArray) { HashMap<String, Integer> escompteIdxToSeqno = new HashMap<String, Integer>(); escompte.clear(); escompteSummaries.clear(); escompte.addItem(Constants.EMPTY_ESCOMPTE.getNom(), Constants.EMPTY_ESCOMPTE.getId()); escompteSummaries.add(Constants.EMPTY_ESCOMPTE); int idx = 1; for (int i = 0; i < escompteArray.length(); i++) { EscompteSummary e = escompteArray.get(i); if (e.getClubId().equals("0") || e.getClubId().equals(jdb.getSelectedClubID())) { escompteSummaries.add(e); escompte.addItem(e.getNom(), e.getId()); escompteIdxToSeqno.put(e.getId(), idx); idx++; } } ServiceData sd = cd.getServices().get(currentServiceNumber); if (sd == null) return; String escompteIndex = sd.getEscompteId(); if (escompteIdxToSeqno.get(escompteIndex) != null) escompte.setSelectedIndex(escompteIdxToSeqno.get(escompteIndex)); else escompte.setSelectedIndex(0); } private void loadProduits(JsArray<ProduitSummary> produitArray) { HashMap<String, Integer> produitIdxToSeqno = new HashMap<String, Integer>(); produit.clear(); produitSummaries.clear(); produit.addItem(Constants.EMPTY_PRODUIT.getNom(), Constants.EMPTY_PRODUIT.getId()); produitSummaries.add(Constants.EMPTY_PRODUIT); int idx = 1; if (produitArray == null) com.google.gwt.user.client.Window.alert("produitArray is null"); for (int i = 0; i < produitArray.length(); i++) { ProduitSummary e = produitArray.get(i); if (e.getClubId().equals("0") || e.getClubId().equals(jdb.getSelectedClubID())) { produitSummaries.add(e); produit.addItem(e.getNom(), e.getId()); produitIdxToSeqno.put(e.getClubId(), idx); idx++; } } ServiceData sd = cd.getServices().get(currentServiceNumber); if (sd == null) return; String produitIndex = sd.getJudogi(); if (produitIdxToSeqno.get(produitIndex) != null) produit.setSelectedIndex(produitIdxToSeqno.get(produitIndex)); else produit.setSelectedIndex(0); } class ClubListHandler implements ChangeHandler { public void onChange(ChangeEvent event) { jdb.selectedClub = dropDownUserClubs.getSelectedIndex(); ClubSummary cs = jdb.getClubSummaryByID(jdb.getSelectedClubID()); hideEscompteResidentIfUnneeded(cs); hidePaypalIfDisabled(cs); retrieveSessions(); retrieveClubPrix(); retrieveCours(); retrieveEscomptes(); retrieveProduits(); updateFrais(); } } @SuppressWarnings("deprecation") private void updateBlurb() { if (cd.getDDNString() == null) return; Date ddn = cd.getDDN(), today = new Date(); if (cd.getDDN() == null) return; int by = ddn.getYear(), bm = ddn.getMonth(), bd = ddn.getDate(), ny = today.getYear(), nm = today.getMonth(), nd = ddn.getDate(); int y = ny - by; if (bm > nm || (bm == nm && bd > nd)) y--; String nom = cd.getPrenom() + " " + cd.getNom(); String nn, mm; if (y >= 18) { nn = nom; mm = "membre"; } else { nn = "__________________________, parent ou tuteur du membre indiqué plus haut,"; mm = "parent ou tuteur"; } ServiceData sd = cd.getServices().get(currentServiceNumber); SafeHtml blurbContents = BLURB.blurb(nn, mm, Constants.STD_DATE_FORMAT.format(today), jdb.getClubSummaryByID(sd.getClubID()).getNom()); blurb.clear(); blurb.add(new HTMLPanel(blurbContents)); } private void disableAllSessionEditingInfo() { saisons.setText(""); verification.setValue(false); no_sessions.setEnabled(false); categorieFrais.setText(""); sans_affiliation.setValue(false); sans_affiliation.setEnabled(false); affiliation_initiation.setValue(false); affiliation_initiation.setEnabled(false); affiliation_ecole.setValue(false); affiliation_ecole.setEnabled(false); affiliationFrais.setText(""); escompte.setEnabled(false); cas_special_note.setText(""); cas_special_note.setReadOnly(true); cas_special_pct.setValue(""); cas_special_pct.setReadOnly(true); escompteFrais.setText(""); produit.setEnabled(false); resident.setValue(false); resident.setEnabled(false); paypal.setValue(false); paypal.setEnabled(false); suppFrais.setText(""); frais.setText(""); solde.setValue(false); } /* depends on retrieveClubList having succeeded */ /** Takes data from ClientData into the form. */ private void loadClientData () { // cannot just test for getSelectedClubID() == null, // since it sets the selected club ID based on the client's data! if (jdb.allClubs == null || currentSession == null) { new Timer() { public void run() { loadClientData(); } }.schedule(100); return; } cid.setInnerText(cd.getID()); nom.setText(cd.getNom()); prenom.setText(cd.getPrenom()); Date ddns = cd.getDDN(); ddn_display.setText(ddns == null ? Constants.STD_DUMMY_DATE : Constants.STD_DATE_FORMAT.format(ddns)); ddn.setValue(ddns == null ? Constants.DB_DUMMY_DATE : Constants.DB_DATE_FORMAT.format(ddns)); sexe.setText(cd.getSexe()); adresse.setText(cd.getAdresse()); ville.setText(cd.getVille()); codePostal.setText(cd.getCodePostal()); tel.setText(cd.getTel()); courriel.setText(cd.getCourriel()); affiliation.setText(cd.getJudoQC()); carte_resident.setText(cd.getCarteResident()); nom_recu_impot.setText(cd.getNomRecuImpot()); tel_contact_urgence.setText(cd.getTelContactUrgence()); if (currentServiceNumber == -1) { addNewService(); } loadGradesData(); date_inscription.clear(); boolean hasToday = false, isToday = false; boolean hasThisSession = cd.getServiceFor(currentSession) != null; String todayString = Constants.DB_DATE_FORMAT.format(new Date()); for (int i = 0; i < cd.getServices().length(); i++) { ServiceData ssd = cd.getServices().get(i); if (todayString.equals(ssd.getDateInscription())) { hasToday = true; isToday = (i == currentServiceNumber); } date_inscription.addItem(Constants.dbToStdDate(ssd.getDateInscription()), Integer.toString(i)); } date_inscription.setSelectedIndex(currentServiceNumber); inscrire.setVisible(!hasToday && !hasThisSession); modifier.setVisible(!hasToday && hasThisSession); desinscrire.setVisible(hasThisSession); ServiceData sd = cd.getServices().get(currentServiceNumber); if (sd == null) { disableAllSessionEditingInfo(); return; } int clubIndex = jdb.getClubListBoxIndexByID(sd.getClubID()); if (-1 != clubIndex) { jdb.refreshSelectedClub(clubIndex); dropDownUserClubs.setSelectedIndex(clubIndex); } else { jdb.setStatus("Le client n'a pas de club enregistré."); return; } saisons.setText(sd.getSaisons()); verification.setValue(sd.getVerification()); int matching_index = 0; for (CoursSummary cs : backingCours) { if (cs.getId().equals(sd.getCours())) { cours.setSelectedIndex(matching_index); break; } matching_index++; } no_sessions.setItemSelected(sd.getSessionCount()-1, true); no_sessions.setEnabled(isToday); categorieFrais.setText(sd.getCategorieFrais()); sans_affiliation.setValue(sd.getSansAffiliation()); sans_affiliation.setEnabled(isToday); affiliation_initiation.setValue(sd.getAffiliationInitiation()); affiliation_initiation.setEnabled(isToday); affiliation_ecole.setValue(sd.getAffiliationEcole()); affiliation_ecole.setEnabled(isToday); affiliationFrais.setText(sd.getAffiliationFrais()); escompte.setEnabled(isToday); cas_special_note.setText(sd.getCasSpecialNote()); cas_special_note.setReadOnly(!isToday); cas_special_pct.setValue(sd.getCasSpecialPct()); cas_special_pct.setReadOnly(!isToday); escompteFrais.setText(sd.getEscompteFrais()); int idx = 0; for (ProduitSummary p : produitSummaries) { if (sd.getJudogi().equals(p.getId())) produit.setSelectedIndex(idx); idx++; } produit.setEnabled(isToday); resident.setValue(sd.getResident()); resident.setEnabled(isToday); paypal.setValue(sd.getPaypal()); paypal.setEnabled(isToday); suppFrais.setText(sd.getSuppFrais()); frais.setText(sd.getFrais()); solde.setValue(sd.getSolde()); updateDynamicFields(); } /** Puts data from the form back onto ClientData. */ private void saveClientData() { cd.setNom(nom.getText()); cd.setPrenom(prenom.getText()); cd.setDDNString(Constants.stdToDbDate(ddn_display.getText())); cd.setSexe(sexe.getText()); cd.setAdresse(adresse.getText()); cd.setVille(ville.getText()); cd.setCodePostal(codePostal.getText()); cd.setTel(tel.getText()); cd.setCourriel(courriel.getText()); cd.setJudoQC(affiliation.getText()); cd.setCarteResident(carte_resident.getText()); cd.setNomRecuImpot(nom_recu_impot.getText()); cd.setTelContactUrgence(tel_contact_urgence.getText()); if (currentServiceNumber == -1) return; if (cd.getServices() == null) return; ServiceData sd = cd.getServices().get(currentServiceNumber); if (currentServiceNumber < date_inscription.getItemCount()) sd.setDateInscription(removeCommas(Constants.stdToDbDate(date_inscription.getItemText(currentServiceNumber)))); sd.setSaisons(removeCommas(saisons.getText())); sd.setClubID(jdb.getSelectedClubID()); sd.setVerification(verification.getValue()); if (cours.getSelectedIndex() != -1) sd.setCours(cours.getValue(cours.getSelectedIndex())); sd.setSessionCount(no_sessions.getSelectedIndex()+1); sd.setCategorieFrais(stripDollars(categorieFrais.getText())); sd.setSansAffiliation(sans_affiliation.getValue()); sd.setAffiliationInitiation(affiliation_initiation.getValue()); sd.setAffiliationEcole(affiliation_ecole.getValue()); sd.setAffiliationFrais(stripDollars(affiliationFrais.getText())); if (escompte.getSelectedIndex() != -1) { sd.setEscompteId(escompte.getValue(escompte.getSelectedIndex())); } sd.setCasSpecialNote(removeCommas(cas_special_note.getText())); sd.setCasSpecialPct(stripDollars(cas_special_pct.getText())); sd.setEscompteFrais(stripDollars(escompteFrais.getText())); if (produit.getSelectedIndex() != -1) { sd.setJudogi(produit.getValue(produit.getSelectedIndex())); } sd.setResident(resident.getValue()); sd.setPaypal(paypal.getValue()); sd.setSuppFrais(stripDollars(suppFrais.getText())); sd.setFrais(stripDollars(frais.getText())); sd.setSolde(solde.getValue()); } /** Load grades data from ClientData into the gradeTable & grade/date_grade. */ private void loadGradesData() { gradeTable.clear(); gradeTable.resize(cd.getGrades().length()+2, 2); gradeTable.setText(0, 0, "Grade"); gradeTable.getCellFormatter().setStyleName(0, 0, "{style.lwp}"); gradeTable.setText(0, 1, "Date"); gradeTable.getCellFormatter().setStyleName(0, 1, "{style.lwp}"); JsArray<GradeData> grades_ = cd.getGrades(); GradeData[] grades = new GradeData[grades_.length()]; for (int i = 0; i < grades_.length(); i++) grades[i] = grades_.get(i); Arrays.sort(grades, new GradeData.GradeComparator()); for (int i = 0; i < grades.length; i++) { setGradesTableRow(i+1, grades[i].getGrade(), Constants.dbToStdDate(grades[i].getDateGrade())); } setGradesTableRow(grades.length+1, "", ""); grade.setText(cd.getGrade()); date_grade.setText(Constants.dbToStdDate(cd.getDateGrade())); } private void setGradesTableRow(int row, String grade, String dateGrade) { TextBox g = new TextBox(); TextBox gd = new TextBox(); g.setValue(grade); g.setVisibleLength(5); gd.setValue(dateGrade); gd.setVisibleLength(10); gradeTable.setWidget(row, 0, g); gradeTable.setWidget(row, 1, gd); ((TextBox)gradeTable.getWidget(row, 0)).addChangeHandler(ensureGradeSpace); ((TextBox)gradeTable.getWidget(row, 1)).addChangeHandler(ensureGradeSpace); } private TextBox getGradeTableTextBox(int row, int col) { return (TextBox) gradeTable.getWidget(row, col); } /** If there are any empty rows in the middle, move them up. * If there is no empty row at the end, create one. */ private ChangeHandler ensureGradeSpace = new ChangeHandler() { public void onChange(ChangeEvent e) { int rc = gradeTable.getRowCount(); for (int i = 1; i < rc-2; i++) { if (getGradeTableTextBox(i, 0).getText().equals("") && getGradeTableTextBox(i, 1).getText().equals("")) { for (int j = i; j < rc-1; j++) { getGradeTableTextBox(j, 0).setText(getGradeTableTextBox(j+1, 0).getText()); getGradeTableTextBox(j, 1).setText(getGradeTableTextBox(j+1, 1).getText()); } getGradeTableTextBox(rc-1, 0).setText(""); getGradeTableTextBox(rc-1, 1).setText(""); } } if (!getGradeTableTextBox(rc-1, 0).getText().equals("") && !getGradeTableTextBox(rc-1, 1).getText().equals("")) { gradeTable.resize(rc+1, 2); setGradesTableRow(rc, "", ""); } } }; /** Save data from the grades table into the ClientData. */ private void saveGradesData() { JsArray<GradeData> newGradesJS = JavaScriptObject.createArray().cast(); ArrayList<GradeData> newGradesList = new ArrayList<GradeData>(); for (int i = 1; i < gradeTable.getRowCount(); i++) { String g = getGradeTableTextBox(i, 0).getText(), gdate = getGradeTableTextBox(i, 1).getText(); if (!g.equals("")) { GradeData gd = GradeData.createObject().cast(); gd.setGrade(g.replaceAll(",", ";")); gd.setDateGrade(Constants.stdToDbDate(gdate).replaceAll(",", ";")); newGradesList.add(gd); } } Collections.sort(newGradesList, new GradeData.GradeComparator()); int gi = 0; for (GradeData gd : newGradesList) { newGradesJS.set(gi++, gd); } cd.setGrades(newGradesJS); } private String encodeGrades() { StringBuffer sb = new StringBuffer(); JsArray<GradeData> grades = cd.getGrades(); for (int i = 0; i < grades.length(); i++) { GradeData gd = grades.get(i); if (i > 0) sb.append(","); sb.append(gd.getGrade()); } return sb.toString(); } private String encodeGradeDates() { StringBuffer sb = new StringBuffer(); JsArray<GradeData> grades = cd.getGrades(); for (int i = 0; i < grades.length(); i++) { GradeData gd = grades.get(i); if (i > 0) sb.append(","); sb.append(gd.getDateGrade()); } return sb.toString(); } private final ChangeHandler directGradeChangeHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { // either no previous grade or no previous date-grade; // erase the old grade if (date_grade.getText().equals(Constants.STD_DUMMY_DATE) || cd.getGrade().equals("")) { date_grade.setText(Constants.STD_DATE_FORMAT.format(new Date())); setGradesTableRow(1, grade.getText(), date_grade.getText()); saveGradesData(); } else { // old grade set, and has date; keep the old grade-date in the array // and update the array. ensureGradeSpace.onChange(null); date_grade.setText(Constants.STD_DATE_FORMAT.format(new Date())); setGradesTableRow(0, grade.getText(), date_grade.getText()); saveGradesData(); } } }; private final ChangeHandler directGradeDateChangeHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { // TODO: if you change the grade-date, and grade is not empty, then // update the array. } }; private final ChangeHandler changeEscompteHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { if (escompte.getValue(escompte.getSelectedIndex()).equals("-1") && cas_special_pct.getValue().equals("-1")) cas_special_pct.setValue("0"); updateDynamicFields(); } }; private final ChangeHandler recomputeHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { updateDynamicFields(); } }; private final ChangeHandler changeSaisonHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { saveClientData(); currentServiceNumber = Integer.parseInt(date_inscription.getValue(date_inscription.getSelectedIndex())); loadClientData(); } }; private final ChangeHandler updateCopySibHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { updateCopySib(); } }; private final ValueChangeHandler<Boolean> recomputeValueHandler = new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> e) { updateDynamicFields(); } }; private final ChangeHandler clearEscomptePctAndRecomputeHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { cas_special_pct.setValue("-1"); regularizeEscompte(); updateDynamicFields(); } }; private final ChangeHandler clearEscompteAmtAndRecomputeHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { escompteFrais.setValue("-1"); regularizeEscompte(); updateDynamicFields(); } }; /** Create a new inscription for the current session. */ private final ClickHandler inscrireClickHandler = new ClickHandler() { public void onClick(ClickEvent e) { saveClientData(); ServiceData sd = cd.getServiceFor(currentSession); if (sd == null) { sd = ServiceData.newServiceData(); sd.setClubID(jdb.getSelectedClubID()); cd.getServices().push(sd); } // actually, sd != null should not occur; that should be modify. sd.inscrireAujourdhui(); currentServiceNumber = cd.getMostRecentServiceNumber(); loadClientData(); updateDynamicFields(); } }; /** Resets the date d'inscription for the current session to today's date. */ private final ClickHandler modifierClickHandler = new ClickHandler() { public void onClick(ClickEvent e) { ServiceData sd = cd.getServiceFor(currentSession); // shouldn't happen, actually. if (sd == null) return; saveClientData(); sd.inscrireAujourdhui(); currentServiceNumber = cd.getMostRecentServiceNumber(); loadClientData(); updateDynamicFields(); } }; private final ClickHandler desinscrireClickHandler = new ClickHandler() { public void onClick(ClickEvent e) { ServiceData sd = cd.getServiceFor(currentSession); if (sd == null) return; saveClientData(); JsArray<ServiceData> newServices = JavaScriptObject.createArray().cast(); for (int i = 0, j = 0; i < cd.getServices().length(); i++) { if (i != currentServiceNumber) newServices.set(j++, cd.getServices().get(i)); } cd.setServices(newServices); currentServiceNumber = cd.getMostRecentServiceNumber(); loadClientData(); updateDynamicFields(); } }; private int emptyGradeDates() { int empty = 0; for (int i = 1; i < gradeTable.getRowCount(); i++) { String gv = getGradeTableTextBox(i, 0).getText(); String gdv = getGradeTableTextBox(i, 1).getText(); if (gdv.equals(Constants.STD_DUMMY_DATE) || (!gv.equals("") && gv.equals(""))) empty++; } return empty; } private final ClickHandler saveGradesHandler = new ClickHandler() { public void onClick(ClickEvent e) { if (emptyGradeDates() > 1) { jdb.setStatus("Seulement une grade sans date est permise."); new Timer() { public void run() { jdb.clearStatus(); } }.schedule(2000); return; } saveGradesData(); loadGradesData(); gradeHistory.setVisible(false); } }; private final ClickHandler annulerGradesHandler = new ClickHandler() { public void onClick(ClickEvent e) { loadGradesData(); gradeHistory.setVisible(false); } }; /** We use , as a separator, so get rid of it in the input. */ private String removeCommas(String s) { return s.replaceAll(",", ";"); } // argh NumberFormat doesn't work for me at all! // stupidly, it says that you have to use ',' as the decimal separator, but people use both '.' and ','. private String stripDollars(String s) { StringBuffer ss = new StringBuffer(""); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '$' || s.charAt(i) == ' ' || s.charAt(i) == ')' || s.charAt(i) == '\u00a0') continue; if (s.charAt(i) == ',') ss.append("."); else if (s.charAt(i) == '(') ss.append("-"); else ss.append(s.charAt(i)); } return ss.toString(); } private static native float parseFloat(String s) /*-{ return parseFloat(s); }-*/; @SuppressWarnings("deprecation") private boolean sameDate(Date d1, Date d2) { return d1.getYear() == d2.getYear() && d1.getMonth() == d2.getMonth() && d1.getDate() == d2.getDate(); } /** Enables user to edit both % escompte and escompte amount by putting them in synch. * Works directly at the View level, not the Model level. */ private void regularizeEscompte() { ServiceData sd = cd.getServices().get(currentServiceNumber); ClubSummary cs = jdb.getClubSummaryByID(sd.getClubID()); double dCategorieFrais = CostCalculator.proratedFraisCours(currentSession, cd, sd, cs, clubPrix); if (CostCalculator.isCasSpecial(sd, CostCalculator.getApplicableEscompte(sd, escompteSummaries))) { NumberFormat nf = NumberFormat.getDecimalFormat(); if (cas_special_pct.getValue().equals("-1")) { float actualEscompteFrais = parseFloat(stripDollars(escompteFrais.getValue())); if (actualEscompteFrais > 0) { actualEscompteFrais *= -1; escompteFrais.setValue(nf.format(actualEscompteFrais)); } cas_special_pct.setValue(nf.format(-100 * actualEscompteFrais / dCategorieFrais)); } else if (escompteFrais.getValue().equals("-1")) { String cpct = stripDollars(cas_special_pct.getValue()); float fCpct = parseFloat(cpct); if (fCpct < 0) { fCpct *= -1; cas_special_pct.setValue(nf.format(fCpct)); } escompteFrais.setValue(nf.format(-fCpct * dCategorieFrais / 100.0)); } } } /** View-level method to pull information from ServiceData and put it onto the form in currency format. */ private void updateFrais() { NumberFormat cf = NumberFormat.getCurrencyFormat("CAD"); ServiceData sd = cd.getServices().get(currentServiceNumber); Date dateInscription = Constants.DB_DATE_FORMAT.parse(sd.getDateInscription()); int sessionCount = sd.getSessionCount(); semaines.setText(CostCalculator.getWeeksSummary(currentSession, dateInscription)); escompteFrais.setReadOnly (!CostCalculator.isCasSpecial(sd, CostCalculator.getApplicableEscompte(sd, escompteSummaries))); saisons.setText(JudoDB.getSessionIds(Constants.DB_DATE_FORMAT.parse(sd.getDateInscription()), sessionCount, sessionSummaries)); try { categorieFrais.setText (cf.format(Double.parseDouble(sd.getCategorieFrais()))); affiliationFrais.setText (cf.format(Double.parseDouble(sd.getAffiliationFrais()))); escompteFrais.setValue(cf.format(Double.parseDouble(sd.getEscompteFrais()))); suppFrais.setText(cf.format(Double.parseDouble(sd.getSuppFrais()))); frais.setText(cf.format(Double.parseDouble(sd.getFrais()))); } catch (NumberFormatException e) {} } private void updateCopySib() { copysib.setVisible(false); // check 1) address fields are empty and 2) there exists a sibling // Note that the following check relies on the data being saved // to the ClientData, which is true after you enter the birthday. ServiceData sd = cd.getServices().get(currentServiceNumber); ClubSummary clb = jdb.getClubSummaryByID(sd.getClubID()); if (!cd.isDefault(clb)) return; // XXX should do an allClients fetch upon load... if (jdb.allClients == null) return; for (ClientSummary cs : jdb.allClients) { // XXX don't copy data across clubs if (cs.getId().equals(cd.getID())) continue; String csn = cs.getNom().toLowerCase(); String n = nom.getText().toLowerCase(); if (n.equals(csn)) { sibid = cs.getId(); copysib.setVisible(true); } } } private void copysib() { final ClientWidget cp = new ClientWidget(Integer.parseInt(sibid), jdb); cp.onPopulated.add (new ChangeHandler () { public void onChange(ChangeEvent e) { cp.actuallyCopy(ClientWidget.this); } }); } private void actuallyCopy(ClientWidget d) { d.adresse.setText(adresse.getText()); d.ville.setText(ville.getText()); d.codePostal.setText(codePostal.getText()); d.tel.setText(tel.getText()); d.tel_contact_urgence.setText(tel_contact_urgence.getText()); d.courriel.setText(courriel.getText()); d.updateCopySib(); } private void hideEscompteResidentIfUnneeded(ClubSummary cs) { if (cs == null) return; String escompteResident = cs.getEscompteResident(); if (escompteResident == null || escompteResident.equals("") || escompteResident.equals("0")) { clientMain.getElementById("rabais_resident_label").getStyle().setProperty("display", "none"); resident.setVisible(false); } else { resident.setVisible(true); clientMain.getElementById("rabais_resident_label").getStyle().setProperty("display", "inline"); } } private void hidePaypalIfDisabled(ClubSummary cs) { if (cs == null) return; boolean showPaypal = cs.getAfficherPaypal(); if (!showPaypal) { clientMain.getElementById("frais_paypal_label").getStyle().setProperty("display", "none"); paypal.setVisible(false); } else { paypal.setVisible(true); clientMain.getElementById("frais_paypal_label").getStyle().setProperty("display", "inline"); } } private void updateDynamicFields() { saveClientData(); ServiceData sd = cd.getServices().get(currentServiceNumber); if (sd == null) return; ClubSummary cs = jdb.getClubSummaryByID(sd.getClubID()); hideEscompteResidentIfUnneeded(cs); hidePaypalIfDisabled(cs); ProduitSummary ps = CostCalculator.getApplicableProduit(sd, produitSummaries);; CostCalculator.recompute(currentSession, cd, sd, cs, ps, prorata.getValue(), clubPrix, escompteSummaries); /* view stuff here */ Display d = Display.NONE; int escompteIdx = escompte.getSelectedIndex(); if (escompteIdx != -1 && CostCalculator.isCasSpecial(sd, CostCalculator.getApplicableEscompte(sd, escompteSummaries))) d = Display.INLINE; ((Element)cas_special_note.getElement().getParentNode()).getStyle().setDisplay(d); ((Element)cas_special_pct.getElement().getParentNode()).getStyle().setDisplay(d); if (sd != null && !sd.getSaisons().equals("")) { String a = sd.getSaisons().split(" ")[0]; SessionSummary that_session = null; for (SessionSummary s : sessionSummaries) { if (a.equals(s.getAbbrev())) that_session = s; } if (that_session != null) { Constants.Division c = cd.getDivision(that_session.getYear()); categorie.setText(c.abbrev); } } updateBlurb(); updateFrais(); updateCopySib(); } private void encodeServices() { StringBuffer di = new StringBuffer(), sais = new StringBuffer(), v = new StringBuffer(), cf = new StringBuffer(), c = new StringBuffer(), sess = new StringBuffer(), e = new StringBuffer(), csn = new StringBuffer(), csp = new StringBuffer(), ef = new StringBuffer(), sa = new StringBuffer(), ai = new StringBuffer(), ae = new StringBuffer(), af = new StringBuffer(), j = new StringBuffer(), p = new StringBuffer(), n = new StringBuffer(), pp = new StringBuffer(), sf = new StringBuffer(), s = new StringBuffer(), f = new StringBuffer(), clubid = new StringBuffer(); JsArray<ServiceData> services = cd.getServices(); for (int i = 0; i < services.length(); i++) { ServiceData sd = services.get(i); di.append(sd.getDateInscription()+","); sais.append(sd.getSaisons()+","); v.append(sd.getVerification() ? "1," : "0,"); cf.append(sd.getCategorieFrais()+","); c.append(sd.getCours()+","); sess.append(Integer.toString(sd.getSessionCount())+","); e.append(sd.getEscompteId()+","); csn.append(sd.getCasSpecialNote()+","); csp.append(sd.getCasSpecialPct()+","); ef.append(sd.getEscompteFrais()+","); sa.append(sd.getSansAffiliation() ? "1," : "0,"); ai.append(sd.getAffiliationInitiation() ? "1," : "0,"); ae.append(sd.getAffiliationEcole() ? "1," : "0,"); af.append(sd.getAffiliationFrais()+","); j.append(sd.getJudogi()+","); // disabled passeport //p.append(sd.getPasseport()+","); p.append("0,"); n.append(sd.getResident()+","); pp.append(sd.getPaypal()+","); sf.append(sd.getSuppFrais()+","); s.append(sd.getSolde() ? "1,":"0,"); f.append(sd.getFrais()+","); clubid.append(sd.getClubID()+","); } date_inscription_encoded.setValue(di.toString()); saisons_encoded.setValue(sais.toString()); verification_encoded.setValue(v.toString()); categorieFrais_encoded.setValue(cf.toString()); cours_encoded.setValue(c.toString()); no_sessions_encoded.setValue(sess.toString()); escompte_encoded.setValue(e.toString()); cas_special_note_encoded.setValue(csn.toString()); cas_special_pct_encoded.setValue(csp.toString()); escompteFrais_encoded.setValue(ef.toString()); sans_affiliation_encoded.setValue(sa.toString()); affiliation_initiation_encoded.setValue(ai.toString()); affiliation_ecole_encoded.setValue(ae.toString()); affiliationFrais_encoded.setValue(af.toString()); judogi_encoded.setValue(j.toString()); resident_encoded.setValue(n.toString()); paypal_encoded.setValue(pp.toString()); suppFrais_encoded.setValue(sf.toString()); solde_encoded.setValue(s.toString()); frais_encoded.setValue(f.toString()); club_id_encoded.setValue(clubid.toString()); } private void pushClientDataToServer(final boolean leaveAfterPush) { if (cd.getNom().equals("") || cd.getPrenom().equals("")) { jdb.displayError("pas de nom ou prenom"); return; } guid = UUID.uuid(); sid.setValue(cd.getID()); guid_on_form.setValue(guid); grades_encoded.setValue(encodeGrades()); grade_dates_encoded.setValue(encodeGradeDates()); saveClientData(); loadClientData(); encodeServices(); // http://stackoverflow.com/questions/2699277/post-data-to-jsonp clientform.submit(); pushTries = 0; new Timer() { public void run() { pushOneClient(guid, leaveAfterPush); } }.schedule(500); } private void pushDeleteToServer() { // no need to delete if there's no ID yet. if (cd.getID().equals("")) return; guid = UUID.uuid(); sid.setValue(cd.getID()); guid_on_form.setValue(guid); deleted.setValue("true"); clientform.submit(); pushTries = 0; new Timer() { public void run() { pushOneClient(guid, true); } }.schedule(500); } private void loadCours(JsArray<CoursSummary> coursArray) { backingCours.clear(); cours.setVisibleItemCount(1); cours.clear(); for (int i = 0; i < coursArray.length(); i++) { CoursSummary c = coursArray.get(i); cours.addItem(c.getShortDesc(), c.getId()); backingCours.add(c); } } /* --- sessions --- */ List<SessionSummary> sessionSummaries = new ArrayList<SessionSummary>(); SessionSummary currentSession; void populateSessions(JsArray<SessionSummary> ss) { sessionSummaries.clear(); for (int i = 0; i < ss.length(); i++) { sessionSummaries.add(ss.get(i)); } currentSession = null; Date today = new Date(); for (SessionSummary s : sessionSummaries) { try { Date inscrBegin = Constants.DB_DATE_FORMAT.parse(s.getFirstSignupDate()); Date inscrEnd = Constants.DB_DATE_FORMAT.parse(s.getLastSignupDate()); if (today.after(inscrBegin) && today.before(inscrEnd)) { currentSession = s; continue; } } catch (IllegalArgumentException e) {} } } /* --- end sessions --- */ /* --- network functions --- */ /* depends on there being sessions */ public void retrieveClient(final int cid) { if (!gotSessions) { new Timer() { public void run() { retrieveClient(cid); } }.schedule(100); return; } String url = PULL_ONE_CLIENT_URL + "?id=" + cid; RequestCallback rc = jdb.createRequestCallback(new JudoDB.Function() { public void eval(String s) { if (s.equals("")) { ClientWidget.this.jdb.displayError("ce client n'existe pas"); new Timer() { public void run() { ClientWidget.this.jdb.popMode(); } }.schedule(2000); return; } ClientWidget.this.cd = JsonUtils.<ClientData>safeEval(s); currentServiceNumber = cd.getMostRecentServiceNumber(); jdb.clearStatus(); loadClientData(); for (ChangeHandler ch : onPopulated) { ch.onChange(null); } } }); jdb.retrieve(url, rc); } /* depends on there being a selected club */ private boolean gotSessions = false; public void retrieveSessions() { if (jdb.getSelectedClubID() == null) { new Timer() { public void run() { retrieveSessions(); } }.schedule(100); return; } String url = JudoDB.PULL_SESSIONS_URL; url += "?club="+jdb.getSelectedClubID(); RequestCallback rc = jdb.createRequestCallback(new JudoDB.Function() { public void eval(String s) { gotSessions = true; populateSessions(JsonUtils.<JsArray<SessionSummary>>safeEval(s)); } }); jdb.retrieve(url, rc); } /* depends on retrieveClubList() and retrieveSessions() having succeeded */ /* also depends on there being a selected club */ public void retrieveClubPrix() { if (jdb.getSelectedClubID() == null || !gotSessions) { new Timer() { public void run() { retrieveClubPrix(); } }.schedule(100); return; } clubPrix = null; ClubSummary cs = jdb.getClubSummaryByID(jdb.getSelectedClubID()); String url = JudoDB.PULL_CLUB_PRIX_URL + "?numero_club=" + cs.getNumeroClub() + "&session_seqno=" + currentSession.getSeqno(); RequestCallback rc = jdb.createRequestCallback(new JudoDB.Function() { public void eval(String s) { JsArray<ClubPrix> cp = JsonUtils.<JsArray<ClubPrix>>safeEval(s); clubPrix = new ClubPrix[cp.length()]; for (int i = 0; i < cp.length(); i++) clubPrix[i] = cp.get(i); } }); jdb.retrieve(url, rc); } /* depends on retrieveClubList() and retrieveSessions() having succeeded */ public void retrieveCours() { if (jdb.getSelectedClubID() == null || !gotSessions) { new Timer() { public void run() { retrieveCours(); } }.schedule(100); return; } backingCours.clear(); ClubSummary cs = jdb.getClubSummaryByID(jdb.getSelectedClubID()); String url = JudoDB.PULL_CLUB_COURS_URL + "?numero_club=" + cs.getNumeroClub() + "&session_seqno=" + currentSession.getSeqno(); RequestCallback rc = jdb.createRequestCallback(new JudoDB.Function() { public void eval(String s) { loadCours (JsonUtils.<JsArray<CoursSummary>>safeEval(s)); } }); jdb.retrieve(url, rc); } /* depends on retrieveClubList() and retrieveSessions() having succeeded */ public void retrieveEscomptes() { if (jdb.getSelectedClubID() == null || !gotSessions) { new Timer() { public void run() { retrieveEscomptes(); } }.schedule(100); return; } escompte.clear(); escompteSummaries.clear(); String url = JudoDB.PULL_ESCOMPTE_URL + "?club_id=" + jdb.getSelectedClubID(); RequestCallback rc = jdb.createRequestCallback(new JudoDB.Function() { public void eval(String s) { loadEscomptes (JsonUtils.<JsArray<EscompteSummary>>safeEval(s)); } }); jdb.retrieve(url, rc); } /* depends on retrieveClubList() having succeeded */ /* technically does not require sessions, but adding it removes a race condition */ public void retrieveProduits() { if (jdb.getSelectedClubID() == null || !gotSessions) { new Timer() { public void run() { retrieveProduits(); } }.schedule(100); return; } produit.clear(); produitSummaries.clear(); String url = JudoDB.PULL_PRODUIT_URL + "?club_id=" + jdb.getSelectedClubID(); RequestCallback rc = jdb.createRequestCallback(new JudoDB.Function() { public void eval(String s) { loadProduits (JsonUtils.<JsArray<ProduitSummary>>safeEval(s)); } }); jdb.retrieve(url, rc); } public void pushOneClient(final String guid, final boolean leaveAfterPush) { String url = CONFIRM_PUSH_URL + "?guid=" + guid; RequestCallback rc = jdb.createRequestCallback(new JudoDB.Function() { public void eval(String s) { ConfirmResponseObject cro = JsonUtils.<ConfirmResponseObject>safeEval(s); String rs = cro.getResult(); if (rs.equals("NOT_YET")) { if (pushTries >= 3) { jdb.displayError("le serveur n'a pas accepté les données"); return; } new Timer() { public void run() { pushOneClient(guid, leaveAfterPush); } }.schedule(2000); pushTries++; } else { jdb.setStatus("Sauvegardé."); jdb.invalidateListWidget(); new Timer() { public void run() { jdb.clearStatus(); if (leaveAfterPush) ClientWidget.this.jdb.popMode(); } }.schedule(2000); if (cd.getID() == null || cd.getID().equals("")) { cd.setID(Integer.toString(cro.getSid())); loadClientData(); } } new Timer() { public void run() { jdb.clearStatus(); } }.schedule(2000); } }); jdb.retrieve(url, rc); } }
src/ca/patricklam/judodb/client/ClientWidget.java
package ca.patricklam.judodb.client; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.HashMap; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsonUtils; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.FormElement; import com.google.gwt.dom.client.Style.Display; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.i18n.client.NumberFormat; import com.google.gwt.safehtml.client.SafeHtmlTemplates; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.Hidden; import com.google.gwt.user.client.ui.InlineLabel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.ValueBoxBase; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; public class ClientWidget extends Composite { interface MyUiBinder extends UiBinder<Widget, ClientWidget> {} public static MyUiBinder uiBinder = GWT.create(MyUiBinder.class); private final JudoDB jdb; @UiField DivElement cid; @UiField HTMLPanel clientMain; @UiField TextBox nom; @UiField TextBox prenom; @UiField TextBox ddn_display; @UiField Hidden ddn; @UiField TextBox sexe; @UiField Anchor copysib; @UiField TextBox adresse; @UiField TextBox ville; @UiField TextBox codePostal; @UiField TextBox tel; @UiField TextBox courriel; @UiField TextBox affiliation; @UiField TextBox grade; @UiField Anchor showgrades; @UiField TextBox date_grade; @UiField TextBox carte_resident; @UiField TextBox nom_recu_impot; @UiField TextBox tel_contact_urgence; @UiField ListBox date_inscription; @UiField InlineLabel semaines; @UiField Anchor inscrire; @UiField Anchor modifier; @UiField Anchor desinscrire; @UiField TextBox saisons; @UiField CheckBox prorata; @UiField CheckBox verification; @UiField TextBox categorie; @UiField TextBox categorieFrais; @UiField ListBox cours; @UiField ListBox no_sessions; @UiField ListBox escompte; @UiField TextBox cas_special_note; @UiField TextBox cas_special_pct; @UiField TextBox escompteFrais; @UiField CheckBox sans_affiliation; @UiField CheckBox affiliation_initiation; @UiField CheckBox affiliation_ecole; @UiField TextBox affiliationFrais; @UiField ListBox produit; @UiField CheckBox resident; @UiField CheckBox paypal; @UiField TextBox suppFrais; @UiField CheckBox solde; @UiField TextBox frais; @UiField Hidden grades_encoded; @UiField Hidden grade_dates_encoded; @UiField Hidden date_inscription_encoded; @UiField Hidden saisons_encoded; @UiField Hidden prorata_encoded; @UiField Hidden verification_encoded; @UiField Hidden categorieFrais_encoded; @UiField Hidden cours_encoded; @UiField Hidden no_sessions_encoded; @UiField Hidden escompte_encoded; @UiField Hidden cas_special_note_encoded; @UiField Hidden cas_special_pct_encoded; @UiField Hidden escompteFrais_encoded; @UiField Hidden sans_affiliation_encoded; @UiField Hidden affiliation_initiation_encoded; @UiField Hidden affiliation_ecole_encoded; @UiField Hidden affiliationFrais_encoded; @UiField Hidden judogi_encoded; @UiField Hidden resident_encoded; @UiField Hidden paypal_encoded; @UiField Hidden suppFrais_encoded; @UiField Hidden solde_encoded; @UiField Hidden frais_encoded; @UiField Hidden club_id_encoded; @UiField Hidden guid_on_form; @UiField Hidden sid; @UiField Hidden deleted; @UiField Button saveClientButton; @UiField Button saveAndReturnClientButton; @UiField Button deleteClientButton; @UiField Button discardClientButton; @UiField HTMLPanel blurb; @UiField HTMLPanel gradeHistory; @UiField Grid gradeTable; @UiField Anchor saveGrades; @UiField Anchor annulerGrades; @UiField ListBox dropDownUserClubs; private final FormElement clientform; private static final String PULL_ONE_CLIENT_URL = JudoDB.BASE_URL + "pull_one_client.php"; private static final String PUSH_ONE_CLIENT_URL = JudoDB.BASE_URL + "push_one_client.php"; private static final String CONFIRM_PUSH_URL = JudoDB.BASE_URL + "confirm_push.php"; private int pushTries; public interface BlurbTemplate extends SafeHtmlTemplates { @Template ("<p>Je {0} certifie que les informations inscrites sur ce formulaire sont véridiques. "+ "En adhèrant au {3}, j'accepte tous les risques d'accident liés à la pratique du "+ "judo qui pourraient survenir dans les locaux ou lors d'activités extérieurs organisées par le Club. "+ "J'accepte de respecter les règlements du Club en tout temps y compris lors des déplacements.</p>"+ "<h4>Politique de remboursement</h4>"+ "<p>Aucun remboursement ne sera accordé sans présentation d'un certificat médical du participant. "+ "Seuls les frais de cours correspondant à la période restante sont remboursables. "+ "En cas d'annulation par le participant, un crédit pourra être émis par le Club, "+ "pour les frais de cours correspondant à la période restante.</p>"+ "<p>Signature {1}: <span style='float:right'>Date: _________</span></p>"+ "<p>Signature résponsable du club: <span style='float:right'>Date: {2}</span></p>") SafeHtml blurb(String nom, String membreOuParent, String today, String clubName); } private static final BlurbTemplate BLURB = GWT.create(BlurbTemplate.class); private ClubPrix[] clubPrix; /** A list of cours as retrieved from the server. * Must stay in synch with the ListBox field cours. */ private List<CoursSummary> backingCours = new ArrayList<CoursSummary>(); private List<EscompteSummary> escompteSummaries = new ArrayList<EscompteSummary>(); private List<ProduitSummary> produitSummaries = new ArrayList<ProduitSummary>(); private ClientData cd; private String guid; private int currentServiceNumber; public int getCurrentServiceNumber() { return currentServiceNumber; } private String sibid; private List<ChangeHandler> onPopulated = new ArrayList<ChangeHandler>(); private ClubListHandler clubListHandler; public ClientWidget(int cid, JudoDB jdb) { this.jdb = jdb; initWidget(uiBinder.createAndBindUi(this)); clientform = FormElement.as(clientMain.getElementById("clientform")); clientform.setAction(PUSH_ONE_CLIENT_URL); deleted.setValue(""); clubListHandler = new ClubListHandler(); dropDownUserClubs.setSelectedIndex(jdb.selectedClub); dropDownUserClubs.addChangeHandler(clubListHandler); no_sessions.addItem("1"); no_sessions.addItem("2"); gradeHistory.setVisible(false); prorata.setValue(true); categorie.setReadOnly(true); saisons.setReadOnly(true); categorieFrais.setReadOnly(true); categorieFrais.setAlignment(ValueBoxBase.TextAlignment.RIGHT); cas_special_pct.setAlignment(ValueBoxBase.TextAlignment.RIGHT); escompteFrais.setReadOnly(true); escompteFrais.setAlignment(ValueBoxBase.TextAlignment.RIGHT); affiliationFrais.setReadOnly(true); affiliationFrais.setAlignment(ValueBoxBase.TextAlignment.RIGHT); suppFrais.setReadOnly(true); suppFrais.setAlignment(ValueBoxBase.TextAlignment.RIGHT); frais.setReadOnly(true); frais.setAlignment(ValueBoxBase.TextAlignment.RIGHT); ((Element)cas_special_note.getElement().getParentNode()).getStyle().setDisplay(Display.NONE); ((Element)cas_special_pct.getElement().getParentNode()).getStyle().setDisplay(Display.NONE); no_sessions.setItemSelected(1, true); if (cid == -1 && jdb.getSelectedClubID() == null) { jdb.setStatus("Veuillez selectionner un club pour le client."); new Timer() { public void run() { ClientWidget.this.jdb.popMode(); } }.schedule(1000); return; } inscrire.addClickHandler(inscrireClickHandler); modifier.addClickHandler(modifierClickHandler); desinscrire.addClickHandler(desinscrireClickHandler); showgrades.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { gradeHistory.setVisible(true); } ; }); saveGrades.addClickHandler(saveGradesHandler); annulerGrades.addClickHandler(annulerGradesHandler); adresse.addChangeHandler(updateCopySibHandler); ville.addChangeHandler(updateCopySibHandler); codePostal.addChangeHandler(updateCopySibHandler); tel.addChangeHandler(updateCopySibHandler); tel_contact_urgence.addChangeHandler(updateCopySibHandler); courriel.addChangeHandler(updateCopySibHandler); ddn_display.addChangeHandler(recomputeHandler); grade.addChangeHandler(directGradeChangeHandler); date_grade.addChangeHandler(directGradeDateChangeHandler); grade.addChangeHandler(recomputeHandler); date_inscription.addChangeHandler(changeSaisonHandler); prorata.addValueChangeHandler(recomputeValueHandler); no_sessions.addChangeHandler(recomputeHandler); escompte.addChangeHandler(changeEscompteHandler); cas_special_pct.addChangeHandler(clearEscompteAmtAndRecomputeHandler); escompteFrais.addChangeHandler(clearEscomptePctAndRecomputeHandler); sans_affiliation.addValueChangeHandler(recomputeValueHandler); affiliation_initiation.addValueChangeHandler(recomputeValueHandler); affiliation_ecole.addValueChangeHandler(recomputeValueHandler); produit.addChangeHandler(recomputeHandler); resident.addValueChangeHandler(recomputeValueHandler); paypal.addValueChangeHandler(recomputeValueHandler); saveAndReturnClientButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { pushClientDataToServer(true); } }); saveClientButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { pushClientDataToServer(false); } }); discardClientButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { ClientWidget.this.jdb.clearStatus(); ClientWidget.this.jdb.popMode(); } }); deleteClientButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { pushDeleteToServer(); } }); copysib.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { copysib(); } }); jdb.populateClubList(false, dropDownUserClubs); jdb.pleaseWait(); if (cid != -1) retrieveClient(cid); else { this.cd = JavaScriptObject.createObject().cast(); this.cd.setID(null); this.cd.setNom(""); addNewService(); ClubSummary cs = jdb.getClubSummaryByID(jdb.getSelectedClubID()); cd.makeDefault(cs); currentServiceNumber = this.cd.getMostRecentServiceNumber(); JsArray<GradeData> ga = JavaScriptObject.createArray().cast(); GradeData gd = JavaScriptObject.createObject().cast(); gd.setGrade("Blanche"); gd.setDateGrade(Constants.DB_DATE_FORMAT.format(new Date())); ga.set(0, gd); this.cd.setGrades(ga); loadClientData(); jdb.clearStatus(); } retrieveSessions(); retrieveClubPrix(); retrieveCours(); retrieveEscomptes(); retrieveProduits(); } private void addNewService() { ServiceData sd = ServiceData.newServiceData(); sd.inscrireAujourdhui(); sd.setClubID(jdb.getSelectedClubID()); JsArray<ServiceData> sa = cd.getServices(); if (sa == null) { sa = JavaScriptObject.createArray().cast(); cd.setServices(sa); } sa.push(sd); } private void loadEscomptes(JsArray<EscompteSummary> escompteArray) { HashMap<String, Integer> escompteIdxToSeqno = new HashMap<String, Integer>(); int idx = 0; escompte.clear(); escompteSummaries.clear(); escompte.addItem(Constants.EMPTY_ESCOMPTE.getNom(), Constants.EMPTY_ESCOMPTE.getId()); escompteSummaries.add(Constants.EMPTY_ESCOMPTE); for (int i = 0; i < escompteArray.length(); i++) { EscompteSummary e = escompteArray.get(i); if (e.getClubId().equals("0") || e.getClubId().equals(jdb.getSelectedClubID())) { escompteSummaries.add(e); escompte.addItem(e.getNom(), e.getId()); escompteIdxToSeqno.put(e.getId(), idx); idx++; } } ServiceData sd = cd.getServices().get(currentServiceNumber); if (sd == null) return; String escompteIndex = sd.getEscompteId(); if (escompteIdxToSeqno.get(escompteIndex) != null) escompte.setSelectedIndex(escompteIdxToSeqno.get(escompteIndex)); else escompte.setSelectedIndex(0); } private void loadProduits(JsArray<ProduitSummary> produitArray) { HashMap<String, Integer> produitIdxToSeqno = new HashMap<String, Integer>(); int idx = 0; produit.clear(); produitSummaries.clear(); produit.addItem(Constants.EMPTY_PRODUIT.getNom(), Constants.EMPTY_PRODUIT.getId()); produitSummaries.add(Constants.EMPTY_PRODUIT); for (int i = 0; i < produitArray.length(); i++) { ProduitSummary e = produitArray.get(i); if (e.getClubId().equals("0") || e.getClubId().equals(jdb.getSelectedClubID())) { produitSummaries.add(e); produit.addItem(e.getNom(), e.getId()); produitIdxToSeqno.put(e.getClubId(), idx); idx++; } } ServiceData sd = cd.getServices().get(currentServiceNumber); String produitIndex = sd.getJudogi(); if (produitIdxToSeqno.get(produitIndex) != null) produit.setSelectedIndex(produitIdxToSeqno.get(produitIndex)); else produit.setSelectedIndex(0); } class ClubListHandler implements ChangeHandler { public void onChange(ChangeEvent event) { jdb.selectedClub = dropDownUserClubs.getSelectedIndex(); ClubSummary cs = jdb.getClubSummaryByID(jdb.getSelectedClubID()); hideEscompteResidentIfUnneeded(cs); hidePaypalIfDisabled(cs); retrieveSessions(); retrieveClubPrix(); retrieveCours(); retrieveEscomptes(); retrieveProduits(); updateFrais(); } } @SuppressWarnings("deprecation") private void updateBlurb() { if (cd.getDDNString() == null) return; Date ddn = cd.getDDN(), today = new Date(); if (cd.getDDN() == null) return; int by = ddn.getYear(), bm = ddn.getMonth(), bd = ddn.getDate(), ny = today.getYear(), nm = today.getMonth(), nd = ddn.getDate(); int y = ny - by; if (bm > nm || (bm == nm && bd > nd)) y--; String nom = cd.getPrenom() + " " + cd.getNom(); String nn, mm; if (y >= 18) { nn = nom; mm = "membre"; } else { nn = "__________________________, parent ou tuteur du membre indiqué plus haut,"; mm = "parent ou tuteur"; } ServiceData sd = cd.getServices().get(currentServiceNumber); SafeHtml blurbContents = BLURB.blurb(nn, mm, Constants.STD_DATE_FORMAT.format(today), jdb.getClubSummaryByID(sd.getClubID()).getNom()); blurb.clear(); blurb.add(new HTMLPanel(blurbContents)); } private void disableAllSessionEditingInfo() { saisons.setText(""); verification.setValue(false); no_sessions.setEnabled(false); categorieFrais.setText(""); sans_affiliation.setValue(false); sans_affiliation.setEnabled(false); affiliation_initiation.setValue(false); affiliation_initiation.setEnabled(false); affiliation_ecole.setValue(false); affiliation_ecole.setEnabled(false); affiliationFrais.setText(""); escompte.setEnabled(false); cas_special_note.setText(""); cas_special_note.setReadOnly(true); cas_special_pct.setValue(""); cas_special_pct.setReadOnly(true); escompteFrais.setText(""); produit.setEnabled(false); resident.setValue(false); resident.setEnabled(false); paypal.setValue(false); paypal.setEnabled(false); suppFrais.setText(""); frais.setText(""); solde.setValue(false); } /* depends on retrieveClubList having succeeded */ /** Takes data from ClientData into the form. */ private void loadClientData () { // cannot just test for getSelectedClubID() == null, // since it sets the selected club ID based on the client's data! if (jdb.allClubs == null || currentSession == null) { new Timer() { public void run() { loadClientData(); } }.schedule(100); return; } cid.setInnerText(cd.getID()); nom.setText(cd.getNom()); prenom.setText(cd.getPrenom()); Date ddns = cd.getDDN(); ddn_display.setText(ddns == null ? Constants.STD_DUMMY_DATE : Constants.STD_DATE_FORMAT.format(ddns)); ddn.setValue(ddns == null ? Constants.DB_DUMMY_DATE : Constants.DB_DATE_FORMAT.format(ddns)); sexe.setText(cd.getSexe()); adresse.setText(cd.getAdresse()); ville.setText(cd.getVille()); codePostal.setText(cd.getCodePostal()); tel.setText(cd.getTel()); courriel.setText(cd.getCourriel()); affiliation.setText(cd.getJudoQC()); carte_resident.setText(cd.getCarteResident()); nom_recu_impot.setText(cd.getNomRecuImpot()); tel_contact_urgence.setText(cd.getTelContactUrgence()); if (currentServiceNumber == -1) { addNewService(); } loadGradesData(); date_inscription.clear(); boolean hasToday = false, isToday = false; boolean hasThisSession = cd.getServiceFor(currentSession) != null; String todayString = Constants.DB_DATE_FORMAT.format(new Date()); for (int i = 0; i < cd.getServices().length(); i++) { ServiceData ssd = cd.getServices().get(i); if (todayString.equals(ssd.getDateInscription())) { hasToday = true; isToday = (i == currentServiceNumber); } date_inscription.addItem(Constants.dbToStdDate(ssd.getDateInscription()), Integer.toString(i)); } date_inscription.setSelectedIndex(currentServiceNumber); inscrire.setVisible(!hasToday && !hasThisSession); modifier.setVisible(!hasToday && hasThisSession); desinscrire.setVisible(hasThisSession); ServiceData sd = cd.getServices().get(currentServiceNumber); if (sd == null) { disableAllSessionEditingInfo(); return; } int clubIndex = jdb.getClubListBoxIndexByID(sd.getClubID()); if (-1 != clubIndex) { jdb.refreshSelectedClub(clubIndex); dropDownUserClubs.setSelectedIndex(clubIndex); } else { jdb.setStatus("Le client n'a pas de club enregistré."); return; } saisons.setText(sd.getSaisons()); verification.setValue(sd.getVerification()); int matching_index = 0; for (CoursSummary cs : backingCours) { if (cs.getId().equals(sd.getCours())) { cours.setSelectedIndex(matching_index); break; } matching_index++; } no_sessions.setItemSelected(sd.getSessionCount()-1, true); no_sessions.setEnabled(isToday); categorieFrais.setText(sd.getCategorieFrais()); sans_affiliation.setValue(sd.getSansAffiliation()); sans_affiliation.setEnabled(isToday); affiliation_initiation.setValue(sd.getAffiliationInitiation()); affiliation_initiation.setEnabled(isToday); affiliation_ecole.setValue(sd.getAffiliationEcole()); affiliation_ecole.setEnabled(isToday); affiliationFrais.setText(sd.getAffiliationFrais()); escompte.setEnabled(isToday); cas_special_note.setText(sd.getCasSpecialNote()); cas_special_note.setReadOnly(!isToday); cas_special_pct.setValue(sd.getCasSpecialPct()); cas_special_pct.setReadOnly(!isToday); escompteFrais.setText(sd.getEscompteFrais()); int idx = 0; for (ProduitSummary p : produitSummaries) { if (sd.getJudogi().equals(p.getId())) produit.setSelectedIndex(idx); idx++; } produit.setEnabled(isToday); resident.setValue(sd.getResident()); resident.setEnabled(isToday); paypal.setValue(sd.getPaypal()); paypal.setEnabled(isToday); suppFrais.setText(sd.getSuppFrais()); frais.setText(sd.getFrais()); solde.setValue(sd.getSolde()); updateDynamicFields(); } /** Puts data from the form back onto ClientData. */ private void saveClientData() { cd.setNom(nom.getText()); cd.setPrenom(prenom.getText()); cd.setDDNString(Constants.stdToDbDate(ddn_display.getText())); cd.setSexe(sexe.getText()); cd.setAdresse(adresse.getText()); cd.setVille(ville.getText()); cd.setCodePostal(codePostal.getText()); cd.setTel(tel.getText()); cd.setCourriel(courriel.getText()); cd.setJudoQC(affiliation.getText()); cd.setCarteResident(carte_resident.getText()); cd.setNomRecuImpot(nom_recu_impot.getText()); cd.setTelContactUrgence(tel_contact_urgence.getText()); if (currentServiceNumber == -1) return; if (cd.getServices() == null) return; ServiceData sd = cd.getServices().get(currentServiceNumber); if (currentServiceNumber < date_inscription.getItemCount()) sd.setDateInscription(removeCommas(Constants.stdToDbDate(date_inscription.getItemText(currentServiceNumber)))); sd.setSaisons(removeCommas(saisons.getText())); sd.setClubID(jdb.getSelectedClubID()); sd.setVerification(verification.getValue()); if (cours.getSelectedIndex() != -1) sd.setCours(cours.getValue(cours.getSelectedIndex())); sd.setSessionCount(no_sessions.getSelectedIndex()+1); sd.setCategorieFrais(stripDollars(categorieFrais.getText())); sd.setSansAffiliation(sans_affiliation.getValue()); sd.setAffiliationInitiation(affiliation_initiation.getValue()); sd.setAffiliationEcole(affiliation_ecole.getValue()); sd.setAffiliationFrais(stripDollars(affiliationFrais.getText())); if (escompte.getSelectedIndex() != -1) { sd.setEscompteId(escompte.getValue(escompte.getSelectedIndex())); } sd.setCasSpecialNote(removeCommas(cas_special_note.getText())); sd.setCasSpecialPct(stripDollars(cas_special_pct.getText())); sd.setEscompteFrais(stripDollars(escompteFrais.getText())); if (produit.getSelectedIndex() != -1) { sd.setJudogi(produit.getValue(produit.getSelectedIndex())); } sd.setResident(resident.getValue()); sd.setPaypal(paypal.getValue()); sd.setSuppFrais(stripDollars(suppFrais.getText())); sd.setFrais(stripDollars(frais.getText())); sd.setSolde(solde.getValue()); } /** Load grades data from ClientData into the gradeTable & grade/date_grade. */ private void loadGradesData() { gradeTable.clear(); gradeTable.resize(cd.getGrades().length()+2, 2); gradeTable.setText(0, 0, "Grade"); gradeTable.getCellFormatter().setStyleName(0, 0, "{style.lwp}"); gradeTable.setText(0, 1, "Date"); gradeTable.getCellFormatter().setStyleName(0, 1, "{style.lwp}"); JsArray<GradeData> grades_ = cd.getGrades(); GradeData[] grades = new GradeData[grades_.length()]; for (int i = 0; i < grades_.length(); i++) grades[i] = grades_.get(i); Arrays.sort(grades, new GradeData.GradeComparator()); for (int i = 0; i < grades.length; i++) { setGradesTableRow(i+1, grades[i].getGrade(), Constants.dbToStdDate(grades[i].getDateGrade())); } setGradesTableRow(grades.length+1, "", ""); grade.setText(cd.getGrade()); date_grade.setText(Constants.dbToStdDate(cd.getDateGrade())); } private void setGradesTableRow(int row, String grade, String dateGrade) { TextBox g = new TextBox(); TextBox gd = new TextBox(); g.setValue(grade); g.setVisibleLength(5); gd.setValue(dateGrade); gd.setVisibleLength(10); gradeTable.setWidget(row, 0, g); gradeTable.setWidget(row, 1, gd); ((TextBox)gradeTable.getWidget(row, 0)).addChangeHandler(ensureGradeSpace); ((TextBox)gradeTable.getWidget(row, 1)).addChangeHandler(ensureGradeSpace); } private TextBox getGradeTableTextBox(int row, int col) { return (TextBox) gradeTable.getWidget(row, col); } /** If there are any empty rows in the middle, move them up. * If there is no empty row at the end, create one. */ private ChangeHandler ensureGradeSpace = new ChangeHandler() { public void onChange(ChangeEvent e) { int rc = gradeTable.getRowCount(); for (int i = 1; i < rc-2; i++) { if (getGradeTableTextBox(i, 0).getText().equals("") && getGradeTableTextBox(i, 1).getText().equals("")) { for (int j = i; j < rc-1; j++) { getGradeTableTextBox(j, 0).setText(getGradeTableTextBox(j+1, 0).getText()); getGradeTableTextBox(j, 1).setText(getGradeTableTextBox(j+1, 1).getText()); } getGradeTableTextBox(rc-1, 0).setText(""); getGradeTableTextBox(rc-1, 1).setText(""); } } if (!getGradeTableTextBox(rc-1, 0).getText().equals("") && !getGradeTableTextBox(rc-1, 1).getText().equals("")) { gradeTable.resize(rc+1, 2); setGradesTableRow(rc, "", ""); } } }; /** Save data from the grades table into the ClientData. */ private void saveGradesData() { JsArray<GradeData> newGradesJS = JavaScriptObject.createArray().cast(); ArrayList<GradeData> newGradesList = new ArrayList<GradeData>(); for (int i = 1; i < gradeTable.getRowCount(); i++) { String g = getGradeTableTextBox(i, 0).getText(), gdate = getGradeTableTextBox(i, 1).getText(); if (!g.equals("")) { GradeData gd = GradeData.createObject().cast(); gd.setGrade(g.replaceAll(",", ";")); gd.setDateGrade(Constants.stdToDbDate(gdate).replaceAll(",", ";")); newGradesList.add(gd); } } Collections.sort(newGradesList, new GradeData.GradeComparator()); int gi = 0; for (GradeData gd : newGradesList) { newGradesJS.set(gi++, gd); } cd.setGrades(newGradesJS); } private String encodeGrades() { StringBuffer sb = new StringBuffer(); JsArray<GradeData> grades = cd.getGrades(); for (int i = 0; i < grades.length(); i++) { GradeData gd = grades.get(i); if (i > 0) sb.append(","); sb.append(gd.getGrade()); } return sb.toString(); } private String encodeGradeDates() { StringBuffer sb = new StringBuffer(); JsArray<GradeData> grades = cd.getGrades(); for (int i = 0; i < grades.length(); i++) { GradeData gd = grades.get(i); if (i > 0) sb.append(","); sb.append(gd.getDateGrade()); } return sb.toString(); } private final ChangeHandler directGradeChangeHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { // either no previous grade or no previous date-grade; // erase the old grade if (date_grade.getText().equals(Constants.STD_DUMMY_DATE) || cd.getGrade().equals("")) { date_grade.setText(Constants.STD_DATE_FORMAT.format(new Date())); setGradesTableRow(1, grade.getText(), date_grade.getText()); saveGradesData(); } else { // old grade set, and has date; keep the old grade-date in the array // and update the array. ensureGradeSpace.onChange(null); date_grade.setText(Constants.STD_DATE_FORMAT.format(new Date())); setGradesTableRow(0, grade.getText(), date_grade.getText()); saveGradesData(); } } }; private final ChangeHandler directGradeDateChangeHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { // TODO: if you change the grade-date, and grade is not empty, then // update the array. } }; private final ChangeHandler changeEscompteHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { if (escompte.getValue(escompte.getSelectedIndex()).equals("-1") && cas_special_pct.getValue().equals("-1")) cas_special_pct.setValue("0"); updateDynamicFields(); } }; private final ChangeHandler recomputeHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { updateDynamicFields(); } }; private final ChangeHandler changeSaisonHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { saveClientData(); currentServiceNumber = Integer.parseInt(date_inscription.getValue(date_inscription.getSelectedIndex())); loadClientData(); } }; private final ChangeHandler updateCopySibHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { updateCopySib(); } }; private final ValueChangeHandler<Boolean> recomputeValueHandler = new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> e) { updateDynamicFields(); } }; private final ChangeHandler clearEscomptePctAndRecomputeHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { cas_special_pct.setValue("-1"); regularizeEscompte(); updateDynamicFields(); } }; private final ChangeHandler clearEscompteAmtAndRecomputeHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { escompteFrais.setValue("-1"); regularizeEscompte(); updateDynamicFields(); } }; /** Create a new inscription for the current session. */ private final ClickHandler inscrireClickHandler = new ClickHandler() { public void onClick(ClickEvent e) { saveClientData(); ServiceData sd = cd.getServiceFor(currentSession); if (sd == null) { sd = ServiceData.newServiceData(); sd.setClubID(jdb.getSelectedClubID()); cd.getServices().push(sd); } // actually, sd != null should not occur; that should be modify. sd.inscrireAujourdhui(); currentServiceNumber = cd.getMostRecentServiceNumber(); loadClientData(); updateDynamicFields(); } }; /** Resets the date d'inscription for the current session to today's date. */ private final ClickHandler modifierClickHandler = new ClickHandler() { public void onClick(ClickEvent e) { ServiceData sd = cd.getServiceFor(currentSession); // shouldn't happen, actually. if (sd == null) return; saveClientData(); sd.inscrireAujourdhui(); currentServiceNumber = cd.getMostRecentServiceNumber(); loadClientData(); updateDynamicFields(); } }; private final ClickHandler desinscrireClickHandler = new ClickHandler() { public void onClick(ClickEvent e) { ServiceData sd = cd.getServiceFor(currentSession); if (sd == null) return; saveClientData(); JsArray<ServiceData> newServices = JavaScriptObject.createArray().cast(); for (int i = 0, j = 0; i < cd.getServices().length(); i++) { if (i != currentServiceNumber) newServices.set(j++, cd.getServices().get(i)); } cd.setServices(newServices); currentServiceNumber = cd.getMostRecentServiceNumber(); loadClientData(); updateDynamicFields(); } }; private int emptyGradeDates() { int empty = 0; for (int i = 1; i < gradeTable.getRowCount(); i++) { String gv = getGradeTableTextBox(i, 0).getText(); String gdv = getGradeTableTextBox(i, 1).getText(); if (gdv.equals(Constants.STD_DUMMY_DATE) || (!gv.equals("") && gv.equals(""))) empty++; } return empty; } private final ClickHandler saveGradesHandler = new ClickHandler() { public void onClick(ClickEvent e) { if (emptyGradeDates() > 1) { jdb.setStatus("Seulement une grade sans date est permise."); new Timer() { public void run() { jdb.clearStatus(); } }.schedule(2000); return; } saveGradesData(); loadGradesData(); gradeHistory.setVisible(false); } }; private final ClickHandler annulerGradesHandler = new ClickHandler() { public void onClick(ClickEvent e) { loadGradesData(); gradeHistory.setVisible(false); } }; /** We use , as a separator, so get rid of it in the input. */ private String removeCommas(String s) { return s.replaceAll(",", ";"); } // argh NumberFormat doesn't work for me at all! // stupidly, it says that you have to use ',' as the decimal separator, but people use both '.' and ','. private String stripDollars(String s) { StringBuffer ss = new StringBuffer(""); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '$' || s.charAt(i) == ' ' || s.charAt(i) == ')' || s.charAt(i) == '\u00a0') continue; if (s.charAt(i) == ',') ss.append("."); else if (s.charAt(i) == '(') ss.append("-"); else ss.append(s.charAt(i)); } return ss.toString(); } private static native float parseFloat(String s) /*-{ return parseFloat(s); }-*/; @SuppressWarnings("deprecation") private boolean sameDate(Date d1, Date d2) { return d1.getYear() == d2.getYear() && d1.getMonth() == d2.getMonth() && d1.getDate() == d2.getDate(); } /** Enables user to edit both % escompte and escompte amount by putting them in synch. * Works directly at the View level, not the Model level. */ private void regularizeEscompte() { ServiceData sd = cd.getServices().get(currentServiceNumber); ClubSummary cs = jdb.getClubSummaryByID(sd.getClubID()); double dCategorieFrais = CostCalculator.proratedFraisCours(currentSession, cd, sd, cs, clubPrix); if (CostCalculator.isCasSpecial(sd, CostCalculator.getApplicableEscompte(sd, escompteSummaries))) { NumberFormat nf = NumberFormat.getDecimalFormat(); if (cas_special_pct.getValue().equals("-1")) { float actualEscompteFrais = parseFloat(stripDollars(escompteFrais.getValue())); if (actualEscompteFrais > 0) { actualEscompteFrais *= -1; escompteFrais.setValue(nf.format(actualEscompteFrais)); } cas_special_pct.setValue(nf.format(-100 * actualEscompteFrais / dCategorieFrais)); } else if (escompteFrais.getValue().equals("-1")) { String cpct = stripDollars(cas_special_pct.getValue()); float fCpct = parseFloat(cpct); if (fCpct < 0) { fCpct *= -1; cas_special_pct.setValue(nf.format(fCpct)); } escompteFrais.setValue(nf.format(-fCpct * dCategorieFrais / 100.0)); } } } /** View-level method to pull information from ServiceData and put it onto the form in currency format. */ private void updateFrais() { NumberFormat cf = NumberFormat.getCurrencyFormat("CAD"); ServiceData sd = cd.getServices().get(currentServiceNumber); Date dateInscription = Constants.DB_DATE_FORMAT.parse(sd.getDateInscription()); int sessionCount = sd.getSessionCount(); semaines.setText(CostCalculator.getWeeksSummary(currentSession, dateInscription)); escompteFrais.setReadOnly (!CostCalculator.isCasSpecial(sd, CostCalculator.getApplicableEscompte(sd, escompteSummaries))); saisons.setText(JudoDB.getSessionIds(Constants.DB_DATE_FORMAT.parse(sd.getDateInscription()), sessionCount, sessionSummaries)); try { categorieFrais.setText (cf.format(Double.parseDouble(sd.getCategorieFrais()))); affiliationFrais.setText (cf.format(Double.parseDouble(sd.getAffiliationFrais()))); escompteFrais.setValue(cf.format(Double.parseDouble(sd.getEscompteFrais()))); suppFrais.setText(cf.format(Double.parseDouble(sd.getSuppFrais()))); frais.setText(cf.format(Double.parseDouble(sd.getFrais()))); } catch (NumberFormatException e) {} } private void updateCopySib() { copysib.setVisible(false); // check 1) address fields are empty and 2) there exists a sibling // Note that the following check relies on the data being saved // to the ClientData, which is true after you enter the birthday. ServiceData sd = cd.getServices().get(currentServiceNumber); ClubSummary clb = jdb.getClubSummaryByID(sd.getClubID()); if (!cd.isDefault(clb)) return; // XXX should do an allClients fetch upon load... if (jdb.allClients == null) return; for (ClientSummary cs : jdb.allClients) { // XXX don't copy data across clubs if (cs.getId().equals(cd.getID())) continue; String csn = cs.getNom().toLowerCase(); String n = nom.getText().toLowerCase(); if (n.equals(csn)) { sibid = cs.getId(); copysib.setVisible(true); } } } private void copysib() { final ClientWidget cp = new ClientWidget(Integer.parseInt(sibid), jdb); cp.onPopulated.add (new ChangeHandler () { public void onChange(ChangeEvent e) { cp.actuallyCopy(ClientWidget.this); } }); } private void actuallyCopy(ClientWidget d) { d.adresse.setText(adresse.getText()); d.ville.setText(ville.getText()); d.codePostal.setText(codePostal.getText()); d.tel.setText(tel.getText()); d.tel_contact_urgence.setText(tel_contact_urgence.getText()); d.courriel.setText(courriel.getText()); d.updateCopySib(); } private void hideEscompteResidentIfUnneeded(ClubSummary cs) { if (cs == null) return; String escompteResident = cs.getEscompteResident(); if (escompteResident == null || escompteResident.equals("") || escompteResident.equals("0")) { clientMain.getElementById("rabais_resident_label").getStyle().setProperty("display", "none"); resident.setVisible(false); } else { resident.setVisible(true); clientMain.getElementById("rabais_resident_label").getStyle().setProperty("display", "inline"); } } private void hidePaypalIfDisabled(ClubSummary cs) { if (cs == null) return; boolean showPaypal = cs.getAfficherPaypal(); if (!showPaypal) { clientMain.getElementById("frais_paypal_label").getStyle().setProperty("display", "none"); paypal.setVisible(false); } else { paypal.setVisible(true); clientMain.getElementById("frais_paypal_label").getStyle().setProperty("display", "inline"); } } private void updateDynamicFields() { saveClientData(); ServiceData sd = cd.getServices().get(currentServiceNumber); if (sd == null) return; ClubSummary cs = jdb.getClubSummaryByID(sd.getClubID()); hideEscompteResidentIfUnneeded(cs); hidePaypalIfDisabled(cs); ProduitSummary ps = CostCalculator.getApplicableProduit(sd, produitSummaries);; CostCalculator.recompute(currentSession, cd, sd, cs, ps, prorata.getValue(), clubPrix, escompteSummaries); /* view stuff here */ Display d = Display.NONE; int escompteIdx = escompte.getSelectedIndex(); if (escompteIdx != -1 && CostCalculator.isCasSpecial(sd, CostCalculator.getApplicableEscompte(sd, escompteSummaries))) d = Display.INLINE; ((Element)cas_special_note.getElement().getParentNode()).getStyle().setDisplay(d); ((Element)cas_special_pct.getElement().getParentNode()).getStyle().setDisplay(d); if (sd != null && !sd.getSaisons().equals("")) { String a = sd.getSaisons().split(" ")[0]; SessionSummary that_session = null; for (SessionSummary s : sessionSummaries) { if (a.equals(s.getAbbrev())) that_session = s; } if (that_session != null) { Constants.Division c = cd.getDivision(that_session.getYear()); categorie.setText(c.abbrev); } } updateBlurb(); updateFrais(); updateCopySib(); } private void encodeServices() { StringBuffer di = new StringBuffer(), sais = new StringBuffer(), v = new StringBuffer(), cf = new StringBuffer(), c = new StringBuffer(), sess = new StringBuffer(), e = new StringBuffer(), csn = new StringBuffer(), csp = new StringBuffer(), ef = new StringBuffer(), sa = new StringBuffer(), ai = new StringBuffer(), ae = new StringBuffer(), af = new StringBuffer(), j = new StringBuffer(), p = new StringBuffer(), n = new StringBuffer(), pp = new StringBuffer(), sf = new StringBuffer(), s = new StringBuffer(), f = new StringBuffer(), clubid = new StringBuffer(); JsArray<ServiceData> services = cd.getServices(); for (int i = 0; i < services.length(); i++) { ServiceData sd = services.get(i); di.append(sd.getDateInscription()+","); sais.append(sd.getSaisons()+","); v.append(sd.getVerification() ? "1," : "0,"); cf.append(sd.getCategorieFrais()+","); c.append(sd.getCours()+","); sess.append(Integer.toString(sd.getSessionCount())+","); e.append(sd.getEscompteId()+","); csn.append(sd.getCasSpecialNote()+","); csp.append(sd.getCasSpecialPct()+","); ef.append(sd.getEscompteFrais()+","); sa.append(sd.getSansAffiliation() ? "1," : "0,"); ai.append(sd.getAffiliationInitiation() ? "1," : "0,"); ae.append(sd.getAffiliationEcole() ? "1," : "0,"); af.append(sd.getAffiliationFrais()+","); j.append(sd.getJudogi()+","); // disabled passeport //p.append(sd.getPasseport()+","); p.append("0,"); n.append(sd.getResident()+","); pp.append(sd.getPaypal()+","); sf.append(sd.getSuppFrais()+","); s.append(sd.getSolde() ? "1,":"0,"); f.append(sd.getFrais()+","); clubid.append(sd.getClubID()+","); } date_inscription_encoded.setValue(di.toString()); saisons_encoded.setValue(sais.toString()); verification_encoded.setValue(v.toString()); categorieFrais_encoded.setValue(cf.toString()); cours_encoded.setValue(c.toString()); no_sessions_encoded.setValue(sess.toString()); escompte_encoded.setValue(e.toString()); cas_special_note_encoded.setValue(csn.toString()); cas_special_pct_encoded.setValue(csp.toString()); escompteFrais_encoded.setValue(ef.toString()); sans_affiliation_encoded.setValue(sa.toString()); affiliation_initiation_encoded.setValue(ai.toString()); affiliation_ecole_encoded.setValue(ae.toString()); affiliationFrais_encoded.setValue(af.toString()); judogi_encoded.setValue(j.toString()); resident_encoded.setValue(n.toString()); paypal_encoded.setValue(pp.toString()); suppFrais_encoded.setValue(sf.toString()); solde_encoded.setValue(s.toString()); frais_encoded.setValue(f.toString()); club_id_encoded.setValue(clubid.toString()); } private void pushClientDataToServer(final boolean leaveAfterPush) { if (cd.getNom().equals("") || cd.getPrenom().equals("")) { jdb.displayError("pas de nom ou prenom"); return; } guid = UUID.uuid(); sid.setValue(cd.getID()); guid_on_form.setValue(guid); grades_encoded.setValue(encodeGrades()); grade_dates_encoded.setValue(encodeGradeDates()); saveClientData(); loadClientData(); encodeServices(); // http://stackoverflow.com/questions/2699277/post-data-to-jsonp clientform.submit(); pushTries = 0; new Timer() { public void run() { pushOneClient(guid, leaveAfterPush); } }.schedule(500); } private void pushDeleteToServer() { // no need to delete if there's no ID yet. if (cd.getID().equals("")) return; guid = UUID.uuid(); sid.setValue(cd.getID()); guid_on_form.setValue(guid); deleted.setValue("true"); clientform.submit(); pushTries = 0; new Timer() { public void run() { pushOneClient(guid, true); } }.schedule(500); } private void loadCours(JsArray<CoursSummary> coursArray) { backingCours.clear(); cours.setVisibleItemCount(1); cours.clear(); for (int i = 0; i < coursArray.length(); i++) { CoursSummary c = coursArray.get(i); cours.addItem(c.getShortDesc(), c.getId()); backingCours.add(c); } } /* --- sessions --- */ List<SessionSummary> sessionSummaries = new ArrayList<SessionSummary>(); SessionSummary currentSession; void populateSessions(JsArray<SessionSummary> ss) { sessionSummaries.clear(); for (int i = 0; i < ss.length(); i++) { sessionSummaries.add(ss.get(i)); } currentSession = null; Date today = new Date(); for (SessionSummary s : sessionSummaries) { try { Date inscrBegin = Constants.DB_DATE_FORMAT.parse(s.getFirstSignupDate()); Date inscrEnd = Constants.DB_DATE_FORMAT.parse(s.getLastSignupDate()); if (today.after(inscrBegin) && today.before(inscrEnd)) { currentSession = s; continue; } } catch (IllegalArgumentException e) {} } } /* --- end sessions --- */ /* --- network functions --- */ /* depends on there being sessions */ public void retrieveClient(final int cid) { if (!gotSessions) { new Timer() { public void run() { retrieveClient(cid); } }.schedule(100); return; } String url = PULL_ONE_CLIENT_URL + "?id=" + cid; RequestCallback rc = jdb.createRequestCallback(new JudoDB.Function() { public void eval(String s) { if (s.equals("")) { ClientWidget.this.jdb.displayError("ce client n'existe pas"); new Timer() { public void run() { ClientWidget.this.jdb.popMode(); } }.schedule(2000); return; } ClientWidget.this.cd = JsonUtils.<ClientData>safeEval(s); currentServiceNumber = cd.getMostRecentServiceNumber(); jdb.clearStatus(); loadClientData(); for (ChangeHandler ch : onPopulated) { ch.onChange(null); } } }); jdb.retrieve(url, rc); } /* depends on there being a selected club */ private boolean gotSessions = false; public void retrieveSessions() { if (jdb.getSelectedClubID() == null) { new Timer() { public void run() { retrieveSessions(); } }.schedule(100); return; } String url = JudoDB.PULL_SESSIONS_URL; url += "?club="+jdb.getSelectedClubID(); RequestCallback rc = jdb.createRequestCallback(new JudoDB.Function() { public void eval(String s) { gotSessions = true; populateSessions(JsonUtils.<JsArray<SessionSummary>>safeEval(s)); } }); jdb.retrieve(url, rc); } /* depends on retrieveClubList() and retrieveSessions() having succeeded */ /* also depends on there being a selected club */ public void retrieveClubPrix() { if (jdb.getSelectedClubID() == null || !gotSessions) { new Timer() { public void run() { retrieveClubPrix(); } }.schedule(100); return; } clubPrix = null; ClubSummary cs = jdb.getClubSummaryByID(jdb.getSelectedClubID()); String url = JudoDB.PULL_CLUB_PRIX_URL + "?numero_club=" + cs.getNumeroClub() + "&session_seqno=" + currentSession.getSeqno(); RequestCallback rc = jdb.createRequestCallback(new JudoDB.Function() { public void eval(String s) { JsArray<ClubPrix> cp = JsonUtils.<JsArray<ClubPrix>>safeEval(s); clubPrix = new ClubPrix[cp.length()]; for (int i = 0; i < cp.length(); i++) clubPrix[i] = cp.get(i); } }); jdb.retrieve(url, rc); } /* depends on retrieveClubList() and retrieveSessions() having succeeded */ public void retrieveCours() { if (jdb.getSelectedClubID() == null || !gotSessions) { new Timer() { public void run() { retrieveCours(); } }.schedule(100); return; } backingCours.clear(); ClubSummary cs = jdb.getClubSummaryByID(jdb.getSelectedClubID()); String url = JudoDB.PULL_CLUB_COURS_URL + "?numero_club=" + cs.getNumeroClub() + "&session_seqno=" + currentSession.getSeqno(); RequestCallback rc = jdb.createRequestCallback(new JudoDB.Function() { public void eval(String s) { loadCours (JsonUtils.<JsArray<CoursSummary>>safeEval(s)); } }); jdb.retrieve(url, rc); } /* depends on retrieveClubList() and retrieveSessions() having succeeded */ public void retrieveEscomptes() { if (jdb.getSelectedClubID() == null || !gotSessions) { new Timer() { public void run() { retrieveEscomptes(); } }.schedule(100); return; } escompte.clear(); escompteSummaries.clear(); String url = JudoDB.PULL_ESCOMPTE_URL + "?club_id=" + jdb.getSelectedClubID(); RequestCallback rc = jdb.createRequestCallback(new JudoDB.Function() { public void eval(String s) { loadEscomptes (JsonUtils.<JsArray<EscompteSummary>>safeEval(s)); } }); jdb.retrieve(url, rc); } /* depends on retrieveClubList() having succeeded */ /* technically does not require sessions, but adding it removes a race condition */ public void retrieveProduits() { if (jdb.getSelectedClubID() == null || !gotSessions) { new Timer() { public void run() { retrieveProduits(); } }.schedule(100); return; } produit.clear(); produitSummaries.clear(); String url = JudoDB.PULL_PRODUIT_URL + "?club_id=" + jdb.getSelectedClubID(); RequestCallback rc = jdb.createRequestCallback(new JudoDB.Function() { public void eval(String s) { loadProduits (JsonUtils.<JsArray<ProduitSummary>>safeEval(s)); } }); jdb.retrieve(url, rc); } public void pushOneClient(final String guid, final boolean leaveAfterPush) { String url = CONFIRM_PUSH_URL + "?guid=" + guid; RequestCallback rc = jdb.createRequestCallback(new JudoDB.Function() { public void eval(String s) { ConfirmResponseObject cro = JsonUtils.<ConfirmResponseObject>safeEval(s); String rs = cro.getResult(); if (rs.equals("NOT_YET")) { if (pushTries >= 3) { jdb.displayError("le serveur n'a pas accepté les données"); return; } new Timer() { public void run() { pushOneClient(guid, leaveAfterPush); } }.schedule(2000); pushTries++; } else { jdb.setStatus("Sauvegardé."); jdb.invalidateListWidget(); new Timer() { public void run() { jdb.clearStatus(); if (leaveAfterPush) ClientWidget.this.jdb.popMode(); } }.schedule(2000); if (cd.getID() == null || cd.getID().equals("")) { cd.setID(Integer.toString(cro.getSid())); loadClientData(); } } new Timer() { public void run() { jdb.clearStatus(); } }.schedule(2000); } }); jdb.retrieve(url, rc); } }
more robustness
src/ca/patricklam/judodb/client/ClientWidget.java
more robustness
<ide><path>rc/ca/patricklam/judodb/client/ClientWidget.java <ide> <ide> private void loadEscomptes(JsArray<EscompteSummary> escompteArray) { <ide> HashMap<String, Integer> escompteIdxToSeqno = new HashMap<String, Integer>(); <del> int idx = 0; <ide> escompte.clear(); escompteSummaries.clear(); <ide> escompte.addItem(Constants.EMPTY_ESCOMPTE.getNom(), Constants.EMPTY_ESCOMPTE.getId()); <ide> escompteSummaries.add(Constants.EMPTY_ESCOMPTE); <add> int idx = 1; <ide> for (int i = 0; i < escompteArray.length(); i++) { <ide> EscompteSummary e = escompteArray.get(i); <ide> if (e.getClubId().equals("0") || e.getClubId().equals(jdb.getSelectedClubID())) { <ide> <ide> private void loadProduits(JsArray<ProduitSummary> produitArray) { <ide> HashMap<String, Integer> produitIdxToSeqno = new HashMap<String, Integer>(); <del> int idx = 0; <ide> produit.clear(); produitSummaries.clear(); <ide> produit.addItem(Constants.EMPTY_PRODUIT.getNom(), Constants.EMPTY_PRODUIT.getId()); <ide> produitSummaries.add(Constants.EMPTY_PRODUIT); <add> int idx = 1; <add> if (produitArray == null) <add> com.google.gwt.user.client.Window.alert("produitArray is null"); <add> <ide> for (int i = 0; i < produitArray.length(); i++) { <ide> ProduitSummary e = produitArray.get(i); <ide> if (e.getClubId().equals("0") || e.getClubId().equals(jdb.getSelectedClubID())) { <ide> } <ide> } <ide> ServiceData sd = cd.getServices().get(currentServiceNumber); <add> if (sd == null) return; <ide> String produitIndex = sd.getJudogi(); <ide> if (produitIdxToSeqno.get(produitIndex) != null) <ide> produit.setSelectedIndex(produitIdxToSeqno.get(produitIndex));
Java
apache-2.0
8656c30c128dd067c51dabcad3a6019eff6880b8
0
hal/hal.next,hal/hal.next,hal/hal.next,michpetrov/hal.next,hpehl/hal.next,hpehl/hal.next,michpetrov/hal.next,michpetrov/hal.next,hpehl/hal.next,michpetrov/hal.next,hpehl/hal.next,hal/hal.next
/* * Copyright 2015-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.hal.core.mbui.form; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import org.jboss.hal.dmr.ModelNode; import org.jboss.hal.meta.Metadata; import org.jetbrains.annotations.NonNls; import static java.util.Arrays.asList; public class OperationFormBuilder<T extends ModelNode> { private final String id; private final Metadata metadata; private final String operation; private final LinkedHashSet<String> includes; private final Set<String> excludes; public OperationFormBuilder(@NonNls String id, Metadata metadata, String operation) { this.id = id; this.metadata = metadata; this.operation = operation; this.includes = new LinkedHashSet<>(); this.excludes = new HashSet<>(); } public OperationFormBuilder<T> include(String[] attributes) { includes.addAll(Arrays.asList(attributes)); return this; } public OperationFormBuilder<T> include(Iterable<String> attributes) { //noinspection ResultOfMethodCallIgnored Iterables.addAll(includes, attributes); return this; } public OperationFormBuilder<T> include(@NonNls String first, @NonNls String... rest) { includes.addAll(Lists.asList(first, rest)); return this; } public OperationFormBuilder<T> exclude(String[] attributes) { excludes.addAll(asList(attributes)); return this; } public OperationFormBuilder<T> exclude(Iterable<String> attributes) { Iterables.addAll(excludes, attributes); return this; } public OperationFormBuilder<T> exclude(@NonNls String first, @NonNls String... rest) { excludes.addAll(Lists.asList(first, rest)); return this; } public ModelNodeForm<T> build() { return new ModelNodeForm.Builder<T>(id, metadata.forOperation(operation)) .include(includes) .exclude(excludes) .addOnly() .build(); } }
core/src/main/java/org/jboss/hal/core/mbui/form/OperationFormBuilder.java
/* * Copyright 2015-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.hal.core.mbui.form; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import org.jboss.hal.dmr.ModelNode; import org.jboss.hal.meta.Metadata; import org.jetbrains.annotations.NonNls; import static java.util.Arrays.asList; public class OperationFormBuilder<T extends ModelNode> { private final String id; private final Metadata metadata; private final String operation; private final LinkedHashSet<String> includes; private final Set<String> excludes; public OperationFormBuilder(@NonNls final String id, final Metadata metadata, final String operation) { this.id = id; this.metadata = metadata; this.operation = operation; this.includes = new LinkedHashSet<>(); this.excludes = new HashSet<>(); } public OperationFormBuilder<T> include(final String[] attributes) { includes.addAll(Arrays.asList(attributes)); return this; } public OperationFormBuilder<T> include(final Iterable<String> attributes) { //noinspection ResultOfMethodCallIgnored Iterables.addAll(includes, attributes); return this; } public OperationFormBuilder<T> include(@NonNls final String first, @NonNls final String... rest) { includes.addAll(Lists.asList(first, rest)); return this; } public OperationFormBuilder<T> exclude(final String[] attributes) { excludes.addAll(asList(attributes)); return this; } public OperationFormBuilder<T> exclude(final Iterable<String> attributes) { Iterables.addAll(excludes, attributes); return this; } public OperationFormBuilder<T> exclude(@NonNls final String first, @NonNls final String... rest) { excludes.addAll(Lists.asList(first, rest)); return this; } public ModelNodeForm<T> build() { return new ModelNodeForm.Builder<T>(id, metadata.forOperation(operation)) .include(includes) .exclude(excludes) .addOnly() .build(); } }
Code format
core/src/main/java/org/jboss/hal/core/mbui/form/OperationFormBuilder.java
Code format
<ide><path>ore/src/main/java/org/jboss/hal/core/mbui/form/OperationFormBuilder.java <ide> private final LinkedHashSet<String> includes; <ide> private final Set<String> excludes; <ide> <del> public OperationFormBuilder(@NonNls final String id, final Metadata metadata, final String operation) { <add> public OperationFormBuilder(@NonNls String id, Metadata metadata, String operation) { <ide> this.id = id; <ide> this.metadata = metadata; <ide> this.operation = operation; <ide> this.excludes = new HashSet<>(); <ide> } <ide> <del> public OperationFormBuilder<T> include(final String[] attributes) { <add> public OperationFormBuilder<T> include(String[] attributes) { <ide> includes.addAll(Arrays.asList(attributes)); <ide> return this; <ide> } <ide> <del> public OperationFormBuilder<T> include(final Iterable<String> attributes) { <add> public OperationFormBuilder<T> include(Iterable<String> attributes) { <ide> //noinspection ResultOfMethodCallIgnored <ide> Iterables.addAll(includes, attributes); <ide> return this; <ide> } <ide> <del> public OperationFormBuilder<T> include(@NonNls final String first, @NonNls final String... rest) { <add> public OperationFormBuilder<T> include(@NonNls String first, @NonNls String... rest) { <ide> includes.addAll(Lists.asList(first, rest)); <ide> return this; <ide> } <ide> <del> public OperationFormBuilder<T> exclude(final String[] attributes) { <add> public OperationFormBuilder<T> exclude(String[] attributes) { <ide> excludes.addAll(asList(attributes)); <ide> return this; <ide> } <ide> <del> public OperationFormBuilder<T> exclude(final Iterable<String> attributes) { <add> public OperationFormBuilder<T> exclude(Iterable<String> attributes) { <ide> Iterables.addAll(excludes, attributes); <ide> return this; <ide> } <ide> <del> public OperationFormBuilder<T> exclude(@NonNls final String first, @NonNls final String... rest) { <add> public OperationFormBuilder<T> exclude(@NonNls String first, @NonNls String... rest) { <ide> excludes.addAll(Lists.asList(first, rest)); <ide> return this; <ide> }
JavaScript
mit
c735ac229eb5abc71c15c66ef1c5a8f76b43790d
0
developit/preact,developit/preact
/** * Copy all properties from `props` onto `obj`. * @param {object} obj Object onto which properties should be copied. * @param {object} props Object from which to copy properties. * @returns {object} * @private */ export function extend(obj, props) { for (let i in props) obj[i] = props[i]; return obj; } /** Invoke or update a ref, depending on whether it is a function or object ref. * @param {object|function} [ref=null] * @param {any} [value] */ export function applyRef(ref, value) { if (ref) { if (typeof ref=='function') ref(value); else ref.current = value; } } /** * Call a function asynchronously, as soon as possible. Makes * use of HTML Promise to schedule the callback if available, * otherwise falling back to `setTimeout` (mainly for IE<11). * @type {(callback: function) => void} */ export const defer = typeof Promise=='function' ? Promise.resolve().then.bind(Promise.resolve()) : setTimeout;
src/util.js
/** * Copy all properties from `props` onto `obj`. * @param {object} obj Object onto which properties should be copied. * @param {object} props Object from which to copy properties. * @returns {object} * @private */ export function extend(obj, props) { for (let i in props) obj[i] = props[i]; return obj; } /** Invoke or update a ref, depending on whether it is a function or object ref. * @param {object|function} [ref=null] * @param {any} [value] */ export function applyRef(ref, value) { if (ref!=null&&ref!==false) { if (typeof ref=='function') ref(value); else ref.current = value; } } /** * Call a function asynchronously, as soon as possible. Makes * use of HTML Promise to schedule the callback if available, * otherwise falling back to `setTimeout` (mainly for IE<11). * @type {(callback: function) => void} */ export const defer = typeof Promise=='function' ? Promise.resolve().then.bind(Promise.resolve()) : setTimeout;
Change the if condition to check if ref is defined, rather than explicitly null or false.
src/util.js
Change the if condition to check if ref is defined, rather than explicitly null or false.
<ide><path>rc/util.js <ide> * @param {any} [value] <ide> */ <ide> export function applyRef(ref, value) { <del> if (ref!=null&&ref!==false) { <add> if (ref) { <ide> if (typeof ref=='function') ref(value); <ide> else ref.current = value; <ide> }
Java
mit
471809ba483bfbf993e0acd8b3dd284bec189dfc
0
cloud-of-things/cot-java-rest-sdk
package com.telekom.m2m.cot.restsdk; import java.io.IOException; import java.io.InterruptedIOException; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.util.Base64; import java.util.concurrent.TimeUnit; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSyntaxException; import com.telekom.m2m.cot.restsdk.smartrest.SmartRequest; import com.telekom.m2m.cot.restsdk.smartrest.SmartResponse; import com.telekom.m2m.cot.restsdk.util.CotSdkException; import com.telekom.m2m.cot.restsdk.util.GsonUtils; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; /** * Created by Patrick Steinert on 30.01.16. */ public class CloudOfThingsRestClient { private final Gson gson = GsonUtils.createGson(); private final String encodedAuthString; private final String host; protected OkHttpClient client; // This is an automatic clone of {@link #client}, which can have it's own, much longer, timeouts, and because we // don't want a real time server advice to change timeout behaviour for the whole application: protected OkHttpClient realTimeClient; // The read timeout for the realTimeClient. It should always be set by the caller, but we store it to detect changes: protected Integer realTimeTimeout = 60000; /** * @param okHttpClient HTTP client that is used to interact with the API. * @param host URL to connect to. Must contain scheme and host, e.g. https://username.int2-ram.m2m.telekom.com * @param user Username for authentication. * @param password Password for authentication. */ public CloudOfThingsRestClient(OkHttpClient okHttpClient, String host, String user, String password) { this.host = host; try { encodedAuthString = Base64.getEncoder().encodeToString((user + ":" + password).getBytes("utf-8")); } catch (UnsupportedEncodingException e) { throw new CotSdkException("Error generating auth string.", e); } client = okHttpClient; } /** * Executes an HTTP POST request and parses the response Header. * Response header 'Location' will be split to get the ID of the object (mostly created). * * @param json * Request body, needs to be a json object correlating to the * contentType. * @param api * the REST API string. * @param contentType * the Content-Type of the JSON Object. * @return the id of the Object. */ public String doRequestWithIdResponse(String json, String api, String contentType, String accept) { Response response = null; try { RequestBody body = RequestBody.create(MediaType.parse(contentType), json); Request request = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .addHeader("Content-Type", contentType) .addHeader("Accept", accept) // .url(tenant + ".test-ram.m2m.telekom.com/" + api) .url(host + "/" + api) .post(body) .build(); response = client.newCall(request).execute(); if (!response.isSuccessful()) { final String err = getErrorMessage(response); throw new CotSdkException(response.code(), err); } String location = response.header("Location"); String result = null; if (location != null) { String[] pathParts = location.split("\\/"); result = pathParts[pathParts.length - 1]; } return result; } catch (CotSdkException e) { // We need to rethrow this in order to not loose the status code. throw e; } catch (Exception e) { throw new CotSdkException("Problem: " + e.getMessage(), e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } /** * Executes an HTTP POST request and returns the response body as String. * * @param json * Request body, needs to be a json object correlating to the * contentType. * @param api * the REST API string. * @param contentType * the Content-Type of the JSON Object. * @param accept * the Accept header for the request * @return the received JSON response body. */ public String doPostRequest(String json, String api, String contentType, String accept) { RequestBody body = RequestBody.create(MediaType.parse(contentType), json); Request.Builder requestBuilder = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .url(host + "/" + api) .post(body); if (contentType != null) { requestBuilder.addHeader("Content-Type", contentType); } if (accept != null) { requestBuilder.addHeader("Accept", accept); } Response response = null; try { response = client.newCall(requestBuilder.build()).execute(); if (!response.isSuccessful()) { final String err = getErrorMessage(response); throw new CotSdkException(response.code(), err); } String bodyContent = response.body().string(); return bodyContent; } catch (IOException e) { throw new CotSdkException("Unexpected error during POST request.", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } /** * Executes a multipart form upload of a string and returns the response body as String. * * @param file Request body, i.e. the first and only form part. * @param name The name of the form field. * @param api the URL path (without leading /) * @param contentType a String with the Content-Type to set in header of the request. * @return the response body */ public String doFormUpload(String file, String name, String api, String contentType) { RequestBody body = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart(name, "", RequestBody.create(MultipartBody.FORM, file)) .build(); Request request = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .addHeader("Content-Type", contentType) .url(host + "/" + api) .post(body) .build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) { final String err = getErrorMessage(response); throw new CotSdkException(response.code(), err); } String bodyContent = response.body().string(); return bodyContent; } catch (IOException e) { throw new CotSdkException("Unexpected error during POST request.", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } /** * Executes an HTTP POST request and returns the response body as String. * * @param files array of byte[], one for each form field. * @param names the names of the form field, same order as files. * @param api the URL path (without leading /) * @return the ID from the Location header (for newly created objects), or null if there's no Location header. */ public String doFormUpload(byte[][] files, String[] names, String api) { if (files.length != names.length) { throw new CotSdkException("Need to have the same number of files and names to upload (actual: "+files.length+" != "+names.length); } MultipartBody.Builder bodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); for (int i=0; i<names.length; i++) { bodyBuilder.addFormDataPart(names[i], "", RequestBody.create(MultipartBody.FORM, files[i])); } Request request = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .addHeader("Content-Type", "text/foo") .url(host + "/" + api) .post(bodyBuilder.build()) .build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) { final String err = getErrorMessage(response); throw new CotSdkException(response.code(), err); } String location = response.header("Location"); String result = null; if (location != null) { String[] pathParts = location.split("\\/"); result = pathParts[pathParts.length - 1]; } return result; } catch (IOException e) { throw new CotSdkException("Unexpected error during POST request.", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } /** * Do a real time polling request, i.e. the connect call. We use a different client for this call, * because it's supposed to have very long timeouts, unsuitable for regular requests. * Regular real time polling and smart rest real time polling share the same client (and therefore timeout) * because it is to be expected that a client will probably use either one of them, but not both. * * @param json * Request body, needs to be a json object correlating to the * contentType. * @param api * the REST API string. * @param contentType * the Content-Type of the JSON Object. * @param timeout the new timeout for real time requests. null = don't change the current timeout * * @return the received JSON response body. */ public String doRealTimePollingRequest(String json, String api, String contentType, Integer timeout) { RequestBody body = RequestBody.create(MediaType.parse(contentType), json); Request request = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .addHeader("Content-Type", contentType) .addHeader("Accept", contentType) .url(host + "/" + api) .post(body) .build(); // For the first request, or any subsequent request that wants to change the timeout, we need to get a new client: if ((realTimeClient == null) || ((timeout != null) && (!timeout.equals(realTimeTimeout)))) { realTimeTimeout = (timeout != null) ? timeout : realTimeTimeout; realTimeClient = client.newBuilder().readTimeout(realTimeTimeout, TimeUnit.MILLISECONDS).build(); } Response response = null; try { response = realTimeClient.newCall(request).execute(); if (!response.isSuccessful()) { final String err = getErrorMessage(response); throw new CotSdkException(response.code(), err); } return response.body().string(); } catch (InterruptedIOException e) { // That's ok and normal. There just weren't any new notifications. return null; } catch (IOException e) { throw new CotSdkException("Unexpected error during POST request.", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } /** * Do a SmartREST real time request. * * @param smartRequest the request with meta information and lines to send to platform. * * @return the SmartResponse */ public SmartResponse doSmartRealTimeRequest(SmartRequest smartRequest) { RequestBody body = RequestBody.create(null, smartRequest.getBody()); Request.Builder builder = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .addHeader("X-Id", smartRequest.getXId()) .url(host + "/cep/realtime") // Same real time endpoint handles smart and regular requests. .post(body); Request request = builder.build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new CotSdkException(response.code(), "Unexpected response code for POST request."); } String responseBody = response.body().string(); return new SmartResponse(responseBody); } catch (IOException e) { throw new CotSdkException("Unexpected error during POST request.", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } /** * Do a SmartREST real time polling request, i.e. the connect call. We use a different client for this call, * because it's supposed to have very long timeouts, unsuitable for regular requests. * Regular real time polling and smart rest real time polling share the same client (and therefore timeout) * because it is to be expected that a client will probably use either one of them, but not both. * * @param smartRequest the request with meta information and lines to send to platform. * @param timeout the new timeout for real time requests. null = don't change the current timeout * * @return the SmartResponse */ public SmartResponse doSmartRealTimePollingRequest(SmartRequest smartRequest, Integer timeout) { RequestBody body = RequestBody.create(null, smartRequest.getBody()); Request request = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .addHeader("X-Id", smartRequest.getXId()) .url(host + "/cep/realtime") // Same real time endpoint handles smart and regular requests. .post(body) .build(); // For the first request, or any subsequent request that wants to change the timeout, we need to get a new client: if ((realTimeClient == null) || ((timeout != null) && (!timeout.equals(realTimeTimeout)))) { realTimeTimeout = (timeout != null) ? timeout : realTimeTimeout; realTimeClient = client.newBuilder().readTimeout(realTimeTimeout, TimeUnit.MILLISECONDS).build(); } Response response = null; try { response = realTimeClient.newCall(request).execute(); if (!response.isSuccessful()) { throw new CotSdkException(response.code(), "Unexpected response code for POST request."); } String responseBody = response.body().string(); return new SmartResponse(responseBody); } catch (InterruptedIOException e) { // That's ok and normal. There just weren't any new notifications. return null; } catch (IOException e) { throw new CotSdkException("Unexpected error during POST request.", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } /** * Do a SmartREST-request. * * @param smartRequest the request with meta information and lines to send to platform. * * @return the SmartResponse */ public SmartResponse doSmartRequest(SmartRequest smartRequest) { RequestBody body = RequestBody.create(null, smartRequest.getBody()); Request.Builder builder = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .url(host + "/s") // SmartRest-endpoint is always just "/s". .post(body); //TODO: do we need to not send the header at all, in that case? if (smartRequest.getXId() != null && !smartRequest.getXId().isEmpty()) { builder.addHeader("X-Id", smartRequest.getXId()); } // PERSISTENT processing mode is the default, so we don't need to handle it in the else-case. if (smartRequest.getProcessingMode() != null) { builder.addHeader("X-Cumulocity-Processing-Mode", smartRequest.getProcessingMode().name()); } Request request = builder.build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new CotSdkException(response.code(), "Unexpected response code for POST request."); } return new SmartResponse(response.body().string()); } catch (IOException e) { throw new CotSdkException("Unexpected error during POST request.", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } public String getResponse(String id, String api, String accept) { byte[] result = getResponseInBytes(id, api, accept); if (result != null){ return new String(result); } return null; } /** * get the response of a request in bytes * @param id part of url for request * @param api part of the url for request * @param accept accpet header for request * @return the response from cloud of things */ public byte[] getResponseInBytes(String id, String api, String accept){ Request.Builder requestBuilder = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .url(host + "/" + api + "/" + id); if (accept != null) { requestBuilder.addHeader("Accept", accept); } Response response = null; try { response = client.newCall(requestBuilder.build()).execute(); byte[] result = null; if (response.isSuccessful()) { result = response.body().bytes(); } else { if (response.code() != HttpURLConnection.HTTP_NOT_FOUND) { throw new CotSdkException(response.code(), "Error in request."); } } return result; } catch (Exception e) { throw new CotSdkException("Error in request", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } public String getResponse(String api) { Request request = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .url(host + "/" + api) .build(); Response response = null; try { response = client.newCall(request).execute(); String result; if (response.isSuccessful()) { result = response.body().string(); } else { final String err = getErrorMessage(response); throw new CotSdkException(response.code(), err); } return result; } catch (CotSdkException e) { // We need to rethrow this in order to not loose the status code. throw e; } catch (Exception e) { throw new CotSdkException("Error in request", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } /** * Execute a PUT request. * * @param data the body to send * @param path the URL path (without leading '/') * @param contentType the Content-Type header * @return the response body, if there was one (empty string otherwise) */ public String doPutRequest(String data, String path, String contentType) { return doPutRequest(data, path, contentType, "*/*"); } /** * Execute a PUT request. * * @param data the body to send * @param path the URL path (without leading '/') * @param contentType the Content-Type header * @param accept the Accept header (may be null) * @return the response body, if there was one (empty string otherwise) */ public String doPutRequest(String data, String path, String contentType, String accept) { RequestBody requestBody = RequestBody.create(MediaType.parse(contentType), data); Request.Builder requestBuilder = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .addHeader("Content-Type", contentType) .url(host + "/" + path) .put(requestBody); if (accept != null) { requestBuilder.addHeader("Accept", accept); } Request request = requestBuilder.build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new CotSdkException(response.code(), "Requested returned error code"); } ResponseBody responseBody = response.body(); return (responseBody == null) ? "" : responseBody.string(); } catch (Exception e) { throw new CotSdkException("Error in request", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } /** * Execute a PUT request that will result in a new or changed ID. * * @param data the body to send in bytes * @param path the URL path (without leading '/') * @param contentType the Content-Type header * @return the ID from the Location header (for newly created objects), or null if there's no Location header. */ public String doPutRequestWithIdResponseInBytes(byte[] data, String path, String contentType) { RequestBody requestBody = RequestBody.create(MediaType.parse(contentType), data); Request.Builder requestBuilder = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .addHeader("Content-Type", contentType) .url(host + "/" + path) .put(requestBody); Request request = requestBuilder.build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new CotSdkException(response.code(), "Requested returned error code"); } String location = response.header("Location"); String result = null; if (location != null) { String[] pathParts = location.split("\\/"); result = pathParts[pathParts.length - 1]; } return result; } catch (Exception e) { throw new CotSdkException("Error in request", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } /** * Execute a PUT request that will result in a new or changed ID. * * @param data the body to send * @param path the URL path (without leading '/') * @param contentType the Content-Type header * @return the ID from the Location header (for newly created objects), or null if there's no Location header. */ public String doPutRequestWithIdResponse(String data, String path, String contentType) { return doPutRequestWithIdResponseInBytes(data.getBytes(), path, contentType); } public void delete(String id, String api) { Request request = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .url(host + "/" + api + "/" + id) .delete() .build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new CotSdkException(response.code(), "Error in delete with ID '" + id + "' (see https://http.cat/" + response.code() + ")"); } } catch( CotSdkException e) { // We need to rethrow this in order to not loose the status code. throw e; } catch (Exception e) { throw new CotSdkException("Error in request", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } public void deleteBy(final String filter, final String api) { final Request request = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .url(host + "/" + api + "?" + filter) .delete() .build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new CotSdkException(response.code(), "Error in delete by criteria '" + filter + "'"); } } catch (CotSdkException e) { // We need to rethrow this in order to not loose the status code. throw e; } catch (Exception e) { throw new CotSdkException("Error in request: " + e.getMessage(), e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } public void delete(String url) { Request request = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .url(url) .delete() .build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new CotSdkException(response.code(), "Error in delete with URL '" + url + "' (see https://http.cat/" + response.code() + ")"); } } catch (Exception e) { throw new CotSdkException("Error in request", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } private String getErrorMessage(final Response response) throws IOException { String errorMessage = "Request failed."; String body = ""; try { body = response.body().string(); final JsonElement e = gson.fromJson(body, JsonElement.class); if (e instanceof JsonObject) { JsonObject o = (JsonObject) e; if (o.has("error")) { errorMessage += " Platform provided details: '" + o.get("error") + "'"; } } else if (e instanceof JsonPrimitive) { JsonPrimitive p = (JsonPrimitive) e; errorMessage += " Platform provided details: '" + p + "'"; } } catch (JsonSyntaxException ex) { errorMessage += " " + body; } catch (NullPointerException ex) { errorMessage += " Response body was empty."; } return errorMessage; } private void closeResponseBodyIfResponseAndBodyNotNull(final Response response) { if (response != null && response.body() != null) { response.body().close(); } } }
src/main/java/com/telekom/m2m/cot/restsdk/CloudOfThingsRestClient.java
package com.telekom.m2m.cot.restsdk; import java.io.IOException; import java.io.InterruptedIOException; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.util.Base64; import java.util.concurrent.TimeUnit; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSyntaxException; import com.telekom.m2m.cot.restsdk.smartrest.SmartRequest; import com.telekom.m2m.cot.restsdk.smartrest.SmartResponse; import com.telekom.m2m.cot.restsdk.util.CotSdkException; import com.telekom.m2m.cot.restsdk.util.GsonUtils; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; /** * Created by Patrick Steinert on 30.01.16. */ public class CloudOfThingsRestClient { private final Gson gson = GsonUtils.createGson(); private final String encodedAuthString; private final String host; protected OkHttpClient client; // This is an automatic clone of {@link #client}, which can have it's own, much longer, timeouts, and because we // don't want a real time server advice to change timeout behaviour for the whole application: protected OkHttpClient realTimeClient; // The read timeout for the realTimeClient. It should always be set by the caller, but we store it to detect changes: protected Integer realTimeTimeout = 60000; /** * @param okHttpClient HTTP client that is used to interact with the API. * @param host URL to connect to. Must contain scheme and host, e.g. https://username.int2-ram.m2m.telekom.com * @param user Username for authentication. * @param password Password for authentication. */ public CloudOfThingsRestClient(OkHttpClient okHttpClient, String host, String user, String password) { this.host = host; try { encodedAuthString = Base64.getEncoder().encodeToString((user + ":" + password).getBytes("utf-8")); } catch (UnsupportedEncodingException e) { throw new CotSdkException("Error generating auth string.", e); } client = okHttpClient; } /** * Executes an HTTP POST request and parses the response Header. * Response header 'Location' will be split to get the ID of the object (mostly created). * * @param json * Request body, needs to be a json object correlating to the * contentType. * @param api * the REST API string. * @param contentType * the Content-Type of the JSON Object. * @return the id of the Object. */ public String doRequestWithIdResponse(String json, String api, String contentType, String accept) { Response response = null; try { RequestBody body = RequestBody.create(MediaType.parse(contentType), json); Request request = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .addHeader("Content-Type", contentType) .addHeader("Accept", accept) // .url(tenant + ".test-ram.m2m.telekom.com/" + api) .url(host + "/" + api) .post(body) .build(); response = client.newCall(request).execute(); if (!response.isSuccessful()) { final String err = getErrorMessage(response); throw new CotSdkException(response.code(), err); } String location = response.header("Location"); String result = null; if (location != null) { String[] pathParts = location.split("\\/"); result = pathParts[pathParts.length - 1]; } return result; } catch (CotSdkException e) { // We need to rethrow this in order to not loose the status code. throw e; } catch (Exception e) { throw new CotSdkException("Problem: " + e.getMessage(), e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } /** * Executes an HTTP POST request and returns the response body as String. * * @param json * Request body, needs to be a json object correlating to the * contentType. * @param api * the REST API string. * @param contentType * the Content-Type of the JSON Object. * @param accept * the Accept header for the request * @return the received JSON response body. */ public String doPostRequest(String json, String api, String contentType, String accept) { RequestBody body = RequestBody.create(MediaType.parse(contentType), json); Request.Builder requestBuilder = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .url(host + "/" + api) .post(body); if (contentType != null) { requestBuilder.addHeader("Content-Type", contentType); } if (accept != null) { requestBuilder.addHeader("Accept", accept); } Response response = null; try { response = client.newCall(requestBuilder.build()).execute(); if (!response.isSuccessful()) { final String err = getErrorMessage(response); throw new CotSdkException(response.code(), err); } String bodyContent = response.body().string(); return bodyContent; } catch (IOException e) { throw new CotSdkException("Unexpected error during POST request.", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } /** * Executes a multipart form upload of a string and returns the response body as String. * * @param file Request body, i.e. the first and only form part. * @param name The name of the form field. * @param api the URL path (without leading /) * @param contentType a String with the Content-Type to set in header of the request. * @return the response body */ public String doFormUpload(String file, String name, String api, String contentType) { RequestBody body = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart(name, "", RequestBody.create(MultipartBody.FORM, file)) .build(); Request request = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .addHeader("Content-Type", contentType) .url(host + "/" + api) .post(body) .build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) { final String err = getErrorMessage(response); throw new CotSdkException(response.code(), err); } String bodyContent = response.body().string(); return bodyContent; } catch (IOException e) { throw new CotSdkException("Unexpected error during POST request.", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } /** * Executes an HTTP POST request and returns the response body as String. * * @param files array of byte[], one for each form field. * @param names the names of the form field, same order as files. * @param api the URL path (without leading /) * @return the ID from the Location header (for newly created objects), or null if there's no Location header. */ public String doFormUpload(byte[][] files, String[] names, String api) { if (files.length != names.length) { throw new CotSdkException("Need to have the same number of files and names to upload (actual: "+files.length+" != "+names.length); } MultipartBody.Builder bodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); for (int i=0; i<names.length; i++) { bodyBuilder.addFormDataPart(names[i], "", RequestBody.create(MultipartBody.FORM, files[i])); } Request request = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .addHeader("Content-Type", "text/foo") .url(host + "/" + api) .post(bodyBuilder.build()) .build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) { final String err = getErrorMessage(response); throw new CotSdkException(response.code(), err); } String location = response.header("Location"); String result = null; if (location != null) { String[] pathParts = location.split("\\/"); result = pathParts[pathParts.length - 1]; } return result; } catch (IOException e) { throw new CotSdkException("Unexpected error during POST request.", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } /** * Do a real time polling request, i.e. the connect call. We use a different client for this call, * because it's supposed to have very long timeouts, unsuitable for regular requests. * Regular real time polling and smart rest real time polling share the same client (and therefore timeout) * because it is to be expected that a client will probably use either one of them, but not both. * * @param json * Request body, needs to be a json object correlating to the * contentType. * @param api * the REST API string. * @param contentType * the Content-Type of the JSON Object. * @param timeout the new timeout for real time requests. null = don't change the current timeout * * @return the received JSON response body. */ public String doRealTimePollingRequest(String json, String api, String contentType, Integer timeout) { RequestBody body = RequestBody.create(MediaType.parse(contentType), json); Request request = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .addHeader("Content-Type", contentType) .addHeader("Accept", contentType) .url(host + "/" + api) .post(body) .build(); // For the first request, or any subsequent request that wants to change the timeout, we need to get a new client: if ((realTimeClient == null) || ((timeout != null) && (!timeout.equals(realTimeTimeout)))) { realTimeTimeout = (timeout != null) ? timeout : realTimeTimeout; realTimeClient = client.newBuilder().readTimeout(realTimeTimeout, TimeUnit.MILLISECONDS).build(); } Response response = null; try { response = realTimeClient.newCall(request).execute(); if (!response.isSuccessful()) { final String err = getErrorMessage(response); throw new CotSdkException(response.code(), err); } return response.body().string(); } catch (InterruptedIOException e) { // That's ok and normal. There just weren't any new notifications. return null; } catch (IOException e) { throw new CotSdkException("Unexpected error during POST request.", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } /** * Do a SmartREST real time request. * * @param smartRequest the request with meta information and lines to send to platform. * * @return the SmartResponse */ public SmartResponse doSmartRealTimeRequest(SmartRequest smartRequest) { RequestBody body = RequestBody.create(null, smartRequest.getBody()); Request.Builder builder = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .addHeader("X-Id", smartRequest.getXId()) .url(host + "/cep/realtime") // Same real time endpoint handles smart and regular requests. .post(body); Request request = builder.build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new CotSdkException(response.code(), "Unexpected response code for POST request."); } String responseBody = response.body().string(); return new SmartResponse(responseBody); } catch (IOException e) { throw new CotSdkException("Unexpected error during POST request.", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } /** * Do a SmartREST real time polling request, i.e. the connect call. We use a different client for this call, * because it's supposed to have very long timeouts, unsuitable for regular requests. * Regular real time polling and smart rest real time polling share the same client (and therefore timeout) * because it is to be expected that a client will probably use either one of them, but not both. * * @param smartRequest the request with meta information and lines to send to platform. * @param timeout the new timeout for real time requests. null = don't change the current timeout * * @return the SmartResponse */ public SmartResponse doSmartRealTimePollingRequest(SmartRequest smartRequest, Integer timeout) { RequestBody body = RequestBody.create(null, smartRequest.getBody()); Request request = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .addHeader("X-Id", smartRequest.getXId()) .url(host + "/cep/realtime") // Same real time endpoint handles smart and regular requests. .post(body) .build(); // For the first request, or any subsequent request that wants to change the timeout, we need to get a new client: if ((realTimeClient == null) || ((timeout != null) && (!timeout.equals(realTimeTimeout)))) { realTimeTimeout = (timeout != null) ? timeout : realTimeTimeout; realTimeClient = client.newBuilder().readTimeout(realTimeTimeout, TimeUnit.MILLISECONDS).build(); } Response response = null; try { response = realTimeClient.newCall(request).execute(); if (!response.isSuccessful()) { throw new CotSdkException(response.code(), "Unexpected response code for POST request."); } String responseBody = response.body().string(); return new SmartResponse(responseBody); } catch (InterruptedIOException e) { // That's ok and normal. There just weren't any new notifications. return null; } catch (IOException e) { throw new CotSdkException("Unexpected error during POST request.", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } /** * Do a SmartREST-request. * * @param smartRequest the request with meta information and lines to send to platform. * * @return the SmartResponse */ public SmartResponse doSmartRequest(SmartRequest smartRequest) { RequestBody body = RequestBody.create(null, smartRequest.getBody()); Request.Builder builder = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .url(host + "/s") // SmartRest-endpoint is always just "/s". .post(body); //TODO: do we need to not send the header at all, in that case? if (smartRequest.getXId() != null && !smartRequest.getXId().isEmpty()) { builder.addHeader("X-Id", smartRequest.getXId()); } // PERSISTENT processing mode is the default, so we don't need to handle it in the else-case. if (smartRequest.getProcessingMode() != null) { builder.addHeader("X-Cumulocity-Processing-Mode", smartRequest.getProcessingMode().name()); } Request request = builder.build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new CotSdkException(response.code(), "Unexpected response code for POST request."); } return new SmartResponse(response.body().string()); } catch (IOException e) { throw new CotSdkException("Unexpected error during POST request.", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } public String getResponse(String id, String api, String accept) { Request.Builder requestBuilder = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .url(host + "/" + api + "/" + id); if (accept != null) { requestBuilder.addHeader("Accept", accept); } Response response = null; try { response = client.newCall(requestBuilder.build()).execute(); String result = null; if (response.isSuccessful()) { result = response.body().string(); } else { if (response.code() != HttpURLConnection.HTTP_NOT_FOUND) { throw new CotSdkException(response.code(), "Error in request."); } } return result; } catch (Exception e) { throw new CotSdkException("Error in request", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } public String getResponse(String api) { Request request = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .url(host + "/" + api) .build(); Response response = null; try { response = client.newCall(request).execute(); String result; if (response.isSuccessful()) { result = response.body().string(); } else { final String err = getErrorMessage(response); throw new CotSdkException(response.code(), err); } return result; } catch (CotSdkException e) { // We need to rethrow this in order to not loose the status code. throw e; } catch (Exception e) { throw new CotSdkException("Error in request", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } /** * Execute a PUT request. * * @param data the body to send * @param path the URL path (without leading '/') * @param contentType the Content-Type header * @return the response body, if there was one (empty string otherwise) */ public String doPutRequest(String data, String path, String contentType) { return doPutRequest(data, path, contentType, "*/*"); } /** * Execute a PUT request. * * @param data the body to send * @param path the URL path (without leading '/') * @param contentType the Content-Type header * @param accept the Accept header (may be null) * @return the response body, if there was one (empty string otherwise) */ public String doPutRequest(String data, String path, String contentType, String accept) { RequestBody requestBody = RequestBody.create(MediaType.parse(contentType), data); Request.Builder requestBuilder = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .addHeader("Content-Type", contentType) .url(host + "/" + path) .put(requestBody); if (accept != null) { requestBuilder.addHeader("Accept", accept); } Request request = requestBuilder.build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new CotSdkException(response.code(), "Requested returned error code"); } ResponseBody responseBody = response.body(); return (responseBody == null) ? "" : responseBody.string(); } catch (Exception e) { throw new CotSdkException("Error in request", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } /** * Execute a PUT request that will result in a new or changed ID. * * @param data the body to send * @param path the URL path (without leading '/') * @param contentType the Content-Type header * @return the ID from the Location header (for newly created objects), or null if there's no Location header. */ public String doPutRequestWithIdResponse(String data, String path, String contentType) { RequestBody requestBody = RequestBody.create(MediaType.parse(contentType), data); Request.Builder requestBuilder = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .addHeader("Content-Type", contentType) .url(host + "/" + path) .put(requestBody); Request request = requestBuilder.build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new CotSdkException(response.code(), "Requested returned error code"); } String location = response.header("Location"); String result = null; if (location != null) { String[] pathParts = location.split("\\/"); result = pathParts[pathParts.length - 1]; } return result; } catch (Exception e) { throw new CotSdkException("Error in request", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } public void delete(String id, String api) { Request request = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .url(host + "/" + api + "/" + id) .delete() .build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new CotSdkException(response.code(), "Error in delete with ID '" + id + "' (see https://http.cat/" + response.code() + ")"); } } catch( CotSdkException e) { // We need to rethrow this in order to not loose the status code. throw e; } catch (Exception e) { throw new CotSdkException("Error in request", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } public void deleteBy(final String filter, final String api) { final Request request = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .url(host + "/" + api + "?" + filter) .delete() .build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new CotSdkException(response.code(), "Error in delete by criteria '" + filter + "'"); } } catch (CotSdkException e) { // We need to rethrow this in order to not loose the status code. throw e; } catch (Exception e) { throw new CotSdkException("Error in request: " + e.getMessage(), e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } public void delete(String url) { Request request = new Request.Builder() .addHeader("Authorization", "Basic " + encodedAuthString) .url(url) .delete() .build(); Response response = null; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new CotSdkException(response.code(), "Error in delete with URL '" + url + "' (see https://http.cat/" + response.code() + ")"); } } catch (Exception e) { throw new CotSdkException("Error in request", e); } finally { closeResponseBodyIfResponseAndBodyNotNull(response); } } private String getErrorMessage(final Response response) throws IOException { String errorMessage = "Request failed."; String body = ""; try { body = response.body().string(); final JsonElement e = gson.fromJson(body, JsonElement.class); if (e instanceof JsonObject) { JsonObject o = (JsonObject) e; if (o.has("error")) { errorMessage += " Platform provided details: '" + o.get("error") + "'"; } } else if (e instanceof JsonPrimitive) { JsonPrimitive p = (JsonPrimitive) e; errorMessage += " Platform provided details: '" + p + "'"; } } catch (JsonSyntaxException ex) { errorMessage += " " + body; } catch (NullPointerException ex) { errorMessage += " Response body was empty."; } return errorMessage; } private void closeResponseBodyIfResponseAndBodyNotNull(final Response response) { if (response != null && response.body() != null) { response.body().close(); } } }
add methods doPutRequestWithIdRepsonseInBytes, getResponseInBytes and change getResponse and doPutRequestWithIdResponse
src/main/java/com/telekom/m2m/cot/restsdk/CloudOfThingsRestClient.java
add methods doPutRequestWithIdRepsonseInBytes, getResponseInBytes and change getResponse and doPutRequestWithIdResponse
<ide><path>rc/main/java/com/telekom/m2m/cot/restsdk/CloudOfThingsRestClient.java <ide> <ide> <ide> public String getResponse(String id, String api, String accept) { <add> byte[] result = getResponseInBytes(id, api, accept); <add> if (result != null){ <add> return new String(result); <add> } <add> return null; <add> } <add> <add> /** <add> * get the response of a request in bytes <add> * @param id part of url for request <add> * @param api part of the url for request <add> * @param accept accpet header for request <add> * @return the response from cloud of things <add> */ <add> public byte[] getResponseInBytes(String id, String api, String accept){ <ide> Request.Builder requestBuilder = new Request.Builder() <ide> .addHeader("Authorization", "Basic " + encodedAuthString) <ide> .url(host + "/" + api + "/" + id); <ide> Response response = null; <ide> try { <ide> response = client.newCall(requestBuilder.build()).execute(); <del> String result = null; <add> byte[] result = null; <ide> if (response.isSuccessful()) { <del> result = response.body().string(); <add> result = response.body().bytes(); <ide> } else { <ide> if (response.code() != HttpURLConnection.HTTP_NOT_FOUND) { <ide> throw new CotSdkException(response.code(), "Error in request."); <ide> } <ide> } <ide> <del> <ide> /** <ide> * Execute a PUT request that will result in a new or changed ID. <ide> * <del> * @param data the body to send <add> * @param data the body to send in bytes <ide> * @param path the URL path (without leading '/') <ide> * @param contentType the Content-Type header <ide> * @return the ID from the Location header (for newly created objects), or null if there's no Location header. <ide> */ <del> public String doPutRequestWithIdResponse(String data, String path, String contentType) { <add> public String doPutRequestWithIdResponseInBytes(byte[] data, String path, String contentType) { <ide> RequestBody requestBody = RequestBody.create(MediaType.parse(contentType), data); <ide> Request.Builder requestBuilder = new Request.Builder() <ide> .addHeader("Authorization", "Basic " + encodedAuthString) <ide> } finally { <ide> closeResponseBodyIfResponseAndBodyNotNull(response); <ide> } <add> } <add> <add> <add> /** <add> * Execute a PUT request that will result in a new or changed ID. <add> * <add> * @param data the body to send <add> * @param path the URL path (without leading '/') <add> * @param contentType the Content-Type header <add> * @return the ID from the Location header (for newly created objects), or null if there's no Location header. <add> */ <add> public String doPutRequestWithIdResponse(String data, String path, String contentType) { <add> return doPutRequestWithIdResponseInBytes(data.getBytes(), path, contentType); <ide> } <ide> <ide>
JavaScript
apache-2.0
87a7288575c6251d377a448fb98a13d93bcf8b47
0
Biotelligent/TiShadow,r8o8s1e0/TiShadow,HazemKhaled/TiShadow,titanium-forks/dbankier.TiShadow,emilyvon/TiShadow,Biotelligent/TiShadow,r8o8s1e0/TiShadow,titanium-forks/dbankier.TiShadow,r8o8s1e0/TiShadow,HazemKhaled/TiShadow,emilyvon/TiShadow,titanium-forks/dbankier.TiShadow,emilyvon/TiShadow,HazemKhaled/TiShadow,FokkeZB/TiShadow,FokkeZB/TiShadow,Biotelligent/TiShadow,FokkeZB/TiShadow
var TiShadow = {}; TiShadow.init = function (session, guest){ var socket = io.connect("http://localhost"); socket.on('connect', function(data) { socket.emit("join", {name: 'controller'}); }); socket.on('device_connect', function(e){ $(".device_list").append('<li id="'+ e.id + '">' + e.name + '</li>'); }); socket.on('device_disconnect', function(e){ $("li#" + e.id).remove(); }); socket.on('device_log', function(e) { var now = new Date(); var log = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + " [" + e.level + "] [" + e.name + "] " + e.message.replace("\n","<br/>"); var style = e.level === "ERROR" || e.level === "FAIL" ? " error" : e.level === "WARN" ? "" : " success" $(".console").append("<div class='alert-message" + style + "'>" + log + "</div>"); $(".console").scrollTop($(".console")[0].scrollHeight); }); TiShadow.socket = socket; }; $(document).ready(function() { TiShadow.init(); var editor = ace.edit("editor"); editor.setTheme("ace/theme/twilight"); var JavaScriptMode = require("ace/mode/javascript").Mode; editor.getSession().setMode(new JavaScriptMode()); $("input#tisubmit").click(function() { TiShadow.socket.emit("generate", {code: editor.getSession().getValue()}); }); $("#editor").keypress(function (event) { if ((event.which == 115 && event.ctrlKey) || (event.which == 115 && event.metaKey)){ $("input#tisubmit").click(); event.preventDefault(); return false; } }); });
server/public/javascript/main.js
var TiShadow = {}; TiShadow.init = function (session, guest){ var socket = io.connect("http://localhost"); socket.on('connect', function(data) { socket.emit("join", {name: 'controller'}); }); socket.on('device_connect', function(e){ $(".device_list").append('<li id="'+ e.id + '">' + e.name + '</li>'); }); socket.on('device_disconnect', function(e){ $("li#" + e.id).remove(); }); socket.on('device_log', function(e) { var now = new Date(); var log = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + " [" + e.level + "] [" + e.name + "] " + e.message.replace("\n","<br/>"); var style = e.level === "ERROR" || e.level === "FAIL" ? " error" : e.level === "WARN" ? "" : " success" $(".console").prepend("<div class='alert-message" + style + "'>" + log + "</div>"); }); TiShadow.socket = socket; }; $(document).ready(function() { TiShadow.init(); var editor = ace.edit("editor"); editor.setTheme("ace/theme/twilight"); var JavaScriptMode = require("ace/mode/javascript").Mode; editor.getSession().setMode(new JavaScriptMode()); $("input#tisubmit").click(function() { TiShadow.socket.emit("generate", {code: editor.getSession().getValue()}); }); $("#editor").keypress(function (event) { if ((event.which == 115 && event.ctrlKey) || (event.which == 115 && event.metaKey)){ $("input#tisubmit").click(); event.preventDefault(); return false; } }); });
Latest logs at the bottom in webpage console Closes #26
server/public/javascript/main.js
Latest logs at the bottom in webpage console
<ide><path>erver/public/javascript/main.js <ide> var now = new Date(); <ide> var log = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + " [" + e.level + "] [" + e.name + "] " + e.message.replace("\n","<br/>"); <ide> var style = e.level === "ERROR" || e.level === "FAIL" ? " error" : e.level === "WARN" ? "" : " success" <del> $(".console").prepend("<div class='alert-message" + style + "'>" + log + "</div>"); <add> $(".console").append("<div class='alert-message" + style + "'>" + log + "</div>"); <add> $(".console").scrollTop($(".console")[0].scrollHeight); <ide> }); <ide> TiShadow.socket = socket; <ide> };
Java
apache-2.0
e14397f45449a3223c9c2479ce711cba463c6f97
0
odiszapc/stem,odiszapc/stem,openaphid/stem,odiszapc/stem,openaphid/stem,odiszapc/stem,openaphid/stem,openaphid/stem
/* * Copyright 2014 Alexey Plotnik * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.stem.api.resources; import org.stem.RestUtils; import org.stem.api.RESTConstants; import org.stem.api.request.AuthorizeNodeRequest; import org.stem.api.request.CreateClusterRequest; import org.stem.api.request.JoinRequest; import org.stem.api.response.ClusterResponse; import org.stem.api.response.JoinResponse; import org.stem.api.response.ListNodesResponse; import org.stem.coordination.Event; import org.stem.coordination.EventFuture; import org.stem.coordination.EventManager; import org.stem.domain.Cluster; import org.stem.domain.topology.Topology; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import java.util.List; @Path(RESTConstants.Api.Cluster.URI) public class ClusterResource { /** * Initialize cluster * * @param req * @return */ @POST @Path(RESTConstants.Api.Cluster.Init.BASE) public Response create(CreateClusterRequest req) { Cluster.instance.initialize(req.getName(), req.getvBuckets(), req.getRf(), req.getPartitioner(), req.getMetaStoreConfiguration()); return RestUtils.ok(); } /** * Show common information about cluster * * @return */ @GET public Response get() { Cluster cluster = Cluster.instance().ensureInitialized(); ClusterResponse response = RestUtils.buildClusterResponse(cluster, true); return RestUtils.ok(response); } /** * Node wants join the cluster. STEP 1 * * @param request * @return * @throws Exception */ @POST @Path(RESTConstants.Api.Cluster.Join.BASE) // TODO: when node restarts between join and accept events public synchronized Response join(JoinRequest request) throws Exception { Topology.StorageNode node = RestUtils.extractNode(request.getNode()); // TODO: delete unused async requests Cluster cluster = Cluster.instance().ensureInitialized(); EventFuture future = EventManager.instance.createSubscription(Event.Type.JOIN); Topology.StorageNode existing = cluster.topology().findStorageNode(node.getId()); if (null == existing) { cluster.unauthorized().add(node, future); } else { // TODO: check node status cluster.approve(future.eventId(), node.getId()); } return RestUtils.ok(new JoinResponse(future.eventId())); } // TODO: save/load unauthorized nodes // TODO: save/load subscriptions @GET @Path(RESTConstants.Api.Cluster.Unauthorized.BASE) public Response unauthorized() throws Exception { Cluster cluster = Cluster.instance().ensureInitialized(); List<Topology.StorageNode> list = cluster.unauthorized().list(); ListNodesResponse resp = RestUtils.buildUnauthorizedListResponse(list); return RestUtils.ok(resp); } /** * Admin approve pending node that wants join cluster, STEP 2 * @param req * @return * @throws Exception */ @POST @Path(RESTConstants.Api.Cluster.Approve.BASE) public Response approveUnauthorized(AuthorizeNodeRequest req) throws Exception { Cluster cluster = Cluster.instance().ensureInitialized(); String datacenter = req.getDatacenter(); String rack = req.getRack(); Event.Join response = cluster.approve(req.getNodeId(), datacenter, rack); return RestUtils.ok(response); // TODO: return an empty result on success as we usual do? } @POST @Path(RESTConstants.Api.Cluster.Refuse.BASE) public Response deny(AuthorizeNodeRequest req) throws Exception { Cluster cluster = Cluster.instance().ensureInitialized(); Event.Join response = cluster.unauthorized().deny(req.getNodeId()); return RestUtils.ok(response); // TODO: return an empty result on success as we usual do? } }
components/clustermanager/src/main/java/org/stem/api/resources/ClusterResource.java
/* * Copyright 2014 Alexey Plotnik * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.stem.api.resources; import org.stem.RestUtils; import org.stem.api.RESTConstants; import org.stem.api.request.AuthorizeNodeRequest; import org.stem.api.request.CreateClusterRequest; import org.stem.api.request.JoinRequest; import org.stem.api.response.ClusterResponse; import org.stem.api.response.JoinResponse; import org.stem.api.response.ListNodesResponse; import org.stem.coordination.Event; import org.stem.coordination.EventFuture; import org.stem.coordination.EventManager; import org.stem.domain.Cluster; import org.stem.domain.topology.Topology; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import java.util.List; @Path(RESTConstants.Api.Cluster.URI) public class ClusterResource { /** * Initialize cluster * * @param req * @return */ @POST @Path(RESTConstants.Api.Cluster.Init.BASE) public Response create(CreateClusterRequest req) { Cluster.instance.initialize(req.getName(), req.getvBuckets(), req.getRf(), req.getPartitioner(), req.getMetaStoreConfiguration()); return RestUtils.ok(); } /** * Show common information about cluster * * @return */ @GET public Response get() { Cluster cluster = Cluster.instance().ensureInitialized(); ClusterResponse response = RestUtils.buildClusterResponse(cluster, true); return RestUtils.ok(response); } /** * Node wants join the cluster. STEP 1 * * @param request * @return * @throws Exception */ @POST @Path(RESTConstants.Api.Cluster.Join.BASE) // TODO: when node restarts between join and accept events public synchronized Response join(JoinRequest request) throws Exception { Topology.StorageNode node = RestUtils.extractNode(request.getNode()); // TODO: delete unused async requests Cluster cluster = Cluster.instance().ensureInitialized(); EventFuture future = EventManager.instance.createSubscription(Event.Type.JOIN); Topology.StorageNode existing = cluster.topology().findStorageNode(node.getId()); if (null == existing) { cluster.unauthorized().add(node, future); } else { // TODO: check node status cluster.approve(future.eventId(), node.getId()); } return RestUtils.ok(new JoinResponse(future.eventId())); } // TODO: save/load unauthorized nodes // TODO: save/load subscriptions @GET @Path(RESTConstants.Api.Cluster.Unauthorized.BASE) public Response unauthorized() throws Exception { Cluster cluster = Cluster.instance().ensureInitialized(); List<Topology.StorageNode> list = cluster.unauthorized().list(); ListNodesResponse resp = RestUtils.buildUnauthorizedListResponse(list); return RestUtils.ok(resp); } @POST @Path(RESTConstants.Api.Cluster.Approve.BASE) public Response approveUnauthorized(AuthorizeNodeRequest req) throws Exception { Cluster cluster = Cluster.instance().ensureInitialized(); String datacenter = req.getDatacenter(); String rack = req.getRack(); Event.Join response = cluster.approve(req.getNodeId(), datacenter, rack); return RestUtils.ok(response); // TODO: return an empty result on success as we usual do? } @POST @Path(RESTConstants.Api.Cluster.Refuse.BASE) public Response deny(AuthorizeNodeRequest req) throws Exception { Cluster cluster = Cluster.instance().ensureInitialized(); Event.Join response = cluster.unauthorized().deny(req.getNodeId()); return RestUtils.ok(response); // TODO: return an empty result on success as we usual do? } }
STEM-6
components/clustermanager/src/main/java/org/stem/api/resources/ClusterResource.java
STEM-6
<ide><path>omponents/clustermanager/src/main/java/org/stem/api/resources/ClusterResource.java <ide> return RestUtils.ok(resp); <ide> } <ide> <add> /** <add> * Admin approve pending node that wants join cluster, STEP 2 <add> * @param req <add> * @return <add> * @throws Exception <add> */ <ide> @POST <ide> @Path(RESTConstants.Api.Cluster.Approve.BASE) <ide> public Response approveUnauthorized(AuthorizeNodeRequest req) throws Exception {
Java
mit
615c7d4af318974ede599b7cacde7fc6693c9846
0
mopsalarm/Pr0,mopsalarm/Pr0,mopsalarm/Pr0
package com.pr0gramm.app; import android.app.Application; import android.content.Context; import android.os.StrictMode; import com.crashlytics.android.Crashlytics; import com.f2prateek.dart.Dart; import com.pr0gramm.app.services.ThemeHelper; import com.pr0gramm.app.ui.ActivityErrorHandler; import com.pr0gramm.app.util.CrashlyticsLogHandler; import com.pr0gramm.app.util.Lazy; import com.pr0gramm.app.util.LooperScheduler; import com.thefinestartist.Base; import net.danlew.android.joda.JodaTimeAndroid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogManager; import butterknife.ButterKnife; import io.fabric.sdk.android.Fabric; import pl.brightinventions.slf4android.LogLevel; import pl.brightinventions.slf4android.LoggerConfiguration; import rx.Scheduler; import rx.android.plugins.RxAndroidPlugins; import rx.android.plugins.RxAndroidSchedulersHook; import static com.pr0gramm.app.ui.dialogs.ErrorDialogFragment.setGlobalErrorDialogHandler; import static com.pr0gramm.app.util.AndroidUtility.buildVersionCode; /** * Global application class for pr0gramm app. */ public class ApplicationClass extends Application { private static final Logger logger = LoggerFactory.getLogger("Pr0grammApplication"); final Lazy<AppComponent> appComponent = Lazy.of(() -> DaggerAppComponent.builder() .appModule(new AppModule(this)) .httpModule(new HttpModule()) .build()); private static ApplicationClass INSTANCE; public ApplicationClass() { INSTANCE = this; } @Override public void onCreate() { super.onCreate(); Stats.init(buildVersionCode()); JodaTimeAndroid.init(this); Base.initialize(this); Settings.initialize(this); if (BuildConfig.DEBUG) { logger.info("This is a development version."); StrictMode.enableDefaults(); ButterKnife.setDebug(true); Dart.setDebug(true); } else { logger.info("Initialize fabric"); Fabric.with(this, new Crashlytics()); LoggerConfiguration.configuration() .removeRootLogcatHandler() .setRootLogLevel(LogLevel.INFO) .addHandlerToRootLogger(new CrashlyticsLogHandler()); } // initialize this to show errors always in the context of the current activity. setGlobalErrorDialogHandler(new ActivityErrorHandler(this)); // set as global constant that we can access from everywhere appComponent().googleAnalytics(); Dagger.initEagerSingletons(this); if (BuildConfig.DEBUG) { StethoWrapper.init(this); } // get the correct theme for the app! ThemeHelper.updateTheme(this); // disable verbose logging java.util.logging.Logger log = LogManager.getLogManager().getLogger(""); if (log != null) { for (Handler h : log.getHandlers()) { h.setLevel(Level.INFO); } } } public static ApplicationClass get(Context context) { return (ApplicationClass) context.getApplicationContext(); } public static AppComponent appComponent() { return INSTANCE.appComponent.get(); } static { RxAndroidPlugins.getInstance().registerSchedulersHook(new RxAndroidSchedulersHook() { @Override public Scheduler getMainThreadScheduler() { return LooperScheduler.MAIN; } }); } }
app/src/main/java/com/pr0gramm/app/ApplicationClass.java
package com.pr0gramm.app; import android.app.Application; import android.content.Context; import android.os.StrictMode; import com.crashlytics.android.Crashlytics; import com.f2prateek.dart.Dart; import com.pr0gramm.app.services.ThemeHelper; import com.pr0gramm.app.ui.ActivityErrorHandler; import com.pr0gramm.app.util.CrashlyticsLogHandler; import com.pr0gramm.app.util.Lazy; import com.pr0gramm.app.util.LooperScheduler; import com.thefinestartist.Base; import net.danlew.android.joda.JodaTimeAndroid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogManager; import butterknife.ButterKnife; import io.fabric.sdk.android.Fabric; import okhttp3.internal.framed.FrameLoggerAccess; import pl.brightinventions.slf4android.LogLevel; import pl.brightinventions.slf4android.LoggerConfiguration; import rx.Scheduler; import rx.android.plugins.RxAndroidPlugins; import rx.android.plugins.RxAndroidSchedulersHook; import static com.pr0gramm.app.ui.dialogs.ErrorDialogFragment.setGlobalErrorDialogHandler; import static com.pr0gramm.app.util.AndroidUtility.buildVersionCode; /** * Global application class for pr0gramm app. */ public class ApplicationClass extends Application { private static final Logger logger = LoggerFactory.getLogger("Pr0grammApplication"); final Lazy<AppComponent> appComponent = Lazy.of(() -> DaggerAppComponent.builder() .appModule(new AppModule(this)) .httpModule(new HttpModule()) .build()); private static ApplicationClass INSTANCE; public ApplicationClass() { INSTANCE = this; } @Override public void onCreate() { super.onCreate(); Stats.init(buildVersionCode()); JodaTimeAndroid.init(this); Base.initialize(this); Settings.initialize(this); if (BuildConfig.DEBUG) { logger.info("This is a development version."); StrictMode.enableDefaults(); ButterKnife.setDebug(true); Dart.setDebug(true); } else { logger.info("Initialize fabric"); Fabric.with(this, new Crashlytics()); LoggerConfiguration.configuration() .removeRootLogcatHandler() .setLogLevel(FrameLoggerAccess.CLASSNAME, LogLevel.INFO) .addHandlerToRootLogger(new CrashlyticsLogHandler()); } // initialize this to show errors always in the context of the current activity. setGlobalErrorDialogHandler(new ActivityErrorHandler(this)); // set as global constant that we can access from everywhere appComponent().googleAnalytics(); Dagger.initEagerSingletons(this); if (BuildConfig.DEBUG) { StethoWrapper.init(this); } // get the correct theme for the app! ThemeHelper.updateTheme(this); // disable verbose logging java.util.logging.Logger log = LogManager.getLogManager().getLogger(""); if (log != null) { for (Handler h : log.getHandlers()) { h.setLevel(Level.INFO); } } } public static ApplicationClass get(Context context) { return (ApplicationClass) context.getApplicationContext(); } public static AppComponent appComponent() { return INSTANCE.appComponent.get(); } static { RxAndroidPlugins.getInstance().registerSchedulersHook(new RxAndroidSchedulersHook() { @Override public Scheduler getMainThreadScheduler() { return LooperScheduler.MAIN; } }); } }
Set root log-level to info.
app/src/main/java/com/pr0gramm/app/ApplicationClass.java
Set root log-level to info.
<ide><path>pp/src/main/java/com/pr0gramm/app/ApplicationClass.java <ide> <ide> import butterknife.ButterKnife; <ide> import io.fabric.sdk.android.Fabric; <del>import okhttp3.internal.framed.FrameLoggerAccess; <ide> import pl.brightinventions.slf4android.LogLevel; <ide> import pl.brightinventions.slf4android.LoggerConfiguration; <ide> import rx.Scheduler; <ide> <ide> LoggerConfiguration.configuration() <ide> .removeRootLogcatHandler() <del> .setLogLevel(FrameLoggerAccess.CLASSNAME, LogLevel.INFO) <add> .setRootLogLevel(LogLevel.INFO) <ide> .addHandlerToRootLogger(new CrashlyticsLogHandler()); <ide> } <ide>
JavaScript
mit
fff942e1ad8658808f069bc41dc59e7104654910
0
EclipseFdn/jquery-eclipsefdn-api
// the semi-colon before function invocation is a safety net against concatenated // scripts and/or other plugins which may not be closed properly. (function($, window, document, undefined) { "use strict"; // undefined is used here as the undefined global variable in ECMAScript 3 is // mutable (ie. it can be changed by someone else). undefined isn"t really being // passed in so we can ensure the value of it is truly undefined. In ES5, undefined // can no longer be modified. // window and document are passed through as local variables rather than global // as this (slightly) quickens the resolution process and can be more efficiently // minified (especially when both are regularly referenced in your plugin). // Create the defaults once var pluginName = "eclipseFdnApi", defaults = { apiUrl: "https://api.eclipse.org", gerritUrl: "https://git.eclipse.org/r", eventUrl: "https://newsroom.eclipse.org/api/events", adsUrl: "https://newsroom.eclipse.org/api/ads", forumsUrl: "https://www.eclipse.org/forums", marketplaceUrl: "https://marketplace.eclipse.org", username: "cguindon", currentUser: "", contentPlaceholder: null, errorMsg: "<i class=\"fa red fa-exclamation-triangle\" aria-hidden=\"true\"></i> An unexpected error has occurred.", gerritUserNotFoundMsg: "<h2 class=\"h3\">Outgoing Reviews</h2>There are no outgoing reviews for this user.<h2 class=\"h3\">Incoming Reviews</h2>There are no incoming reviews for this account.", type: "", itemsPerPage: 10, accountsUrl: "https://accounts.eclipse.org", newsroomUrl: "https://newsroom.eclipse.org/api", featuredContent: {}, featuredContentType: "" }; // The actual plugin constructor function Plugin(element, options) { this.element = element; // jQuery has an extend method which merges the contents of two or // more objects, storing the result in the first object. The first object // is generally empty as we don"t want to alter the default options for // future instances of the plugin this.settings = $.extend({}, defaults, options); this._defaults = defaults; this._name = pluginName; this.init(); } // Avoid Plugin.prototype conflicts $.extend(Plugin.prototype, { init: function() { // Place initialization logic here // You already have access to the DOM element and // the options via the instance, e.g. this.element // and this.settings // you can add more functions like the one below and // call them like the example below var validTypes = [ "mpFavorites", "gerritReviews", "recentEvents", "forumsMsg", "gerritReviewCount", "projectsList", "mailingListSubscription", "newsItems", "filteredEvents", "featuredStory", "featuredFooter", "customFeaturedContent", "allPromos", "singlePromo" ]; if ($.type(this.settings.type) === "string" && $.inArray(this.settings.type, validTypes) !== -1) { this[this.settings.type](); } }, projectsList: function() { var self = this; var username = this.settings.username; var apiUrl = this.settings.apiUrl; // Exit if variables are not set. if (!username && !api_url) { return false; } // Build api URI. var url = apiUrl + "/account/profile/" + username + "/projects"; // Execute ajax request $.ajax(url, { context: this.element, success: function(data) { var project_count = Object.keys(data).length; if (project_count === undefined) { project_count = 0; } $(this).children("strong").text(project_count + self.plurialString(" project", project_count)); // Exit now if contentPlaceholder is not defined if (!(self.settings.contentPlaceholder instanceof jQuery)) { return false; } var container = $(self.settings.contentPlaceholder); var a = $("<a></a>"); container.append($("<h2></h2>").addClass("h3").text("Eclipse Projects")); container.append("<p>Projects are the organizational unit for open source " + "development work at the Eclipse Foundation. Projects have developers " + "(committers), source code repositories, build servers, downloads, " + "and other resources. The Eclipse Foundation's open source projects " + "are governed by the <a href=\"https://eclipse.org/projects/dev_process/\">Eclipse Development Process</a>.</p>"); var warning_prefix = "This user is"; if (self.settings.currentUser === self.settings.username) { warning_prefix = "You are"; } if (project_count === 0) { container.append("<div class=\"alert alert-warning\" role=\"alert\">" + warning_prefix + " not involved in any Eclipse Projects." + "</div>"); return false; } // Create table var table = $("<table></table>").attr({ "width": "100%", "class": "table" }); var tr = $("<tr></tr>"); var th = $("<th></th>"); var td = $("<td></td>"); tr.append(th.clone().text("Project").attr("width", "85%")); tr.append(th.clone().text("Relation").attr({ "width": "15%", "class": "text-center" })); table.append(tr); // Insert rows in table $.each(data, function(index, value) { var roles = []; var projectName = ""; var activeDate = ""; $.each(value, function(i, v) { roles.push(v.Relation.Description); projectName = v.ProjectName; activeDate = v.ActiveDate; if (v.url !== "") { projectName = a.clone().attr({ "href": v.url }).text(projectName); } }); tr = $("<tr></tr>"); // Replies column tr.append(td.clone().html(projectName).append("<br/><small>Since: " + self.dateFormat(new Date(activeDate)) + "</small>")); tr.append(td.clone().text(roles.join(", ")).attr("class", "text-center")); table.append(tr); }); // append table to container var responsive_wrapper = $("<div></div>").attr({ "class": "table-responsive" }); responsive_wrapper.append(table); container.append(responsive_wrapper); }, error: function() { $(this).html(self.settings.errorMsg); } }); }, forumsMsg: function() { var self = this; var username = this.settings.username; var apiUrl = this.settings.apiUrl; // Exit if variables are not set. if (!username && !api_url) { return false; } // Build api URI. var url = apiUrl + "/account/profile/" + username + "/forum?page=1&pagesize=" + self.settings.itemsPerPage; // Execute ajax request $.ajax(url, { context: this.element, success: function(data, textStatus, jqXHR) { var user_msg_count = 0; if (data.posted_msg_count !== undefined && data.id !== undefined) { user_msg_count = data.posted_msg_count; $(this).attr({ "href": self.settings.forumsUrl + "/index.php/sp/" + data.id + "/", }); } $(this).children("strong").text(user_msg_count + self.plurialString(" topic", user_msg_count)); // Exit now if contentPlaceholder is not defined if (!(self.settings.contentPlaceholder instanceof jQuery)) { return false; } var container = $(self.settings.contentPlaceholder); var a = $("<a></a>"); container.append($("<h2></h2>").addClass("h3").text("Eclipse Forums")); container.append($("<p></p>").append("The Eclipse forums are your way of communicating with the community " + "of people developing and using Eclipse-based tools hosted at Eclipse.org. " + "Please stick to technical issues - and remember, no confidential information - " + "these are public forums!")); var more_forums_link = a.clone().attr({ "href": self.settings.forumsUrl, "class": "btn btn-primary btn-sm", "style": "display:block" }).html("<i class=\"fa fa-angle-double-right\" aria-hidden=\"true\"></i> More"); if (data.posts.length === 0) { container.append("<div class=\"alert alert-warning\" role=\"alert\">" + "This user does not have any activities on Eclipse Forums." + "</div>"); container.append(more_forums_link); return false; } // Create table var table = $("<table></table>").attr({ "width": "100%", "class": "table", "id": "forum-posts" }); var tr = $("<tr></tr>"); var th = $("<th></th>"); if (self.settings.currentUser === self.settings.username) { tr.append(th.clone().attr("width", "8%")); } tr.append(th.clone().text("Topics").attr("width", "50%")); tr.append(th.clone().text("Replies").attr({ "width": "8%", "class": "text-center" })); tr.append(th.clone().text("Views").attr({ "width": "8%", "class": "text-center" })); tr.append(th.clone().text("Last message").attr({ "class": "text-center" })); // Insert heading row in table table.append(tr); // append table to container var responsive_wrapper = $("<div></div>").attr({ "class": "table-responsive" }); responsive_wrapper.append(table); container.append(responsive_wrapper); // draw the inital row data drawForumRows(data); // check the link header for total pages var linkHeader = new self.linkHeaderParser(jqXHR.getResponseHeader("Link")); var lastPage = linkHeader.getLastPageNum(); // check if itemsPerPage should be updated to returned value if (linkHeader.getPageSize() !== self.settings.itemsPerPage) { self.settings.itemsPerPage = linkHeader.getPageSize(); } // set fetch posts event table.on("fetchPageItemsEvent", fetchForumPosts); // store items per page so we know how many to fetch per page table.data("postsPerPage", self.settings.itemsPerPage); // add pagination bar container.append(self.getPaginationBar(lastPage * self.settings.itemsPerPage, "forum-posts")); // get the user id var current_user_id = data.id; // update more forums link more_forums_link.attr({ "href": self.settings.forumsUrl + "/index.php/sp/" + current_user_id + "/", }); // append read more link container.append(more_forums_link); }, error: function() { $(this).html(self.settings.errorMsg); } }); function drawForumRows(data) { var forumTable = $("#forum-posts"); $.each(data.posts, function(index, value) { var request_data = { forum_id: value.thread_forum_id, forum_name: value.forum_name, forum_cat_id: value.forum_name, forum_cat_name: value.cat_name, root_subject: value.root_msg_subject, current_user_last_post_timestamp: value.msg_group_post_stamp, current_user_last_post_subject: value.last_user_msg_subject, thread_id: value.msg_thread_id, thread_reply_count: value.thread_replies, thread_views_count: value.thread_views, thread_last_post_date: value.thread_last_post_date, last_message_timestamp: value.last_msg_post_stamp, last_message_poster_id: value.last_msg_poster_id, last_message_poster_alias: value.last_poster_alias, last_message_last_view: value.read_last_view, current_user_id: data.id }; var tr = $("<tr></tr>"); var td = $("<td></td>"); var a = $("<a></a>"); // Link to forum var forumLink = a.clone().attr({ "href": self.settings.forumsUrl + "/index.php/f/" + request_data.forum_id + "/" }).text(request_data.forum_name); // Link to category var catLink = a.clone().attr({ "href": self.settings.forumsUrl + "/index.php/i/" + request_data.forum_cat_id + "/" }).text(request_data.forum_cat_name); // Concatenate category and form link var forum_cat_link = $("<small></small>").append("<br/>") .append(catLink) .append(" &gt; ") .append(forumLink) .append(" &gt; ") .append(request_data.root_subject) .append("<br>Posted on " + self.dateFormat(new Date(parseInt(request_data.current_user_last_post_timestamp * 1000)))); var read_icon = "fa fa-envelope-open-o"; // Add warning class to row if the user did not see the message if (self.settings.currentUser === self.settings.username && request_data.last_message_last_view < request_data.thread_last_post_date && request_data.last_message_poster_id !== request_data.current_user_id) { tr.addClass("warning"); read_icon = "fa fa-envelope-o"; } if (self.settings.currentUser === self.settings.username) { tr.append(td.clone().html("<i class=\"" + read_icon + "\" aria-hidden=\"true\"></i>").attr("class", "text-center")); } // Topic column tr.append(td.clone().html(a.clone().attr({ "href": self.settings.forumsUrl + "/index.php/t/" + request_data.thread_id + "/" }) .text(request_data.current_user_last_post_subject)) .append(forum_cat_link) ); // Replies column tr.append(td.clone().text(request_data.thread_reply_count).attr("class", "text-center")); // Views column tr.append(td.clone().text(request_data.thread_views_count).attr("class", "text-center")); // Last message column var last_message = $("<small></small>").append(self.dateFormat(new Date(parseInt(request_data.last_message_timestamp * 1000)))).append("<br/> By: ").append(a.clone().attr({ "href": self.settings.forumsUrl + "/index.php/sp/" + request_data.last_message_poster_id + "/" }).text(request_data.last_message_poster_alias)); tr.append(td.clone().html(last_message).attr("class", "text-center")); forumTable.append(tr); }); } function fetchForumPosts(event, page, numPosts) { getForumPostsByPage(page, numPosts); } function getForumPostsByPage(pageNum, pageSize) { if (typeof (pageNum) === "undefined") { // default to page 1 pageNum = 1; } if (typeof (pageSize) === "undefined") { // default to settings pageSize = self.settings.itemsPerPage; } // Build api URI. var url = apiUrl + "/account/profile/" + username + "/forum?page=" + pageNum + "&pagesize=" + pageSize; $.ajax(url, { context: self.element, success: function(data) { drawForumRows(data); }, error: function() { $(this).html(self.settings.errorMsg); } }); } }, mpFavorites: function() { var self = this; var username = this.settings.username; var apiUrl = this.settings.apiUrl; // Exit if variables are not set. if (!username && !api_url) { return false; } // Add content if contentPlaceholder is defined if (self.settings.contentPlaceholder instanceof jQuery) { var container = $(self.settings.contentPlaceholder); var more_marketplace_link = $("<a></a>").attr({ "href": self.settings.marketplaceUrl + "/user/" + username + "/favorites", "class": "btn btn-primary btn-sm", "style": "display:block" }).html("<i class=\"fa fa-angle-double-right\" aria-hidden=\"true\"></i> More"); container.append($("<h2></h2>").addClass("h3").text("Eclipse Marketplace Favorites")); container.append($("<p></p>").append("Eclipse Marketplace is the source for " + "Eclipse-based solutions, products and add-on features. " + "Thousands of developers visit Marketplace on a monthly " + "basis to find new and innovative solutions. Solution providers " + "are encouraged to list their products on Marketplace to " + "gain exposure to the Eclipse developer community.")); } // Build api URI. var url = apiUrl + "/marketplace/favorites?name=" + username + "&page=1&pagesize=" + self.settings.itemsPerPage; // Execute ajax request $.ajax(url, { context: this.element, success: function(data, textStatus, jqXHR) { $(this).children("strong").text(data.result.count + self.plurialString(" favorite", data.result.count)); // Exit now if container is not defined if (typeof container === "undefined") { return false; } // break down the nodestr by itemsPerPage var nodes = []; $.each(data.mpc_favorites, function(k, v) { nodes.push(v.content_id); }); if (nodes.length === 0) { container.append("<div class=\"alert alert-warning\" role=\"alert\">" + "There are no marketplace favorites for this user." + "</div>"); container.append(more_marketplace_link); return false; } // check the link header for total pages var linkHeader = new self.linkHeaderParser(jqXHR.getResponseHeader("Link")); var lastPage = linkHeader.getLastPageNum(); // check if itemsPerPage should be updated to returned value if (linkHeader.getPageSize() !== self.settings.itemsPerPage) { self.settings.itemsPerPage = linkHeader.getPageSize(); } // set the fetch favorites as custom event container.on("fetchPageItemsEvent", fetchFavorites); container.append("<h3 id=\"mpc_list_name\">" + data.mpc_list_name + "</h3>"); container.append("<div class=\"row\"><div class=\"col-md-17\"><div class=\"form-item form-type-textfield form-disabled\">" + "<label>Favorites URL <a href=\"#\" class=\"install-user-favorites\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"top\" title=\"\" data-original-title=\"How to install?\">" + "<i class=\"fa fa-question-circle\" aria-hidden=\"true\"></i></a> </label>" + "<input disabled=\"true\" class=\"form-control form-text\" type=\"text\" value=\"http://marketplace.eclipse.org/user/" + self.settings.username + "/favorites\" size=\"60\" maxlength=\"128\">" + "</div></div><div class=\"col-md-7 margin-top-25 text-right\"><div class=\"drag_installbutton drag_installbutton_v2 drag-install-favorites\">" + "<a href=\"http://marketplace.eclipse.org/user/" + self.settings.username + "/favorites\" class=\"drag\" title=\"How to install?\">" + "<span class=\"btn btn-default\"><i class=\"fa fa-download orange\"></i> Install Favorites</span>" + "<div class=\"tooltip tooltip-below-right\"><h3>Drag to Install!</h3>" + "Drag to your running Eclipse<sup>*</sup> workspace to install this " + "favorite list. <br><sup>*</sup>Requires Eclipse Marketplace Client.</div></a></div></div></div>"); container.append("<div id=\"mpfavorites-list\"></div>"); container.find("#mpfavorites-list").data("postsPerPage", self.settings.itemsPerPage); getFavoritesByNodes(nodes.join()); container.append(self.getPaginationBar(lastPage * self.settings.itemsPerPage, "mpfavorites-list")); container.append(more_marketplace_link); // Add instructions to popover $("a.install-user-favorites").on("click", function(e) { e.preventDefault(); }); $("a.install-user-favorites").popover({ html: true, content: function() { return $("<ol></ol>") .addClass("padding-left-20") .append("<li>Copy <strong>URL</strong> from textfield.</li>") .append("<li>Open Eclipse Marketplace Client (MPC).</li>") .append("<li>Open <strong>Favorites</strong> tab.</li>") .append("<li>Click on <strong>Import Favorites list</strong>.</li>") .append("<li>Paste <strong>URL</strong> in the textfield.</li>"); } }); }, error: function() { $(this).html(self.settings.errorMsg); } }); function getFavoritesByNodes(nodestr) { var url = self.settings.marketplaceUrl + "/node/" + nodestr + "/api/p"; $.ajax(url, { context: self.element, success: function(data) { var listingContainer = $("#mpfavorites-list"); var nodes = $("node", data); nodes.each(function(index, value) { // Extract relevant data from XML var node = $(value); var shortdescription = node.find("shortdescription").text(); var title = value.getAttribute("name"); var timestamp_lastupdated = node.find("changed").text(); var owner = node.find("owner").text(); var lastupdated = "Last Updated on " + self.dateFormat(new Date(parseInt(timestamp_lastupdated * 1000))) + " by " + owner; var nid = value.getAttribute("id"); var listing = $("#mp-listing-template").clone().removeClass("hidden").removeAttr("id"); var link = $("<a></a>"); var category = $("category", value); var url_listing = self.settings.marketplaceUrl + "/node/" + nid; var image = node.find("image").text(); var link_listing = link.clone().attr({ "href": url_listing }); category.each(function(i, v) { var catlink = link.clone().attr({ "href": v.getAttribute("url") }).text(v.getAttribute("name")); if (category.length !== (i + 1)) { catlink.append(", "); } listing.find(".content-categories").append(catlink); }); listing.find(".listing-image").attr({ "href": url_listing, "style": "background:url('" + image + "') no-repeat center;" }); listing.find(".drag").attr({ "href": self.settings.marketplaceUrl + "/marketplace-client-intro?mpc_install=" + nid, }); listing.find(".listing-title").html(link_listing.clone().text(title)); listing.find(".content-teaser").html(shortdescription); listing.find(".content-last-updated").html(lastupdated); listingContainer.append(listing); }); }, error: function() { $(this).html(self.settings.errorMsg); } }); } function fetchFavorites(event, page, numPosts) { getFavoritesListByPage(page, numPosts); } function getFavoritesListByPage(pageNum, totalItems) { if (typeof (pageNum) === "undefined") { // default to page 1 pageNum = 1; } if (typeof (totalItems) === "undefined") { // default to settings totalItems = self.settings.itemsPerPage; } var url = apiUrl + "/marketplace/favorites?name=" + username + "&page=" + pageNum + "&pagesize=" + totalItems; $.ajax(url, { context: self.element, success: function(data) { var nodes = []; $.each(data.mpc_favorites, function(k, v) { nodes.push(v.content_id); }); getFavoritesByNodes(nodes.join()); }, error: function() { $(this).html(self.settings.errorMsg); } }); } }, gerritReviewCount: function() { var self = this; var username = this.settings.username; var apiUrl = this.settings.apiUrl; var url = apiUrl + "/account/profile/" + username + "/gerrit"; // Execute ajax request $.ajax(url, { context: this.element, success: function(data) { var count = data.merged_changes_count; $(this).children("strong").text(count + self.plurialString(" review", count)); if (count > 0) { $(this).attr({ "href": self.settings.gerritUrl + "/#/q/owner:" + self.settings.username }); } }, error: function() { $(this).html(self.settings.errorMsg); } }); }, mailingListSubscription: function() { var self = this; var username = self.settings.username; var currentUser = self.settings.currentUser; var currentUserUid = self.settings.currentUserUid; var userCanEditOwnMailingList = self.settings.userCanEditOwnMailingList; var apiUrl = this.settings.apiUrl; // Exit if variables are not set. if (!username && !api_url) { return false; } var container = self.element; var url = apiUrl + "/account/profile/" + username + "/mailing-list"; // Execute ajax request $.ajax(url, { context: this.element, success: function(data) { var subsriptions = data.mailing_list_subscriptions; var p = $("<p></p>"); var h2 = $("<h2></h2>"); var a = $("<a></a>"); var strong = $("<strong></strong>"); var message_user = "This user is"; if (currentUser === username) { message_user = "You are"; } var link = a.clone().attr({ "href": "/user/" + currentUserUid + "/mailing-list", "class": "fa fa-pencil", "aria-hidden": "true" }); $(container).append(h2.text("Eclipse Mailing Lists ").append(link)); if (!jQuery.isEmptyObject(subsriptions)) { $(container).append(p.clone().text("The Eclipse Mailing lists are another way for you to interact with your favorite Eclipse project.")); $(container).append(p.clone().text("Below is a list of the public mailing lists that " + message_user.toLowerCase() + " currently subscribed to at Eclipse.org. When posting emails " + "to our mailing lists, please remember that these lists are public, avoid posting ") .append(strong.clone().text("personal")).append(" or ").append(strong.clone().text("private information")).append(".")); $(container).append(p.clone().text("If you are having trouble using our mailing lists, please contact ") .append(a.clone().attr("href", "mailto:[email protected]").text("[email protected]")).append(".")); // Create table var table = $("<table></table>").attr({ "width": "100%", "class": "table", "id": "aeri-reports" }); var tr = $("<tr></tr>"); var th = $("<th></th>"); // Title Header tr.append(th.clone().text("Mailing List").attr("width", "30%")); tr.append(th.clone().text("Description").attr("width", "70%")); // Insert heading row in table table.append(tr); // Responsive container to wrap the table var responsive_wrapper = $("<div></div>").attr({ "class": "table-responsive" }); // append table to container responsive_wrapper.append(table); $(container).append(responsive_wrapper); $(container).append(p); // Add a row in the table for each Error Reports $.each(subsriptions, function(index, value) { var tr = $("<tr></tr>"); var td = $("<td></td>"); // Title column tr.append(td.clone().append(a.clone().attr("href", "/mailing-list/" + value.list_name).text(value.list_name))); // Description column tr.append(td.clone().append(value.list_description)); table.append(tr); }); } else { $(container).append(p.clone().text(message_user + " not subscribed to any Eclipse mailing list.")); } if (currentUser === username && userCanEditOwnMailingList) { $(container).append(p.clone().append(a.clone().attr({ "href": "/user/" + currentUserUid + "/mailing-list", "class": "btn btn-primary btn-xs" }).text("Manage your Mailing Lists"))); } }, error: function() { $(this).html(self.settings.errorMsg); } }); }, gerritReviews: function() { var self = this; // Build gerrit url var gerrit_url = this.settings.gerritUrl + "/changes/?q=owner:" + this.settings.username + "+status:open&q=reviewer:" + this.settings.username + "+status:open+-owner:" + this.settings.username + "&pp=0"; $(this.element).append($("<h2>Eclipse Gerrit</h2>").addClass("h3")); $(this.element).append("<p>Gerrit is a web based code review system, facilitating " + "online code reviews for projects using the Git version control system.</p>"); // Fetch data gerritRequest(gerrit_url); function gerritRequest(url) { var pagesize = 100; var skip = 0; var errorCondition = false; var labels = [ ["gerrit-outgoing", []], ["gerrit-incoming", []] ]; $(self.element).on("drawTableEvent", drawOutput); // get all pages of data getAllPages(url, pagesize, skip); function drawOutput() { // table id's and to determine section title $.each(labels, function(index, value) { var title = ""; switch (value[0]) { case "gerrit-outgoing": title = "Outgoing Reviews"; break; case "gerrit-incoming": title = "Incoming Reviews"; break; } var h2 = $("<h4></h4>").addClass("h4").text(title); $(self.element).append(h2); if (value[1].length === 0) { // this result array is empty $(self.element).append("<div class=\"alert alert-warning\" role=\"alert\">" + "There are no " + title.toLowerCase() + " for this user." + "</div>"); return; } $(self.element).append(buildGerritTable(value[0], value[1])); $(self.element).append(self.getPaginationBar(value[1].length, value[0])); }); var more_gerritlink = $("<a></a>").attr({ "href": self.settings.gerritUrl + "/#/q/owner:" + self.settings.username, "class": "btn btn-primary btn-sm", "style": "display:block" }).html("<i class=\"fa fa-angle-double-right\" aria-hidden=\"true\"></i> More"); $(self.element).append(more_gerritlink); function buildGerritTable(id, data) { // Create table var table = $("<table></table>").attr({ "width": "100%", "class": "table", "id": id }); var tr = $("<tr></tr>"); var th = $("<th></th>"); var td = $("<td></td>"); tr.append(th.clone().text("Subject").attr("width", "70%")); tr.append(th.clone().text("Status").attr({ "width": "18%", "class": "text-center" })); tr.append(th.clone().text("Updated").attr({ "width": "12%", "class": "text-center" })); table.append(tr); // Insert rows in table var a = $("<a></a>"); $.each(data, function(index, value) { tr = $("<tr></tr>"); var merge_conflict = ""; if (value.mergeable === false) { merge_conflict = "Merge Conflict"; tr.addClass("warning"); } var date = value.updated.substring(0, value.updated.indexOf(" ")); tr.append(td.clone().html(a.clone().attr({ "href": self.settings.gerritUrl + "/" + value._number }).text(value.subject)).append("<br/>" + value.project)); tr.append(td.clone().text(merge_conflict).attr("class", "text-center")); tr.append(td.clone().text(date).attr("class", "text-center")); table.append(tr); }); // append table to container var responsive_wrapper = $("<div></div>").attr({ "class": "table-responsive" }); responsive_wrapper.append(table); return responsive_wrapper; } } function getAllPages(url, pagesize, skip) { pagesize = (typeof (pagesize) !== "undefined") ? pagesize : 100; skip = (typeof (skip) !== "undefined") ? skip : 0; url += "&start=" + skip + "&n=" + pagesize; return $.ajax(url, { dataType: "gerrit_XSSI", context: self.element, converters: { "text gerrit_XSSI": function(result) { var lines = result.substring(result.indexOf("\n") + 1); return jQuery.parseJSON(lines); } }, success: function(data) { var lastElement1 = Object; var lastElement2 = Object; if (data[0].length !== 0) { $.merge(labels[0][1], data[0]); lastElement1 = data[0][data[0].length - 1]; } if (data[1].length !== 0) { $.merge(labels[1][1], data[1]); lastElement2 = data[1][data[1].length - 1]; } if (("_more_changes" in lastElement1 && lastElement1._more_changes === true) || ("_more_changes" in lastElement2 && lastElement2._more_changes === true)) { getAllPages(url, pagesize, skip + pagesize); } else { $(self.element).trigger("drawTableEvent"); } }, error: function(data) { if (data.status === 400) { $(this).html(self.settings.gerritUserNotFoundMsg); } else { $(this).html(self.settings.errorMsg); } errorCondition = true; } }); } } }, recentEvents: function() { var self = this; // compare two dates function compareDates(d1, d2) { return (d1.dateTime - d2.dateTime); } // Execute ajax request $.ajax(this.settings.eventUrl, { context: this.element, success: function(data) { var today = new Date(); var upcomingEvents = []; // Fetch only upcoming events. for (var i in data.events) { data.events[i].dateTime = new Date(data.events[i].date); if (data.events[i].dateTime >= today) { upcomingEvents.push(data.events[i]); } } // Sort upcoming events. upcomingEvents.sort(compareDates); // Build output var list = $("<ul></ul>").attr({ "class": "nav", "style": "margin:0" }); for (var x in upcomingEvents.slice(0, 5)) { var ed = upcomingEvents[x].dateTime; var formatedDate = self.dateFormat(ed); var link = $("<a>").attr({ "href": upcomingEvents[x].infoLink }) .html(upcomingEvents[x].title + "<br/><small>" + formatedDate + "</small>"); var item = $("<li></li>").append(link); list.append(item); } // Remove loading $(this).children(".loading").remove(); // Display events $(this).append(list); var more_link = $("<a>").attr({ "href": "http://events.eclipse.org", "class": "btn btn-simple btn-sm" }).text("more"); $(this).append(more_link); }, error: function() { $(this).html(self.settings.errorMsg); } }); }, plurialString: function(string, count) { if (count > 1) { string += "s"; } return string; }, dateFormat: function(date) { var monthList = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var dayList = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", ]; var fullYear = date.getFullYear(); var fullMonth = monthList[date.getMonth()]; var fullDay = dayList[date.getDay()]; var day = date.getDate(); var hour = ("0" + (date.getHours())).slice(-2); var min = ("0" + (date.getMinutes())).slice(-2); var time = fullDay + ", " + fullMonth + " " + day + ", " + fullYear + " - " + hour + ":" + min; return time; }, // Class to parse and fetch values from the link header pagination linkHeaderParser: function(header) { var self = this; this.links = 0; this.getLastPageNum = function() { if (typeof (self.links.last) === "undefined") { return 0; } return getParamValue(self.links.last, "page"); }; this.getPageSize = function() { // grab pagesize from the first item if (typeof (self.links.first) === "undefined") { return 0; } // check first for pagesize, which we use var size = getParamValue(self.links.first, "pagesize"); if (size === 0) { // it's not there, try size (used by aeri) return getParamValue(self.links.first, "size"); } return size; }; if (typeof (header) === "undefined" || header === null) { // nothing to do return; } // Split the links by comma var linkItem = header.split(","); var links = {}; // Parse each link item for (var i = 0; i < linkItem.length; i++) { // convert any &amp; back to & linkItem[i] = linkItem[i].replace("&amp;", "&"); var section = linkItem[i].split(";"); if (section.length < 2) { // Missing sections from link header, skip to next item continue; } // store the url and query params var url = section[0].replace(/<(.*)>/, "$1").trim(); // use name as index (next, prev, first, last) var name = section[1].replace(/rel="(.*)"/, "$1").trim(); links[name] = url; } this.links = links; function getParamValue(link, param) { if (typeof (param) === "undefined" || typeof (link) === "undefined") { return 0; } var query = link.substr(link.lastIndexOf("?") + 1); var params = query.split("&"); for (var i = 0; i < params.length; i++) { var queryItem = params[i].split("="); if (decodeURIComponent(queryItem[0]) === param) { // return query param value return decodeURIComponent(queryItem[1]); } } // no matching query param found return 0; } }, /** * Create and instantiate the pagination bar for content. In order to make use of this * pagination bar, the given content type must have a listener for the event 'fetchPageItemsEvent'. * * The implementation for the fetchPageItemsEvent listener should have the parameters * (pageNumber, itemsPerPage) to fetch the paged items, and inject them into the * current container context. This will be called when pagination links on the bar are * clicked. * * @param totalItems - * number of items that will be paginated over. * @param elementID - * string constant representing different types of operations * that can be performed. This value should match the ID of * a container that can be acted upon within the application. * @returns a jQuery element containing a navigation bar */ getPaginationBar: function(totalItems, elementID) { var self = this; if (typeof (totalItems) === "undefined") { totalItems = 1; } if (totalItems <= 0 || totalItems <= self.settings.itemsPerPage) { // nothing to do or everything fits on single page return; } //initialize to first page var activePageNum = 1; var pageNav = $("<nav></nav>").attr({ "arial-label": "Page navigation", "id": elementID + "-pager" }).addClass("text-center"); var totalPages = Math.ceil(totalItems / self.settings.itemsPerPage); var ul = drawPageNums(totalPages, activePageNum, elementID); pageNav.append(ul); // create cache if (typeof ($("#" + elementID).data("pageCache")) === "undefined") { cachePages(); } // return the pagination bar return pageNav; /** * Writes each of the numbered pagination links for the pagination bar. * Each of the links will trigger an event to reload the section it is * acting on rather than reload the entire page. * * @param numPages - * maximum number of pages * @param currentPageNum - * the current page number * @param elementID - * the ID of the element calling for an update. This is used * for content matching + event triggers */ function drawPageNums(numPages, currentPageNum, elementID) { var li = $("<li></li>"); var ul = $("<ul></ul>").addClass("pagination"); if (typeof (elementID) !== "undefined") { ul.attr({ "data-eclipseFdnApi-elementID": elementID }); } var showEllipses = false; var ellipses = ""; var minRange = 1; var maxRange = numPages; var clickEvent = function() { var $this = $(this); var toPageNum = $this.attr("data-goto-page"); var parentUL = $this.parents(".pagination").eq(0); var elementID = parentUL.data("eclipsefdnapiElementid"); $("#" + elementID).trigger("changePageEvent", [toPageNum]); }; // if num pages > 9 then set the page range if (numPages > 9) { // default to first of last 9 pages minRange = numPages - 8; if (currentPageNum <= 5) { maxRange = 9; minRange = 1; } else if (currentPageNum <= numPages - 4) { // center the page range relative to current page minRange = currentPageNum - 4; maxRange = currentPageNum + 4; } showEllipses = true; var span = $("<span></span>"); ellipses = li.clone().append( span.clone().html("...").attr({ "aria-hidden": "true" }) ).addClass("pager-ellipses disabled"); } if (currentPageNum !== 1) { ul.append(li.clone().addClass("pager-first").html( getPagerLink("First", "first page", 1, "<< first").on("click", clickEvent) )); ul.append(li.clone().html( getPagerLink("Previous", "previous page", currentPageNum - 1, "< previous").on("click", clickEvent) )); if (showEllipses === true && minRange > 1) { ul.append(ellipses.clone()); } } // write out page #'s var i; for (i = minRange; i <= maxRange; i++) { var pager = li.clone(); var pagerLink = getPagerLink("Page " + parseInt(i), "page " + parseInt(i), i).on("click", clickEvent); if (currentPageNum === i) { pager.addClass("active"); } pager.html(pagerLink); ul.append(pager); } // close the pager if not at end of index if (currentPageNum < numPages) { if (showEllipses === true && maxRange < numPages) { ul.append(ellipses.clone()); } ul.append(li.clone().html( getPagerLink("Next", "next page", currentPageNum + 1, "next >").on("click", clickEvent) )); ul.append(li.clone().addClass("pager-last").html( getPagerLink("Last", "last page", numPages, "last >>").on("click", clickEvent) )); } return ul; } /** * Creates the pagination link given the following attributes. */ function getPagerLink(label, titlePiece, gotoPage, text) { if (typeof (text) === "undefined") { // use the page num text = parseInt(gotoPage); } var a = $("<a></a>"); return a.attr({ "aria-label": label, "href": "#", "onclick": "return false;", "title": "Go to " + titlePiece, "data-goto-page": parseInt(gotoPage) }).text(text); } /** * Builds the page cache for the current container. This will only live * for the current page, and will disappear when the page is left as * this cache lives on request rather than in-browser or elsewhere. */ function cachePages() { var theElement = $("#" + elementID); var pageCache = []; var pageCacheType; // set the cache type and perform any special handling if needed switch (elementID) { case "gerrit-incoming": case "gerrit-outgoing": pageCacheType = "gerrit"; // build out entire page cache based on existing element data pageCache = buildPageCache(theElement.find("tr")); break; case "mpfavorites-list": pageCacheType = "mpfav"; break; case "forum-posts": case "aeri-reports": pageCacheType = "table"; pageCache = buildPageCache(theElement.find("tr")); break; case "news-container": pageCacheType = "news"; break; case "events-container": pageCacheType = "events"; break; default: pageCacheType = "generic"; } // setup the element data and event for changing pages theElement.data("pageCache", pageCache); theElement.data("pageCacheType", pageCacheType); theElement.data("pageCacheTotalPages", totalPages); theElement.on("changePageEvent", changePage); switch (pageCacheType) { case "gerrit": // trigger redraw of first page theElement.trigger("changePageEvent", [1]); break; } function buildPageCache(data) { var counter = 0; var pageNum = 0; var page = []; var theCache = []; // grab the heading row if this is gerrit or forum table switch (pageCacheType) { case "gerrit": case "table": // set heading row in cache theCache[0] = data[0]; break; } $.each(data, function(index, value) { if ($(value).children().first().is("th")) { // don't cache table headings return true; } if (counter === self.settings.itemsPerPage) { counter = 0; theCache[++pageNum] = page; page = []; } page[counter++] = value; }); // check if any remainder items in page if (page.length > 0) { // add page to the cache theCache[++pageNum] = page; } return theCache; } } /** * Callback for page changes events triggered by pagination links. This * will trigger a call to update the containers content with the next * pages content, as well as update the pagination bar with the new page * set as current. Numbers are shifted if necessary to properly display * the current and following pages. * * This method is internal and requires a listener function be * registered for the 'fetchPageItemsEvent' event. Without the listener * registered, this function will not be able to update content based on * pagination requests. * * @param event - * the triggering pagination update request. * @param goToPageNum - * the requested page number */ function changePage(event, gotoPageNum) { var element = $(event.currentTarget); var pageType = element.data("pageCacheType"); var pageCache = element.data("pageCache"); // get the pager var elementID = element.attr("id"); var nav = $("#" + elementID + "-pager"); // get pager's current page var currentPage = nav.data("currentPage"); if (typeof (currentPage) === "undefined" || currentPage === null) { // if it's not set, assume it's 1st page currentPage = 1; } if (typeof (gotoPageNum) === "undefined") { // something is wrong. go back to 1st page gotoPageNum = 1; } // comes in as string gotoPageNum = parseInt(gotoPageNum); switch (pageType) { case "gerrit": fillElementWithPage(); break; default: addCurrentPageToCache(); fillElementWithPage(); break; } //Replace the pager bar with updated layout if (currentPage !== gotoPageNum) { var totalPages = element.data("pageCacheTotalPages"); var newUL = drawPageNums(totalPages, gotoPageNum, elementID); nav.find("ul").replaceWith(newUL); nav.data("currentPage", gotoPageNum); } function fillElementWithPage() { // empty element first element.empty(); //if not in cache if (typeof (pageCache[gotoPageNum]) === "undefined") { var params = []; // different params for mpc or forum / AERI switch (pageType) { case "mpfav": case "table": case "news": case "events": params.push(gotoPageNum); params.push(element.data("postsPerPage")); break; } // if table, put the heading back before triggering fetch and returning if (element.is("table")) { // this should be just the heading element.append(pageCache[0]); } element.trigger("fetchPageItemsEvent", params); return; } // fill in items from cache if (element.is("table")) { element.append(pageCache[0]); } $.each(pageCache[gotoPageNum], function(index, value) { element.append(value); }); } /** * Creates an entry in the page cache for the current container with the * current page of data. This reduces outward calls while browsing between pages */ function addCurrentPageToCache() { // only store it if current page is not currently cached if (typeof (pageCache[currentPage]) === "undefined") { var items = []; pageCache[currentPage] = []; if (element.is("table")) { // pull out the table rows items = element.find("tr"); } else if (element.is("div")) { // assume mpc nodes or items items = element.find(".node,.item"); } $.each(items, function(index, value) { if ($(value).children().first().is("th")) { // heading is already cached - skip to next return true; } pageCache[currentPage].push(value); }); // update stored cache element.data("pageCache", pageCache); } } } }, /** * Injects news items into the page from the Eclipse newsroom, given a few * HTML data attributes on the element this is called on. The data * attributes that can be used will filter the results that are displayed on * page. */ newsItems: function() { // set up initial state and call data var self = this; var $container = $($(this)[0].element); // get the news item container var $newsContainer = $container.find("> div.news-container"); if ($newsContainer.length === 0) { $newsContainer = $("<div></div>"); $newsContainer.attr({ "class": "news-container", "id": "news-container" }); $container.append($newsContainer); } if ($container.data("pagination") === true) { $newsContainer.on("fetchPageItemsEvent", retrieveNewsItems); } retrieveNewsItemsByPage($newsContainer, 1, 5); /** * Listener callback method for fetchPageItemsEvent event. */ function retrieveNewsItems(event, page, pageSize) { retrieveNewsItemsByPage(event.target, page, pageSize); } /** * Retrieves news items for the given page, injected into the element that is passed * as the context element. This method uses the following data attributes to filter * the data, allowing the use of strings or array values: * * - data-publish-target * - data-news-count * - data-news-type * * The data attribute 'data-template-id' can be used to defined a new mustache script * template ID. This script would need to be present on the page and would be used in * place of the default template to generate news items. * * @param contextEl - * the element that called for the news items injection * @param page - * page of news items to retrieve * @param pageSize - * the number of items to retrieve. This is overridden by whatever is * explicitly defined in the data-news-count attribute on the parent container. */ function retrieveNewsItemsByPage(contextEl, page, pageSize) { // get the container element for the current call var $newsContainer = $(contextEl); var $parent = $newsContainer.parent(); // check how many to display with a default of 5 var displayCount = $parent.data("news-count") || pageSize || 5; var filter = "?page=" + page; filter += "&pagesize=" + displayCount; // generate filters based on publish and type targets filter += convertDataToURLParameters($parent, "publish-target", "publish_to", "eclipse_org"); filter += convertDataToURLParameters($parent, "news-type", "news_type", ""); // create the GET URL for news items var url = self.settings.newsroomUrl + "/news" + filter; $.ajax(url, { success: function(data, textStatus, jqXHR) { var newsItems = data["news"]; if (newsItems.length > displayCount) { newsItems = newsItems.slice(0, displayCount); } // post process the date to update date format for (var i = 0; i < newsItems.length; i++) { newsItems[i].date = self.dateFormat(new Date(newsItems[i].date)); newsItems[i].index = i; } // allow template ID to be set on a per run basis with a default. var templateId = $parent.data("template-id") || "template-news-items"; var template = getTemplate(templateId); var rendered = Mustache.render(template, { news: newsItems }); // clear the container before creating elements $newsContainer.html(rendered); if ($parent.data("pagination") === true && $parent.find("nav").length === 0) { var linkHeader = new self.linkHeaderParser(jqXHR.getResponseHeader("Link")); var lastPage = linkHeader.getLastPageNum(); // check if itemsPerPage should be updated to returned value if (linkHeader.getPageSize() !== self.settings.itemsPerPage) { self.settings.itemsPerPage = linkHeader.getPageSize(); } // add pagination bar $parent.append(self.getPaginationBar(lastPage * self.settings.itemsPerPage, $newsContainer.attr("id"))); } $parent.trigger("shown.ef.news"); }, error: function() { // clear the loading placeholder $container.empty(); // display an error message var $errorEl = $("<div></div>"); $errorEl.attr("class", "alert alert-warning"); $errorEl.text("Unable to load news content currently."); $container.append($errorEl); } }); } /** * Returns the mustache template for generating the list of news items from * the JSON data. * * @param templateId - * the ID of the script template to use when generating the news items * @returns the mustache template for generating the news list HTML */ function getTemplate(templateId) { var newsTemplate = $("#" + templateId); if (newsTemplate !== undefined && newsTemplate.length !== 0) { return newsTemplate[0].innerHTML; } return "{{#news}}" + "<div class=\"item block-summary-item\" data-mh=\"group-{{ index }}\">" + "<p>{{ date }}</p>" + "<h4><a href=\"{{ link }}\">{{ title }}</a></h4>" + "<p>{{ body }}</p>" + "</div>" + "{{/news}}"; } }, filteredEvents: function() { // set up initial state and call data var self = this; var $container = $($(this)[0].element); // get the news item container var $eventsContainer = $container.find("> div.events-container"); if ($eventsContainer.length === 0) { $eventsContainer = $("<div></div>"); $eventsContainer.attr({ "class": "events-container", "id": "events-container" }); $container.append($eventsContainer); } if ($container.data("pagination") === true) { $eventsContainer.on("fetchPageItemsEvent", retrieveFilteredEvents); } retrieveFilteredEventsByPage($eventsContainer, 1, 5); /** * Listener callback method for fetchPageItemsEvent event. */ function retrieveFilteredEvents(event, page, pageSize) { retrieveFilteredEventsByPage(event.target, page, pageSize); } /** * Retrieves event items for the given page, injected into the element that is passed * as the context element. This method uses the following data attributes to filter * the data, allowing the use of strings or array values: * * - data-publish-target * - data-count * - data-type * - data-upcoming * - data-sort-order * - data-sort-field * * The data attribute 'data-template-id' can be used to defined a new mustache script * template ID. This script would need to be present on the page and would be used in * place of the default template to generate event items. * * @param contextEl - * the element that called for the news items injection * @param page - * page of news items to retrieve * @param pageSize - * the number of items to retrieve. This is overridden by whatever is * explicitly defined in the data-count attribute on the parent container. */ function retrieveFilteredEventsByPage(contextEl, page, pageSize) { // get the container element for the currentcall var $eventsContainer = $(contextEl); var $parent = $eventsContainer.parent(); var displayCount = $parent.data("count") || pageSize || 5; var filter = "?page=" + page; filter += "&pagesize=" + displayCount; filter += convertDataToURLParameters($parent, "publish-target", "publish_to", undefined); filter += convertDataToURLParameters($parent, "type", "type", undefined); filter += convertDataToURLParameters($parent, "upcoming", "upcoming_only", undefined); // if upcoming is set to 1 (PHP true) then set default sorting var upcoming = $parent.data("upcoming") === 1 ? true : false; var sortOrder = $parent.data("sort-order") || (upcoming ? "ASC" : undefined); var sortField = $parent.data("sort-field") || (upcoming ? "field_event_date" : undefined); // special treatment for sort option if (sortOrder && sortField) { filter += "&options%5Borderby%5D%5B" + sortField + "%5D=" + sortOrder; } // create the GET URL for news items var url = self.settings.newsroomUrl + "/events" + filter; $.ajax(url, { success: function(data, textStatus, jqXHR) { var events = data["events"]; if (events.length > displayCount) { events = events.slice(0, displayCount); } // post process the date to update date format for (var i = 0; i < events.length; i++) { // remove registration completely if event is in the past or link is missing if (Date.now() > new Date(events[i]["end-date"]) || !events[i]["registration"]) { delete events[i]["registration"]; } if (!events[i]["infoLink"]) { delete events[i]["infoLink"]; } events[i].date = self.dateFormat(new Date(events[i].date)); events[i]["end-date"] = self.dateFormat(new Date(events[i]["end-date"])); } // allow template ID to be set on a per run basis with a default. var templateId = $parent.data("template-id") || "template-event-items"; var isArchive = $parent.data("archive") || false; var template = getTemplate(templateId, isArchive); var rendered = Mustache.render(template, { "events": events }); // set the container HTML to the rendered HTML $eventsContainer.html(rendered); if ($parent.data("pagination") === true && $parent.find("nav").length === 0) { var linkHeader = new self.linkHeaderParser(jqXHR.getResponseHeader("Link")); var lastPage = linkHeader.getLastPageNum(); // check if itemsPerPage should be updated to returned value if (linkHeader.getPageSize() !== self.settings.itemsPerPage) { self.settings.itemsPerPage = linkHeader.getPageSize(); } // add pagination bar $parent.append(self.getPaginationBar(lastPage * self.settings.itemsPerPage, $eventsContainer.attr("id"))); } $parent.trigger("shown.ef.events"); }, error: function() { // clear the loading placeholder $container.empty(); // display an error message var $errorEl = $("<div></div>"); $errorEl.attr("class", "alert alert-warning"); $errorEl.text("Unable to load events content currently."); $container.append($errorEl); } }); } /** * Returns the mustache template for generating the * list of events from the JSON data. * * @param templateId - * the ID of the script template to use * when generating the events * @returns the mustache template for generating the * events list HTML */ function getTemplate(templateId, isArchive) { var eventsTemplate = $("#" + templateId); if (eventsTemplate !== undefined && eventsTemplate.length !== 0) { return eventsTemplate[0].innerHTML; } if (isArchive) { return "{{#events}}" + "<div class=\"item block-summary-item match-height-item\">" + "<h3 class=\"h4\">{{ title }}</h3>" + "<p>{{ locationName }}</p>" + "<p>{{ date }} - {{ end-date }}</p>" + "<p class=\"margin-bottom-0\">" + "{{#registration}}" + "<a class=\"btn btn-secondary\" href=\"{{ registration }}\">Register Now</a>" + "{{/registration}}" + "{{#infoLink}}" + "<a class=\"btn btn-secondary\" href=\"{{ infoLink }}\">More information</a>" + "{{/infoLink}}" + "</p>" + "</div>" + "{{/events}}"; } return "{{#events}}" + "<div class=\"col-sm-12 col-md-6 event item match-height-item-by-row flex-column\">" + "<h3 class=\"h4 flex-grow\">{{ title }}</h3>" + "<p>{{ locationName }}</p>" + "<p class=\"flex-grow\">{{ date }} - {{ end-date }}</p>" + "<p class=\"margin-bottom-0\">" + "{{#infoLink}}" + "<a class=\"btn btn-secondary\" href=\"{{ infoLink }}\">More information</a>" + "{{/infoLink}}" + "{{^infoLink}}" + "{{#registration}}" + "<a class=\"btn btn-secondary\" href=\"{{ registration }}\">Register Now</a>" + "{{/registration}}" + "{{/infoLink}}" + "</p>" + "</div>" + "{{/events}}"; } }, featuredStory: function() { var $container = $($(this)[0].element); updateFeaturedContent($container, "story", this.settings); }, featuredFooter: function() { var $container = $($(this)[0].element); updateFeaturedContent($container, "footer", this.settings); }, customFeaturedContent: function() { var $container = $($(this)[0].element); writeFeaturedContainer(this.settings.featuredContent, $container, this.settings.featuredContentType); }, /** Retrieves and inserts a list of promotions onto the page in the calling container. Will pass the publish target (if set) to target a particular sites promotions. These promotions will not include or create impressions as they aren't meant to be consumed in production by the public. */ allPromos: function() { // set up the callbacks + containers for promos var $container = $($(this)[0].element); var self = this; // create container for promos, to enable pagination bar var $promosContainer = $container.find("> div.promos-container"); if ($promosContainer.length === 0) { $promosContainer = $("<div></div>"); $promosContainer.attr({ "class": "promos-container", "id": "promos-container-" + getPseudoRandomNumber() }); $container.append($promosContainer); } if ($container.data("pagination") === true) { $promosContainer.on("fetchPageItemsAd", retrievePromos); } // trigger first update of promos using first page retrievePromosByPage($promosContainer, 1, 10); /** * Listener callback method for fetchPageItemsAd event. */ function retrievePromos(event, page, pageSize) { retrievePromosByPage(event.target, page, pageSize); } function retrievePromosByPage(contextEl, page, pageSize) { var $currentContainer = $(contextEl); var $parent = $currentContainer.parent(); var displayCount = $parent.data("count") || pageSize || 10; // generate the URL for retrieve promotions var url = self.settings.adsUrl; var filter = "?page=" + page; filter += "&pagesize=" + displayCount; filter += convertDataToURLParameters($parent, "publish-target", "publish_to", undefined); // retrieve the promo data via ajax $.ajax(url + filter, { dataType: "json", type: "GET", success: function(data) { if (data["ads"] === undefined) { console.log("Could not load promotional content. AD-01"); } // add the index of the ad for printing out index to all ads page for (var i = 0; i < data["ads"].length; i++) { data["ads"][i].idx = i; } // call and write the actual promo content writePromoContent($currentContainer, data["ads"], self.settings); // add the pagination bar if ($parent.data("pagination") === true && $parent.find("nav").length === 0) { var linkHeader = new self.linkHeaderParser(jqXHR.getResponseHeader("Link")); var lastPage = linkHeader.getLastPageNum(); // check if itemsPerPage should be updated to returned value if (linkHeader.getPageSize() !== self.settings.itemsPerPage) { self.settings.itemsPerPage = linkHeader.getPageSize(); } // add pagination bar $parent.append(self.getPaginationBar(lastPage * self.settings.itemsPerPage, $currentContainer.attr("id"))); } }, error: function() { console.log("Could not load promotional content. AD-02"); } }); } }, /** Retrieves and inserts a single promotion onto the page in the calling container. Will pass the host, absolute URI path, and additional parameters for the publish target, and promo ID. With these parameters, a post request will be formed that will retrieve a promo with an impressions ID. */ singlePromo: function() { var self = this; var $container = $($(self)[0].element); var $parent = $container.parent(); var url = self.settings.adsUrl; var params = { "host": window.location.host, "source": window.location.pathname, "publish_to": $container.data("publish-target"), }; $.ajax(url, { dataType: "json", contentType: "application/json", type: "POST", data: JSON.stringify(params), success: function(data) { if (data === undefined) { console.log("Could not load promotional content, bad content received. AD-03"); } writePromoContent($container, data, self.settings); $parent.trigger("shown.ef.ads"); }, error: function() { console.log("Could not load promotional content. AD-04"); } }); } }); // A really lightweight plugin wrapper around the constructor, // preventing against multiple instantiations $.fn[pluginName] = function(options) { return this.each(function() { if (!$.data(this, "plugin_" + pluginName)) { $.data(this, "plugin_" + pluginName, new Plugin(this, options)); } }); }; var writePromoContent = function($container, promos, settings) { var template = getPromoTemplate($container.data("template-id"), settings); $container.html(Mustache.render(template, { "content": promos })); } /** Centralize the fetching of promo templates to make it more transparent and easy to manage. @param templateId the id of the Mustache template script if it exists @param settings the current plugin settings */ var getPromoTemplate = function(templateId, settings) { if (settings.type === "allPromos") { return getMustacheTemplate(templateId, "{{#content}}" + "<p>" + "<a href=\"http://www.eclipse.org/home/index.php?ad_id={{ id }}\">Ad ID: {{ id }}</a>" + "<span class=\"margin-left-10\">prob: {{ weight }}%</span>" + "<div class=\"eclipsefnd-ad ad-strategic ad-strategic-default\">" + "<a href=\"{{ url }}\" rel=\"nofollow\" style=\"background-image: url('{{ image }}')\">{{ member_name }}</a>" + "</div>" + "</p>" + "{{/content}}"); } return getMustacheTemplate(templateId, "{{#content}}" + "<div class=\"eclipsefnd-ad ad-strategic ad-strategic-default\">" + "<a href=\"{{ url }}\" rel=\"nofollow\" style=\"background-image: url('{{ image }}')\">{{ member_name }}</a>" + "</div>" + "{{/content}}"); } var updateFeaturedContent = function(container, type, settings) { var $container = $(container); var url = settings.newsroomUrl + "/featured_story"; // get the ID of the featured story if set var id = $container.data("id"); if (id !== undefined) { url += "/" + id; } // add parameter for publish target for featured content url += convertDataToURLParameters($container, "publish-target", "publish_to", undefined, true); $.ajax(url, { success: function(data) { if (data["featured_story"] === undefined) { console.log("Could not load featured content, bad content recieved"); } var json = data["featured_story"].filter(function(a) { return new Date(a["end-date"]) > new Date() && (a["start-date"] === undefined || new Date(a["start-date"]) < new Date()); }).filter(function(a) { return a["type"] === type || a["type"] === "both"; }); // shuffle the array so that a random available data is featured if (json.length > 1) { shuffleArray(json); } // make sure we have a promotion to display if (json.length > 0) { writeFeaturedContainer(json[0], $container, type); } else { var default_featured_story = { id: "default-featured-story", layout: "light", title: "Eclipse Foundation Events", body: "Join the world’s leading technologists and open source leaders at Eclipse Foundation events to share ideas, learn and collaborate.", links: [ { url: "https://events.eclipse.org", title: "View Events" } ], } writeFeaturedContainer(default_featured_story, $container, "both"); } }, error: function() { // clear the loading placeholder console.log("Could not load featured content!"); } }); } var writeFeaturedContainer = function(item, $container, type) { // get the content container and append the content var $featuredContentContainer = $container.find(".featured-container"); $container.addClass("featured-story-nid-" + item.id); $container.addClass("featured-story-" + item.layout); // allow template ID to be set on a per run basis with a default. var templateId = $container.data("template-id") || "template-featured-" + type; var template = getMustacheTemplate(templateId, "{{#content}}" + "<h2 class=\"margin-top-30\">{{ title }}</h2>" + "<p>{{ body }}</p>" + "<ul class=\"list-inline list-inline-xs-margin\">{{#links}}<li><a class=\"btn btn-primary\" href=\"{{ url }}\">{{ title }}</a></li>{{/links}}</ul>" + "{{/content}}"); var rendered = Mustache.render(template, { "content": item }); // set the container HTML to the rendered HTML $featuredContentContainer.html(rendered); } var convertDataToURLParameters = function(el, name, parameterName, defaultVal, first) { var dataValue = el.data(name) || defaultVal; var filter = ""; if (Array.isArray(dataValue)) { for (var dataIdx = 0; dataIdx < dataValue.length; dataIdx++) { if (first && dataIdx === 0) { filter += "?"; } else { filter += "&"; } filter += "parameters%5B" + parameterName + "%5D%5B%5D=" + dataValue[dataIdx]; } } else if (dataValue !== undefined) { if (first) { filter += "?"; } else { filter += "&"; } filter += "parameters%5B" + parameterName + "%5D=" + dataValue; } return filter; }; var getMustacheTemplate = function(templateId, defaultTemplate) { var template = $("#" + templateId); if (template !== undefined && template.length !== 0) { return template[0].innerHTML; } return defaultTemplate; } /** * Randomize array element order in-place. Using Durstenfeld shuffle algorithm. * source: * https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array */ var shuffleArray = function(array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp; } }; })(jQuery, window, document);
src/jquery.eclipsefdn-api.js
// the semi-colon before function invocation is a safety net against concatenated // scripts and/or other plugins which may not be closed properly. (function($, window, document, undefined) { "use strict"; // undefined is used here as the undefined global variable in ECMAScript 3 is // mutable (ie. it can be changed by someone else). undefined isn"t really being // passed in so we can ensure the value of it is truly undefined. In ES5, undefined // can no longer be modified. // window and document are passed through as local variables rather than global // as this (slightly) quickens the resolution process and can be more efficiently // minified (especially when both are regularly referenced in your plugin). // Create the defaults once var pluginName = "eclipseFdnApi", defaults = { apiUrl: "https://api.eclipse.org", gerritUrl: "https://git.eclipse.org/r", eventUrl: "https://newsroom.eclipse.org/api/events", adsUrl: "https://newsroom.eclipse.org/api/ads", forumsUrl: "https://www.eclipse.org/forums", marketplaceUrl: "https://marketplace.eclipse.org", username: "cguindon", currentUser: "", contentPlaceholder: null, errorMsg: "<i class=\"fa red fa-exclamation-triangle\" aria-hidden=\"true\"></i> An unexpected error has occurred.", gerritUserNotFoundMsg: "<h2 class=\"h3\">Outgoing Reviews</h2>There are no outgoing reviews for this user.<h2 class=\"h3\">Incoming Reviews</h2>There are no incoming reviews for this account.", type: "", itemsPerPage: 10, accountsUrl: "https://accounts.eclipse.org", newsroomUrl: "https://newsroom.eclipse.org/api", featuredContent: {}, featuredContentType: "" }; // The actual plugin constructor function Plugin(element, options) { this.element = element; // jQuery has an extend method which merges the contents of two or // more objects, storing the result in the first object. The first object // is generally empty as we don"t want to alter the default options for // future instances of the plugin this.settings = $.extend({}, defaults, options); this._defaults = defaults; this._name = pluginName; this.init(); } // Avoid Plugin.prototype conflicts $.extend(Plugin.prototype, { init: function() { // Place initialization logic here // You already have access to the DOM element and // the options via the instance, e.g. this.element // and this.settings // you can add more functions like the one below and // call them like the example below var validTypes = [ "mpFavorites", "gerritReviews", "recentEvents", "forumsMsg", "gerritReviewCount", "projectsList", "errorReports", "mailingListSubscription", "newsItems", "filteredEvents", "featuredStory", "featuredFooter", "customFeaturedContent", "allPromos", "singlePromo" ]; if ($.type(this.settings.type) === "string" && $.inArray(this.settings.type, validTypes) !== -1) { this[this.settings.type](); } }, errorReports: function() { var self = this; var userEmail; var container = self.element; var dontProceed = false; // error for unable to get account email info var dspAcctError = "Unable to retrieve account information required to process this request."; // error for authorization denied / failed var dspAuthError = "Authorization to retrieve error reports was denied."; // we're going to need the user's email address to pull in the reports var accountApi = self.settings.apiUrl + "/account/profile/" + self.settings.username; // igc settings // use default auth url for AERI, which will be production accounts var igcSettings = { clientName: "aeriReports", apiUrl: "https://dev.eclipse.org", completeOnAuthorization: false, username: self.settings.username, encodeStorage: true, }; // we'll use this to build the request path, with email in the middle and page options trailing var pathPrefix = "/recommenders/community/aeri/v2/api/v1/reporters/"; var pathSuffix = "/problems"; // default request options, will build path before request var requestOptions = { path: "", method: "GET", cid: "aeri_reports", scope: "eclipse_aeri_view_own_report email openid", // we'll set success callback individually for initial calls and paginated calls successCallback: "", // error callback can be the same for both errorCallback: function(jqXHR) { // display default error msg - we may get more details later if necessary switch (jqXHR.status) { case 404: displayErrorMsg("No submissions found."); break; default: displayErrorMsg(); } } }; // event handler for authorization failed event $(document).on("igcAuthFailed", function(event, authError) { // this is probably message worthy if (authError.clientName === igcSettings.clientName) { displayErrorMsg(dspAuthError); dontProceed = true; } }); // initialize IGC, if an authorization error is pending it should get triggered in the init $(container).eclipseFdnIgc(igcSettings); // we probably want to check if the user cancelled the authorization and not proceed. // timing may be an issue here. if (dontProceed) { // msg already displayed at this point return; } $.ajax({ url: accountApi, context: self.element }) .done(function(data) { if (typeof (data.mail) === "undefined") { displayErrorMsg(dspAcctError, true); return; } userEmail = data.mail; // check again if we should proceed. authorization failure/cancel should have been flagged by now if (dontProceed) { // if we got here, the initial error was not displayed. displayErrorMsg(dspAuthError); return; } // make the call to get the data, we'll need initial lot to build pager requestOptions.path = pathPrefix + userEmail + pathSuffix + "?page=1&size=" + self.settings.itemsPerPage; requestOptions.successCallback = function(data, textStatus, jqXHR) { // create the error reports table buildReportTable(data); // check the link header for total pages // currently the jqXHR object is returned, consider just returning header block along with data var linkHeader = new self.linkHeaderParser(jqXHR.getResponseHeader("Link")); var lastPage = linkHeader.getLastPageNum(); // check if itemsPerPage should be updated to returned value if (linkHeader.getPageSize() !== self.settings.itemsPerPage) { self.settings.itemsPerPage = linkHeader.getPageSize(); } // set fetch posts event $("#aeri-reports").on("fetchPageItemsEvent", fetchErrorReports); // store items per page so we know how many to fetch per page $("#aeri-reports").data("postsPerPage", self.settings.itemsPerPage); // add pagination bar $(container).append(self.getPaginationBar(lastPage * self.settings.itemsPerPage, "aeri-reports")); }; $(document).eclipseFdnIgc.makeRequest(requestOptions); }) .fail(function() { // we're not capturing the reason it failed, but we will display it on the page displayErrorMsg(dspAcctError, true); }); function buildReportTable(data) { // Create table var table = $("<table></table>").attr({ "width": "100%", "class": "table", "id": "aeri-reports" }); var tr = $("<tr></tr>"); var th = $("<th></th>"); // Title Header tr.append(th.clone().text("Title").attr("width", "50%")); // Status Header tr.append(th.clone().text("Status").attr({ "width": "10%", "class": "text-center" })); // Resolution Header tr.append(th.clone().text("Resolution").attr({ "width": "10%", "class": "text-center" })); // Reporters Header tr.append(th.clone().text("Reporters").attr({ "width": "10%", "class": "text-center" })); // Your First Report Header tr.append(th.clone().text("Your First Report").attr({ "width": "20%", "class": "text-center" })); // Insert heading row in table table.append(tr); // Responsive container to wrap the table var responsive_wrapper = $("<div></div>").attr({ "class": "table-responsive" }); // append table to container responsive_wrapper.append(table); $(container).append(responsive_wrapper); // Add a row in the table for each Error Reports $.each(data, function(index, value) { var tr = $("<tr></tr>"); var td = $("<td></td>"); var a = $("<a></a>"); var submissionLinks = $("<ul></ul>"); var li = $("<li></li>"); // main title / problem link var problemLink; // open links in new window a.attr("target", "_blank"); // cycle through links and build out Title column $.each(value.links, function(index, link) { if (link.rel === "problem") { //the problem link - main title link problemLink = a.clone().attr({ "href": link.href }).text(link.title); } if (link.rel === "submission") { if (!link.title) { link.title = "(No error message)"; } submissionLinks.append(li.clone().append(a.clone().attr({ "href": link.href }).html( "<small>" + link.title + "</small>" ))); } }); // Title column tr.append(td.clone().append(problemLink).append(submissionLinks).attr({ "class": "ellipsis white-space-normal", "style": "max-width:200px;" })); // Status column tr.append(td.clone().text(value.status).attr("class", "text-center")); // Resolution column tr.append(td.clone().text(value.resolution).attr("class", "text-center")); // # Reporters column var span = $("<span></span>").attr("class", "badge"); span.text(value.numberOfReporters); tr.append(td.clone().append(span).attr("class", "text-center")); // Date column var d = new Date(value.firstReported); var month = d.getMonth() < 10 ? "0" + d.getMonth() : d.getMonth(); var day = d.getDate() < 10 ? "0" + d.getDate() : d.getDate(); var reportedOn = d.getFullYear() + "-" + month + "-" + day; tr.append(td.clone().text(reportedOn).attr("class", "text-center")); table.append(tr); }); } function displayErrorMsg(msg, prependDefault) { if (typeof (prependDefault) !== "boolean") { prependDefault = false; } if (typeof (msg) === "undefined") { // use the default msg msg = self.settings.errorMsg; } if (prependDefault) { msg = self.settings.errorMsg + msg; } var feedback = $("<p></p>").append(msg); $(self.element).append(feedback); } function fetchErrorReports(event, page, pageSize) { getErrorReportsByPage(page, pageSize); } // fetch reports by page number and use regular call handler // we already have pager and everything setup. function getErrorReportsByPage(pageNum, pageSize) { if (typeof (pageNum) === "undefined") { // default to page 1 pageNum = 1; } if (typeof (pageSize) === "undefined") { // default to settings pageSize = self.settings.itemsPerPage; } // make the call to get the data, we'll need initial lot to build pager requestOptions.path = pathPrefix + userEmail + pathSuffix + "?page=" + pageNum + "&size=" + pageSize; requestOptions.successCallback = function(data) { // send diretly to addReportRows addReportRows(data); }; $(document).eclipseFdnIgc.makeRequest(requestOptions); } }, projectsList: function() { var self = this; var username = this.settings.username; var apiUrl = this.settings.apiUrl; // Exit if variables are not set. if (!username && !api_url) { return false; } // Build api URI. var url = apiUrl + "/account/profile/" + username + "/projects"; // Execute ajax request $.ajax(url, { context: this.element, success: function(data) { var project_count = Object.keys(data).length; if (project_count === undefined) { project_count = 0; } $(this).children("strong").text(project_count + self.plurialString(" project", project_count)); // Exit now if contentPlaceholder is not defined if (!(self.settings.contentPlaceholder instanceof jQuery)) { return false; } var container = $(self.settings.contentPlaceholder); var a = $("<a></a>"); container.append($("<h2></h2>").addClass("h3").text("Eclipse Projects")); container.append("<p>Projects are the organizational unit for open source " + "development work at the Eclipse Foundation. Projects have developers " + "(committers), source code repositories, build servers, downloads, " + "and other resources. The Eclipse Foundation's open source projects " + "are governed by the <a href=\"https://eclipse.org/projects/dev_process/\">Eclipse Development Process</a>.</p>"); var warning_prefix = "This user is"; if (self.settings.currentUser === self.settings.username) { warning_prefix = "You are"; } if (project_count === 0) { container.append("<div class=\"alert alert-warning\" role=\"alert\">" + warning_prefix + " not involved in any Eclipse Projects." + "</div>"); return false; } // Create table var table = $("<table></table>").attr({ "width": "100%", "class": "table" }); var tr = $("<tr></tr>"); var th = $("<th></th>"); var td = $("<td></td>"); tr.append(th.clone().text("Project").attr("width", "85%")); tr.append(th.clone().text("Relation").attr({ "width": "15%", "class": "text-center" })); table.append(tr); // Insert rows in table $.each(data, function(index, value) { var roles = []; var projectName = ""; var activeDate = ""; $.each(value, function(i, v) { roles.push(v.Relation.Description); projectName = v.ProjectName; activeDate = v.ActiveDate; if (v.url !== "") { projectName = a.clone().attr({ "href": v.url }).text(projectName); } }); tr = $("<tr></tr>"); // Replies column tr.append(td.clone().html(projectName).append("<br/><small>Since: " + self.dateFormat(new Date(activeDate)) + "</small>")); tr.append(td.clone().text(roles.join(", ")).attr("class", "text-center")); table.append(tr); }); // append table to container var responsive_wrapper = $("<div></div>").attr({ "class": "table-responsive" }); responsive_wrapper.append(table); container.append(responsive_wrapper); }, error: function() { $(this).html(self.settings.errorMsg); } }); }, forumsMsg: function() { var self = this; var username = this.settings.username; var apiUrl = this.settings.apiUrl; // Exit if variables are not set. if (!username && !api_url) { return false; } // Build api URI. var url = apiUrl + "/account/profile/" + username + "/forum?page=1&pagesize=" + self.settings.itemsPerPage; // Execute ajax request $.ajax(url, { context: this.element, success: function(data, textStatus, jqXHR) { var user_msg_count = 0; if (data.posted_msg_count !== undefined && data.id !== undefined) { user_msg_count = data.posted_msg_count; $(this).attr({ "href": self.settings.forumsUrl + "/index.php/sp/" + data.id + "/", }); } $(this).children("strong").text(user_msg_count + self.plurialString(" topic", user_msg_count)); // Exit now if contentPlaceholder is not defined if (!(self.settings.contentPlaceholder instanceof jQuery)) { return false; } var container = $(self.settings.contentPlaceholder); var a = $("<a></a>"); container.append($("<h2></h2>").addClass("h3").text("Eclipse Forums")); container.append($("<p></p>").append("The Eclipse forums are your way of communicating with the community " + "of people developing and using Eclipse-based tools hosted at Eclipse.org. " + "Please stick to technical issues - and remember, no confidential information - " + "these are public forums!")); var more_forums_link = a.clone().attr({ "href": self.settings.forumsUrl, "class": "btn btn-primary btn-sm", "style": "display:block" }).html("<i class=\"fa fa-angle-double-right\" aria-hidden=\"true\"></i> More"); if (data.posts.length === 0) { container.append("<div class=\"alert alert-warning\" role=\"alert\">" + "This user does not have any activities on Eclipse Forums." + "</div>"); container.append(more_forums_link); return false; } // Create table var table = $("<table></table>").attr({ "width": "100%", "class": "table", "id": "forum-posts" }); var tr = $("<tr></tr>"); var th = $("<th></th>"); if (self.settings.currentUser === self.settings.username) { tr.append(th.clone().attr("width", "8%")); } tr.append(th.clone().text("Topics").attr("width", "50%")); tr.append(th.clone().text("Replies").attr({ "width": "8%", "class": "text-center" })); tr.append(th.clone().text("Views").attr({ "width": "8%", "class": "text-center" })); tr.append(th.clone().text("Last message").attr({ "class": "text-center" })); // Insert heading row in table table.append(tr); // append table to container var responsive_wrapper = $("<div></div>").attr({ "class": "table-responsive" }); responsive_wrapper.append(table); container.append(responsive_wrapper); // draw the inital row data drawForumRows(data); // check the link header for total pages var linkHeader = new self.linkHeaderParser(jqXHR.getResponseHeader("Link")); var lastPage = linkHeader.getLastPageNum(); // check if itemsPerPage should be updated to returned value if (linkHeader.getPageSize() !== self.settings.itemsPerPage) { self.settings.itemsPerPage = linkHeader.getPageSize(); } // set fetch posts event table.on("fetchPageItemsEvent", fetchForumPosts); // store items per page so we know how many to fetch per page table.data("postsPerPage", self.settings.itemsPerPage); // add pagination bar container.append(self.getPaginationBar(lastPage * self.settings.itemsPerPage, "forum-posts")); // get the user id var current_user_id = data.id; // update more forums link more_forums_link.attr({ "href": self.settings.forumsUrl + "/index.php/sp/" + current_user_id + "/", }); // append read more link container.append(more_forums_link); }, error: function() { $(this).html(self.settings.errorMsg); } }); function drawForumRows(data) { var forumTable = $("#forum-posts"); $.each(data.posts, function(index, value) { var request_data = { forum_id: value.thread_forum_id, forum_name: value.forum_name, forum_cat_id: value.forum_name, forum_cat_name: value.cat_name, root_subject: value.root_msg_subject, current_user_last_post_timestamp: value.msg_group_post_stamp, current_user_last_post_subject: value.last_user_msg_subject, thread_id: value.msg_thread_id, thread_reply_count: value.thread_replies, thread_views_count: value.thread_views, thread_last_post_date: value.thread_last_post_date, last_message_timestamp: value.last_msg_post_stamp, last_message_poster_id: value.last_msg_poster_id, last_message_poster_alias: value.last_poster_alias, last_message_last_view: value.read_last_view, current_user_id: data.id }; var tr = $("<tr></tr>"); var td = $("<td></td>"); var a = $("<a></a>"); // Link to forum var forumLink = a.clone().attr({ "href": self.settings.forumsUrl + "/index.php/f/" + request_data.forum_id + "/" }).text(request_data.forum_name); // Link to category var catLink = a.clone().attr({ "href": self.settings.forumsUrl + "/index.php/i/" + request_data.forum_cat_id + "/" }).text(request_data.forum_cat_name); // Concatenate category and form link var forum_cat_link = $("<small></small>").append("<br/>") .append(catLink) .append(" &gt; ") .append(forumLink) .append(" &gt; ") .append(request_data.root_subject) .append("<br>Posted on " + self.dateFormat(new Date(parseInt(request_data.current_user_last_post_timestamp * 1000)))); var read_icon = "fa fa-envelope-open-o"; // Add warning class to row if the user did not see the message if (self.settings.currentUser === self.settings.username && request_data.last_message_last_view < request_data.thread_last_post_date && request_data.last_message_poster_id !== request_data.current_user_id) { tr.addClass("warning"); read_icon = "fa fa-envelope-o"; } if (self.settings.currentUser === self.settings.username) { tr.append(td.clone().html("<i class=\"" + read_icon + "\" aria-hidden=\"true\"></i>").attr("class", "text-center")); } // Topic column tr.append(td.clone().html(a.clone().attr({ "href": self.settings.forumsUrl + "/index.php/t/" + request_data.thread_id + "/" }) .text(request_data.current_user_last_post_subject)) .append(forum_cat_link) ); // Replies column tr.append(td.clone().text(request_data.thread_reply_count).attr("class", "text-center")); // Views column tr.append(td.clone().text(request_data.thread_views_count).attr("class", "text-center")); // Last message column var last_message = $("<small></small>").append(self.dateFormat(new Date(parseInt(request_data.last_message_timestamp * 1000)))).append("<br/> By: ").append(a.clone().attr({ "href": self.settings.forumsUrl + "/index.php/sp/" + request_data.last_message_poster_id + "/" }).text(request_data.last_message_poster_alias)); tr.append(td.clone().html(last_message).attr("class", "text-center")); forumTable.append(tr); }); } function fetchForumPosts(event, page, numPosts) { getForumPostsByPage(page, numPosts); } function getForumPostsByPage(pageNum, pageSize) { if (typeof (pageNum) === "undefined") { // default to page 1 pageNum = 1; } if (typeof (pageSize) === "undefined") { // default to settings pageSize = self.settings.itemsPerPage; } // Build api URI. var url = apiUrl + "/account/profile/" + username + "/forum?page=" + pageNum + "&pagesize=" + pageSize; $.ajax(url, { context: self.element, success: function(data) { drawForumRows(data); }, error: function() { $(this).html(self.settings.errorMsg); } }); } }, mpFavorites: function() { var self = this; var username = this.settings.username; var apiUrl = this.settings.apiUrl; // Exit if variables are not set. if (!username && !api_url) { return false; } // Add content if contentPlaceholder is defined if (self.settings.contentPlaceholder instanceof jQuery) { var container = $(self.settings.contentPlaceholder); var more_marketplace_link = $("<a></a>").attr({ "href": self.settings.marketplaceUrl + "/user/" + username + "/favorites", "class": "btn btn-primary btn-sm", "style": "display:block" }).html("<i class=\"fa fa-angle-double-right\" aria-hidden=\"true\"></i> More"); container.append($("<h2></h2>").addClass("h3").text("Eclipse Marketplace Favorites")); container.append($("<p></p>").append("Eclipse Marketplace is the source for " + "Eclipse-based solutions, products and add-on features. " + "Thousands of developers visit Marketplace on a monthly " + "basis to find new and innovative solutions. Solution providers " + "are encouraged to list their products on Marketplace to " + "gain exposure to the Eclipse developer community.")); } // Build api URI. var url = apiUrl + "/marketplace/favorites?name=" + username + "&page=1&pagesize=" + self.settings.itemsPerPage; // Execute ajax request $.ajax(url, { context: this.element, success: function(data, textStatus, jqXHR) { $(this).children("strong").text(data.result.count + self.plurialString(" favorite", data.result.count)); // Exit now if container is not defined if (typeof container === "undefined") { return false; } // break down the nodestr by itemsPerPage var nodes = []; $.each(data.mpc_favorites, function(k, v) { nodes.push(v.content_id); }); if (nodes.length === 0) { container.append("<div class=\"alert alert-warning\" role=\"alert\">" + "There are no marketplace favorites for this user." + "</div>"); container.append(more_marketplace_link); return false; } // check the link header for total pages var linkHeader = new self.linkHeaderParser(jqXHR.getResponseHeader("Link")); var lastPage = linkHeader.getLastPageNum(); // check if itemsPerPage should be updated to returned value if (linkHeader.getPageSize() !== self.settings.itemsPerPage) { self.settings.itemsPerPage = linkHeader.getPageSize(); } // set the fetch favorites as custom event container.on("fetchPageItemsEvent", fetchFavorites); container.append("<h3 id=\"mpc_list_name\">" + data.mpc_list_name + "</h3>"); container.append("<div class=\"row\"><div class=\"col-md-17\"><div class=\"form-item form-type-textfield form-disabled\">" + "<label>Favorites URL <a href=\"#\" class=\"install-user-favorites\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"top\" title=\"\" data-original-title=\"How to install?\">" + "<i class=\"fa fa-question-circle\" aria-hidden=\"true\"></i></a> </label>" + "<input disabled=\"true\" class=\"form-control form-text\" type=\"text\" value=\"http://marketplace.eclipse.org/user/" + self.settings.username + "/favorites\" size=\"60\" maxlength=\"128\">" + "</div></div><div class=\"col-md-7 margin-top-25 text-right\"><div class=\"drag_installbutton drag_installbutton_v2 drag-install-favorites\">" + "<a href=\"http://marketplace.eclipse.org/user/" + self.settings.username + "/favorites\" class=\"drag\" title=\"How to install?\">" + "<span class=\"btn btn-default\"><i class=\"fa fa-download orange\"></i> Install Favorites</span>" + "<div class=\"tooltip tooltip-below-right\"><h3>Drag to Install!</h3>" + "Drag to your running Eclipse<sup>*</sup> workspace to install this " + "favorite list. <br><sup>*</sup>Requires Eclipse Marketplace Client.</div></a></div></div></div>"); container.append("<div id=\"mpfavorites-list\"></div>"); container.find("#mpfavorites-list").data("postsPerPage", self.settings.itemsPerPage); getFavoritesByNodes(nodes.join()); container.append(self.getPaginationBar(lastPage * self.settings.itemsPerPage, "mpfavorites-list")); container.append(more_marketplace_link); // Add instructions to popover $("a.install-user-favorites").on("click", function(e) { e.preventDefault(); }); $("a.install-user-favorites").popover({ html: true, content: function() { return $("<ol></ol>") .addClass("padding-left-20") .append("<li>Copy <strong>URL</strong> from textfield.</li>") .append("<li>Open Eclipse Marketplace Client (MPC).</li>") .append("<li>Open <strong>Favorites</strong> tab.</li>") .append("<li>Click on <strong>Import Favorites list</strong>.</li>") .append("<li>Paste <strong>URL</strong> in the textfield.</li>"); } }); }, error: function() { $(this).html(self.settings.errorMsg); } }); function getFavoritesByNodes(nodestr) { var url = self.settings.marketplaceUrl + "/node/" + nodestr + "/api/p"; $.ajax(url, { context: self.element, success: function(data) { var listingContainer = $("#mpfavorites-list"); var nodes = $("node", data); nodes.each(function(index, value) { // Extract relevant data from XML var node = $(value); var shortdescription = node.find("shortdescription").text(); var title = value.getAttribute("name"); var timestamp_lastupdated = node.find("changed").text(); var owner = node.find("owner").text(); var lastupdated = "Last Updated on " + self.dateFormat(new Date(parseInt(timestamp_lastupdated * 1000))) + " by " + owner; var nid = value.getAttribute("id"); var listing = $("#mp-listing-template").clone().removeClass("hidden").removeAttr("id"); var link = $("<a></a>"); var category = $("category", value); var url_listing = self.settings.marketplaceUrl + "/node/" + nid; var image = node.find("image").text(); var link_listing = link.clone().attr({ "href": url_listing }); category.each(function(i, v) { var catlink = link.clone().attr({ "href": v.getAttribute("url") }).text(v.getAttribute("name")); if (category.length !== (i + 1)) { catlink.append(", "); } listing.find(".content-categories").append(catlink); }); listing.find(".listing-image").attr({ "href": url_listing, "style": "background:url('" + image + "') no-repeat center;" }); listing.find(".drag").attr({ "href": self.settings.marketplaceUrl + "/marketplace-client-intro?mpc_install=" + nid, }); listing.find(".listing-title").html(link_listing.clone().text(title)); listing.find(".content-teaser").html(shortdescription); listing.find(".content-last-updated").html(lastupdated); listingContainer.append(listing); }); }, error: function() { $(this).html(self.settings.errorMsg); } }); } function fetchFavorites(event, page, numPosts) { getFavoritesListByPage(page, numPosts); } function getFavoritesListByPage(pageNum, totalItems) { if (typeof (pageNum) === "undefined") { // default to page 1 pageNum = 1; } if (typeof (totalItems) === "undefined") { // default to settings totalItems = self.settings.itemsPerPage; } var url = apiUrl + "/marketplace/favorites?name=" + username + "&page=" + pageNum + "&pagesize=" + totalItems; $.ajax(url, { context: self.element, success: function(data) { var nodes = []; $.each(data.mpc_favorites, function(k, v) { nodes.push(v.content_id); }); getFavoritesByNodes(nodes.join()); }, error: function() { $(this).html(self.settings.errorMsg); } }); } }, gerritReviewCount: function() { var self = this; var username = this.settings.username; var apiUrl = this.settings.apiUrl; var url = apiUrl + "/account/profile/" + username + "/gerrit"; // Execute ajax request $.ajax(url, { context: this.element, success: function(data) { var count = data.merged_changes_count; $(this).children("strong").text(count + self.plurialString(" review", count)); if (count > 0) { $(this).attr({ "href": self.settings.gerritUrl + "/#/q/owner:" + self.settings.username }); } }, error: function() { $(this).html(self.settings.errorMsg); } }); }, mailingListSubscription: function() { var self = this; var username = self.settings.username; var currentUser = self.settings.currentUser; var currentUserUid = self.settings.currentUserUid; var userCanEditOwnMailingList = self.settings.userCanEditOwnMailingList; var apiUrl = this.settings.apiUrl; // Exit if variables are not set. if (!username && !api_url) { return false; } var container = self.element; var url = apiUrl + "/account/profile/" + username + "/mailing-list"; // Execute ajax request $.ajax(url, { context: this.element, success: function(data) { var subsriptions = data.mailing_list_subscriptions; var p = $("<p></p>"); var h2 = $("<h2></h2>"); var a = $("<a></a>"); var strong = $("<strong></strong>"); var message_user = "This user is"; if (currentUser === username) { message_user = "You are"; } var link = a.clone().attr({ "href": "/user/" + currentUserUid + "/mailing-list", "class": "fa fa-pencil", "aria-hidden": "true" }); $(container).append(h2.text("Eclipse Mailing Lists ").append(link)); if (!jQuery.isEmptyObject(subsriptions)) { $(container).append(p.clone().text("The Eclipse Mailing lists are another way for you to interact with your favorite Eclipse project.")); $(container).append(p.clone().text("Below is a list of the public mailing lists that " + message_user.toLowerCase() + " currently subscribed to at Eclipse.org. When posting emails " + "to our mailing lists, please remember that these lists are public, avoid posting ") .append(strong.clone().text("personal")).append(" or ").append(strong.clone().text("private information")).append(".")); $(container).append(p.clone().text("If you are having trouble using our mailing lists, please contact ") .append(a.clone().attr("href", "mailto:[email protected]").text("[email protected]")).append(".")); // Create table var table = $("<table></table>").attr({ "width": "100%", "class": "table", "id": "aeri-reports" }); var tr = $("<tr></tr>"); var th = $("<th></th>"); // Title Header tr.append(th.clone().text("Mailing List").attr("width", "30%")); tr.append(th.clone().text("Description").attr("width", "70%")); // Insert heading row in table table.append(tr); // Responsive container to wrap the table var responsive_wrapper = $("<div></div>").attr({ "class": "table-responsive" }); // append table to container responsive_wrapper.append(table); $(container).append(responsive_wrapper); $(container).append(p); // Add a row in the table for each Error Reports $.each(subsriptions, function(index, value) { var tr = $("<tr></tr>"); var td = $("<td></td>"); // Title column tr.append(td.clone().append(a.clone().attr("href", "/mailing-list/" + value.list_name).text(value.list_name))); // Description column tr.append(td.clone().append(value.list_description)); table.append(tr); }); } else { $(container).append(p.clone().text(message_user + " not subscribed to any Eclipse mailing list.")); } if (currentUser === username && userCanEditOwnMailingList) { $(container).append(p.clone().append(a.clone().attr({ "href": "/user/" + currentUserUid + "/mailing-list", "class": "btn btn-primary btn-xs" }).text("Manage your Mailing Lists"))); } }, error: function() { $(this).html(self.settings.errorMsg); } }); }, gerritReviews: function() { var self = this; // Build gerrit url var gerrit_url = this.settings.gerritUrl + "/changes/?q=owner:" + this.settings.username + "+status:open&q=reviewer:" + this.settings.username + "+status:open+-owner:" + this.settings.username + "&pp=0"; $(this.element).append($("<h2>Eclipse Gerrit</h2>").addClass("h3")); $(this.element).append("<p>Gerrit is a web based code review system, facilitating " + "online code reviews for projects using the Git version control system.</p>"); // Fetch data gerritRequest(gerrit_url); function gerritRequest(url) { var pagesize = 100; var skip = 0; var errorCondition = false; var labels = [ ["gerrit-outgoing", []], ["gerrit-incoming", []] ]; $(self.element).on("drawTableEvent", drawOutput); // get all pages of data getAllPages(url, pagesize, skip); function drawOutput() { // table id's and to determine section title $.each(labels, function(index, value) { var title = ""; switch (value[0]) { case "gerrit-outgoing": title = "Outgoing Reviews"; break; case "gerrit-incoming": title = "Incoming Reviews"; break; } var h2 = $("<h4></h4>").addClass("h4").text(title); $(self.element).append(h2); if (value[1].length === 0) { // this result array is empty $(self.element).append("<div class=\"alert alert-warning\" role=\"alert\">" + "There are no " + title.toLowerCase() + " for this user." + "</div>"); return; } $(self.element).append(buildGerritTable(value[0], value[1])); $(self.element).append(self.getPaginationBar(value[1].length, value[0])); }); var more_gerritlink = $("<a></a>").attr({ "href": self.settings.gerritUrl + "/#/q/owner:" + self.settings.username, "class": "btn btn-primary btn-sm", "style": "display:block" }).html("<i class=\"fa fa-angle-double-right\" aria-hidden=\"true\"></i> More"); $(self.element).append(more_gerritlink); function buildGerritTable(id, data) { // Create table var table = $("<table></table>").attr({ "width": "100%", "class": "table", "id": id }); var tr = $("<tr></tr>"); var th = $("<th></th>"); var td = $("<td></td>"); tr.append(th.clone().text("Subject").attr("width", "70%")); tr.append(th.clone().text("Status").attr({ "width": "18%", "class": "text-center" })); tr.append(th.clone().text("Updated").attr({ "width": "12%", "class": "text-center" })); table.append(tr); // Insert rows in table var a = $("<a></a>"); $.each(data, function(index, value) { tr = $("<tr></tr>"); var merge_conflict = ""; if (value.mergeable === false) { merge_conflict = "Merge Conflict"; tr.addClass("warning"); } var date = value.updated.substring(0, value.updated.indexOf(" ")); tr.append(td.clone().html(a.clone().attr({ "href": self.settings.gerritUrl + "/" + value._number }).text(value.subject)).append("<br/>" + value.project)); tr.append(td.clone().text(merge_conflict).attr("class", "text-center")); tr.append(td.clone().text(date).attr("class", "text-center")); table.append(tr); }); // append table to container var responsive_wrapper = $("<div></div>").attr({ "class": "table-responsive" }); responsive_wrapper.append(table); return responsive_wrapper; } } function getAllPages(url, pagesize, skip) { pagesize = (typeof (pagesize) !== "undefined") ? pagesize : 100; skip = (typeof (skip) !== "undefined") ? skip : 0; url += "&start=" + skip + "&n=" + pagesize; return $.ajax(url, { dataType: "gerrit_XSSI", context: self.element, converters: { "text gerrit_XSSI": function(result) { var lines = result.substring(result.indexOf("\n") + 1); return jQuery.parseJSON(lines); } }, success: function(data) { var lastElement1 = Object; var lastElement2 = Object; if (data[0].length !== 0) { $.merge(labels[0][1], data[0]); lastElement1 = data[0][data[0].length - 1]; } if (data[1].length !== 0) { $.merge(labels[1][1], data[1]); lastElement2 = data[1][data[1].length - 1]; } if (("_more_changes" in lastElement1 && lastElement1._more_changes === true) || ("_more_changes" in lastElement2 && lastElement2._more_changes === true)) { getAllPages(url, pagesize, skip + pagesize); } else { $(self.element).trigger("drawTableEvent"); } }, error: function(data) { if (data.status === 400) { $(this).html(self.settings.gerritUserNotFoundMsg); } else { $(this).html(self.settings.errorMsg); } errorCondition = true; } }); } } }, recentEvents: function() { var self = this; // compare two dates function compareDates(d1, d2) { return (d1.dateTime - d2.dateTime); } // Execute ajax request $.ajax(this.settings.eventUrl, { context: this.element, success: function(data) { var today = new Date(); var upcomingEvents = []; // Fetch only upcoming events. for (var i in data.events) { data.events[i].dateTime = new Date(data.events[i].date); if (data.events[i].dateTime >= today) { upcomingEvents.push(data.events[i]); } } // Sort upcoming events. upcomingEvents.sort(compareDates); // Build output var list = $("<ul></ul>").attr({ "class": "nav", "style": "margin:0" }); for (var x in upcomingEvents.slice(0, 5)) { var ed = upcomingEvents[x].dateTime; var formatedDate = self.dateFormat(ed); var link = $("<a>").attr({ "href": upcomingEvents[x].infoLink }) .html(upcomingEvents[x].title + "<br/><small>" + formatedDate + "</small>"); var item = $("<li></li>").append(link); list.append(item); } // Remove loading $(this).children(".loading").remove(); // Display events $(this).append(list); var more_link = $("<a>").attr({ "href": "http://events.eclipse.org", "class": "btn btn-simple btn-sm" }).text("more"); $(this).append(more_link); }, error: function() { $(this).html(self.settings.errorMsg); } }); }, plurialString: function(string, count) { if (count > 1) { string += "s"; } return string; }, dateFormat: function(date) { var monthList = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var dayList = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", ]; var fullYear = date.getFullYear(); var fullMonth = monthList[date.getMonth()]; var fullDay = dayList[date.getDay()]; var day = date.getDate(); var hour = ("0" + (date.getHours())).slice(-2); var min = ("0" + (date.getMinutes())).slice(-2); var time = fullDay + ", " + fullMonth + " " + day + ", " + fullYear + " - " + hour + ":" + min; return time; }, // Class to parse and fetch values from the link header pagination linkHeaderParser: function(header) { var self = this; this.links = 0; this.getLastPageNum = function() { if (typeof (self.links.last) === "undefined") { return 0; } return getParamValue(self.links.last, "page"); }; this.getPageSize = function() { // grab pagesize from the first item if (typeof (self.links.first) === "undefined") { return 0; } // check first for pagesize, which we use var size = getParamValue(self.links.first, "pagesize"); if (size === 0) { // it's not there, try size (used by aeri) return getParamValue(self.links.first, "size"); } return size; }; if (typeof (header) === "undefined" || header === null) { // nothing to do return; } // Split the links by comma var linkItem = header.split(","); var links = {}; // Parse each link item for (var i = 0; i < linkItem.length; i++) { // convert any &amp; back to & linkItem[i] = linkItem[i].replace("&amp;", "&"); var section = linkItem[i].split(";"); if (section.length < 2) { // Missing sections from link header, skip to next item continue; } // store the url and query params var url = section[0].replace(/<(.*)>/, "$1").trim(); // use name as index (next, prev, first, last) var name = section[1].replace(/rel="(.*)"/, "$1").trim(); links[name] = url; } this.links = links; function getParamValue(link, param) { if (typeof (param) === "undefined" || typeof (link) === "undefined") { return 0; } var query = link.substr(link.lastIndexOf("?") + 1); var params = query.split("&"); for (var i = 0; i < params.length; i++) { var queryItem = params[i].split("="); if (decodeURIComponent(queryItem[0]) === param) { // return query param value return decodeURIComponent(queryItem[1]); } } // no matching query param found return 0; } }, /** * Create and instantiate the pagination bar for content. In order to make use of this * pagination bar, the given content type must have a listener for the event 'fetchPageItemsEvent'. * * The implementation for the fetchPageItemsEvent listener should have the parameters * (pageNumber, itemsPerPage) to fetch the paged items, and inject them into the * current container context. This will be called when pagination links on the bar are * clicked. * * @param totalItems - * number of items that will be paginated over. * @param elementID - * string constant representing different types of operations * that can be performed. This value should match the ID of * a container that can be acted upon within the application. * @returns a jQuery element containing a navigation bar */ getPaginationBar: function(totalItems, elementID) { var self = this; if (typeof (totalItems) === "undefined") { totalItems = 1; } if (totalItems <= 0 || totalItems <= self.settings.itemsPerPage) { // nothing to do or everything fits on single page return; } //initialize to first page var activePageNum = 1; var pageNav = $("<nav></nav>").attr({ "arial-label": "Page navigation", "id": elementID + "-pager" }).addClass("text-center"); var totalPages = Math.ceil(totalItems / self.settings.itemsPerPage); var ul = drawPageNums(totalPages, activePageNum, elementID); pageNav.append(ul); // create cache if (typeof ($("#" + elementID).data("pageCache")) === "undefined") { cachePages(); } // return the pagination bar return pageNav; /** * Writes each of the numbered pagination links for the pagination bar. * Each of the links will trigger an event to reload the section it is * acting on rather than reload the entire page. * * @param numPages - * maximum number of pages * @param currentPageNum - * the current page number * @param elementID - * the ID of the element calling for an update. This is used * for content matching + event triggers */ function drawPageNums(numPages, currentPageNum, elementID) { var li = $("<li></li>"); var ul = $("<ul></ul>").addClass("pagination"); if (typeof (elementID) !== "undefined") { ul.attr({ "data-eclipseFdnApi-elementID": elementID }); } var showEllipses = false; var ellipses = ""; var minRange = 1; var maxRange = numPages; var clickEvent = function() { var $this = $(this); var toPageNum = $this.attr("data-goto-page"); var parentUL = $this.parents(".pagination").eq(0); var elementID = parentUL.data("eclipsefdnapiElementid"); $("#" + elementID).trigger("changePageEvent", [toPageNum]); }; // if num pages > 9 then set the page range if (numPages > 9) { // default to first of last 9 pages minRange = numPages - 8; if (currentPageNum <= 5) { maxRange = 9; minRange = 1; } else if (currentPageNum <= numPages - 4) { // center the page range relative to current page minRange = currentPageNum - 4; maxRange = currentPageNum + 4; } showEllipses = true; var span = $("<span></span>"); ellipses = li.clone().append( span.clone().html("...").attr({ "aria-hidden": "true" }) ).addClass("pager-ellipses disabled"); } if (currentPageNum !== 1) { ul.append(li.clone().addClass("pager-first").html( getPagerLink("First", "first page", 1, "<< first").on("click", clickEvent) )); ul.append(li.clone().html( getPagerLink("Previous", "previous page", currentPageNum - 1, "< previous").on("click", clickEvent) )); if (showEllipses === true && minRange > 1) { ul.append(ellipses.clone()); } } // write out page #'s var i; for (i = minRange; i <= maxRange; i++) { var pager = li.clone(); var pagerLink = getPagerLink("Page " + parseInt(i), "page " + parseInt(i), i).on("click", clickEvent); if (currentPageNum === i) { pager.addClass("active"); } pager.html(pagerLink); ul.append(pager); } // close the pager if not at end of index if (currentPageNum < numPages) { if (showEllipses === true && maxRange < numPages) { ul.append(ellipses.clone()); } ul.append(li.clone().html( getPagerLink("Next", "next page", currentPageNum + 1, "next >").on("click", clickEvent) )); ul.append(li.clone().addClass("pager-last").html( getPagerLink("Last", "last page", numPages, "last >>").on("click", clickEvent) )); } return ul; } /** * Creates the pagination link given the following attributes. */ function getPagerLink(label, titlePiece, gotoPage, text) { if (typeof (text) === "undefined") { // use the page num text = parseInt(gotoPage); } var a = $("<a></a>"); return a.attr({ "aria-label": label, "href": "#", "onclick": "return false;", "title": "Go to " + titlePiece, "data-goto-page": parseInt(gotoPage) }).text(text); } /** * Builds the page cache for the current container. This will only live * for the current page, and will disappear when the page is left as * this cache lives on request rather than in-browser or elsewhere. */ function cachePages() { var theElement = $("#" + elementID); var pageCache = []; var pageCacheType; // set the cache type and perform any special handling if needed switch (elementID) { case "gerrit-incoming": case "gerrit-outgoing": pageCacheType = "gerrit"; // build out entire page cache based on existing element data pageCache = buildPageCache(theElement.find("tr")); break; case "mpfavorites-list": pageCacheType = "mpfav"; break; case "forum-posts": case "aeri-reports": pageCacheType = "table"; pageCache = buildPageCache(theElement.find("tr")); break; case "news-container": pageCacheType = "news"; break; case "events-container": pageCacheType = "events"; break; default: pageCacheType = "generic"; } // setup the element data and event for changing pages theElement.data("pageCache", pageCache); theElement.data("pageCacheType", pageCacheType); theElement.data("pageCacheTotalPages", totalPages); theElement.on("changePageEvent", changePage); switch (pageCacheType) { case "gerrit": // trigger redraw of first page theElement.trigger("changePageEvent", [1]); break; } function buildPageCache(data) { var counter = 0; var pageNum = 0; var page = []; var theCache = []; // grab the heading row if this is gerrit or forum table switch (pageCacheType) { case "gerrit": case "table": // set heading row in cache theCache[0] = data[0]; break; } $.each(data, function(index, value) { if ($(value).children().first().is("th")) { // don't cache table headings return true; } if (counter === self.settings.itemsPerPage) { counter = 0; theCache[++pageNum] = page; page = []; } page[counter++] = value; }); // check if any remainder items in page if (page.length > 0) { // add page to the cache theCache[++pageNum] = page; } return theCache; } } /** * Callback for page changes events triggered by pagination links. This * will trigger a call to update the containers content with the next * pages content, as well as update the pagination bar with the new page * set as current. Numbers are shifted if necessary to properly display * the current and following pages. * * This method is internal and requires a listener function be * registered for the 'fetchPageItemsEvent' event. Without the listener * registered, this function will not be able to update content based on * pagination requests. * * @param event - * the triggering pagination update request. * @param goToPageNum - * the requested page number */ function changePage(event, gotoPageNum) { var element = $(event.currentTarget); var pageType = element.data("pageCacheType"); var pageCache = element.data("pageCache"); // get the pager var elementID = element.attr("id"); var nav = $("#" + elementID + "-pager"); // get pager's current page var currentPage = nav.data("currentPage"); if (typeof (currentPage) === "undefined" || currentPage === null) { // if it's not set, assume it's 1st page currentPage = 1; } if (typeof (gotoPageNum) === "undefined") { // something is wrong. go back to 1st page gotoPageNum = 1; } // comes in as string gotoPageNum = parseInt(gotoPageNum); switch (pageType) { case "gerrit": fillElementWithPage(); break; default: addCurrentPageToCache(); fillElementWithPage(); break; } //Replace the pager bar with updated layout if (currentPage !== gotoPageNum) { var totalPages = element.data("pageCacheTotalPages"); var newUL = drawPageNums(totalPages, gotoPageNum, elementID); nav.find("ul").replaceWith(newUL); nav.data("currentPage", gotoPageNum); } function fillElementWithPage() { // empty element first element.empty(); //if not in cache if (typeof (pageCache[gotoPageNum]) === "undefined") { var params = []; // different params for mpc or forum / AERI switch (pageType) { case "mpfav": case "table": case "news": case "events": params.push(gotoPageNum); params.push(element.data("postsPerPage")); break; } // if table, put the heading back before triggering fetch and returning if (element.is("table")) { // this should be just the heading element.append(pageCache[0]); } element.trigger("fetchPageItemsEvent", params); return; } // fill in items from cache if (element.is("table")) { element.append(pageCache[0]); } $.each(pageCache[gotoPageNum], function(index, value) { element.append(value); }); } /** * Creates an entry in the page cache for the current container with the * current page of data. This reduces outward calls while browsing between pages */ function addCurrentPageToCache() { // only store it if current page is not currently cached if (typeof (pageCache[currentPage]) === "undefined") { var items = []; pageCache[currentPage] = []; if (element.is("table")) { // pull out the table rows items = element.find("tr"); } else if (element.is("div")) { // assume mpc nodes or items items = element.find(".node,.item"); } $.each(items, function(index, value) { if ($(value).children().first().is("th")) { // heading is already cached - skip to next return true; } pageCache[currentPage].push(value); }); // update stored cache element.data("pageCache", pageCache); } } } }, /** * Injects news items into the page from the Eclipse newsroom, given a few * HTML data attributes on the element this is called on. The data * attributes that can be used will filter the results that are displayed on * page. */ newsItems: function() { // set up initial state and call data var self = this; var $container = $($(this)[0].element); // get the news item container var $newsContainer = $container.find("> div.news-container"); if ($newsContainer.length === 0) { $newsContainer = $("<div></div>"); $newsContainer.attr({ "class": "news-container", "id": "news-container" }); $container.append($newsContainer); } if ($container.data("pagination") === true) { $newsContainer.on("fetchPageItemsEvent", retrieveNewsItems); } retrieveNewsItemsByPage($newsContainer, 1, 5); /** * Listener callback method for fetchPageItemsEvent event. */ function retrieveNewsItems(event, page, pageSize) { retrieveNewsItemsByPage(event.target, page, pageSize); } /** * Retrieves news items for the given page, injected into the element that is passed * as the context element. This method uses the following data attributes to filter * the data, allowing the use of strings or array values: * * - data-publish-target * - data-news-count * - data-news-type * * The data attribute 'data-template-id' can be used to defined a new mustache script * template ID. This script would need to be present on the page and would be used in * place of the default template to generate news items. * * @param contextEl - * the element that called for the news items injection * @param page - * page of news items to retrieve * @param pageSize - * the number of items to retrieve. This is overridden by whatever is * explicitly defined in the data-news-count attribute on the parent container. */ function retrieveNewsItemsByPage(contextEl, page, pageSize) { // get the container element for the current call var $newsContainer = $(contextEl); var $parent = $newsContainer.parent(); // check how many to display with a default of 5 var displayCount = $parent.data("news-count") || pageSize || 5; var filter = "?page=" + page; filter += "&pagesize=" + displayCount; // generate filters based on publish and type targets filter += convertDataToURLParameters($parent, "publish-target", "publish_to", "eclipse_org"); filter += convertDataToURLParameters($parent, "news-type", "news_type", ""); // create the GET URL for news items var url = self.settings.newsroomUrl + "/news" + filter; $.ajax(url, { success: function(data, textStatus, jqXHR) { var newsItems = data["news"]; if (newsItems.length > displayCount) { newsItems = newsItems.slice(0, displayCount); } // post process the date to update date format for (var i = 0; i < newsItems.length; i++) { newsItems[i].date = self.dateFormat(new Date(newsItems[i].date)); newsItems[i].index = i; } // allow template ID to be set on a per run basis with a default. var templateId = $parent.data("template-id") || "template-news-items"; var template = getTemplate(templateId); var rendered = Mustache.render(template, { news: newsItems }); // clear the container before creating elements $newsContainer.html(rendered); if ($parent.data("pagination") === true && $parent.find("nav").length === 0) { var linkHeader = new self.linkHeaderParser(jqXHR.getResponseHeader("Link")); var lastPage = linkHeader.getLastPageNum(); // check if itemsPerPage should be updated to returned value if (linkHeader.getPageSize() !== self.settings.itemsPerPage) { self.settings.itemsPerPage = linkHeader.getPageSize(); } // add pagination bar $parent.append(self.getPaginationBar(lastPage * self.settings.itemsPerPage, $newsContainer.attr("id"))); } $parent.trigger("shown.ef.news"); }, error: function() { // clear the loading placeholder $container.empty(); // display an error message var $errorEl = $("<div></div>"); $errorEl.attr("class", "alert alert-warning"); $errorEl.text("Unable to load news content currently."); $container.append($errorEl); } }); } /** * Returns the mustache template for generating the list of news items from * the JSON data. * * @param templateId - * the ID of the script template to use when generating the news items * @returns the mustache template for generating the news list HTML */ function getTemplate(templateId) { var newsTemplate = $("#" + templateId); if (newsTemplate !== undefined && newsTemplate.length !== 0) { return newsTemplate[0].innerHTML; } return "{{#news}}" + "<div class=\"item block-summary-item\" data-mh=\"group-{{ index }}\">" + "<p>{{ date }}</p>" + "<h4><a href=\"{{ link }}\">{{ title }}</a></h4>" + "<p>{{ body }}</p>" + "</div>" + "{{/news}}"; } }, filteredEvents: function() { // set up initial state and call data var self = this; var $container = $($(this)[0].element); // get the news item container var $eventsContainer = $container.find("> div.events-container"); if ($eventsContainer.length === 0) { $eventsContainer = $("<div></div>"); $eventsContainer.attr({ "class": "events-container", "id": "events-container" }); $container.append($eventsContainer); } if ($container.data("pagination") === true) { $eventsContainer.on("fetchPageItemsEvent", retrieveFilteredEvents); } retrieveFilteredEventsByPage($eventsContainer, 1, 5); /** * Listener callback method for fetchPageItemsEvent event. */ function retrieveFilteredEvents(event, page, pageSize) { retrieveFilteredEventsByPage(event.target, page, pageSize); } /** * Retrieves event items for the given page, injected into the element that is passed * as the context element. This method uses the following data attributes to filter * the data, allowing the use of strings or array values: * * - data-publish-target * - data-count * - data-type * - data-upcoming * - data-sort-order * - data-sort-field * * The data attribute 'data-template-id' can be used to defined a new mustache script * template ID. This script would need to be present on the page and would be used in * place of the default template to generate event items. * * @param contextEl - * the element that called for the news items injection * @param page - * page of news items to retrieve * @param pageSize - * the number of items to retrieve. This is overridden by whatever is * explicitly defined in the data-count attribute on the parent container. */ function retrieveFilteredEventsByPage(contextEl, page, pageSize) { // get the container element for the currentcall var $eventsContainer = $(contextEl); var $parent = $eventsContainer.parent(); var displayCount = $parent.data("count") || pageSize || 5; var filter = "?page=" + page; filter += "&pagesize=" + displayCount; filter += convertDataToURLParameters($parent, "publish-target", "publish_to", undefined); filter += convertDataToURLParameters($parent, "type", "type", undefined); filter += convertDataToURLParameters($parent, "upcoming", "upcoming_only", undefined); // if upcoming is set to 1 (PHP true) then set default sorting var upcoming = $parent.data("upcoming") === 1 ? true : false; var sortOrder = $parent.data("sort-order") || (upcoming ? "ASC" : undefined); var sortField = $parent.data("sort-field") || (upcoming ? "field_event_date" : undefined); // special treatment for sort option if (sortOrder && sortField) { filter += "&options%5Borderby%5D%5B" + sortField + "%5D=" + sortOrder; } // create the GET URL for news items var url = self.settings.newsroomUrl + "/events" + filter; $.ajax(url, { success: function(data, textStatus, jqXHR) { var events = data["events"]; if (events.length > displayCount) { events = events.slice(0, displayCount); } // post process the date to update date format for (var i = 0; i < events.length; i++) { // remove registration completely if event is in the past or link is missing if (Date.now() > new Date(events[i]["end-date"]) || !events[i]["registration"]) { delete events[i]["registration"]; } if (!events[i]["infoLink"]) { delete events[i]["infoLink"]; } events[i].date = self.dateFormat(new Date(events[i].date)); events[i]["end-date"] = self.dateFormat(new Date(events[i]["end-date"])); } // allow template ID to be set on a per run basis with a default. var templateId = $parent.data("template-id") || "template-event-items"; var isArchive = $parent.data("archive") || false; var template = getTemplate(templateId, isArchive); var rendered = Mustache.render(template, { "events": events }); // set the container HTML to the rendered HTML $eventsContainer.html(rendered); if ($parent.data("pagination") === true && $parent.find("nav").length === 0) { var linkHeader = new self.linkHeaderParser(jqXHR.getResponseHeader("Link")); var lastPage = linkHeader.getLastPageNum(); // check if itemsPerPage should be updated to returned value if (linkHeader.getPageSize() !== self.settings.itemsPerPage) { self.settings.itemsPerPage = linkHeader.getPageSize(); } // add pagination bar $parent.append(self.getPaginationBar(lastPage * self.settings.itemsPerPage, $eventsContainer.attr("id"))); } $parent.trigger("shown.ef.events"); }, error: function() { // clear the loading placeholder $container.empty(); // display an error message var $errorEl = $("<div></div>"); $errorEl.attr("class", "alert alert-warning"); $errorEl.text("Unable to load events content currently."); $container.append($errorEl); } }); } /** * Returns the mustache template for generating the * list of events from the JSON data. * * @param templateId - * the ID of the script template to use * when generating the events * @returns the mustache template for generating the * events list HTML */ function getTemplate(templateId, isArchive) { var eventsTemplate = $("#" + templateId); if (eventsTemplate !== undefined && eventsTemplate.length !== 0) { return eventsTemplate[0].innerHTML; } if (isArchive) { return "{{#events}}" + "<div class=\"item block-summary-item match-height-item\">" + "<h3 class=\"h4\">{{ title }}</h3>" + "<p>{{ locationName }}</p>" + "<p>{{ date }} - {{ end-date }}</p>" + "<p class=\"margin-bottom-0\">" + "{{#registration}}" + "<a class=\"btn btn-secondary\" href=\"{{ registration }}\">Register Now</a>" + "{{/registration}}" + "{{#infoLink}}" + "<a class=\"btn btn-secondary\" href=\"{{ infoLink }}\">More information</a>" + "{{/infoLink}}" + "</p>" + "</div>" + "{{/events}}"; } return "{{#events}}" + "<div class=\"col-sm-12 col-md-6 event item match-height-item-by-row flex-column\">" + "<h3 class=\"h4 flex-grow\">{{ title }}</h3>" + "<p>{{ locationName }}</p>" + "<p class=\"flex-grow\">{{ date }} - {{ end-date }}</p>" + "<p class=\"margin-bottom-0\">" + "{{#infoLink}}" + "<a class=\"btn btn-secondary\" href=\"{{ infoLink }}\">More information</a>" + "{{/infoLink}}" + "{{^infoLink}}" + "{{#registration}}" + "<a class=\"btn btn-secondary\" href=\"{{ registration }}\">Register Now</a>" + "{{/registration}}" + "{{/infoLink}}" + "</p>" + "</div>" + "{{/events}}"; } }, featuredStory: function() { var $container = $($(this)[0].element); updateFeaturedContent($container, "story", this.settings); }, featuredFooter: function() { var $container = $($(this)[0].element); updateFeaturedContent($container, "footer", this.settings); }, customFeaturedContent: function() { var $container = $($(this)[0].element); writeFeaturedContainer(this.settings.featuredContent, $container, this.settings.featuredContentType); }, /** Retrieves and inserts a list of promotions onto the page in the calling container. Will pass the publish target (if set) to target a particular sites promotions. These promotions will not include or create impressions as they aren't meant to be consumed in production by the public. */ allPromos: function() { // set up the callbacks + containers for promos var $container = $($(this)[0].element); var self = this; // create container for promos, to enable pagination bar var $promosContainer = $container.find("> div.promos-container"); if ($promosContainer.length === 0) { $promosContainer = $("<div></div>"); $promosContainer.attr({ "class": "promos-container", "id": "promos-container-" + getPseudoRandomNumber() }); $container.append($promosContainer); } if ($container.data("pagination") === true) { $promosContainer.on("fetchPageItemsAd", retrievePromos); } // trigger first update of promos using first page retrievePromosByPage($promosContainer, 1, 10); /** * Listener callback method for fetchPageItemsAd event. */ function retrievePromos(event, page, pageSize) { retrievePromosByPage(event.target, page, pageSize); } function retrievePromosByPage(contextEl, page, pageSize) { var $currentContainer = $(contextEl); var $parent = $currentContainer.parent(); var displayCount = $parent.data("count") || pageSize || 10; // generate the URL for retrieve promotions var url = self.settings.adsUrl; var filter = "?page=" + page; filter += "&pagesize=" + displayCount; filter += convertDataToURLParameters($parent, "publish-target", "publish_to", undefined); // retrieve the promo data via ajax $.ajax(url + filter, { dataType: "json", type: "GET", success: function(data) { if (data["ads"] === undefined) { console.log("Could not load promotional content. AD-01"); } // add the index of the ad for printing out index to all ads page for (var i = 0; i < data["ads"].length; i++) { data["ads"][i].idx = i; } // call and write the actual promo content writePromoContent($currentContainer, data["ads"], self.settings); // add the pagination bar if ($parent.data("pagination") === true && $parent.find("nav").length === 0) { var linkHeader = new self.linkHeaderParser(jqXHR.getResponseHeader("Link")); var lastPage = linkHeader.getLastPageNum(); // check if itemsPerPage should be updated to returned value if (linkHeader.getPageSize() !== self.settings.itemsPerPage) { self.settings.itemsPerPage = linkHeader.getPageSize(); } // add pagination bar $parent.append(self.getPaginationBar(lastPage * self.settings.itemsPerPage, $currentContainer.attr("id"))); } }, error: function() { console.log("Could not load promotional content. AD-02"); } }); } }, /** Retrieves and inserts a single promotion onto the page in the calling container. Will pass the host, absolute URI path, and additional parameters for the publish target, and promo ID. With these parameters, a post request will be formed that will retrieve a promo with an impressions ID. */ singlePromo: function() { var self = this; var $container = $($(self)[0].element); var $parent = $container.parent(); var url = self.settings.adsUrl; var params = { "host": window.location.host, "source": window.location.pathname, "publish_to": $container.data("publish-target"), }; $.ajax(url, { dataType: "json", contentType: "application/json", type: "POST", data: JSON.stringify(params), success: function(data) { if (data === undefined) { console.log("Could not load promotional content, bad content received. AD-03"); } writePromoContent($container, data, self.settings); $parent.trigger("shown.ef.ads"); }, error: function() { console.log("Could not load promotional content. AD-04"); } }); } }); // A really lightweight plugin wrapper around the constructor, // preventing against multiple instantiations $.fn[pluginName] = function(options) { return this.each(function() { if (!$.data(this, "plugin_" + pluginName)) { $.data(this, "plugin_" + pluginName, new Plugin(this, options)); } }); }; var writePromoContent = function($container, promos, settings) { var template = getPromoTemplate($container.data("template-id"), settings); $container.html(Mustache.render(template, { "content": promos })); } /** Centralize the fetching of promo templates to make it more transparent and easy to manage. @param templateId the id of the Mustache template script if it exists @param settings the current plugin settings */ var getPromoTemplate = function(templateId, settings) { if (settings.type === "allPromos") { return getMustacheTemplate(templateId, "{{#content}}" + "<p>" + "<a href=\"http://www.eclipse.org/home/index.php?ad_id={{ id }}\">Ad ID: {{ id }}</a>" + "<span class=\"margin-left-10\">prob: {{ weight }}%</span>" + "<div class=\"eclipsefnd-ad ad-strategic ad-strategic-default\">" + "<a href=\"{{ url }}\" rel=\"nofollow\" style=\"background-image: url('{{ image }}')\">{{ member_name }}</a>" + "</div>" + "</p>" + "{{/content}}"); } return getMustacheTemplate(templateId, "{{#content}}" + "<div class=\"eclipsefnd-ad ad-strategic ad-strategic-default\">" + "<a href=\"{{ url }}\" rel=\"nofollow\" style=\"background-image: url('{{ image }}')\">{{ member_name }}</a>" + "</div>" + "{{/content}}"); } var updateFeaturedContent = function(container, type, settings) { var $container = $(container); var url = settings.newsroomUrl + "/featured_story"; // get the ID of the featured story if set var id = $container.data("id"); if (id !== undefined) { url += "/" + id; } // add parameter for publish target for featured content url += convertDataToURLParameters($container, "publish-target", "publish_to", undefined, true); $.ajax(url, { success: function(data) { if (data["featured_story"] === undefined) { console.log("Could not load featured content, bad content recieved"); } var json = data["featured_story"].filter(function(a) { return new Date(a["end-date"]) > new Date() && (a["start-date"] === undefined || new Date(a["start-date"]) < new Date()); }).filter(function(a) { return a["type"] === type || a["type"] === "both"; }); // shuffle the array so that a random available data is featured if (json.length > 1) { shuffleArray(json); } // make sure we have a promotion to display if (json.length > 0) { writeFeaturedContainer(json[0], $container, type); } else { var default_featured_story = { id: "default-featured-story", layout: "light", title: "Eclipse Foundation Events", body: "Join the world’s leading technologists and open source leaders at Eclipse Foundation events to share ideas, learn and collaborate.", links: [ { url: "https://events.eclipse.org", title: "View Events" } ], } writeFeaturedContainer(default_featured_story, $container, "both"); } }, error: function() { // clear the loading placeholder console.log("Could not load featured content!"); } }); } var writeFeaturedContainer = function(item, $container, type) { // get the content container and append the content var $featuredContentContainer = $container.find(".featured-container"); $container.addClass("featured-story-nid-" + item.id); $container.addClass("featured-story-" + item.layout); // allow template ID to be set on a per run basis with a default. var templateId = $container.data("template-id") || "template-featured-" + type; var template = getMustacheTemplate(templateId, "{{#content}}" + "<h2 class=\"margin-top-30\">{{ title }}</h2>" + "<p>{{ body }}</p>" + "<ul class=\"list-inline list-inline-xs-margin\">{{#links}}<li><a class=\"btn btn-primary\" href=\"{{ url }}\">{{ title }}</a></li>{{/links}}</ul>" + "{{/content}}"); var rendered = Mustache.render(template, { "content": item }); // set the container HTML to the rendered HTML $featuredContentContainer.html(rendered); } var convertDataToURLParameters = function(el, name, parameterName, defaultVal, first) { var dataValue = el.data(name) || defaultVal; var filter = ""; if (Array.isArray(dataValue)) { for (var dataIdx = 0; dataIdx < dataValue.length; dataIdx++) { if (first && dataIdx === 0) { filter += "?"; } else { filter += "&"; } filter += "parameters%5B" + parameterName + "%5D%5B%5D=" + dataValue[dataIdx]; } } else if (dataValue !== undefined) { if (first) { filter += "?"; } else { filter += "&"; } filter += "parameters%5B" + parameterName + "%5D=" + dataValue; } return filter; }; var getMustacheTemplate = function(templateId, defaultTemplate) { var template = $("#" + templateId); if (template !== undefined && template.length !== 0) { return template[0].innerHTML; } return defaultTemplate; } /** * Randomize array element order in-place. Using Durstenfeld shuffle algorithm. * source: * https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array */ var shuffleArray = function(array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp; } }; })(jQuery, window, document);
Infra 2887 - Remove errorReports (#37) * Infra 2887 - Remove errorReports Signed-off-by: Eric Poirier <[email protected]> * Remove errorReports from validTypes Signed-off-by: Eric Poirier <[email protected]>
src/jquery.eclipsefdn-api.js
Infra 2887 - Remove errorReports (#37)
<ide><path>rc/jquery.eclipsefdn-api.js <ide> "forumsMsg", <ide> "gerritReviewCount", <ide> "projectsList", <del> "errorReports", <ide> "mailingListSubscription", <ide> "newsItems", <ide> "filteredEvents", <ide> if ($.type(this.settings.type) === "string" && $.inArray(this.settings.type, validTypes) !== -1) { <ide> this[this.settings.type](); <ide> } <del> }, <del> errorReports: function() { <del> var self = this; <del> var userEmail; <del> var container = self.element; <del> var dontProceed = false; <del> // error for unable to get account email info <del> var dspAcctError = "Unable to retrieve account information required to process this request."; <del> // error for authorization denied / failed <del> var dspAuthError = "Authorization to retrieve error reports was denied."; <del> // we're going to need the user's email address to pull in the reports <del> var accountApi = self.settings.apiUrl + "/account/profile/" + self.settings.username; <del> // igc settings <del> // use default auth url for AERI, which will be production accounts <del> var igcSettings = { <del> clientName: "aeriReports", <del> apiUrl: "https://dev.eclipse.org", <del> completeOnAuthorization: false, <del> username: self.settings.username, <del> encodeStorage: true, <del> }; <del> // we'll use this to build the request path, with email in the middle and page options trailing <del> var pathPrefix = "/recommenders/community/aeri/v2/api/v1/reporters/"; <del> var pathSuffix = "/problems"; <del> // default request options, will build path before request <del> var requestOptions = { <del> path: "", <del> method: "GET", <del> cid: "aeri_reports", <del> scope: "eclipse_aeri_view_own_report email openid", <del> // we'll set success callback individually for initial calls and paginated calls <del> successCallback: "", <del> // error callback can be the same for both <del> errorCallback: function(jqXHR) { <del> // display default error msg - we may get more details later if necessary <del> switch (jqXHR.status) { <del> case 404: <del> displayErrorMsg("No submissions found."); <del> break; <del> default: <del> displayErrorMsg(); <del> } <del> } <del> }; <del> // event handler for authorization failed event <del> $(document).on("igcAuthFailed", function(event, authError) { <del> // this is probably message worthy <del> if (authError.clientName === igcSettings.clientName) { <del> displayErrorMsg(dspAuthError); <del> dontProceed = true; <del> } <del> }); <del> // initialize IGC, if an authorization error is pending it should get triggered in the init <del> $(container).eclipseFdnIgc(igcSettings); <del> <del> // we probably want to check if the user cancelled the authorization and not proceed. <del> // timing may be an issue here. <del> if (dontProceed) { <del> // msg already displayed at this point <del> return; <del> } <del> <del> $.ajax({ <del> url: accountApi, <del> context: self.element <del> }) <del> .done(function(data) { <del> if (typeof (data.mail) === "undefined") { <del> displayErrorMsg(dspAcctError, true); <del> return; <del> } <del> userEmail = data.mail; <del> // check again if we should proceed. authorization failure/cancel should have been flagged by now <del> if (dontProceed) { <del> // if we got here, the initial error was not displayed. <del> displayErrorMsg(dspAuthError); <del> return; <del> } <del> <del> // make the call to get the data, we'll need initial lot to build pager <del> requestOptions.path = pathPrefix + userEmail + pathSuffix + "?page=1&size=" + self.settings.itemsPerPage; <del> requestOptions.successCallback = function(data, textStatus, jqXHR) { <del> <del> // create the error reports table <del> buildReportTable(data); <del> // check the link header for total pages <del> // currently the jqXHR object is returned, consider just returning header block along with data <del> var linkHeader = new self.linkHeaderParser(jqXHR.getResponseHeader("Link")); <del> var lastPage = linkHeader.getLastPageNum(); <del> // check if itemsPerPage should be updated to returned value <del> if (linkHeader.getPageSize() !== self.settings.itemsPerPage) { <del> self.settings.itemsPerPage = linkHeader.getPageSize(); <del> } <del> // set fetch posts event <del> $("#aeri-reports").on("fetchPageItemsEvent", fetchErrorReports); <del> // store items per page so we know how many to fetch per page <del> $("#aeri-reports").data("postsPerPage", self.settings.itemsPerPage); <del> // add pagination bar <del> $(container).append(self.getPaginationBar(lastPage * self.settings.itemsPerPage, "aeri-reports")); <del> }; <del> <del> $(document).eclipseFdnIgc.makeRequest(requestOptions); <del> }) <del> .fail(function() { <del> // we're not capturing the reason it failed, but we will display it on the page <del> displayErrorMsg(dspAcctError, true); <del> }); <del> <del> function buildReportTable(data) { <del> // Create table <del> var table = $("<table></table>").attr({ <del> "width": "100%", <del> "class": "table", <del> "id": "aeri-reports" <del> }); <del> <del> var tr = $("<tr></tr>"); <del> var th = $("<th></th>"); <del> <del> // Title Header <del> tr.append(th.clone().text("Title").attr("width", "50%")); <del> <del> // Status Header <del> tr.append(th.clone().text("Status").attr({ <del> "width": "10%", <del> "class": "text-center" <del> })); <del> <del> // Resolution Header <del> tr.append(th.clone().text("Resolution").attr({ <del> "width": "10%", <del> "class": "text-center" <del> })); <del> <del> // Reporters Header <del> tr.append(th.clone().text("Reporters").attr({ <del> "width": "10%", <del> "class": "text-center" <del> })); <del> <del> // Your First Report Header <del> tr.append(th.clone().text("Your First Report").attr({ <del> "width": "20%", <del> "class": "text-center" <del> })); <del> <del> // Insert heading row in table <del> table.append(tr); <del> <del> // Responsive container to wrap the table <del> var responsive_wrapper = $("<div></div>").attr({ <del> "class": "table-responsive" <del> }); <del> <del> // append table to container <del> responsive_wrapper.append(table); <del> $(container).append(responsive_wrapper); <del> <del> // Add a row in the table for each Error Reports <del> $.each(data, function(index, value) { <del> var tr = $("<tr></tr>"); <del> var td = $("<td></td>"); <del> var a = $("<a></a>"); <del> var submissionLinks = $("<ul></ul>"); <del> var li = $("<li></li>"); <del> // main title / problem link <del> var problemLink; <del> // open links in new window <del> a.attr("target", "_blank"); <del> // cycle through links and build out Title column <del> $.each(value.links, function(index, link) { <del> if (link.rel === "problem") { <del> //the problem link - main title link <del> problemLink = a.clone().attr({ <del> "href": link.href <del> }).text(link.title); <del> } <del> if (link.rel === "submission") { <del> if (!link.title) { <del> link.title = "(No error message)"; <del> } <del> submissionLinks.append(li.clone().append(a.clone().attr({ <del> "href": link.href <del> }).html( <del> "<small>" + link.title + "</small>" <del> ))); <del> } <del> }); <del> <del> // Title column <del> tr.append(td.clone().append(problemLink).append(submissionLinks).attr({ "class": "ellipsis white-space-normal", "style": "max-width:200px;" })); <del> // Status column <del> tr.append(td.clone().text(value.status).attr("class", "text-center")); <del> // Resolution column <del> tr.append(td.clone().text(value.resolution).attr("class", "text-center")); <del> // # Reporters column <del> var span = $("<span></span>").attr("class", "badge"); <del> span.text(value.numberOfReporters); <del> tr.append(td.clone().append(span).attr("class", "text-center")); <del> <del> // Date column <del> var d = new Date(value.firstReported); <del> var month = d.getMonth() < 10 ? "0" + d.getMonth() : d.getMonth(); <del> var day = d.getDate() < 10 ? "0" + d.getDate() : d.getDate(); <del> var reportedOn = d.getFullYear() + "-" + month + "-" + day; <del> tr.append(td.clone().text(reportedOn).attr("class", "text-center")); <del> table.append(tr); <del> }); <del> } <del> <del> function displayErrorMsg(msg, prependDefault) { <del> <del> if (typeof (prependDefault) !== "boolean") { <del> prependDefault = false; <del> } <del> <del> if (typeof (msg) === "undefined") { <del> // use the default msg <del> msg = self.settings.errorMsg; <del> } <del> <del> if (prependDefault) { <del> msg = self.settings.errorMsg + msg; <del> } <del> var feedback = $("<p></p>").append(msg); <del> $(self.element).append(feedback); <del> } <del> <del> function fetchErrorReports(event, page, pageSize) { <del> getErrorReportsByPage(page, pageSize); <del> } <del> // fetch reports by page number and use regular call handler <del> // we already have pager and everything setup. <del> function getErrorReportsByPage(pageNum, pageSize) { <del> if (typeof (pageNum) === "undefined") { <del> // default to page 1 <del> pageNum = 1; <del> } <del> if (typeof (pageSize) === "undefined") { <del> // default to settings <del> pageSize = self.settings.itemsPerPage; <del> } <del> // make the call to get the data, we'll need initial lot to build pager <del> requestOptions.path = pathPrefix + userEmail + pathSuffix + "?page=" + pageNum + "&size=" + pageSize; <del> requestOptions.successCallback = function(data) { <del> // send diretly to addReportRows <del> addReportRows(data); <del> }; <del> $(document).eclipseFdnIgc.makeRequest(requestOptions); <del> } <del> <ide> }, <ide> projectsList: function() { <ide> var self = this;
Java
epl-1.0
1bfb465cdb4c0e282bfa8a01616502b64952588e
0
sbrannen/junit-lambda,junit-team/junit-lambda
/* * Copyright 2015-2017 the original author or authors. * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v2.0 which * accompanies this distribution and is available at * * http://www.eclipse.org/legal/epl-v20.html */ package org.junit.jupiter.api.extension; import static org.apiguardian.api.API.Status.STABLE; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import org.apiguardian.api.API; import org.junit.platform.commons.support.ReflectionSupport; import org.junit.platform.commons.util.PreconditionViolationException; import org.junit.platform.commons.util.Preconditions; /** * {@code ExtensionContext} encapsulates the <em>context</em> in which the * current test or container is being executed. * * <p>{@link Extension Extensions} are provided an instance of * {@code ExtensionContext} to perform their work. * * @since 5.0 * @see Store * @see Namespace */ @API(status = STABLE, since = "5.0") public interface ExtensionContext { /** * Get the parent extension context, if available. * * @return an {@code Optional} containing the parent; never {@code null} but * potentially empty * @see #getRoot() */ Optional<ExtensionContext> getParent(); /** * Get the <em>root</em> {@code ExtensionContext}. * * @return the root extension context; never {@code null} but potentially * <em>this</em> {@code ExtensionContext} * @see #getParent() */ ExtensionContext getRoot(); /** * Get the unique ID of the current test or container. * * @return the unique ID of the test or container; never {@code null} or blank */ String getUniqueId(); /** * Get the display name for the current test or container. * * <p>The display name is either a default name or a custom name configured * via {@link org.junit.jupiter.api.DisplayName @DisplayName}. * * <p>For details on default display names consult the Javadoc for * {@link org.junit.jupiter.api.TestInfo#getDisplayName()}. * * <p>Note that display names are typically used for test reporting in IDEs * and build tools and may contain spaces, special characters, and even emoji. * * @return the display name of the test or container; never {@code null} or blank */ String getDisplayName(); /** * Get the set of all tags for the current test or container. * * <p>Tags may be declared directly on the test element or <em>inherited</em> * from an outer context. * * @return the set of tags for the test or container; never {@code null} but * potentially empty */ Set<String> getTags(); /** * Get the {@link AnnotatedElement} corresponding to the current extension * context, if available. * * <p>For example, if the current extension context encapsulates a test * class, test method, test factory method, or test template method, the * annotated element will be the corresponding {@link Class} or {@link Method} * reference. * * <p>Favor this method over more specific methods whenever the * {@code AnnotatedElement} API suits the task at hand &mdash; for example, * when looking up annotations regardless of concrete element type. * * @return an {@code Optional} containing the {@code AnnotatedElement}; * never {@code null} but potentially empty * @see #getTestClass() * @see #getTestMethod() */ Optional<AnnotatedElement> getElement(); /** * Get the {@link Class} associated with the current test or container, * if available. * * @return an {@code Optional} containing the class; never {@code null} but * potentially empty * @see #getRequiredTestClass() */ Optional<Class<?>> getTestClass(); /** * Get the <em>required</em> {@link Class} associated with the current test * or container. * * <p>Use this method as an alternative to {@link #getTestClass()} for use * cases in which the test class is required to be present. * * @return the test class; never {@code null} * @throws PreconditionViolationException if the test class is not present * in this {@code ExtensionContext} */ default Class<?> getRequiredTestClass() { return Preconditions.notNull(getTestClass().orElse(null), "Illegal state: required test class is not present in the current ExtensionContext"); } /** * Get the test instance associated with the current test or container, * if available. * * @return an {@code Optional} containing the test instance; never * {@code null} but potentially empty * @see #getRequiredTestInstance() */ Optional<Object> getTestInstance(); /** * Get the <em>required</em> test instance associated with the current test * or container. * * <p>Use this method as an alternative to {@link #getTestInstance()} for use * cases in which the test instance is required to be present. * * @return the test instance; never {@code null} * @throws PreconditionViolationException if the test instance is not present * in this {@code ExtensionContext} */ default Object getRequiredTestInstance() { return Preconditions.notNull(getTestInstance().orElse(null), "Illegal state: required test instance is not present in the current ExtensionContext"); } /** * Get the {@link Method} associated with the current test, if available. * * @return an {@code Optional} containing the method; never {@code null} but * potentially empty * @see #getRequiredTestMethod() */ Optional<Method> getTestMethod(); /** * Get the <em>required</em> {@link Method} associated with the current test * or container. * * <p>Use this method as an alternative to {@link #getTestMethod()} for use * cases in which the test method is required to be present. * * @return the test method; never {@code null} * @throws PreconditionViolationException if the test method is not present * in this {@code ExtensionContext} */ default Method getRequiredTestMethod() { return Preconditions.notNull(getTestMethod().orElse(null), "Illegal state: required test method is not present in the current ExtensionContext"); } /** * Get the exception that was thrown during execution of the test or container * associated with this {@code ExtensionContext}, if available. * * <p>This method is typically used for logging and tracing purposes. If you * wish to actually <em>handle</em> an exception thrown during test execution, * implement the {@link TestExecutionExceptionHandler} API. * * <p>Unlike the exception passed to a {@code TestExecutionExceptionHandler}, * an <em>execution exception</em> returned by this method can be any * exception thrown during the invocation of a {@code @Test} method, its * surrounding {@code @BeforeEach} and {@code @AfterEach} methods, or a * test-level {@link Extension}. Similarly, if this {@code ExtensionContext} * represents a test class, the <em>execution exception</em> returned by * this method can be any exception thrown in a {@code @BeforeAll} or * {@code AfterAll} method or a class-level {@link Extension}. * * <p>Note, however, that this method will never return an exception * swallowed by a {@code TestExecutionExceptionHandler}. Furthermore, if * multiple exceptions have been thrown during test execution, the exception * returned by this method will be the first such exception with all * additional exceptions {@linkplain Throwable#addSuppressed(Throwable) * suppressed} in the first one. * * @return an {@code Optional} containing the exception thrown; never * {@code null} but potentially empty if test execution has not (yet) * resulted in an exception */ Optional<Throwable> getExecutionException(); /** * Get the configuration parameter stored under the specified {@code key}. * * <p>If no such key is present in the {@code ConfigurationParameters} for * the JUnit Platform, an attempt will be made to look up the value as a * JVM system property. If no such system property exists, an attempt will * be made to look up the value in the JUnit Platform properties file. * * @param key the key to look up; never {@code null} or blank * @return an {@code Optional} containing the value; never {@code null} * but potentially empty * * @see System#getProperty(String) * @see org.junit.platform.engine.ConfigurationParameters * @since 5.1 */ @API(status = STABLE, since = "5.1") Optional<String> getConfigurationParameter(String key); /** * Publish a map of key-value pairs to be consumed by an * {@code org.junit.platform.engine.EngineExecutionListener}. * * @param map the key-value pairs to be published; never {@code null}; * keys and values within entries in the map also must not be * {@code null} or blank */ void publishReportEntry(Map<String, String> map); /** * Publish the specified key-value pair to be consumed by an * {@code org.junit.platform.engine.EngineExecutionListener}. * * @param key the key of the published pair; never {@code null} or blank * @param value the value of the published pair; never {@code null} or blank */ default void publishReportEntry(String key, String value) { this.publishReportEntry(Collections.singletonMap(key, value)); } /** * Get the {@link Store} for the supplied {@link Namespace}. * * <p>Use {@code getStore(Namespace.GLOBAL)} to get the default, global {@link Namespace}. * * @param namespace the {@code Namespace} to get the store for; never {@code null} * @return the store in which to put and get objects for other invocations * working in the same namespace; never {@code null} * @see Namespace#GLOBAL */ Store getStore(Namespace namespace); /** * {@code Store} provides methods for extensions to save and retrieve data. */ interface Store { /** * Get the value that is stored under the supplied {@code key}. * * <p>If no value is stored in the current {@link ExtensionContext} * for the supplied {@code key}, ancestors of the context will be queried * for a value with the same {@code key} in the {@code Namespace} used * to create this store. * * <p>For greater type safety, consider using {@link #get(Object, Class)} * instead. * * @param key the key; never {@code null} * @return the value; potentially {@code null} * @see #get(Object, Class) */ Object get(Object key); /** * Get the value of the specified required type that is stored under * the supplied {@code key}. * * <p>If no value is stored in the current {@link ExtensionContext} * for the supplied {@code key}, ancestors of the context will be queried * for a value with the same {@code key} in the {@code Namespace} used * to create this store. * * @param key the key; never {@code null} * @param requiredType the required type of the value; never {@code null} * @param <V> the value type * @return the value; potentially {@code null} * @see #get(Object) */ <V> V get(Object key, Class<V> requiredType); /** * Get the object of type {@code type} that is present in this * {@code Store} (<em>keyed</em> by {@code type}); and otherwise invoke * the default constructor for {@code type} to generate the object, * store it, and return it. * * <p>This method is a shortcut for the following, where {@code X} is * the type of object we wish to retrieve from the store. * * <pre style="code"> * X x = store.getOrComputeIfAbsent(X.class, key -&gt; new X(), X.class); * // Equivalent to: * // X x = store.getOrComputeIfAbsent(X.class); * </pre> * * <p>See {@link #getOrComputeIfAbsent(Object, Function, Class)} for * further details. * * @param type the type of object to retrieve; never {@code null} * @param <V> the key and value type * @return the object; never {@code null} * @see #getOrComputeIfAbsent(Object, Function) * @see #getOrComputeIfAbsent(Object, Function, Class) */ default <V> V getOrComputeIfAbsent(Class<V> type) { return getOrComputeIfAbsent(type, ReflectionSupport::newInstance, type); } /** * Get the value that is stored under the supplied {@code key}. * * <p>If no value is stored in the current {@link ExtensionContext} * for the supplied {@code key}, ancestors of the context will be queried * for a value with the same {@code key} in the {@code Namespace} used * to create this store. If no value is found for the supplied {@code key}, * a new value will be computed by the {@code defaultCreator} (given * the {@code key} as input), stored, and returned. * * <p>For greater type safety, consider using * {@link #getOrComputeIfAbsent(Object, Function, Class)} instead. * * @param key the key; never {@code null} * @param defaultCreator the function called with the supplied {@code key} * to create a new value; never {@code null} * @param <K> the key type * @param <V> the value type * @return the value; potentially {@code null} * @see #getOrComputeIfAbsent(Class) * @see #getOrComputeIfAbsent(Object, Function, Class) */ <K, V> Object getOrComputeIfAbsent(K key, Function<K, V> defaultCreator); /** * Get the value of the specified required type that is stored under the * supplied {@code key}. * * <p>If no value is stored in the current {@link ExtensionContext} * for the supplied {@code key}, ancestors of the context will be queried * for a value with the same {@code key} in the {@code Namespace} used * to create this store. If no value is found for the supplied {@code key}, * a new value will be computed by the {@code defaultCreator} (given * the {@code key} as input), stored, and returned. * * @param key the key; never {@code null} * @param defaultCreator the function called with the supplied {@code key} * to create a new value; never {@code null} * @param requiredType the required type of the value; never {@code null} * @param <K> the key type * @param <V> the value type * @return the value; potentially {@code null} * @see #getOrComputeIfAbsent(Class) * @see #getOrComputeIfAbsent(Object, Function) */ <K, V> V getOrComputeIfAbsent(K key, Function<K, V> defaultCreator, Class<V> requiredType); /** * Store a {@code value} for later retrieval under the supplied {@code key}. * * <p>A stored {@code value} is visible in child {@link ExtensionContext * ExtensionContexts} for the store's {@code Namespace} unless they * overwrite it. * * @param key the key under which the value should be stored; never * {@code null} * @param value the value to store; may be {@code null} */ void put(Object key, Object value); /** * Remove the value that was previously stored under the supplied {@code key}. * * <p>The value will only be removed in the current {@link ExtensionContext}, * not in ancestors. * * <p>For greater type safety, consider using {@link #remove(Object, Class)} * instead. * * @param key the key; never {@code null} * @return the previous value or {@code null} if no value was present * for the specified key * @see #remove(Object, Class) */ Object remove(Object key); /** * Remove the value of the specified required type that was previously stored * under the supplied {@code key}. * * <p>The value will only be removed in the current {@link ExtensionContext}, * not in ancestors. * * @param key the key; never {@code null} * @param requiredType the required type of the value; never {@code null} * @param <V> the value type * @return the previous value or {@code null} if no value was present * for the specified key * @see #remove(Object) */ <V> V remove(Object key, Class<V> requiredType); } /** * A {@code Namespace} is used to provide a <em>scope</em> for data saved by * extensions within a {@link Store}. * * <p>Storing data in custom namespaces allows extensions to avoid accidentally * mixing data between extensions or across different invocations within the * lifecycle of a single extension. */ class Namespace { /** * The default, global namespace which allows access to stored data from * all extensions. */ public static final Namespace GLOBAL = Namespace.create(new Object()); /** * Create a namespace which restricts access to data to all extensions * which use the same sequence of {@code parts} for creating a namespace. * * <p>The order of the {@code parts} is significant. * * <p>Internally the {@code parts} are compared using {@link Object#equals(Object)}. */ public static Namespace create(Object... parts) { Preconditions.notEmpty(parts, "parts array must not be null or empty"); Preconditions.containsNoNullElements(parts, "individual parts must not be null"); return new Namespace(parts); } private final List<?> parts; private Namespace(Object... parts) { this.parts = new ArrayList<>(Arrays.asList(parts)); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Namespace that = (Namespace) o; return this.parts.equals(that.parts); } @Override public int hashCode() { return this.parts.hashCode(); } } }
junit-jupiter-api/src/main/java/org/junit/jupiter/api/extension/ExtensionContext.java
/* * Copyright 2015-2017 the original author or authors. * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v2.0 which * accompanies this distribution and is available at * * http://www.eclipse.org/legal/epl-v20.html */ package org.junit.jupiter.api.extension; import static org.apiguardian.api.API.Status.STABLE; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import org.apiguardian.api.API; import org.junit.platform.commons.support.ReflectionSupport; import org.junit.platform.commons.util.PreconditionViolationException; import org.junit.platform.commons.util.Preconditions; /** * {@code ExtensionContext} encapsulates the <em>context</em> in which the * current test or container is being executed. * * <p>{@link Extension Extensions} are provided an instance of * {@code ExtensionContext} to perform their work. * * @since 5.0 * @see Store * @see Namespace */ @API(status = STABLE, since = "5.0") public interface ExtensionContext { /** * Get the parent extension context, if available. * * @return an {@code Optional} containing the parent; never {@code null} but * potentially empty * @see #getRoot() */ Optional<ExtensionContext> getParent(); /** * Get the <em>root</em> {@code ExtensionContext}. * * @return the root extension context; never {@code null} but potentially * <em>this</em> {@code ExtensionContext} * @see #getParent() */ ExtensionContext getRoot(); /** * Get the unique ID of the current test or container. * * @return the unique ID of the test or container; never {@code null} or blank */ String getUniqueId(); /** * Get the display name for the current test or container. * * <p>The display name is either a default name or a custom name configured * via {@link org.junit.jupiter.api.DisplayName @DisplayName}. * * <p>For details on default display names consult the Javadoc for * {@link org.junit.jupiter.api.TestInfo#getDisplayName()}. * * <p>Note that display names are typically used for test reporting in IDEs * and build tools and may contain spaces, special characters, and even emoji. * * @return the display name of the test or container; never {@code null} or blank */ String getDisplayName(); /** * Get the set of all tags for the current test or container. * * <p>Tags may be declared directly on the test element or <em>inherited</em> * from an outer context. * * @return the set of tags for the test or container; never {@code null} but * potentially empty */ Set<String> getTags(); /** * Get the {@link AnnotatedElement} corresponding to the current extension * context, if available. * * <p>For example, if the current extension context encapsulates a test * class, test method, test factory method, or test template method, the * annotated element will be the corresponding {@link Class} or {@link Method} * reference. * * <p>Favor this method over more specific methods whenever the * {@code AnnotatedElement} API suits the task at hand &mdash; for example, * when looking up annotations regardless of concrete element type. * * @return an {@code Optional} containing the {@code AnnotatedElement}; * never {@code null} but potentially empty * @see #getTestClass() * @see #getTestMethod() */ Optional<AnnotatedElement> getElement(); /** * Get the {@link Class} associated with the current test or container, * if available. * * @return an {@code Optional} containing the class; never {@code null} but * potentially empty * @see #getRequiredTestClass() */ Optional<Class<?>> getTestClass(); /** * Get the <em>required</em> {@link Class} associated with the current test * or container. * * <p>Use this method as an alternative to {@link #getTestClass()} for use * cases in which the test class is required to be present. * * @return the test class; never {@code null} * @throws PreconditionViolationException if the test class is not present * in this {@code ExtensionContext} */ default Class<?> getRequiredTestClass() { return Preconditions.notNull(getTestClass().orElse(null), "Illegal state: required test class is not present in the current ExtensionContext"); } /** * Get the test instance associated with the current test or container, * if available. * * @return an {@code Optional} containing the test instance; never * {@code null} but potentially empty * @see #getRequiredTestInstance() */ Optional<Object> getTestInstance(); /** * Get the <em>required</em> test instance associated with the current test * or container. * * <p>Use this method as an alternative to {@link #getTestInstance()} for use * cases in which the test instance is required to be present. * * @return the test instance; never {@code null} * @throws PreconditionViolationException if the test instance is not present * in this {@code ExtensionContext} */ default Object getRequiredTestInstance() { return Preconditions.notNull(getTestInstance().orElse(null), "Illegal state: required test instance is not present in the current ExtensionContext"); } /** * Get the {@link Method} associated with the current test, if available. * * @return an {@code Optional} containing the method; never {@code null} but * potentially empty * @see #getRequiredTestMethod() */ Optional<Method> getTestMethod(); /** * Get the <em>required</em> {@link Method} associated with the current test * or container. * * <p>Use this method as an alternative to {@link #getTestMethod()} for use * cases in which the test method is required to be present. * * @return the test method; never {@code null} * @throws PreconditionViolationException if the test method is not present * in this {@code ExtensionContext} */ default Method getRequiredTestMethod() { return Preconditions.notNull(getTestMethod().orElse(null), "Illegal state: required test method is not present in the current ExtensionContext"); } /** * Get the exception that was thrown during execution of the test or container * associated with this {@code ExtensionContext}, if available. * * <p>This method is typically used for logging and tracing purposes. If you * wish to actually <em>handle</em> an exception thrown during test execution, * implement the {@link TestExecutionExceptionHandler} API. * * <p>Unlike the exception passed to a {@code TestExecutionExceptionHandler}, * an <em>execution exception</em> returned by this method can be any * exception thrown during the invocation of a {@code @Test} method, its * surrounding {@code @BeforeEach} and {@code @AfterEach} methods, or a * test-level {@link Extension}. Similarly, if this {@code ExtensionContext} * represents a test class, the <em>execution exception</em> returned by * this method can be any exception thrown in a {@code @BeforeAll} or * {@code AfterAll} method or a class-level {@link Extension}. * * <p>Note, however, that this method will never return an exception * swallowed by a {@code TestExecutionExceptionHandler}. Furthermore, if * multiple exceptions have been thrown during test execution, the exception * returned by this method will be the first such exception with all * additional exceptions {@linkplain Throwable#addSuppressed(Throwable) * suppressed} in the first one. * * @return an {@code Optional} containing the exception thrown; never * {@code null} but potentially empty if test execution has not (yet) * resulted in an exception */ Optional<Throwable> getExecutionException(); /** * Get the configuration parameter stored under the specified {@code key}. * * <p>If no such key is present in the {@code ConfigurationParameters} for * the JUnit Platform, an attempt will be made to look up the value as a * JVM system property. If no such system property exists, an attempt will * be made to look up the value in the {@code JUnit Platform properties file}. * * @param key the key to look up; never {@code null} or blank * @return an {@code Optional} containing the value; never {@code null} * but potentially empty * * @see System#getProperty(String) * @see org.junit.platform.engine.ConfigurationParameters * @since 5.1 */ @API(status = STABLE, since = "5.1") Optional<String> getConfigurationParameter(String key); /** * Publish a map of key-value pairs to be consumed by an * {@code org.junit.platform.engine.EngineExecutionListener}. * * @param map the key-value pairs to be published; never {@code null}; * keys and values within entries in the map also must not be * {@code null} or blank */ void publishReportEntry(Map<String, String> map); /** * Publish the specified key-value pair to be consumed by an * {@code org.junit.platform.engine.EngineExecutionListener}. * * @param key the key of the published pair; never {@code null} or blank * @param value the value of the published pair; never {@code null} or blank */ default void publishReportEntry(String key, String value) { this.publishReportEntry(Collections.singletonMap(key, value)); } /** * Get the {@link Store} for the supplied {@link Namespace}. * * <p>Use {@code getStore(Namespace.GLOBAL)} to get the default, global {@link Namespace}. * * @param namespace the {@code Namespace} to get the store for; never {@code null} * @return the store in which to put and get objects for other invocations * working in the same namespace; never {@code null} * @see Namespace#GLOBAL */ Store getStore(Namespace namespace); /** * {@code Store} provides methods for extensions to save and retrieve data. */ interface Store { /** * Get the value that is stored under the supplied {@code key}. * * <p>If no value is stored in the current {@link ExtensionContext} * for the supplied {@code key}, ancestors of the context will be queried * for a value with the same {@code key} in the {@code Namespace} used * to create this store. * * <p>For greater type safety, consider using {@link #get(Object, Class)} * instead. * * @param key the key; never {@code null} * @return the value; potentially {@code null} * @see #get(Object, Class) */ Object get(Object key); /** * Get the value of the specified required type that is stored under * the supplied {@code key}. * * <p>If no value is stored in the current {@link ExtensionContext} * for the supplied {@code key}, ancestors of the context will be queried * for a value with the same {@code key} in the {@code Namespace} used * to create this store. * * @param key the key; never {@code null} * @param requiredType the required type of the value; never {@code null} * @param <V> the value type * @return the value; potentially {@code null} * @see #get(Object) */ <V> V get(Object key, Class<V> requiredType); /** * Get the object of type {@code type} that is present in this * {@code Store} (<em>keyed</em> by {@code type}); and otherwise invoke * the default constructor for {@code type} to generate the object, * store it, and return it. * * <p>This method is a shortcut for the following, where {@code X} is * the type of object we wish to retrieve from the store. * * <pre style="code"> * X x = store.getOrComputeIfAbsent(X.class, key -&gt; new X(), X.class); * // Equivalent to: * // X x = store.getOrComputeIfAbsent(X.class); * </pre> * * <p>See {@link #getOrComputeIfAbsent(Object, Function, Class)} for * further details. * * @param type the type of object to retrieve; never {@code null} * @param <V> the key and value type * @return the object; never {@code null} * @see #getOrComputeIfAbsent(Object, Function) * @see #getOrComputeIfAbsent(Object, Function, Class) */ default <V> V getOrComputeIfAbsent(Class<V> type) { return getOrComputeIfAbsent(type, ReflectionSupport::newInstance, type); } /** * Get the value that is stored under the supplied {@code key}. * * <p>If no value is stored in the current {@link ExtensionContext} * for the supplied {@code key}, ancestors of the context will be queried * for a value with the same {@code key} in the {@code Namespace} used * to create this store. If no value is found for the supplied {@code key}, * a new value will be computed by the {@code defaultCreator} (given * the {@code key} as input), stored, and returned. * * <p>For greater type safety, consider using * {@link #getOrComputeIfAbsent(Object, Function, Class)} instead. * * @param key the key; never {@code null} * @param defaultCreator the function called with the supplied {@code key} * to create a new value; never {@code null} * @param <K> the key type * @param <V> the value type * @return the value; potentially {@code null} * @see #getOrComputeIfAbsent(Class) * @see #getOrComputeIfAbsent(Object, Function, Class) */ <K, V> Object getOrComputeIfAbsent(K key, Function<K, V> defaultCreator); /** * Get the value of the specified required type that is stored under the * supplied {@code key}. * * <p>If no value is stored in the current {@link ExtensionContext} * for the supplied {@code key}, ancestors of the context will be queried * for a value with the same {@code key} in the {@code Namespace} used * to create this store. If no value is found for the supplied {@code key}, * a new value will be computed by the {@code defaultCreator} (given * the {@code key} as input), stored, and returned. * * @param key the key; never {@code null} * @param defaultCreator the function called with the supplied {@code key} * to create a new value; never {@code null} * @param requiredType the required type of the value; never {@code null} * @param <K> the key type * @param <V> the value type * @return the value; potentially {@code null} * @see #getOrComputeIfAbsent(Class) * @see #getOrComputeIfAbsent(Object, Function) */ <K, V> V getOrComputeIfAbsent(K key, Function<K, V> defaultCreator, Class<V> requiredType); /** * Store a {@code value} for later retrieval under the supplied {@code key}. * * <p>A stored {@code value} is visible in child {@link ExtensionContext * ExtensionContexts} for the store's {@code Namespace} unless they * overwrite it. * * @param key the key under which the value should be stored; never * {@code null} * @param value the value to store; may be {@code null} */ void put(Object key, Object value); /** * Remove the value that was previously stored under the supplied {@code key}. * * <p>The value will only be removed in the current {@link ExtensionContext}, * not in ancestors. * * <p>For greater type safety, consider using {@link #remove(Object, Class)} * instead. * * @param key the key; never {@code null} * @return the previous value or {@code null} if no value was present * for the specified key * @see #remove(Object, Class) */ Object remove(Object key); /** * Remove the value of the specified required type that was previously stored * under the supplied {@code key}. * * <p>The value will only be removed in the current {@link ExtensionContext}, * not in ancestors. * * @param key the key; never {@code null} * @param requiredType the required type of the value; never {@code null} * @param <V> the value type * @return the previous value or {@code null} if no value was present * for the specified key * @see #remove(Object) */ <V> V remove(Object key, Class<V> requiredType); } /** * A {@code Namespace} is used to provide a <em>scope</em> for data saved by * extensions within a {@link Store}. * * <p>Storing data in custom namespaces allows extensions to avoid accidentally * mixing data between extensions or across different invocations within the * lifecycle of a single extension. */ class Namespace { /** * The default, global namespace which allows access to stored data from * all extensions. */ public static final Namespace GLOBAL = Namespace.create(new Object()); /** * Create a namespace which restricts access to data to all extensions * which use the same sequence of {@code parts} for creating a namespace. * * <p>The order of the {@code parts} is significant. * * <p>Internally the {@code parts} are compared using {@link Object#equals(Object)}. */ public static Namespace create(Object... parts) { Preconditions.notEmpty(parts, "parts array must not be null or empty"); Preconditions.containsNoNullElements(parts, "individual parts must not be null"); return new Namespace(parts); } private final List<?> parts; private Namespace(Object... parts) { this.parts = new ArrayList<>(Arrays.asList(parts)); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Namespace that = (Namespace) o; return this.parts.equals(that.parts); } @Override public int hashCode() { return this.parts.hashCode(); } } }
Polishing
junit-jupiter-api/src/main/java/org/junit/jupiter/api/extension/ExtensionContext.java
Polishing
<ide><path>unit-jupiter-api/src/main/java/org/junit/jupiter/api/extension/ExtensionContext.java <ide> * <p>If no such key is present in the {@code ConfigurationParameters} for <ide> * the JUnit Platform, an attempt will be made to look up the value as a <ide> * JVM system property. If no such system property exists, an attempt will <del> * be made to look up the value in the {@code JUnit Platform properties file}. <add> * be made to look up the value in the JUnit Platform properties file. <ide> * <ide> * @param key the key to look up; never {@code null} or blank <ide> * @return an {@code Optional} containing the value; never {@code null}
Java
bsd-3-clause
b2421f4c321714d8f45c9ff9e0eac57588663d0f
0
gchauvet/purejavacomm,nyholku/purejavacomm,nyholku/purejavacomm,nyholku/purejavacomm,gchauvet/purejavacomm
/* * Copyright (c) 2011, Kustaa Nyholm / SpareTimeLabs * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * Neither the name of the Kustaa Nyholm or SpareTimeLabs nor the names of its * contributors may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ package purejavacomm.testsuite; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.Random; import purejavacomm.CommPortIdentifier; import purejavacomm.NoSuchPortException; import purejavacomm.SerialPort; public class TestBase { static class TestFailedException extends Exception { } protected static volatile String m_TestPortName; protected static volatile SerialPort m_Port; private static volatile long m_T0; protected static volatile OutputStream m_Out; protected static volatile InputStream m_In; protected static volatile int[] m_SyncSema4 = { 0 }; protected static int m_Tab; protected static int m_Progress; protected static void sync(int N) throws InterruptedException { synchronized (m_SyncSema4) { m_SyncSema4[0]++; if (m_SyncSema4[0] < N) { m_SyncSema4.wait(); } else { m_SyncSema4[0] = 0; m_SyncSema4.notifyAll(); } } } static protected void openPort() throws Exception { try { CommPortIdentifier portid = CommPortIdentifier.getPortIdentifier(m_TestPortName); m_Port = (SerialPort) portid.open("PureJavaCommTestSuite", 1000); m_Out = m_Port.getOutputStream(); m_In = m_Port.getInputStream(); drain(m_In); } catch (NoSuchPortException e) { fail("could no open port '%s'\n", m_TestPortName); } } static protected void closePort() { if (m_Port != null) { try { m_Out.flush(); m_Port.close(); } catch (IOException e) { e.printStackTrace(); } finally { m_Port = null; } } } static protected void drain(InputStream ins) throws Exception { sleep(100); int n; while ((n = ins.available()) > 0) { for (int i = 0; i < n; ++i) ins.read(); sleep(100); } } static void begin(String name) { System.out.printf("%-46s", name); m_Tab = 46; m_T0 = System.currentTimeMillis(); m_Progress = 0; } /** * Sleep a short amount of time to allow hardware feedback, which isn't * instant */ static protected void sleep() throws InterruptedException { sleep(40); } static protected void sleep(int t) throws InterruptedException { int m = 1000; while (t > 0) { Thread.sleep(t > m ? m : t); t -= m; while ((System.currentTimeMillis() - m_T0) / m > m_Progress) { System.out.print("."); m_Tab--; m_Progress++; } } } static void fail(String format, Object... args) throws TestFailedException { System.out.println(" FAILED"); System.out.println("------------------------------------------------------------"); System.out.printf(format, args); System.out.println(); System.out.println("------------------------------------------------------------"); throw new TestFailedException(); } static void finishedOK() { finishedOK(""); } static void finishedOK(String format, Object... args) { for (int i = 0; i < m_Tab; i++) System.out.print("."); System.out.printf(" OK " + format, args); System.out.println(); } static public void init(String[] args) { m_TestPortName = "cu.usbserial-FTOXM3NX"; if (args.length > 0) m_TestPortName = args[0]; } static public String getPortName() { return m_TestPortName; } }
src/purejavacomm/testsuite/TestBase.java
/* * Copyright (c) 2011, Kustaa Nyholm / SpareTimeLabs * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * Neither the name of the Kustaa Nyholm or SpareTimeLabs nor the names of its * contributors may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ package purejavacomm.testsuite; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.Random; import purejavacomm.CommPortIdentifier; import purejavacomm.NoSuchPortException; import purejavacomm.SerialPort; public class TestBase { static class TestFailedException extends Exception { } protected static volatile String m_TestPortName; protected static volatile SerialPort m_Port; private static volatile long m_T0; protected static volatile OutputStream m_Out; protected static volatile InputStream m_In; protected static volatile int[] m_SyncSema4 = { 0 }; protected static int m_Tab; protected static int m_Progress; protected static void sync(int N) throws InterruptedException { synchronized (m_SyncSema4) { m_SyncSema4[0]++; if (m_SyncSema4[0] < N) { m_SyncSema4.wait(); } else { m_SyncSema4[0] = 0; m_SyncSema4.notifyAll(); } } } static protected void openPort() throws Exception { try { CommPortIdentifier portid = CommPortIdentifier.getPortIdentifier(m_TestPortName); m_Port = (SerialPort) portid.open("PureJavaCommTestSuite", 1000); m_Out = m_Port.getOutputStream(); m_In = m_Port.getInputStream(); drain(m_In); } catch (NoSuchPortException e) { fail("could no open port '%s'\n", m_TestPortName); } } static protected void closePort() { if (m_Port != null) { try { m_Out.flush(); m_Port.close(); } catch (IOException e) { e.printStackTrace(); } finally { m_Port = null; } } } static protected void drain(InputStream ins) throws Exception { sleep(100); int n; while ((n = ins.available()) > 0) { for (int i = 0; i < n; ++i) ins.read(); sleep(100); } } static void begin(String name) { System.out.printf("%-46s", name); m_Tab = 46; m_T0 = System.currentTimeMillis(); m_Progress = 0; } /** * Sleep a short amount of time to allow hardware feedback, which isn't * instant */ static protected void sleep() throws InterruptedException { sleep(40); } static protected void sleep(int t) throws InterruptedException { int m = 1000; while (t > 0) { Thread.sleep(t > m ? m : t); t -= m; while ((System.currentTimeMillis() - m_T0) / m > m_Progress) { System.out.print("."); m_Tab--; m_Progress++; } } } static void fail(String format, Object... args) throws TestFailedException { System.out.println(" FAILED"); System.out.println("------------------------------------------------------------"); System.out.printf(format, args); System.out.println(); System.out.println("------------------------------------------------------------"); throw new TestFailedException(); } static void finishedOK() { finishedOK(""); } static void finishedOK(String format, Object... args) { for (int i = 0; i < m_Tab; i++) System.out.print("."); System.out.printf(" OK " + format, args); System.out.println(); } static public void init(String[] args) { m_TestPortName = "cu.usbserial-FTOXM3NX"; if (args.length > 0) m_TestPortName = args[0]; Enumeration e = CommPortIdentifier.getPortIdentifiers(); boolean found = false; String last = null; while (e.hasMoreElements()) { CommPortIdentifier portid = (CommPortIdentifier) e.nextElement(); if (portid.getPortType() == CommPortIdentifier.PORT_SERIAL) { if (portid.getName().equals(m_TestPortName)) found = true; last = portid.getName(); } } if (!found) m_TestPortName = last; } static public String getPortName() { return m_TestPortName; } }
Removed port detection feature from the TestBase. It's been preventing a proper test setup
src/purejavacomm/testsuite/TestBase.java
Removed port detection feature from the TestBase. It's been preventing a proper test setup
<ide><path>rc/purejavacomm/testsuite/TestBase.java <ide> m_TestPortName = "cu.usbserial-FTOXM3NX"; <ide> if (args.length > 0) <ide> m_TestPortName = args[0]; <del> Enumeration e = CommPortIdentifier.getPortIdentifiers(); <del> boolean found = false; <del> String last = null; <del> while (e.hasMoreElements()) { <del> CommPortIdentifier portid = (CommPortIdentifier) e.nextElement(); <del> if (portid.getPortType() == CommPortIdentifier.PORT_SERIAL) { <del> if (portid.getName().equals(m_TestPortName)) <del> found = true; <del> last = portid.getName(); <del> } <del> } <del> if (!found) <del> m_TestPortName = last; <del> <ide> } <ide> <ide> static public String getPortName() {
Java
apache-2.0
be653bdab984697a5eb02b39155e654419a8b81e
0
KartiKeya123/android-log-viewer,ohjongin/android-log-viewer,CCDMK/android-log-viewer,ujiro99/android-log-viewer,ohjongin/android-log-viewer,vdiskmobile/android-log-viewer,CCDMK/android-log-viewer,ujiro99/android-log-viewer,KartiKeya123/android-log-viewer,vdiskmobile/android-log-viewer
/* * Copyright 2011 Mikhail Lopatkin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitbucket.mlopatkin.android.logviewer; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.RowSorter.SortKey; import javax.swing.SortOrder; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.border.EmptyBorder; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import org.bitbucket.mlopatkin.android.liblogcat.DataSource; /** * Displays list of available processes and their pids. */ public class ProcessListFrame extends JFrame { private JTable table; public ProcessListFrame() { setTitle("Processes"); setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); setBounds(100, 100, 450, 300); JPanel contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); JScrollPane scrollPane = new JScrollPane(); contentPane.add(scrollPane, BorderLayout.CENTER); table = new JTable(); table.setFillsViewportHeight(true); table.setAutoCreateRowSorter(true); scrollPane.setViewportView(table); } private static final TableModel EMPTY_MODEL = new DefaultTableModel(); private void reset() { updateTimer.stop(); model = null; table.setModel(EMPTY_MODEL); } private static final List<SortKey> DEFAULT_SORTING = Arrays.asList(new SortKey( ProcessListModel.COLUMN_PID, SortOrder.ASCENDING)); public void setSource(DataSource source) { assert SwingUtilities.isEventDispatchThread(); @SuppressWarnings("unchecked") List<SortKey> oldKeys = (List<SortKey>) table.getRowSorter().getSortKeys(); reset(); if (source != null) { assert source.getPidToProcessConverter() != null; model = new ProcessListModel(source.getPidToProcessConverter()); table.setModel(model); if (oldKeys.isEmpty()) { table.getRowSorter().setSortKeys(DEFAULT_SORTING); } else { table.getRowSorter().setSortKeys(oldKeys); } updateTimer.start(); } else { if (isVisible()) { setVisible(false); } } } private ProcessListModel model; private static final String[] COLUMN_NAMES = new String[] { "PID", "Process" }; private static final Class<?>[] COLUMN_CLASSES = new Class<?>[] { Integer.class, String.class }; @SuppressWarnings("rawtypes") private class ProcessListModel extends AbstractTableModel { static final int COLUMN_PID = 0; static final int COLUMN_PROCESS = 1; private static final int COLUMNS_COUNT = 2; private List[] items = new List<?>[COLUMNS_COUNT]; private Map<Integer, String> mapper; public ProcessListModel(Map<Integer, String> mapper) { int l = mapper.size(); this.mapper = mapper; items[COLUMN_PID] = new ArrayList<Integer>(l); items[COLUMN_PROCESS] = new ArrayList<Integer>(l); fillItems(); } @SuppressWarnings("unchecked") private void fillItems() { for (Entry<Integer, String> entry : mapper.entrySet()) { items[COLUMN_PID].add(entry.getKey()); items[COLUMN_PROCESS].add(entry.getValue()); } } @Override public String getColumnName(int column) { return COLUMN_NAMES[column]; } @Override public Class<?> getColumnClass(int column) { return COLUMN_CLASSES[column]; } @Override public int getColumnCount() { return COLUMNS_COUNT; } @Override public boolean isCellEditable(int row, int column) { return false; } @Override public int getRowCount() { return items[COLUMN_PID].size(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { return items[columnIndex].get(rowIndex); } public void update() { assert SwingUtilities.isEventDispatchThread(); int oldSize = getRowCount(); for (List l : items) { l.clear(); } fillItems(); int newSize = getRowCount(); if (newSize < oldSize) { fireTableRowsUpdated(0, newSize - 1); fireTableRowsDeleted(newSize, oldSize - 1); } else if (newSize > oldSize) { fireTableRowsUpdated(0, oldSize - 1); fireTableRowsInserted(oldSize, newSize - 1); } else { fireTableRowsUpdated(0, newSize - 1); } } } private static final int UPDATE_DELAY_MS = 1000; private Timer updateTimer = new Timer(UPDATE_DELAY_MS, new ActionListener() { public void actionPerformed(ActionEvent e) { model.update(); } }); }
src/org/bitbucket/mlopatkin/android/logviewer/ProcessListFrame.java
/* * Copyright 2011 Mikhail Lopatkin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitbucket.mlopatkin.android.logviewer; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.RowSorter.SortKey; import javax.swing.SortOrder; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.border.EmptyBorder; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import org.bitbucket.mlopatkin.android.liblogcat.DataSource; /** * Displays list of available processes and their pids. */ public class ProcessListFrame extends JFrame { private JTable table; public ProcessListFrame() { setTitle("Processes"); setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); setBounds(100, 100, 450, 300); JPanel contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); JScrollPane scrollPane = new JScrollPane(); contentPane.add(scrollPane, BorderLayout.CENTER); table = new JTable(); table.setFillsViewportHeight(true); table.setAutoCreateRowSorter(true); scrollPane.setViewportView(table); } private static final TableModel EMPTY_MODEL = new DefaultTableModel(); private void reset() { updateTimer.stop(); model = null; table.setModel(EMPTY_MODEL); } private static final List<SortKey> DEFAULT_SORTING = Arrays.asList(new SortKey( ProcessListModel.COLUMN_PID, SortOrder.ASCENDING)); public void setSource(DataSource source) { assert SwingUtilities.isEventDispatchThread(); @SuppressWarnings("unchecked") List<SortKey> oldKeys = (List<SortKey>) table.getRowSorter().getSortKeys(); reset(); if (source != null) { assert source.getPidToProcessConverter() != null; model = new ProcessListModel(source.getPidToProcessConverter()); table.setModel(model); if (oldKeys.isEmpty()) { table.getRowSorter().setSortKeys(DEFAULT_SORTING); } else { table.getRowSorter().setSortKeys(oldKeys); } updateTimer.start(); } else { if (isVisible()) { setVisible(false); } } } private ProcessListModel model; private static final String[] COLUMN_NAMES = new String[] { "PID", "Process" }; private static final Class<?>[] COLUMN_CLASSES = new Class<?>[] { Integer.class, String.class }; @SuppressWarnings("rawtypes") private class ProcessListModel extends AbstractTableModel { static final int COLUMN_PID = 0; static final int COLUMN_PROCESS = 1; private static final int COLUMNS_COUNT = 2; private List[] items = new List<?>[COLUMNS_COUNT]; private Map<Integer, String> mapper; public ProcessListModel(Map<Integer, String> mapper) { int l = mapper.size(); this.mapper = mapper; items[COLUMN_PID] = new ArrayList<Integer>(l); items[COLUMN_PROCESS] = new ArrayList<Integer>(l); fillItems(); } @SuppressWarnings("unchecked") private void fillItems() { for (Entry<Integer, String> entry : mapper.entrySet()) { items[COLUMN_PID].add(entry.getKey()); items[COLUMN_PROCESS].add(entry.getValue()); } } @Override public String getColumnName(int column) { return COLUMN_NAMES[column]; } @Override public Class<?> getColumnClass(int column) { return COLUMN_CLASSES[column]; } @Override public int getColumnCount() { return COLUMNS_COUNT; } @Override public boolean isCellEditable(int row, int column) { return false; } @Override public int getRowCount() { return items[COLUMN_PID].size(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { return items[columnIndex].get(rowIndex); } public void update() { assert SwingUtilities.isEventDispatchThread(); for (List l : items) { l.clear(); } fillItems(); fireTableDataChanged(); } } private static final int UPDATE_DELAY_MS = 1000; private Timer updateTimer = new Timer(UPDATE_DELAY_MS, new ActionListener() { public void actionPerformed(ActionEvent e) { model.update(); } }); }
Fixed problem with disappearing selection in ProcessList
src/org/bitbucket/mlopatkin/android/logviewer/ProcessListFrame.java
Fixed problem with disappearing selection in ProcessList
<ide><path>rc/org/bitbucket/mlopatkin/android/logviewer/ProcessListFrame.java <ide> <ide> public void update() { <ide> assert SwingUtilities.isEventDispatchThread(); <add> int oldSize = getRowCount(); <ide> for (List l : items) { <ide> l.clear(); <ide> } <ide> fillItems(); <del> fireTableDataChanged(); <add> int newSize = getRowCount(); <add> if (newSize < oldSize) { <add> fireTableRowsUpdated(0, newSize - 1); <add> fireTableRowsDeleted(newSize, oldSize - 1); <add> } else if (newSize > oldSize) { <add> fireTableRowsUpdated(0, oldSize - 1); <add> fireTableRowsInserted(oldSize, newSize - 1); <add> } else { <add> fireTableRowsUpdated(0, newSize - 1); <add> } <ide> } <ide> } <ide>
JavaScript
mit
077719d0ff0c4f1538191d90cbf4c17cfeaef567
0
brettz9/atyourcommand,brettz9/atyourcommand
/*globals self*/ /*jslint vars: true*/ /* // For "context" events, "node" will always be the SelectorContext node, // even if a child node is the one responsible for activating the menu self.on('context', function (node) {'use strict'; }); */ // For "click" events where "SelectorContext" was used, "node" will be // the SelectorContext node; otherwise, it will be the actual node clicked self.on('click', function (node, data) {'use strict'; var msg = { selector: data.selector, contentType: document.contentType, pageURL: document.URL, selectedHTML: node.outerHTML, selectedText: node.textContent, // Could require user to specify these (as associatable with specific tags) pageTitle: document.title, // hidden pageHTML: document.documentElement.outerHTML, // Treat like hidden to avoid need to select anything bodyText: document.body.textContent // Treat like hidden to avoid need to select anything }; var nodeName = node.nodeName.toLowerCase(); if (data.customProperty) { msg.customProperty = node[data.customProperty]; } // Retrieve "linkPageTitle", "linkBodyText", and "linkPageHTML" only as needed self.postMessage(msg); // We need privs on the dialogs we open });
data/main-context-menu.js
/*globals self*/ /*jslint vars: true*/ /* // For "context" events, "node" will always be the SelectorContext node, // even if a child node is the one responsible for activating the menu self.on('context', function (node) {'use strict'; }); */ // For "click" events where "SelectorContext" was used, "node" will be // the SelectorContext node; otherwise, it will be the actual node clicked self.on('click', function (node, data) {'use strict'; var msg = { type: data, contentType: document.contentType, pageURL: document.URL, pageTitle: document.title, pageHTML: document.documentElement.outerHTML, bodyText: document.body.textContent, selectedHTML: node.outerHTML, selectedText: node.textContent selector: data.selector }; var nodeName = node.nodeName.toLowerCase(); if (data.customProperty) { msg.customProperty = node[data.customProperty]; } // Retrieve "linkPageTitle", "linkBodyText", and "linkPageHTML" only as needed self.postMessage(msg); // We need privs on the dialogs we open });
Reorg. properties with info on status
data/main-context-menu.js
Reorg. properties with info on status
<ide><path>ata/main-context-menu.js <ide> // the SelectorContext node; otherwise, it will be the actual node clicked <ide> self.on('click', function (node, data) {'use strict'; <ide> var msg = { <del> type: data, <add> selector: data.selector, <ide> contentType: document.contentType, <ide> pageURL: document.URL, <del> pageTitle: document.title, <del> pageHTML: document.documentElement.outerHTML, <del> bodyText: document.body.textContent, <ide> selectedHTML: node.outerHTML, <del> selectedText: node.textContent <del> selector: data.selector <add> selectedText: node.textContent, <add> // Could require user to specify these (as associatable with specific tags) <add> pageTitle: document.title, // hidden <add> pageHTML: document.documentElement.outerHTML, // Treat like hidden to avoid need to select anything <add> bodyText: document.body.textContent // Treat like hidden to avoid need to select anything <ide> }; <ide> var nodeName = node.nodeName.toLowerCase(); <ide> if (data.customProperty) {
Java
mpl-2.0
e84f62a339763a51b386643f80f82a8c5d63d639
0
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
/* Weave (Web-based Analysis and Visualization Environment) Copyright (C) 2008-2011 University of Massachusetts Lowell This file is a part of Weave. Weave is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License, Version 3, as published by the Free Software Foundation. Weave is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Weave. If not, see <http://www.gnu.org/licenses/>. */ package weave.config.tables; import java.rmi.RemoteException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Vector; import weave.config.ConnectionConfig; import weave.utils.MapUtils; import weave.utils.SQLResult; import weave.utils.SQLUtils; import weave.utils.SQLUtils.WhereClause; import weave.utils.StringUtils; /** * @author Philip Kovac */ public class MetadataTable extends AbstractTable { public static final String FIELD_ID = "entity_id"; public static final String FIELD_PROPERTY = "property"; public static final String FIELD_VALUE = "value"; private static final Set<String> caseSensitiveFields = new HashSet<String>(Arrays.asList(FIELD_PROPERTY, FIELD_VALUE)); private ManifestTable manifest = null; public MetadataTable(ConnectionConfig connectionConfig, String schemaName, String tableName, ManifestTable manifest) throws RemoteException { super(connectionConfig, schemaName, tableName, FIELD_ID, FIELD_PROPERTY, FIELD_VALUE); this.manifest = manifest; if (!tableExists()) initTable(); } protected void initTable() throws RemoteException { if (manifest == null) return; Connection conn; try { conn = connectionConfig.getAdminConnection(); // primary key is (id,property) for indexing and because // we don't want duplicate properties for the same id SQLUtils.createTable( conn, schemaName, tableName, Arrays.asList(fieldNames), Arrays.asList( "BIGINT UNSIGNED", SQLUtils.getVarcharTypeString(conn, 255), SQLUtils.getVarcharTypeString(conn, 2048) ), Arrays.asList(FIELD_ID, FIELD_PROPERTY) ); // addForeignKey(FIELD_ID, manifest, ManifestTable.FIELD_ID); } catch (SQLException e) { throw new RemoteException("Unable to initialize attribute-value-table.", e); } try { /* Index of (property) */ SQLUtils.createIndex( conn, schemaName, tableName, tableName+FIELD_PROPERTY, new String[]{FIELD_PROPERTY}, null ); /* Index of (Property, Value), important for finding ids with metadata criteria */ SQLUtils.createIndex( conn, schemaName, tableName, tableName+FIELD_PROPERTY+FIELD_VALUE, new String[]{FIELD_PROPERTY, FIELD_VALUE}, new Integer[]{32,32} ); } catch (SQLException e) { System.err.println("WARNING: Failed to create index. This may happen if the table already exists."); } } public void setProperties(Integer id, Map<String,String> diff) throws RemoteException { try { if (!connectionConfig.migrationPending()) { Connection conn = connectionConfig.getAdminConnection(); List<Map<String,Object>> records = new Vector<Map<String,Object>>(diff.size()); for (String property : diff.keySet()) { Map<String,Object> record = MapUtils.fromPairs(FIELD_ID, id, FIELD_PROPERTY, property); records.add(record); } WhereClause<Object> where = new WhereClause<Object>(conn, records, caseSensitiveFields, false); SQLUtils.deleteRows(conn, schemaName, tableName, where); } for (Entry<String,String> entry : diff.entrySet()) { String value = entry.getValue(); if (value != null && value.length() > 0) insertRecord(id, entry.getKey(), value); } } catch (SQLException e) { throw new RemoteException("Unable to set property.", e); } } public void removeAllProperties(Integer id) throws RemoteException { try { Connection conn = connectionConfig.getAdminConnection(); Map<String,Object> conditions = MapUtils.fromPairs(FIELD_ID, id); WhereClause<Object> where = new WhereClause<Object>(conn, conditions, caseSensitiveFields, true); SQLUtils.deleteRows(conn, schemaName, tableName, where); } catch (SQLException e) { throw new RemoteException("Unable to clear properties for a given id.", e); } } public Map<Integer, String> getPropertyMap(Collection<Integer> ids, String property) throws RemoteException { ResultSet rs = null; PreparedStatement stmt = null; try { Connection conn = connectionConfig.getAdminConnection(); Map<Integer,String> result = new HashMap<Integer,String>(); // build query String quotedIdField = SQLUtils.quoteSymbol(conn, FIELD_ID); String query = String.format( "SELECT %s,%s FROM %s WHERE %s=?", quotedIdField, SQLUtils.quoteSymbol(conn, FIELD_VALUE), SQLUtils.quoteSchemaTable(conn, schemaName, tableName), SQLUtils.quoteSymbol(conn, FIELD_PROPERTY) ); if (ids != null) query += String.format(" AND %s IN (%s)", quotedIdField, StringUtils.join(",", ids)); // make query and get values stmt = SQLUtils.prepareStatement(conn, query, Arrays.asList(property)); rs = stmt.executeQuery(); rs.setFetchSize(SQLResult.FETCH_SIZE); while (rs.next()) result.put(rs.getInt(FIELD_ID), rs.getString(FIELD_VALUE)); return result; } catch (SQLException e) { throw new RemoteException("Unable to get all instances of a property.", e); } finally { SQLUtils.cleanup(rs); SQLUtils.cleanup(stmt); } } public Map<Integer, Map<String,String>> getProperties(Collection<Integer> ids) throws RemoteException { PreparedStatement stmt = null; ResultSet rs = null; try { Map<Integer,Map<String,String>> result = MapUtils.fromPairs(); if (ids.size() == 0) return result; for (int id : ids) result.put(id, new HashMap<String,String>()); Connection conn = connectionConfig.getAdminConnection(); String query = String.format( "SELECT * FROM %s WHERE %s IN (%s)", SQLUtils.quoteSchemaTable(conn, schemaName, tableName), SQLUtils.quoteSymbol(conn, FIELD_ID), StringUtils.join(",", ids) ); stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); rs.setFetchSize(SQLResult.FETCH_SIZE); while (rs.next()) { int id = rs.getInt(FIELD_ID); String property = rs.getString(FIELD_PROPERTY); String value = rs.getString(FIELD_VALUE); result.get(id).put(property, value); } return result; } catch (SQLException e) { throw new RemoteException("Unable to retrieve metadata", e); } finally { SQLUtils.cleanup(rs); SQLUtils.cleanup(stmt); } } public Set<Integer> filter(Map<String,String> constraints) throws RemoteException { try { Connection conn = connectionConfig.getAdminConnection(); List<Map<String,String>> crossRowArgs = new Vector<Map<String,String>>(constraints.size()); for (Entry<String,String> keyValPair : constraints.entrySet()) { if (keyValPair.getKey() == null || keyValPair.getValue() == null) continue; Map<String,String> colValPair = MapUtils.fromPairs( FIELD_PROPERTY, keyValPair.getKey(), FIELD_VALUE, keyValPair.getValue() ); crossRowArgs.add(colValPair); } return new HashSet<Integer>(SQLUtils.crossRowSelect(conn, schemaName, tableName, FIELD_ID, crossRowArgs, caseSensitiveFields)); } catch (SQLException e) { throw new RemoteException("Unable to get ids given a set of property/value pairs.", e); } } }
WeaveServices/src/weave/config/tables/MetadataTable.java
/* Weave (Web-based Analysis and Visualization Environment) Copyright (C) 2008-2011 University of Massachusetts Lowell This file is a part of Weave. Weave is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License, Version 3, as published by the Free Software Foundation. Weave is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Weave. If not, see <http://www.gnu.org/licenses/>. */ package weave.config.tables; import java.rmi.RemoteException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Vector; import weave.config.ConnectionConfig; import weave.utils.MapUtils; import weave.utils.SQLResult; import weave.utils.SQLUtils; import weave.utils.SQLUtils.WhereClause; import weave.utils.StringUtils; /** * @author Philip Kovac */ public class MetadataTable extends AbstractTable { public static final String FIELD_ID = "entity_id"; public static final String FIELD_PROPERTY = "property"; public static final String FIELD_VALUE = "value"; private static final Set<String> caseSensitiveFields = new HashSet<String>(Arrays.asList(FIELD_PROPERTY, FIELD_VALUE)); private ManifestTable manifest = null; public MetadataTable(ConnectionConfig connectionConfig, String schemaName, String tableName, ManifestTable manifest) throws RemoteException { super(connectionConfig, schemaName, tableName, FIELD_ID, FIELD_PROPERTY, FIELD_VALUE); this.manifest = manifest; if (!tableExists()) initTable(); } protected void initTable() throws RemoteException { if (manifest == null) return; Connection conn; try { conn = connectionConfig.getAdminConnection(); // primary key is (id,property) for indexing and because // we don't want duplicate properties for the same id SQLUtils.createTable( conn, schemaName, tableName, Arrays.asList(fieldNames), Arrays.asList( "BIGINT UNSIGNED", SQLUtils.getVarcharTypeString(conn, 255), SQLUtils.getVarcharTypeString(conn, 2048) ), Arrays.asList(FIELD_ID, FIELD_PROPERTY) ); // addForeignKey(FIELD_ID, manifest, ManifestTable.FIELD_ID); } catch (SQLException e) { throw new RemoteException("Unable to initialize attribute-value-table.", e); } try { // /* Index of (id) */ // SQLUtils.createIndex( // conn, schemaName, tableName, // tableName+FIELD_ID, // new String[]{FIELD_ID}, // null // ); /* Index of (Property, Value), important for finding ids with metadata criteria */ SQLUtils.createIndex( conn, schemaName, tableName, tableName+FIELD_PROPERTY+FIELD_VALUE, new String[]{FIELD_PROPERTY, FIELD_VALUE}, new Integer[]{32,32} ); } catch (SQLException e) { System.err.println("WARNING: Failed to create index. This may happen if the table already exists."); } } public void setProperties(Integer id, Map<String,String> diff) throws RemoteException { try { if (!connectionConfig.migrationPending()) { Connection conn = connectionConfig.getAdminConnection(); List<Map<String,Object>> records = new Vector<Map<String,Object>>(diff.size()); for (String property : diff.keySet()) { Map<String,Object> record = MapUtils.fromPairs(FIELD_ID, id, FIELD_PROPERTY, property); records.add(record); } WhereClause<Object> where = new WhereClause<Object>(conn, records, caseSensitiveFields, false); SQLUtils.deleteRows(conn, schemaName, tableName, where); } for (Entry<String,String> entry : diff.entrySet()) { String value = entry.getValue(); if (value != null && value.length() > 0) insertRecord(id, entry.getKey(), value); } } catch (SQLException e) { throw new RemoteException("Unable to set property.", e); } } public void removeAllProperties(Integer id) throws RemoteException { try { Connection conn = connectionConfig.getAdminConnection(); Map<String,Object> conditions = MapUtils.fromPairs(FIELD_ID, id); WhereClause<Object> where = new WhereClause<Object>(conn, conditions, caseSensitiveFields, true); SQLUtils.deleteRows(conn, schemaName, tableName, where); } catch (SQLException e) { throw new RemoteException("Unable to clear properties for a given id.", e); } } public Map<Integer, String> getPropertyMap(Collection<Integer> ids, String property) throws RemoteException { ResultSet rs = null; PreparedStatement stmt = null; try { Connection conn = connectionConfig.getAdminConnection(); Map<Integer,String> result = new HashMap<Integer,String>(); // build query String quotedIdField = SQLUtils.quoteSymbol(conn, FIELD_ID); String query = String.format( "SELECT %s,%s FROM %s WHERE %s=?", quotedIdField, SQLUtils.quoteSymbol(conn, FIELD_VALUE), SQLUtils.quoteSchemaTable(conn, schemaName, tableName), SQLUtils.quoteSymbol(conn, FIELD_PROPERTY) ); if (ids != null) query += String.format(" AND %s IN (%s)", quotedIdField, StringUtils.join(",", ids)); // make query and get values stmt = SQLUtils.prepareStatement(conn, query, Arrays.asList(property)); rs = stmt.executeQuery(); rs.setFetchSize(SQLResult.FETCH_SIZE); while (rs.next()) result.put(rs.getInt(FIELD_ID), rs.getString(FIELD_VALUE)); return result; } catch (SQLException e) { throw new RemoteException("Unable to get all instances of a property.", e); } finally { SQLUtils.cleanup(rs); SQLUtils.cleanup(stmt); } } public Map<Integer, Map<String,String>> getProperties(Collection<Integer> ids) throws RemoteException { PreparedStatement stmt = null; ResultSet rs = null; try { Map<Integer,Map<String,String>> result = MapUtils.fromPairs(); if (ids.size() == 0) return result; for (int id : ids) result.put(id, new HashMap<String,String>()); Connection conn = connectionConfig.getAdminConnection(); String query = String.format( "SELECT * FROM %s WHERE %s IN (%s)", SQLUtils.quoteSchemaTable(conn, schemaName, tableName), SQLUtils.quoteSymbol(conn, FIELD_ID), StringUtils.join(",", ids) ); stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); rs.setFetchSize(SQLResult.FETCH_SIZE); while (rs.next()) { int id = rs.getInt(FIELD_ID); String property = rs.getString(FIELD_PROPERTY); String value = rs.getString(FIELD_VALUE); result.get(id).put(property, value); } return result; } catch (SQLException e) { throw new RemoteException("Unable to retrieve metadata", e); } finally { SQLUtils.cleanup(rs); SQLUtils.cleanup(stmt); } } public Set<Integer> filter(Map<String,String> constraints) throws RemoteException { try { Connection conn = connectionConfig.getAdminConnection(); List<Map<String,String>> crossRowArgs = new Vector<Map<String,String>>(constraints.size()); for (Entry<String,String> keyValPair : constraints.entrySet()) { if (keyValPair.getKey() == null || keyValPair.getValue() == null) continue; Map<String,String> colValPair = MapUtils.fromPairs( FIELD_PROPERTY, keyValPair.getKey(), FIELD_VALUE, keyValPair.getValue() ); crossRowArgs.add(colValPair); } return new HashSet<Integer>(SQLUtils.crossRowSelect(conn, schemaName, tableName, FIELD_ID, crossRowArgs, caseSensitiveFields)); } catch (SQLException e) { throw new RemoteException("Unable to get ids given a set of property/value pairs.", e); } } }
add index on property field in metadata table
WeaveServices/src/weave/config/tables/MetadataTable.java
add index on property field in metadata table
<ide><path>eaveServices/src/weave/config/tables/MetadataTable.java <ide> <ide> try <ide> { <del>// /* Index of (id) */ <del>// SQLUtils.createIndex( <del>// conn, schemaName, tableName, <del>// tableName+FIELD_ID, <del>// new String[]{FIELD_ID}, <del>// null <del>// ); <add> /* Index of (property) */ <add> SQLUtils.createIndex( <add> conn, schemaName, tableName, <add> tableName+FIELD_PROPERTY, <add> new String[]{FIELD_PROPERTY}, <add> null <add> ); <ide> /* Index of (Property, Value), important for finding ids with metadata criteria */ <ide> SQLUtils.createIndex( <ide> conn, schemaName, tableName,
Java
apache-2.0
04f56df22b6520046039d4e739ed5b5b610cc30d
0
gravitee-io/gravitee-repository-test
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gravitee.repository; import io.gravitee.common.data.domain.Page; import io.gravitee.repository.config.AbstractRepositoryTest; import io.gravitee.repository.management.api.search.EventCriteria; import io.gravitee.repository.management.api.search.builder.PageableBuilder; import io.gravitee.repository.management.model.Event; import io.gravitee.repository.management.model.EventType; import org.junit.Test; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class EventRepositoryTest extends AbstractRepositoryTest { @Override protected String getTestCasesPath() { return "/data/event-tests/"; } @Test public void createEventTest() throws Exception { Event event = new Event(); event.setId(io.gravitee.common.utils.UUID.random().toString()); event.setType(EventType.PUBLISH_API); event.setPayload("{}"); event.setParentId(null); event.setCreatedAt(new Date()); event.setUpdatedAt(event.getCreatedAt()); Event eventCreated = eventRepository.create(event); assertEquals("Invalid saved event type.", EventType.PUBLISH_API, eventCreated.getType()); assertEquals("Invalid saved event payload.", "{}", eventCreated.getPayload()); } @Test public void findByIdTest() throws Exception { Optional<Event> event = eventRepository.findById("event1"); assertTrue("Event not found", event.isPresent()); assertEquals(EventType.PUBLISH_API, event.get().getType()); } @Test public void checkModifiabledMap() throws Exception { Optional<Event> event = eventRepository.findById("event1"); assertTrue("Event not found", event.isPresent()); assertEquals(EventType.PUBLISH_API, event.get().getType()); event.get().getProperties().put("key", "value"); } @Test public void searchNoResults() { Page<Event> eventPage = eventRepository.search( new EventCriteria.Builder().from(1420070400000L).to(1422748800000L) .types(EventType.START_API).build(), new PageableBuilder().pageNumber(0).pageSize(10).build()); assertTrue(0L == eventPage.getTotalElements()); } @Test public void searchBySingleEventType() throws Exception { Page<Event> eventPage = eventRepository.search( new EventCriteria.Builder().from(1451606400000L).to(1470157767000L) .types(EventType.START_API).build(), new PageableBuilder().pageNumber(0).pageSize(10).build()); assertTrue(2L == eventPage.getTotalElements()); Event event = eventPage.getContent().iterator().next(); assertTrue("event6".equals(event.getId())); } @Test public void searchByMultipleEventType() throws Exception { Page<Event> eventPage = eventRepository.search( new EventCriteria.Builder().from(1451606400000L).to(1470157767000L) .types(EventType.START_API, EventType.STOP_API).build(), new PageableBuilder().pageNumber(0).pageSize(10).build()); assertTrue(3L == eventPage.getTotalElements()); Event event = eventPage.getContent().iterator().next(); assertTrue("event6".equals(event.getId())); } @Test public void searchByAPIId() throws Exception { Page<Event> eventPage = eventRepository.search( new EventCriteria.Builder() .from(1451606400000L).to(1470157767000L) .property(Event.EventProperties.API_ID.getValue(), "api-1") .build(), new PageableBuilder().pageNumber(0).pageSize(10).build()); assertTrue(2L == eventPage.getTotalElements()); Event event = eventPage.getContent().iterator().next(); assertTrue("event2".equals(event.getId())); } @Test public void searchByAPI_EmptyPageable() throws Exception { Page<Event> eventPage = eventRepository.search( new EventCriteria.Builder() .from(1451606400000L).to(1470157767000L) .property(Event.EventProperties.API_ID.getValue(), "api-1") .build(), null); assertTrue(2L == eventPage.getTotalElements()); Event event = eventPage.getContent().iterator().next(); assertTrue("event2".equals(event.getId())); } @Test public void searchByMixProperties() throws Exception { Page<Event> eventPage = eventRepository.search( new EventCriteria.Builder() .from(1451606400000L).to(1470157767000L) .property(Event.EventProperties.API_ID.getValue(), "api-3") .types(EventType.START_API, EventType.STOP_API) .build(), new PageableBuilder().pageNumber(0).pageSize(10).build()); assertTrue(1L == eventPage.getTotalElements()); Event event = eventPage.getContent().iterator().next(); assertTrue("event4".equals(event.getId())); } @Test public void searchByCollectionProperty() throws Exception { Page<Event> eventPage = eventRepository.search( new EventCriteria.Builder() .from(1451606400000L).to(1470157767000L) .property(Event.EventProperties.API_ID.getValue(), Arrays.asList("api-1", "api-3")) .build(), null); assertTrue(3L == eventPage.getTotalElements()); Event event = eventPage.getContent().iterator().next(); assertTrue("event4".equals(event.getId())); } @Test public void searchByCollectionPropertyWithoutPaging() throws Exception { List<Event> events = eventRepository.search( new EventCriteria.Builder() .from(1451606400000L).to(1470157767000L) .property(Event.EventProperties.API_ID.getValue(), Arrays.asList("api-1", "api-3")) .build()); assertTrue(3L == events.size()); Event event = events.iterator().next(); assertTrue("event4".equals(event.getId())); } @Test public void searchByCollectionPropertyWithoutPagingAndBoundary() throws Exception { List<Event> events = eventRepository.search( new EventCriteria.Builder() .property(Event.EventProperties.API_ID.getValue(), Arrays.asList("api-1", "api-3")) .build()); assertTrue(3L == events.size()); Event event = events.iterator().next(); assertTrue("event4".equals(event.getId())); } }
src/test/java/io/gravitee/repository/EventRepositoryTest.java
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gravitee.repository; import io.gravitee.common.data.domain.Page; import io.gravitee.repository.config.AbstractRepositoryTest; import io.gravitee.repository.management.api.search.EventCriteria; import io.gravitee.repository.management.api.search.builder.PageableBuilder; import io.gravitee.repository.management.model.Event; import io.gravitee.repository.management.model.EventType; import org.junit.Test; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class EventRepositoryTest extends AbstractRepositoryTest { @Override protected String getTestCasesPath() { return "/data/event-tests/"; } @Test public void createEventTest() throws Exception { Event event = new Event(); event.setId(io.gravitee.common.utils.UUID.random().toString()); event.setType(EventType.PUBLISH_API); event.setPayload("{}"); event.setParentId(null); event.setCreatedAt(new Date()); event.setUpdatedAt(event.getCreatedAt()); Event eventCreated = eventRepository.create(event); assertEquals("Invalid saved event type.", EventType.PUBLISH_API, eventCreated.getType()); assertEquals("Invalid saved event payload.", "{}", eventCreated.getPayload()); } @Test public void findByIdTest() throws Exception { Optional<Event> event = eventRepository.findById("event1"); assertTrue("Event not found", event.isPresent()); assertEquals(EventType.PUBLISH_API, event.get().getType()); } @Test public void searchNoResults() { Page<Event> eventPage = eventRepository.search( new EventCriteria.Builder().from(1420070400000L).to(1422748800000L) .types(EventType.START_API).build(), new PageableBuilder().pageNumber(0).pageSize(10).build()); assertTrue(0L == eventPage.getTotalElements()); } @Test public void searchBySingleEventType() throws Exception { Page<Event> eventPage = eventRepository.search( new EventCriteria.Builder().from(1451606400000L).to(1470157767000L) .types(EventType.START_API).build(), new PageableBuilder().pageNumber(0).pageSize(10).build()); assertTrue(2L == eventPage.getTotalElements()); Event event = eventPage.getContent().iterator().next(); assertTrue("event6".equals(event.getId())); } @Test public void searchByMultipleEventType() throws Exception { Page<Event> eventPage = eventRepository.search( new EventCriteria.Builder().from(1451606400000L).to(1470157767000L) .types(EventType.START_API, EventType.STOP_API).build(), new PageableBuilder().pageNumber(0).pageSize(10).build()); assertTrue(3L == eventPage.getTotalElements()); Event event = eventPage.getContent().iterator().next(); assertTrue("event6".equals(event.getId())); } @Test public void searchByAPIId() throws Exception { Page<Event> eventPage = eventRepository.search( new EventCriteria.Builder() .from(1451606400000L).to(1470157767000L) .property(Event.EventProperties.API_ID.getValue(), "api-1") .build(), new PageableBuilder().pageNumber(0).pageSize(10).build()); assertTrue(2L == eventPage.getTotalElements()); Event event = eventPage.getContent().iterator().next(); assertTrue("event2".equals(event.getId())); } @Test public void searchByAPI_EmptyPageable() throws Exception { Page<Event> eventPage = eventRepository.search( new EventCriteria.Builder() .from(1451606400000L).to(1470157767000L) .property(Event.EventProperties.API_ID.getValue(), "api-1") .build(), null); assertTrue(2L == eventPage.getTotalElements()); Event event = eventPage.getContent().iterator().next(); assertTrue("event2".equals(event.getId())); } @Test public void searchByMixProperties() throws Exception { Page<Event> eventPage = eventRepository.search( new EventCriteria.Builder() .from(1451606400000L).to(1470157767000L) .property(Event.EventProperties.API_ID.getValue(), "api-3") .types(EventType.START_API, EventType.STOP_API) .build(), new PageableBuilder().pageNumber(0).pageSize(10).build()); assertTrue(1L == eventPage.getTotalElements()); Event event = eventPage.getContent().iterator().next(); assertTrue("event4".equals(event.getId())); } @Test public void searchByCollectionProperty() throws Exception { Page<Event> eventPage = eventRepository.search( new EventCriteria.Builder() .from(1451606400000L).to(1470157767000L) .property(Event.EventProperties.API_ID.getValue(), Arrays.asList("api-1", "api-3")) .build(), null); assertTrue(3L == eventPage.getTotalElements()); Event event = eventPage.getContent().iterator().next(); assertTrue("event4".equals(event.getId())); } @Test public void searchByCollectionPropertyWithoutPaging() throws Exception { List<Event> events = eventRepository.search( new EventCriteria.Builder() .from(1451606400000L).to(1470157767000L) .property(Event.EventProperties.API_ID.getValue(), Arrays.asList("api-1", "api-3")) .build()); assertTrue(3L == events.size()); Event event = events.iterator().next(); assertTrue("event4".equals(event.getId())); } @Test public void searchByCollectionPropertyWithoutPagingAndBoundary() throws Exception { List<Event> events = eventRepository.search( new EventCriteria.Builder() .property(Event.EventProperties.API_ID.getValue(), Arrays.asList("api-1", "api-3")) .build()); assertTrue(3L == events.size()); Event event = events.iterator().next(); assertTrue("event4".equals(event.getId())); } }
test: check that properties from Event are modifiable
src/test/java/io/gravitee/repository/EventRepositoryTest.java
test: check that properties from Event are modifiable
<ide><path>rc/test/java/io/gravitee/repository/EventRepositoryTest.java <ide> Optional<Event> event = eventRepository.findById("event1"); <ide> assertTrue("Event not found", event.isPresent()); <ide> assertEquals(EventType.PUBLISH_API, event.get().getType()); <add> } <add> <add> @Test <add> public void checkModifiabledMap() throws Exception { <add> Optional<Event> event = eventRepository.findById("event1"); <add> assertTrue("Event not found", event.isPresent()); <add> assertEquals(EventType.PUBLISH_API, event.get().getType()); <add> <add> event.get().getProperties().put("key", "value"); <ide> } <ide> <ide> @Test
Java
mit
9e00ba118416b154a894f096d01c5a3e8d194f00
0
binaryoverload/FlareBot,weeryan17/FlareBot,FlareBot/FlareBot
package stream.flarebot.flarebot.commands.general; import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.MessageBuilder; import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.TextChannel; import net.dv8tion.jda.core.entities.User; import stream.flarebot.flarebot.FlareBot; import stream.flarebot.flarebot.commands.Command; import stream.flarebot.flarebot.commands.CommandType; import stream.flarebot.flarebot.commands.FlareBotManager; import stream.flarebot.flarebot.util.MessageUtils; import java.awt.*; import java.util.Set; public class SelfAssignCommand implements Command { @Override public void onCommand(User sender, TextChannel channel, Message message, String[] args, Member member) { if (args.length == 0) { MessageUtils.sendUsage(this, channel).queue(); } else if (args.length == 1) { if (args[0].equalsIgnoreCase("add")) { if (FlareBot.getInstance().getPermissions(channel).hasPermission(member, "flarebot.selfassign.admin")) { MessageUtils.sendUsage(this, channel).queue(); } else { MessageUtils.sendAutoDeletedMessage(new EmbedBuilder() .setDescription("You need `flarebot.selfassign.admin` in order to do this!") .setColor(Color.red).build(), 5000, channel); } } else if (args[0].equalsIgnoreCase("remove")) { if (FlareBot.getInstance().getPermissions(channel).hasPermission(member, "flarebot.selfassign.admin")) { MessageUtils.sendUsage(this, channel).queue(); } else { MessageUtils.sendAutoDeletedMessage(new EmbedBuilder() .setDescription("You need `flarebot.selfassign.admin` in order to do this!") .setColor(Color.red).build(), 5000, channel); } } else if (args[0].equalsIgnoreCase("list")) { StringBuilder sb = new StringBuilder(); Set<String> roles = FlareBotManager.getInstance().getSelfAssignRoles(channel.getGuild().getId()); if (roles.isEmpty()) { MessageUtils.sendAutoDeletedMessage(MessageUtils.getEmbed(sender).setColor(Color.RED).setDescription("There are no self-assignable roles!").build(), 10, channel); return; } sb.append("**Self assignable roles**").append("\n```\n"); roles.forEach(role -> sb.append(channel.getGuild().getRoleById(role).getName()).append(" (") .append(role).append(")\n")); sb.append("```"); channel.sendMessage(sb.toString()).queue(); } else { String roleId; try { Long.parseLong(args[0]); roleId = args[0]; } catch (NumberFormatException e) { if (channel.getGuild().getRolesByName(args[0], true).isEmpty()) { MessageUtils.sendErrorMessage("That role does not exist!", channel); return; } else roleId = channel.getGuild().getRolesByName(args[0], true).get(0).getId(); } if (FlareBotManager.getInstance().getSelfAssignRoles(channel.getGuild().getId()).contains(roleId)) { handleRole(member, channel, roleId); } else { MessageUtils.sendErrorMessage("You cannot auto-assign that role! Do `" + getPrefix(channel .getGuild()) + "selfassign list` to see what you can assign to yourself!", channel); } } } else if (args.length == 2) { if (args[0].equalsIgnoreCase("add")) { if (!FlareBot.getInstance().getPermissions(channel) .hasPermission(member, "flarebot.selfassign.admin")) { MessageUtils.sendAutoDeletedMessage(new EmbedBuilder() .setDescription("You need `flarebot.selfassign.admin` in order to do this!") .setColor(Color.red).build(), 5000, channel); return; } String roleId = args[1]; try { Long.parseLong(roleId); } catch (NumberFormatException e) { MessageUtils.sendErrorMessage("Make sure to use the role ID!", channel); return; } if (channel.getGuild().getRoleById(roleId) != null) { FlareBotManager.getInstance().getSelfAssignRoles(channel.getGuild().getId()).add(roleId); channel.sendMessage(new EmbedBuilder() .setDescription("Added `" + channel.getGuild().getRoleById(roleId) .getName() + "` to the self-assign list!").build()) .queue(); } else MessageUtils.sendErrorMessage("That role does not exist!", channel); } else if (args[0].equalsIgnoreCase("remove")) { if (!FlareBot.getInstance().getPermissions(channel) .hasPermission(member, "flarebot.selfassign.admin")) { MessageUtils.sendAutoDeletedMessage(new EmbedBuilder() .setDescription("You need `flarebot.selfassign.admin` in order to do this!") .setColor(Color.red).build(), 5000, channel); return; } String roleId = args[1]; if (channel.getGuild().getRoleById(roleId) != null) { FlareBotManager.getInstance().getSelfAssignRoles(channel.getGuild().getId()).remove(roleId); channel.sendMessage(new EmbedBuilder() .setDescription("Removed `" + channel.getGuild().getRoleById(roleId) .getName() + "` from the self-assign list!").build()) .queue(); } else MessageUtils.sendErrorMessage("That role does not exist!", channel); } else { String roleId; if (channel.getGuild().getRolesByName(MessageUtils.getMessage(args, 0), true).isEmpty()) { MessageUtils.sendErrorMessage("That role does not exist!", channel); return; } else roleId = channel.getGuild().getRolesByName(MessageUtils.getMessage(args, 0), true).get(0).getId(); if (FlareBotManager.getInstance().getSelfAssignRoles(channel.getGuild().getId()).contains(roleId)) { handleRole(member, channel, roleId); } else { MessageUtils.sendErrorMessage("You cannot auto-assign that role! Do `" + getPrefix(channel .getGuild()) + "selfassign list` to see what you can assign to yourself!", channel); } } } else { String roleId; if (channel.getGuild().getRolesByName(MessageUtils.getMessage(args, 0), true).isEmpty()) { MessageUtils.sendErrorMessage("That role does not exist!", channel); return; } else roleId = channel.getGuild().getRolesByName(MessageUtils.getMessage(args, 0), true).get(0).getId(); if (FlareBotManager.getInstance().getSelfAssignRoles(channel.getGuild().getId()).contains(roleId)) { handleRole(member, channel, roleId); } else { MessageUtils.sendErrorMessage("You cannot auto-assign that role! Do `" + getPrefix(channel .getGuild()) + "selfassign list` to see what you can assign to yourself!", channel); } } } private void handleRole(Member member, TextChannel channel, String roleId) { if (!member.getRoles().contains(channel.getGuild().getRoleById(roleId))) { channel.getGuild().getController().addRolesToMember(member, channel.getGuild().getRoleById(roleId)).queue(); MessageUtils.sendAutoDeletedMessage(new MessageBuilder().append(member.getAsMention()) .setEmbed(new EmbedBuilder() .setDescription("You have been assigned `" + channel .getGuild() .getRoleById(roleId) .getName() + "` to yourself!") .setColor(Color.green).build()) .build(), 30_000, channel); } else { channel.getGuild().getController().removeRolesFromMember(member, channel.getGuild().getRoleById(roleId)) .queue(); MessageUtils.sendAutoDeletedMessage(new MessageBuilder().append(member.getAsMention()) .setEmbed(new EmbedBuilder() .setDescription("You have removed the role `" + channel .getGuild() .getRoleById(roleId) .getName() + "` from yourself!") .setColor(Color.orange).build()) .build(), 30_000, channel); } } @Override public String getCommand() { return "selfassign"; } @Override public String getDescription() { return "Self assign a role to yourself!\nTo add roles to selfassign do `selfassign add (userId)`"; } @Override public String getUsage() { return "`{%}selfassign <roleID/name>` - Adds a role to yourself\n" + "`{%}selfassign <add/remove> <roleID/name>` - Allows admins to add roles to the self assign list\n" + "`{%}selfassign list` - Lists roles that are self-assignable"; } @Override public CommandType getType() { return CommandType.GENERAL; } }
src/main/java/stream/flarebot/flarebot/commands/general/SelfAssignCommand.java
package stream.flarebot.flarebot.commands.general; import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.MessageBuilder; import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.TextChannel; import net.dv8tion.jda.core.entities.User; import stream.flarebot.flarebot.FlareBot; import stream.flarebot.flarebot.commands.Command; import stream.flarebot.flarebot.commands.CommandType; import stream.flarebot.flarebot.commands.FlareBotManager; import stream.flarebot.flarebot.util.MessageUtils; import java.awt.*; public class SelfAssignCommand implements Command { @Override public void onCommand(User sender, TextChannel channel, Message message, String[] args, Member member) { if (args.length == 0) { MessageUtils.sendUsage(this, channel).queue(); } else if (args.length == 1) { if (args[0].equalsIgnoreCase("add")) { if (FlareBot.getInstance().getPermissions(channel).hasPermission(member, "flarebot.selfassign.admin")) { MessageUtils.sendUsage(this, channel).queue(); } else { MessageUtils.sendAutoDeletedMessage(new EmbedBuilder() .setDescription("You need `flarebot.selfassign.admin` in order to do this!") .setColor(Color.red).build(), 5000, channel); } } else if (args[0].equalsIgnoreCase("remove")) { if (FlareBot.getInstance().getPermissions(channel).hasPermission(member, "flarebot.selfassign.admin")) { MessageUtils.sendUsage(this, channel).queue(); } else { MessageUtils.sendAutoDeletedMessage(new EmbedBuilder() .setDescription("You need `flarebot.selfassign.admin` in order to do this!") .setColor(Color.red).build(), 5000, channel); } } else if (args[0].equalsIgnoreCase("list")) { StringBuilder sb = new StringBuilder(); sb.append("**Self assignable roles**").append("\n```\n"); FlareBotManager.getInstance().getSelfAssignRoles(channel.getGuild().getId()) .forEach(role -> sb.append(channel.getGuild().getRoleById(role).getName()).append(" (") .append(role).append(")\n")); sb.append("```"); channel.sendMessage(sb.toString()).queue(); } else { String roleId; try { Long.parseLong(args[0]); roleId = args[0]; } catch (NumberFormatException e) { if (channel.getGuild().getRolesByName(args[0], true).isEmpty()) { MessageUtils.sendErrorMessage("That role does not exist!", channel); return; } else roleId = channel.getGuild().getRolesByName(args[0], true).get(0).getId(); } if (FlareBotManager.getInstance().getSelfAssignRoles(channel.getGuild().getId()).contains(roleId)) { handleRole(member, channel, roleId); } else { MessageUtils.sendErrorMessage("You cannot auto-assign that role! Do `" + getPrefix(channel .getGuild()) + "selfassign list` to see what you can assign to yourself!", channel); } } } else if (args.length == 2) { if (args[0].equalsIgnoreCase("add")) { if (!FlareBot.getInstance().getPermissions(channel) .hasPermission(member, "flarebot.selfassign.admin")) { MessageUtils.sendAutoDeletedMessage(new EmbedBuilder() .setDescription("You need `flarebot.selfassign.admin` in order to do this!") .setColor(Color.red).build(), 5000, channel); return; } String roleId = args[1]; try { Long.parseLong(roleId); } catch (NumberFormatException e) { MessageUtils.sendErrorMessage("Make sure to use the role ID!", channel); return; } if (channel.getGuild().getRoleById(roleId) != null) { FlareBotManager.getInstance().getSelfAssignRoles(channel.getGuild().getId()).add(roleId); channel.sendMessage(new EmbedBuilder() .setDescription("Added `" + channel.getGuild().getRoleById(roleId) .getName() + "` to the self-assign list!").build()) .queue(); } else MessageUtils.sendErrorMessage("That role does not exist!", channel); } else if (args[0].equalsIgnoreCase("remove")) { if (!FlareBot.getInstance().getPermissions(channel) .hasPermission(member, "flarebot.selfassign.admin")) { MessageUtils.sendAutoDeletedMessage(new EmbedBuilder() .setDescription("You need `flarebot.selfassign.admin` in order to do this!") .setColor(Color.red).build(), 5000, channel); return; } String roleId = args[1]; if (channel.getGuild().getRoleById(roleId) != null) { FlareBotManager.getInstance().getSelfAssignRoles(channel.getGuild().getId()).remove(roleId); channel.sendMessage(new EmbedBuilder() .setDescription("Removed `" + channel.getGuild().getRoleById(roleId) .getName() + "` from the self-assign list!").build()) .queue(); } else MessageUtils.sendErrorMessage("That role does not exist!", channel); } else { String roleId; if (channel.getGuild().getRolesByName(MessageUtils.getMessage(args, 0), true).isEmpty()) { MessageUtils.sendErrorMessage("That role does not exist!", channel); return; } else roleId = channel.getGuild().getRolesByName(MessageUtils.getMessage(args, 0), true).get(0).getId(); if (FlareBotManager.getInstance().getSelfAssignRoles(channel.getGuild().getId()).contains(roleId)) { handleRole(member, channel, roleId); } else { MessageUtils.sendErrorMessage("You cannot auto-assign that role! Do `" + getPrefix(channel .getGuild()) + "selfassign list` to see what you can assign to yourself!", channel); } } } else { String roleId; if (channel.getGuild().getRolesByName(MessageUtils.getMessage(args, 0), true).isEmpty()) { MessageUtils.sendErrorMessage("That role does not exist!", channel); return; } else roleId = channel.getGuild().getRolesByName(MessageUtils.getMessage(args, 0), true).get(0).getId(); if (FlareBotManager.getInstance().getSelfAssignRoles(channel.getGuild().getId()).contains(roleId)) { handleRole(member, channel, roleId); } else { MessageUtils.sendErrorMessage("You cannot auto-assign that role! Do `" + getPrefix(channel .getGuild()) + "selfassign list` to see what you can assign to yourself!", channel); } } } private void handleRole(Member member, TextChannel channel, String roleId) { if (!member.getRoles().contains(channel.getGuild().getRoleById(roleId))) { channel.getGuild().getController().addRolesToMember(member, channel.getGuild().getRoleById(roleId)).queue(); MessageUtils.sendAutoDeletedMessage(new MessageBuilder().append(member.getAsMention()) .setEmbed(new EmbedBuilder() .setDescription("You have been assigned `" + channel .getGuild() .getRoleById(roleId) .getName() + "` to yourself!") .setColor(Color.green).build()) .build(), 30_000, channel); } else { channel.getGuild().getController().removeRolesFromMember(member, channel.getGuild().getRoleById(roleId)) .queue(); MessageUtils.sendAutoDeletedMessage(new MessageBuilder().append(member.getAsMention()) .setEmbed(new EmbedBuilder() .setDescription("You have removed the role `" + channel .getGuild() .getRoleById(roleId) .getName() + "` from yourself!") .setColor(Color.orange).build()) .build(), 30_000, channel); } } @Override public String getCommand() { return "selfassign"; } @Override public String getDescription() { return "Self assign a role to yourself!\nTo add roles to selfassign do `selfassign add (userId)`"; } @Override public String getUsage() { return "`{%}selfassign <roleID/name>` - Adds a role to yourself\n" + "`{%}selfassign <add/remove> <roleID/name>` - Allows admins to add roles to the self assign list\n" + "`{%}selfassign list` - Lists roles that are self-assignable"; } @Override public CommandType getType() { return CommandType.GENERAL; } }
Make self assign more user friendly
src/main/java/stream/flarebot/flarebot/commands/general/SelfAssignCommand.java
Make self assign more user friendly
<ide><path>rc/main/java/stream/flarebot/flarebot/commands/general/SelfAssignCommand.java <ide> import stream.flarebot.flarebot.util.MessageUtils; <ide> <ide> import java.awt.*; <add>import java.util.Set; <ide> <ide> public class SelfAssignCommand implements Command { <ide> <ide> } <ide> } else if (args[0].equalsIgnoreCase("list")) { <ide> StringBuilder sb = new StringBuilder(); <add> Set<String> roles = FlareBotManager.getInstance().getSelfAssignRoles(channel.getGuild().getId()); <add> if (roles.isEmpty()) { <add> MessageUtils.sendAutoDeletedMessage(MessageUtils.getEmbed(sender).setColor(Color.RED).setDescription("There are no self-assignable roles!").build(), 10, channel); <add> return; <add> } <ide> sb.append("**Self assignable roles**").append("\n```\n"); <del> FlareBotManager.getInstance().getSelfAssignRoles(channel.getGuild().getId()) <del> .forEach(role -> sb.append(channel.getGuild().getRoleById(role).getName()).append(" (") <del> .append(role).append(")\n")); <add> roles.forEach(role -> sb.append(channel.getGuild().getRoleById(role).getName()).append(" (") <add> .append(role).append(")\n")); <ide> sb.append("```"); <ide> channel.sendMessage(sb.toString()).queue(); <ide> } else {
Java
apache-2.0
b4ed175656b0bab1e6a6c297956bf043c43e9259
0
PramodSSImmaneni/Netlet,243826/Netlet,Celeral/Netlet,DataTorrent/Netlet,ilooner/Netlet,vrozov/Netlet
/* * Copyright (c) 2012 Malhar, Inc. * All Rights Reserved. */ package com.malhartech.util; /** * * @author Chetan Narsude <[email protected]> */ import static java.lang.Thread.sleep; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provides a premium implementation of circular buffer<p> * <br> * * @param <T> type of the objects in this buffer. */ public class CircularBuffer<T> implements UnsafeBlockingQueue<T> { private final T[] buffer; private final int buffermask; private final int spinMillis; protected volatile long tail; protected volatile long head; /** * * Constructing a circular buffer of 'n' integers<p> * <br> * * @param n size of the buffer to be constructed * @param spin time in milliseconds for which to wait before checking for expected value if it's missing * <br> */ @SuppressWarnings("unchecked") public CircularBuffer(int n, int spin) { int i = 1; while (i < n) { i <<= 1; } buffer = (T[])new Object[i]; buffermask = i - 1; spinMillis = spin; } private CircularBuffer(T[] buffer, int buffermask, int spinMillis) { this.buffer = buffer; this.buffermask = buffermask; this.spinMillis = spinMillis; } /** * * Constructing a circular buffer of 'n' integers<p> * <br> * * @param n size of the buffer to be constructed * <br> */ public CircularBuffer(int n) { this(n, 10); } @Override public boolean add(T e) { if (head - tail <= buffermask) { buffer[(int)(head & buffermask)] = e; head++; return true; } throw new IllegalStateException("Collection is full"); } @Override public T remove() { if (head > tail) { int pos = (int)(tail & buffermask); T t = buffer[pos]; buffer[pos] = null; tail++; return t; } throw new IllegalStateException("Collection is empty"); } @Override public T peek() { if (head > tail) { return buffer[(int)(tail & buffermask)]; } return null; } @Override public int size() { return (int)(head - tail); } /** * * Total design capacity of the buffer<p> * <br> * * @return Total return capacity of the buffer * <br> */ public int capacity() { return buffermask + 1; } @Override public int drainTo(Collection<? super T> container) { int size = size(); while (head > tail) { container.add(buffer[(int)(tail & buffermask)]); tail++; } return size; } @Override public String toString() { return "head=" + head + ", tail=" + tail + ", capacity=" + (buffermask + 1); } @Override public boolean offer(T e) { if (head - tail <= buffermask) { buffer[(int)(head & buffermask)] = e; head++; return true; } return false; } @Override @SuppressWarnings("SleepWhileInLoop") public void put(T e) throws InterruptedException { do { if (head - tail < buffermask) { buffer[(int)(head & buffermask)] = e; head++; return; } Thread.sleep(spinMillis); } while (true); } @Override @SuppressWarnings("SleepWhileInLoop") public boolean offer(T e, long timeout, TimeUnit unit) throws InterruptedException { long millis = unit.toMillis(timeout); do { if (head - tail < buffermask) { buffer[(int)(head & buffermask)] = e; head++; return true; } Thread.sleep(spinMillis); } while ((millis -= spinMillis) >= 0); return false; } @Override @SuppressWarnings("SleepWhileInLoop") public T take() throws InterruptedException { do { if (head > tail) { int pos = (int)(tail & buffermask); T t = buffer[pos]; buffer[pos] = null; tail++; return t; } Thread.sleep(spinMillis); } while (true); } @Override @SuppressWarnings("SleepWhileInLoop") public T poll(long timeout, TimeUnit unit) throws InterruptedException { long millis = unit.toMillis(timeout); do { if (head > tail) { int pos = (int)(tail & buffermask); T t = buffer[pos]; buffer[pos] = null; tail++; return t; } Thread.sleep(spinMillis); } while ((millis -= spinMillis) >= 0); return null; } @Override public int remainingCapacity() { return buffermask + 1 - (int)(head - tail); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean contains(Object o) { throw new UnsupportedOperationException("Not supported yet."); } @Override public int drainTo(final Collection<? super T> collection, final int maxElements) { int i = -1; int pos; while (i++ < maxElements && head > tail) { pos = (int)(tail & buffermask); collection.add(buffer[pos]); buffer[pos] = null; tail++; } return i; } @Override public T poll() { if (head > tail) { int pos = (int)(tail & buffermask); T t = buffer[pos]; buffer[pos] = null; tail++; return t; } return null; } @Override public T pollUnsafe() { int pos = (int)(tail & buffermask); T t = buffer[pos]; buffer[pos] = null; tail++; return t; } @Override public T element() { if (head > tail) { return buffer[(int)(tail & buffermask)]; } throw new IllegalStateException("Collection is empty"); } @Override public boolean isEmpty() { return head == tail; } public Iterator<T> getFrozenIterator() { return new Iterator<T>() { private final long head = CircularBuffer.this.head; private long tail = CircularBuffer.this.tail; @Override public boolean hasNext() { return tail < head; } @Override public T next() { return buffer[(int)(tail++ & buffermask)]; } @Override public void remove() { buffer[(int)((tail - 1) & buffermask)] = null; } }; } @Override public Iterator<T> iterator() { return new Iterator<T>() { @Override public boolean hasNext() { return head > tail; } @Override public T next() { int pos = (int)(tail & buffermask); T t = buffer[pos]; buffer[pos] = null; tail++; return t; } @Override public void remove() { } }; } @Override public Object[] toArray() { final int count = (int)(head - tail); Object[] array = new Object[count]; int pos; for (int i = 0; i < count; i++) { pos = (int)(tail & buffermask); array[i] = buffer[pos]; buffer[pos] = null; tail++; } return array; } @Override @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { int count = (int)(head - tail); if (a.length < count) { a = (T[])new Object[count]; } int pos; for (int i = 0; i < count; i++) { pos = (int)(tail & buffermask); a[i] = (T)buffer[pos]; buffer[pos] = null; tail++; } return a; } @Override public boolean containsAll(Collection<?> c) { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean addAll(Collection<? extends T> c) { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void clear() { head = 0; tail = 0; Arrays.fill(buffer, null); } @Override public T peekUnsafe() { return buffer[(int)(tail & buffermask)]; } public CircularBuffer<T> getWhitehole(final String exceptionMessage) { CircularBuffer<T> cb = new CircularBuffer<T>(buffer, buffermask, spinMillis) { @Override public boolean add(T e) { throw new IllegalStateException(exceptionMessage); } @Override @SuppressWarnings("SleepWhileInLoop") public void put(T e) throws InterruptedException { while (true) { sleep(spinMillis); } } @Override public boolean offer(T e) { return false; } @Override public boolean offer(T e, long timeout, TimeUnit unit) throws InterruptedException { long millis = unit.toMillis(timeout); sleep(millis); return false; } @Override public int remainingCapacity() { return 0; } @Override public boolean addAll(Collection<? extends T> c) { throw new IllegalStateException(exceptionMessage); } }; cb.head = head; cb.tail = tail; return cb; } private static final Logger logger = LoggerFactory.getLogger(CircularBuffer.class); }
src/main/java/com/malhartech/util/CircularBuffer.java
/* * Copyright (c) 2012 Malhar, Inc. * All Rights Reserved. */ package com.malhartech.util; /** * * @author Chetan Narsude <[email protected]> */ import static java.lang.Thread.sleep; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provides a premium implementation of circular buffer<p> * <br> * * @param <T> type of the objects in this buffer. */ public class CircularBuffer<T> implements UnsafeBlockingQueue<T> { private final T[] buffer; private final int buffermask; private final int spinMillis; protected volatile long tail; protected volatile long head; /** * * Constructing a circular buffer of 'n' integers<p> * <br> * * @param n size of the buffer to be constructed * @param spin time in milliseconds for which to wait before checking for expected value if it's missing * <br> */ @SuppressWarnings("unchecked") public CircularBuffer(int n, int spin) { int i = 1; while (i < n) { i <<= 1; } buffer = (T[])new Object[i]; buffermask = i - 1; spinMillis = spin; } private CircularBuffer(T[] buffer, int buffermask, int spinMillis) { this.buffer = buffer; this.buffermask = buffermask; this.spinMillis = spinMillis; } /** * * Constructing a circular buffer of 'n' integers<p> * <br> * * @param n size of the buffer to be constructed * <br> */ public CircularBuffer(int n) { this(n, 10); } @Override public boolean add(T e) { if (head - tail <= buffermask) { buffer[(int)(head & buffermask)] = e; head++; return true; } throw new IllegalStateException("Collection is full"); } @Override public T remove() { if (head > tail) { T t = buffer[(int)(tail & buffermask)]; tail++; return t; } throw new IllegalStateException("Collection is empty"); } @Override public T peek() { if (head > tail) { return buffer[(int)(tail & buffermask)]; } return null; } @Override public int size() { return (int)(head - tail); } /** * * Total design capacity of the buffer<p> * <br> * * @return Total return capacity of the buffer * <br> */ public int capacity() { return buffermask + 1; } @Override public int drainTo(Collection<? super T> container) { int size = size(); while (head > tail) { container.add(buffer[(int)(tail & buffermask)]); tail++; } return size; } @Override public String toString() { return "head=" + head + ", tail=" + tail + ", capacity=" + (buffermask + 1); } @Override public boolean offer(T e) { if (head - tail <= buffermask) { buffer[(int)(head & buffermask)] = e; head++; return true; } return false; } @Override @SuppressWarnings("SleepWhileInLoop") public void put(T e) throws InterruptedException { do { if (head - tail < buffermask) { buffer[(int)(head & buffermask)] = e; head++; return; } Thread.sleep(spinMillis); } while (true); } @Override @SuppressWarnings("SleepWhileInLoop") public boolean offer(T e, long timeout, TimeUnit unit) throws InterruptedException { long millis = unit.toMillis(timeout); do { if (head - tail < buffermask) { buffer[(int)(head & buffermask)] = e; head++; return true; } Thread.sleep(spinMillis); } while ((millis -= spinMillis) >= 0); return false; } @Override @SuppressWarnings("SleepWhileInLoop") public T take() throws InterruptedException { do { if (head > tail) { T t = buffer[(int)(tail & buffermask)]; tail++; return t; } Thread.sleep(spinMillis); } while (true); } @Override @SuppressWarnings("SleepWhileInLoop") public T poll(long timeout, TimeUnit unit) throws InterruptedException { long millis = unit.toMillis(timeout); do { if (head > tail) { T t = buffer[(int)(tail & buffermask)]; tail++; return t; } Thread.sleep(spinMillis); } while ((millis -= spinMillis) >= 0); return null; } @Override public int remainingCapacity() { return buffermask + 1 - (int)(head - tail); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean contains(Object o) { throw new UnsupportedOperationException("Not supported yet."); } @Override public int drainTo(final Collection<? super T> collection, final int maxElements) { int i = -1; while (i++ < maxElements && head > tail) { collection.add(buffer[(int)(tail & buffermask)]); tail++; } return i; } @Override public T poll() { if (head > tail) { T t = buffer[(int)(tail & buffermask)]; tail++; return t; } return null; } @Override public T pollUnsafe() { T t = buffer[(int)(tail & buffermask)]; tail++; return t; } @Override public T element() { if (head > tail) { return buffer[(int)(tail & buffermask)]; } throw new IllegalStateException("Collection is empty"); } @Override public boolean isEmpty() { return head == tail; } public Iterator<T> getFrozenIterator() { return new Iterator<T>() { private final long head = CircularBuffer.this.head; private long tail = CircularBuffer.this.tail; @Override public boolean hasNext() { return tail < head; } @Override public T next() { return buffer[(int)(tail++ & buffermask)]; } @Override public void remove() { buffer[(int)((tail - 1) & buffermask)] = null; } }; } @Override public Iterator<T> iterator() { return new Iterator<T>() { @Override public boolean hasNext() { return head > tail; } @Override public T next() { T t = buffer[(int)(tail & buffermask)]; tail++; return t; } @Override public void remove() { } }; } @Override public Object[] toArray() { final int count = (int)(head - tail); Object[] array = new Object[count]; for (int i = 0; i < count; i++) { array[i] = buffer[(int)(tail & buffermask)]; tail++; } return array; } @Override @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { int count = (int)(head - tail); if (a.length < count) { a = (T[])new Object[count]; } for (int i = 0; i < count; i++) { a[i] = (T)buffer[(int)(tail & buffermask)]; tail++; } return a; } @Override public boolean containsAll(Collection<?> c) { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean addAll(Collection<? extends T> c) { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void clear() { head = 0; tail = 0; Arrays.fill(buffer, null); } @Override public T peekUnsafe() { return buffer[(int)(tail & buffermask)]; } public CircularBuffer<T> getWhitehole(final String exceptionMessage) { CircularBuffer<T> cb = new CircularBuffer<T>(buffer, buffermask, spinMillis) { @Override public boolean add(T e) { throw new IllegalStateException(exceptionMessage); } @Override @SuppressWarnings("SleepWhileInLoop") public void put(T e) throws InterruptedException { while (true) { sleep(spinMillis); } } @Override public boolean offer(T e) { return false; } @Override public boolean offer(T e, long timeout, TimeUnit unit) throws InterruptedException { long millis = unit.toMillis(timeout); sleep(millis); return false; } @Override public int remainingCapacity() { return 0; } @Override public boolean addAll(Collection<? extends T> c) { throw new IllegalStateException(exceptionMessage); } }; cb.head = head; cb.tail = tail; return cb; } private static final Logger logger = LoggerFactory.getLogger(CircularBuffer.class); }
clear references after items are consumed so GC can do its work
src/main/java/com/malhartech/util/CircularBuffer.java
clear references after items are consumed so GC can do its work
<ide><path>rc/main/java/com/malhartech/util/CircularBuffer.java <ide> public T remove() <ide> { <ide> if (head > tail) { <del> T t = buffer[(int)(tail & buffermask)]; <add> int pos = (int)(tail & buffermask); <add> T t = buffer[pos]; <add> buffer[pos] = null; <ide> tail++; <ide> return t; <ide> } <ide> { <ide> do { <ide> if (head > tail) { <del> T t = buffer[(int)(tail & buffermask)]; <add> int pos = (int)(tail & buffermask); <add> T t = buffer[pos]; <add> buffer[pos] = null; <ide> tail++; <ide> return t; <ide> } <ide> long millis = unit.toMillis(timeout); <ide> do { <ide> if (head > tail) { <del> T t = buffer[(int)(tail & buffermask)]; <add> int pos = (int)(tail & buffermask); <add> T t = buffer[pos]; <add> buffer[pos] = null; <ide> tail++; <ide> return t; <ide> } <ide> public int drainTo(final Collection<? super T> collection, final int maxElements) <ide> { <ide> int i = -1; <add> int pos; <ide> while (i++ < maxElements && head > tail) { <del> collection.add(buffer[(int)(tail & buffermask)]); <add> pos = (int)(tail & buffermask); <add> collection.add(buffer[pos]); <add> buffer[pos] = null; <ide> tail++; <ide> } <ide> <ide> public T poll() <ide> { <ide> if (head > tail) { <del> T t = buffer[(int)(tail & buffermask)]; <add> int pos = (int)(tail & buffermask); <add> T t = buffer[pos]; <add> buffer[pos] = null; <ide> tail++; <ide> return t; <ide> } <ide> @Override <ide> public T pollUnsafe() <ide> { <del> T t = buffer[(int)(tail & buffermask)]; <add> int pos = (int)(tail & buffermask); <add> T t = buffer[pos]; <add> buffer[pos] = null; <ide> tail++; <ide> return t; <ide> } <ide> @Override <ide> public T next() <ide> { <del> T t = buffer[(int)(tail & buffermask)]; <add> int pos = (int)(tail & buffermask); <add> T t = buffer[pos]; <add> buffer[pos] = null; <ide> tail++; <ide> return t; <ide> } <ide> { <ide> final int count = (int)(head - tail); <ide> Object[] array = new Object[count]; <add> int pos; <ide> for (int i = 0; i < count; i++) { <del> array[i] = buffer[(int)(tail & buffermask)]; <add> pos = (int)(tail & buffermask); <add> array[i] = buffer[pos]; <add> buffer[pos] = null; <ide> tail++; <ide> } <ide> <ide> a = (T[])new Object[count]; <ide> } <ide> <add> int pos; <ide> for (int i = 0; i < count; i++) { <del> a[i] = (T)buffer[(int)(tail & buffermask)]; <add> pos = (int)(tail & buffermask); <add> a[i] = (T)buffer[pos]; <add> buffer[pos] = null; <ide> tail++; <ide> } <ide>
Java
bsd-3-clause
ecf1f5f8710e8dd11111730be0d4a1311430303c
0
ndexbio/ndex-common
package org.ndexbio.common.query; import org.ndexbio.common.NdexClasses; import org.ndexbio.common.models.dao.orientdb.Helper; import org.ndexbio.common.models.dao.orientdb.NetworkDocDAO; import org.ndexbio.common.query.filter.orientdb.EdgeByEdgePropertyFilterODB; import org.ndexbio.common.query.filter.orientdb.EdgeByNodePropertyFilterODB; import org.ndexbio.common.query.filter.orientdb.EdgeCollectionQueryODB; import org.ndexbio.model.exceptions.NdexException; import org.ndexbio.model.network.query.EdgeByEdgePropertyFilter; import org.ndexbio.model.network.query.EdgeByNodePropertyFilter; import org.ndexbio.model.network.query.EdgeCollectionQuery; import org.ndexbio.model.network.query.PropertySpecification; import com.orientechnologies.orient.core.record.impl.ODocument; public class NetworkFilterQueryExecutorFactory { private static final String edgePredicatePropertyName = "ndex:predicate"; private static final String nodePropertyFunctionTermType = "ndex:functionTermType"; private static final String nodePropertyNameORTerm = "ndex:nameOrTermName"; private static final String nodePropertyNodeName = "ndex:nodeName"; public static NetworkFilterQueryExecutor createODBExecutor(String networkIdStr, EdgeCollectionQuery query) throws NdexException { // check if the query is valid if ( query.getEdgeFilter() == null || query.getEdgeFilter().getPropertySpecifications().size() == 0) { if ( query.getNodeFilter() == null || query.getNodeFilter().getPropertySpecifications().size() == 0 ) { //error throw new NdexException ("Invalid query object received. Both filters are empty."); } } //TODO: optimize the case that when filter compiled to an empty list. Should just return empty collection without iteration. EdgeCollectionQueryODB edgeQuery = new EdgeCollectionQueryODB(); edgeQuery.setQueryName(query.getQueryName()); edgeQuery.setEdgeLimit(query.getEdgeLimit()); try ( NetworkDocDAO networkDao = new NetworkDocDAO()) { ODocument networkDoc = networkDao.getNetworkDocByUUIDString(networkIdStr); EdgeByEdgePropertyFilterODB edgeFilter = preprocessEdgeByEdgePropertyFilter( query.getEdgeFilter(), networkDoc) ; EdgeByNodePropertyFilterODB nodeFilter = preprocessEdgeByNodePropertyFilter( query.getNodeFilter(), networkDoc); edgeQuery.setEdgeFilter(edgeFilter); edgeQuery.setNodeFilter(nodeFilter); NetworkFilterQueryExecutor executor = new NetworkFilterQueryExecutor(networkIdStr, edgeQuery); return executor; } } private static EdgeByEdgePropertyFilterODB preprocessEdgeByEdgePropertyFilter( EdgeByEdgePropertyFilter filter, ODocument networkDoc) { if ( filter == null) return null; EdgeByEdgePropertyFilterODB odbFilter = new EdgeByEdgePropertyFilterODB(); for ( PropertySpecification spec : filter.getPropertySpecifications()) { String value = spec.getValue(); String propName = spec.getName(); if ( propName.equalsIgnoreCase(edgePredicatePropertyName) ) { Iterable<ODocument> bTerms = Helper.getNetworkElements(networkDoc, NdexClasses.Network_E_BaseTerms); if ( bTerms !=null) { for ( ODocument d : bTerms) { String name = d.field(NdexClasses.BTerm_P_name); if ( name !=null && name.equalsIgnoreCase(value)) { odbFilter.addPredicateId(d.getIdentity().toString()); } } } } else { for ( ODocument baseTermDoc : Helper.getNetworkElements(networkDoc, NdexClasses.Network_E_BaseTerms)) { String name = baseTermDoc.field(NdexClasses.BTerm_P_name); if ( name !=null && name.equalsIgnoreCase(propName)) { for ( ODocument prop : Helper.getDocumentLinks(baseTermDoc, "in_", NdexClasses.ndexProp_E_predicate)) { String v = prop.field(NdexClasses.ndexProp_P_value); if ( v.equalsIgnoreCase(value)) { odbFilter.addPropertyId(prop.getIdentity().toString()); } } } } } } return odbFilter; } private static EdgeByNodePropertyFilterODB preprocessEdgeByNodePropertyFilter( EdgeByNodePropertyFilter filter, ODocument networkDoc) { if ( filter == null) return null; EdgeByNodePropertyFilterODB odbFilter = new EdgeByNodePropertyFilterODB(); odbFilter.setMode(filter.getMode()); for (PropertySpecification spec: filter.getPropertySpecifications()) { String value = spec.getValue(); String propName = spec.getName(); if ( propName.equalsIgnoreCase(nodePropertyNodeName) ) { odbFilter.addNodeName(value); } else if (propName.equalsIgnoreCase(nodePropertyNameORTerm)) { odbFilter.addNodeName(value); for ( ODocument d : Helper.getNetworkElements(networkDoc, NdexClasses.Network_E_BaseTerms)) { String name = d.field(NdexClasses.BTerm_P_name); if ( name !=null && name.equalsIgnoreCase(value)) { odbFilter.addRepresentTermID(d.getIdentity().toString()); } } } else if (propName.equalsIgnoreCase(nodePropertyFunctionTermType)) { for ( ODocument funcTermDoc : Helper.getNetworkElements(networkDoc, NdexClasses.Network_E_FunctionTerms)) { ODocument fBTerm = funcTermDoc.field("out_"+NdexClasses.FunctionTerm_E_baseTerm); String name = fBTerm.field(NdexClasses.BTerm_P_name); if ( name !=null && name.equalsIgnoreCase(value)) { odbFilter.addRepresentTermID(funcTermDoc.getIdentity().toString()); } } } else { // normal property for ( ODocument baseTermDoc : Helper.getNetworkElements(networkDoc, NdexClasses.Network_E_BaseTerms)) { String name = baseTermDoc.field(NdexClasses.BTerm_P_name); if ( name !=null && name.equalsIgnoreCase(propName)) { for ( ODocument prop : Helper.getDocumentLinks(baseTermDoc, "in_", NdexClasses.ndexProp_E_predicate)) { String v = prop.field(NdexClasses.ndexProp_P_value); if ( v.equalsIgnoreCase(value)) { odbFilter.addPropertyId(prop.getIdentity().toString()); } } } } } } return odbFilter; } }
src/main/java/org/ndexbio/common/query/NetworkFilterQueryExecutorFactory.java
package org.ndexbio.common.query; import org.ndexbio.common.NdexClasses; import org.ndexbio.common.models.dao.orientdb.Helper; import org.ndexbio.common.models.dao.orientdb.NetworkDocDAO; import org.ndexbio.common.query.filter.orientdb.EdgeByEdgePropertyFilterODB; import org.ndexbio.common.query.filter.orientdb.EdgeByNodePropertyFilterODB; import org.ndexbio.common.query.filter.orientdb.EdgeCollectionQueryODB; import org.ndexbio.model.exceptions.NdexException; import org.ndexbio.model.network.query.EdgeByEdgePropertyFilter; import org.ndexbio.model.network.query.EdgeByNodePropertyFilter; import org.ndexbio.model.network.query.EdgeCollectionQuery; import org.ndexbio.model.network.query.PropertySpecification; import com.orientechnologies.orient.core.record.impl.ODocument; public class NetworkFilterQueryExecutorFactory { private static final String edgePredicatePropertyName = "ndex:predicate"; private static final String nodePropertyFunctionTermType = "ndex:functionTermType"; private static final String nodePropertyNameORTerm = "ndex:nameOrTermName"; private static final String nodePropertyNodeName = "ndex:nodeName"; public static NetworkFilterQueryExecutor createODBExecutor(String networkIdStr, EdgeCollectionQuery query) throws NdexException { EdgeCollectionQueryODB edgeQuery = new EdgeCollectionQueryODB(); edgeQuery.setQueryName(query.getQueryName()); edgeQuery.setEdgeLimit(query.getEdgeLimit()); try ( NetworkDocDAO networkDao = new NetworkDocDAO()) { ODocument networkDoc = networkDao.getNetworkDocByUUIDString(networkIdStr); EdgeByEdgePropertyFilterODB edgeFilter = preprocessEdgeByEdgePropertyFilter( query.getEdgeFilter(), networkDoc) ; EdgeByNodePropertyFilterODB nodeFilter = preprocessEdgeByNodePropertyFilter( query.getNodeFilter(), networkDoc); edgeQuery.setEdgeFilter(edgeFilter); edgeQuery.setNodeFilter(nodeFilter); NetworkFilterQueryExecutor executor = new NetworkFilterQueryExecutor(networkIdStr, edgeQuery); return executor; } } private static EdgeByEdgePropertyFilterODB preprocessEdgeByEdgePropertyFilter( EdgeByEdgePropertyFilter filter, ODocument networkDoc) { if ( filter == null) return null; EdgeByEdgePropertyFilterODB odbFilter = new EdgeByEdgePropertyFilterODB(); for ( PropertySpecification spec : filter.getPropertySpecList()) { String value = spec.getValue(); String propName = spec.getName(); if ( propName.equalsIgnoreCase(edgePredicatePropertyName) ) { Iterable<ODocument> bTerms = Helper.getNetworkElements(networkDoc, NdexClasses.Network_E_BaseTerms); if ( bTerms !=null) { for ( ODocument d : bTerms) { String name = d.field(NdexClasses.BTerm_P_name); if ( name !=null && name.equalsIgnoreCase(value)) { odbFilter.addPredicateId(d.getIdentity().toString()); } } } } else { for ( ODocument baseTermDoc : Helper.getNetworkElements(networkDoc, NdexClasses.Network_E_BaseTerms)) { String name = baseTermDoc.field(NdexClasses.BTerm_P_name); if ( name !=null && name.equalsIgnoreCase(propName)) { for ( ODocument prop : Helper.getDocumentLinks(baseTermDoc, "in_", NdexClasses.ndexProp_E_predicate)) { String v = prop.field(NdexClasses.ndexProp_P_value); if ( v.equalsIgnoreCase(value)) { odbFilter.addPropertyId(prop.getIdentity().toString()); } } } } } } return odbFilter; } private static EdgeByNodePropertyFilterODB preprocessEdgeByNodePropertyFilter( EdgeByNodePropertyFilter filter, ODocument networkDoc) { if ( filter == null) return null; EdgeByNodePropertyFilterODB odbFilter = new EdgeByNodePropertyFilterODB(); odbFilter.setMode(filter.getMode()); for (PropertySpecification spec: filter.getPropertySpecList()) { String value = spec.getValue(); String propName = spec.getName(); if ( propName.equalsIgnoreCase(nodePropertyNodeName) ) { odbFilter.addNodeName(value); } else if (propName.equalsIgnoreCase(nodePropertyNameORTerm)) { odbFilter.addNodeName(value); for ( ODocument d : Helper.getNetworkElements(networkDoc, NdexClasses.Network_E_BaseTerms)) { String name = d.field(NdexClasses.BTerm_P_name); if ( name !=null && name.equalsIgnoreCase(value)) { odbFilter.addRepresentTermID(d.getIdentity().toString()); } } } else if (propName.equalsIgnoreCase(nodePropertyFunctionTermType)) { for ( ODocument funcTermDoc : Helper.getNetworkElements(networkDoc, NdexClasses.Network_E_FunctionTerms)) { ODocument fBTerm = funcTermDoc.field("out_"+NdexClasses.FunctionTerm_E_baseTerm); String name = fBTerm.field(NdexClasses.BTerm_P_name); if ( name !=null && name.equalsIgnoreCase(value)) { odbFilter.addRepresentTermID(funcTermDoc.getIdentity().toString()); } } } else { // normal property for ( ODocument baseTermDoc : Helper.getNetworkElements(networkDoc, NdexClasses.Network_E_BaseTerms)) { String name = baseTermDoc.field(NdexClasses.BTerm_P_name); if ( name !=null && name.equalsIgnoreCase(propName)) { for ( ODocument prop : Helper.getDocumentLinks(baseTermDoc, "in_", NdexClasses.ndexProp_E_predicate)) { String v = prop.field(NdexClasses.ndexProp_P_value); if ( v.equalsIgnoreCase(value)) { odbFilter.addPropertyId(prop.getIdentity().toString()); } } } } } } return odbFilter; } }
Added error checking of query object
src/main/java/org/ndexbio/common/query/NetworkFilterQueryExecutorFactory.java
Added error checking of query object
<ide><path>rc/main/java/org/ndexbio/common/query/NetworkFilterQueryExecutorFactory.java <ide> private static final String nodePropertyNodeName = "ndex:nodeName"; <ide> <ide> public static NetworkFilterQueryExecutor createODBExecutor(String networkIdStr, EdgeCollectionQuery query) throws NdexException { <add> <add> // check if the query is valid <add> if ( query.getEdgeFilter() == null || query.getEdgeFilter().getPropertySpecifications().size() == 0) { <add> if ( query.getNodeFilter() == null || query.getNodeFilter().getPropertySpecifications().size() == 0 ) { //error <add> throw new NdexException ("Invalid query object received. Both filters are empty."); <add> } <add> } <add> <add> //TODO: optimize the case that when filter compiled to an empty list. Should just return empty collection without iteration. <ide> <ide> EdgeCollectionQueryODB edgeQuery = new EdgeCollectionQueryODB(); <ide> edgeQuery.setQueryName(query.getQueryName()); <ide> <ide> EdgeByEdgePropertyFilterODB odbFilter = new EdgeByEdgePropertyFilterODB(); <ide> <del> for ( PropertySpecification spec : filter.getPropertySpecList()) { <add> for ( PropertySpecification spec : filter.getPropertySpecifications()) { <ide> String value = spec.getValue(); <ide> String propName = spec.getName(); <ide> if ( propName.equalsIgnoreCase(edgePredicatePropertyName) ) { <ide> EdgeByNodePropertyFilterODB odbFilter = new EdgeByNodePropertyFilterODB(); <ide> odbFilter.setMode(filter.getMode()); <ide> <del> for (PropertySpecification spec: filter.getPropertySpecList()) { <add> for (PropertySpecification spec: filter.getPropertySpecifications()) { <ide> String value = spec.getValue(); <ide> String propName = spec.getName(); <ide> if ( propName.equalsIgnoreCase(nodePropertyNodeName) ) {
Java
apache-2.0
513a8717ae4d76c80933be4eadf7edd9e58c7bb4
0
gdanguy/training-java-gdanguy,gdanguy/training-java-gdanguy,gdanguy/training-java-gdanguy
package Service; import java.sql.SQLException; import java.util.ArrayList; import java.util.Scanner; import Main.Config; import model.company.Company; import model.computer.Computer; import model.db.company.CompanyDB; import model.db.computer.ComputerDB; public class CLIService { /** * Returns a String containing the list of options * @return */ public static String listeOption(){ String message = Config.LIST_COMPUTER+"\n"; message+= Config.LIST_COMPANIES+"\n"; message+= Config.SHOW_COMPUTER_DETAILS+"\n"; message+= Config.CREATE_COMPUTER+"\n"; message+= Config.UPDATE_COMPUTER+"\n"; message+= Config.DELETE_COMPUTER+"\n"; message+= Config.QUIT; return message; } /** * Return the user input. * @param s * @return */ public static String lireSaisieUtilisateur(Scanner s){ return lireSaisieUtilisateur(s,null); } /** * Displays the requested message and return the user input. * @param s * @param message * @return */ public static String lireSaisieUtilisateur(Scanner s, String message){ if( message != null ){ System.out.println(message); } String str = s.nextLine(); str.toLowerCase(); return str; } /** * Call the method corresponding to the parameter. * @param action * @param s * @return * @throws ClassNotFoundException * @throws SQLException */ public static String choixAction(String action, Scanner s) throws ClassNotFoundException, SQLException{ int id; try{ switch(action){ case Config.LIST_COMPUTER : return listComputers(); case Config.LIST_COMPANIES : return listCompanies(); case Config.SHOW_COMPUTER_DETAILS : id = Integer.parseInt(lireSaisieUtilisateur(s,"Enter computer ID : ")); return showComputerdetails(id); case Config.CREATE_COMPUTER : Computer c = inputComputer(s); return createComputer(c); case Config.UPDATE_COMPUTER : id = Integer.parseInt(lireSaisieUtilisateur(s,"Enter computer ID : ")); return updateComputer(inputComputer(s,getComputer(id),id)); case Config.DELETE_COMPUTER : id = Integer.parseInt(lireSaisieUtilisateur(s,"Enter computer ID : ")); return deleteComputer(id); case Config.HELP : return listeOption(); case Config.QUIT : return Config.QUIT; default : return "Invalid input"; } }catch(NullPointerException | NumberFormatException e){ System.err.println(e); return "Invalid input"; } } private static Computer inputComputer(Scanner s) { try{ String name = lireSaisieUtilisateur(s,"Enter computer Name : "); String introduced = lireSaisieUtilisateur(s,"Enter computer Introduced (format :YYYY-MM-DD hh:mm:ss or press enter) : "); String discontinued = lireSaisieUtilisateur(s,"Enter computer Discontinued (format :YYYY-MM-DD hh:mm:ss or press enter) : "); int companyId = Integer.parseInt(lireSaisieUtilisateur(s,"Enter computer Company id : ")); return new Computer(-1,name,introduced,discontinued,companyId); }catch(NullPointerException | NumberFormatException e){ System.err.println(e); return null; } } private static Computer inputComputer(Scanner s, Computer c, int id) { try{ String name = lireSaisieUtilisateur(s,"Enter computer Name (before : "+c.getName()+") : "); String introduced = lireSaisieUtilisateur(s,"Enter computer Introduced (format :YYYY-MM-DD hh:mm:ss or press enter) (before : "+c.getIntroduced()+") : "); String discontinued = lireSaisieUtilisateur(s,"Enter computer Discontinued (format :YYYY-MM-DD hh:mm:ss or press enter) (before : "+c.getDiscontinued()+") : "); int companyId = Integer.parseInt(lireSaisieUtilisateur(s,"Enter computer Company id (before : "+c.getCompany_id()+"): ")); return new Computer(id,name,introduced,discontinued,companyId); }catch(NullPointerException | NumberFormatException e){ System.err.println(e); return null; } } /** * List computers * @return * @throws ClassNotFoundException * @throws SQLException */ public static String listComputers() throws ClassNotFoundException, SQLException{ ComputerDB db = new ComputerDB(); ArrayList<Computer> result = db.getComputer(); if( result == null ){ return "No computer in the database"; }else{ return result.toString(); } } /** * List companies * @return * @throws ClassNotFoundException * @throws SQLException */ public static String listCompanies() throws ClassNotFoundException, SQLException{ CompanyDB db = new CompanyDB(); ArrayList<Company> result = db.getCompanies(); if( result == null ){ return "No computer in the database"; }else{ return result.toString(); } } /** * Show computer details (the detailed information of only one computer) * @param id * @return * @throws ClassNotFoundException * @throws SQLException */ public static String showComputerdetails(int id) throws ClassNotFoundException, SQLException{ Computer result = getComputer(id); if( result == null ){ return "No computer corresponding in the database"; }else{ return result.toStringDetails(); } } private static Computer getComputer(int id) throws ClassNotFoundException, SQLException{ ComputerDB db = new ComputerDB(); return db.getComputerDetails(id); } /** * Create a computer, the id of parameter is no matter. * @param computer * @return * @throws ClassNotFoundException * @throws SQLException */ public static String createComputer(Computer computer) throws ClassNotFoundException, SQLException, NumberFormatException{ ComputerDB db = new ComputerDB(); return db.createComputer(computer).toStringDetails(); } /** * Update a computer * @param computer * @return * @throws ClassNotFoundException * @throws SQLException */ public static String updateComputer(Computer computer) throws ClassNotFoundException, SQLException, NumberFormatException{ ComputerDB db = new ComputerDB(); return db.updateComputer(computer).toStringDetails(); } /** * Delete a computer * @param id * @return * @throws ClassNotFoundException * @throws SQLException */ public static String deleteComputer(int id) throws ClassNotFoundException, SQLException{ ComputerDB db = new ComputerDB(); return db.deleteComputer(id); } }
src/Service/CLIService.java
package Service; import java.sql.SQLException; import java.util.ArrayList; import java.util.Scanner; import Main.Config; import model.company.Company; import model.computer.Computer; import model.db.company.CompanyDB; import model.db.computer.ComputerDB; public class CLIService { /** * Returns a String containing the list of options * @return */ public static String listeOption(){ String message = Config.LIST_COMPUTER+"\n"; message+= Config.LIST_COMPANIES+"\n"; message+= Config.SHOW_COMPUTER_DETAILS+"\n"; message+= Config.CREATE_COMPUTER+"\n"; message+= Config.UPDATE_COMPUTER+"\n"; message+= Config.DELETE_COMPUTER+"\n"; message+= Config.QUIT; return message; } /** * Retrieves the user input. * @param s * @return */ public static String lireSaisieUtilisateur(Scanner s){ return lireSaisieUtilisateur(s,null); } /** * Displays the requested message and retrieves the user input. * @param s * @param message * @return */ public static String lireSaisieUtilisateur(Scanner s, String message){ if( message != null ){ System.out.println(message); } String str = s.nextLine(); str.toLowerCase(); return str; } /** * Call the method corresponding to the parameter. * @param action * @param s * @return * @throws ClassNotFoundException * @throws SQLException */ public static String choixAction(String action, Scanner s) throws ClassNotFoundException, SQLException{ int id; try{ switch(action){ case Config.LIST_COMPUTER : return listComputers(); case Config.LIST_COMPANIES : return listCompanies(); case Config.SHOW_COMPUTER_DETAILS : id = Integer.parseInt(lireSaisieUtilisateur(s,"Enter computer ID : ")); return showComputerdetails(id); case Config.CREATE_COMPUTER : Computer c = inputComputer(s); return createComputer(c); case Config.UPDATE_COMPUTER : id = Integer.parseInt(lireSaisieUtilisateur(s,"Enter computer ID : ")); return updateComputer(inputComputer(s,getComputer(id),id)); case Config.DELETE_COMPUTER : id = Integer.parseInt(lireSaisieUtilisateur(s,"Enter computer ID : ")); return deleteComputer(id); case Config.HELP : return listeOption(); case Config.QUIT : return Config.QUIT; default : return "Invalid input"; } }catch(NullPointerException | NumberFormatException e){ System.err.println(e); return "Invalid input"; } } private static Computer inputComputer(Scanner s) { try{ String name = lireSaisieUtilisateur(s,"Enter computer Name : "); String introduced = lireSaisieUtilisateur(s,"Enter computer Introduced (format :YYYY-MM-DD hh:mm:ss or press enter) : "); String discontinued = lireSaisieUtilisateur(s,"Enter computer Discontinued (format :YYYY-MM-DD hh:mm:ss or press enter) : "); int companyId = Integer.parseInt(lireSaisieUtilisateur(s,"Enter computer Company id : ")); return new Computer(-1,name,introduced,discontinued,companyId); }catch(NullPointerException | NumberFormatException e){ System.err.println(e); return null; } } private static Computer inputComputer(Scanner s, Computer c, int id) { try{ String name = lireSaisieUtilisateur(s,"Enter computer Name (before : "+c.getName()+") : "); String introduced = lireSaisieUtilisateur(s,"Enter computer Introduced (format :YYYY-MM-DD hh:mm:ss or press enter) (before : "+c.getIntroduced()+") : "); String discontinued = lireSaisieUtilisateur(s,"Enter computer Discontinued (format :YYYY-MM-DD hh:mm:ss or press enter) (before : "+c.getDiscontinued()+") : "); int companyId = Integer.parseInt(lireSaisieUtilisateur(s,"Enter computer Company id (before : "+c.getCompany_id()+"): ")); return new Computer(id,name,introduced,discontinued,companyId); }catch(NullPointerException | NumberFormatException e){ System.err.println(e); return null; } } /** * List computers * @return * @throws ClassNotFoundException * @throws SQLException */ public static String listComputers() throws ClassNotFoundException, SQLException{ ComputerDB db = new ComputerDB(); ArrayList<Computer> result = db.getComputer(); if( result == null ){ return "No computer in the database"; }else{ return result.toString(); } } /** * List companies * @return * @throws ClassNotFoundException * @throws SQLException */ public static String listCompanies() throws ClassNotFoundException, SQLException{ CompanyDB db = new CompanyDB(); ArrayList<Company> result = db.getCompanies(); if( result == null ){ return "No computer in the database"; }else{ return result.toString(); } } /** * Show computer details (the detailed information of only one computer) * @param id * @return * @throws ClassNotFoundException * @throws SQLException */ public static String showComputerdetails(int id) throws ClassNotFoundException, SQLException{ Computer result = getComputer(id); if( result == null ){ return "No computer corresponding in the database"; }else{ return result.toStringDetails(); } } private static Computer getComputer(int id) throws ClassNotFoundException, SQLException{ ComputerDB db = new ComputerDB(); return db.getComputerDetails(id); } /** * Create a computer, the id of parameter is no matter. * @param computer * @return * @throws ClassNotFoundException * @throws SQLException */ public static String createComputer(Computer computer) throws ClassNotFoundException, SQLException, NumberFormatException{ ComputerDB db = new ComputerDB(); return db.createComputer(computer).toStringDetails(); } /** * Update a computer * @param computer * @return * @throws ClassNotFoundException * @throws SQLException */ public static String updateComputer(Computer computer) throws ClassNotFoundException, SQLException, NumberFormatException{ ComputerDB db = new ComputerDB(); return db.updateComputer(computer).toStringDetails(); } /** * Delete a computer * @param id * @return * @throws ClassNotFoundException * @throws SQLException */ public static String deleteComputer(int id) throws ClassNotFoundException, SQLException{ ComputerDB db = new ComputerDB(); return db.deleteComputer(id); } }
Correct javadoc
src/Service/CLIService.java
Correct javadoc
<ide><path>rc/Service/CLIService.java <ide> } <ide> <ide> /** <del> * Retrieves the user input. <add> * Return the user input. <ide> * @param s <ide> * @return <ide> */ <ide> } <ide> <ide> /** <del> * Displays the requested message and retrieves the user input. <add> * Displays the requested message and return the user input. <ide> * @param s <ide> * @param message <ide> * @return
JavaScript
apache-2.0
fa68bb5b365b7543b87b3d4ca2b99735ad92d36f
0
djaymago/ptc,djaymago/ptc,djaymago/ptc
var $dom = $(document); var btnJoin = '.join-now-wrap'; var btnNew = '.btn-submit-new'; var btnLike = '.btn-like-click'; var btnLikeConf = '.btn-like-confirm'; var btnShare = '.btn-share-click'; var btnShareConf = '.btn-share-confirm'; var btnGoGallery = '.btn-go-gallery'; var btnSubmitNew = '.btn-submit-new'; var frmSection = '.frm-section'; var modalThankYou = '#confirmation-thankyou'; var modalSubmit = '#confirmation-submit'; var modalLike = '#confirmation-like'; var modalShare = '#confirmation-share'; var sectComplete = '#upload-complete'; var serverHost = getHost(); var host = serverHost+"listener/poten-cee"; var galleryActiveID = 0; var hastag; $.getScript('//connect.facebook.net/en_US/sdk.js', function(){ FB.init({ appId: '487951431561097', version: 'v2.10' }); }); function getHost() { console.log(location.href, location.href.indexOf('local.potencee.com')); if(location.href.indexOf('local.potencee.com') > -1) return 'http://tools.propelrr.net/'; else if(location.href.indexOf('ptc-campaign.herokuapp.com') > -1 || location.href.indexOf('raw2.statichtmlapp.com') > -1) return 'https://tools-dev.propelrr.com/'; return 'https://tools.propelrr.com/'; } function getList() { var url = host+'/getList'; $.ajax({ url: url, type: 'POST', data: {}, crossDomain: true, processData: false, contentType: false }).done( function(data) { var entryDiv = $('.video-gallery ul'); entryDiv.html(data.list); if(data.list=='') { entryDiv.html('<div style="text-align: center;">There\'s no entry yet.<br><br>Be the first to submit your entry and get a chance to win the prize!</div>'); } }).always( function(data) { }); } function bindClicks() { $dom.on('click', btnJoin, function(e) { e.preventDefault(); FB.login(function (response) { checkLoginState(); }); }); $dom.on('click', btnNew, function(e) { e.preventDefault(); $(modalThankYou).removeClass('active'); }); $dom.on('click', btnSubmitNew, function(e) { e.preventDefault(); $(sectComplete).css({'display':'none'}); $('#step1').css({'display':'block'}); }); $dom.on('click', btnGoGallery, function(e) { e.preventDefault(); $('.menu').find('li:nth-child(2)').find('a').trigger('click'); $(sectComplete).css({'display':'none'}); }); $dom.on('click', btnLike, function(e) { e.preventDefault(); galleryActiveID = $(this).closest('li').data('id'); $(modalLike).addClass('active'); }); $dom.on('click', btnLikeConf, function(e) { var targetE = $('li[data-id="'+galleryActiveID+'"]'); loader(modalLike, 1, true); FB.getLoginStatus(function(response) { if (response.status === 'connected') { likeEntry(galleryActiveID, targetE); } else { FB.login(function(response){ likeEntry(galleryActiveID, targetE); }, {scope: 'publish_actions, email, public_profile, user_birthday, user_location'}); } }); }); $dom.on('click', btnShare, function(e) { e.preventDefault(); galleryActiveID = $(this).closest('li').data('id'); $(modalShare).addClass('active'); }); $dom.on('click', btnShareConf, function(e) { var targetE = $('li[data-id="'+galleryActiveID+'"]'); loader(modalShare, 1, true); FB.getLoginStatus(function(response) { if (response.status === 'connected') { shareEntry(galleryActiveID, targetE); } else { FB.login(function(response){ shareEntry(galleryActiveID, targetE); }, {scope: 'publish_actions, email, public_profile, user_birthday, user_location'}); } loader(modalShare, 0); }); }); $dom.on('click', '.btn-gallery-nav', function() { getList(); }); $('.menu ul li a').click(function(e){ e.preventDefault(); $('.menu li').removeClass('active'); $(this).closest('li').addClass('active'); var _this = $(this).attr('href'); $('.step-wrap').css({'display' : 'none'}); $(_this).css({'display' : 'block'}); }); $('.btn-cancel-modal').click( function(e) { $(this).closest('.popup-wrap').removeClass('active'); e.preventDefault(); }); $('.btn-confirm-submit').click( function(e) { e.preventDefault(); submitEntry(); }); /** Video Player **/ $dom.on('click', '.close-video', function(e) { e.preventDefault(); $('.popup-wrap').removeClass('active'); $('.video-holder video')[0].pause(); }); $dom.on('click', '.play-btn', function(e) { e.preventDefault(); $('#video-wrap').addClass('active'); $('.video-holder').html(''); var videoUrl = $(this).attr('data-html-video'); var videoElem = '<video width="100%" height="100%" autoplay="true" preload="none">' + '<source src="'+videoUrl+'" type="video/mp4">' + '<source src="'+videoUrl+'" type="video/webm">' + '</video>'; $('#video-wrap').addClass('active'); if($('.video-holder').children('*').size() > 0) { $('.video-holder video')[0].play(); } else { $('.video-holder').html(videoElem); } $(".video-holder video").bind("ended", function() { console.log('end'); $('.video-holder video')[0].autoplay=false $('#video-holder').removeClass('active'); }); }); } function bindEvents() { document.getElementById("upload-file").accept = "video/*" $('#term-checkbox').change(function(){ if( $('#terms-checkbox').is(':checked')) $('#terms-checkbox').closest('.custom-checkbox').removeClass('error') else $('#terms-checkbox').closest('.custom-checkbox').addClass('error'); }); $('#upload-file').change( function() { console.log(); if(this.files.length) { $('.required-file').text(this.files[0].name); $('.required-file').attr('style', 'visibility:visible;opacity:1;'); } else { $('.required-file').text(''); } }); $('.form-content form').submit(function(e){ e.preventDefault(); $('.form-content .input-wrap:not(.no-error)').addClass('error'); isvalidate = true; if(!$('#complete-name').val() == '') { $('#complete-name').closest('.input-wrap').removeClass('error'); } else { isvalidate = false; } if(!$('#p-address').val() == '') { $('#p-address').closest('.input-wrap').removeClass('error'); } else { isvalidate = false; } if( IsEmail($('#email-add').val() )) { $('#email-add').closest('.input-wrap').removeClass('error'); } else { isvalidate = false; } if(!$('#contact-num').val() == '' && $('#contact-num').val().length==11) { $('#contact-num').closest('.input-wrap').removeClass('error'); } else { isvalidate = false; } if ($('#captionText').val() != '' && hastag) { $('#captionText').closest('.captionfield').removeClass('error'); $('.captionfield .error-message').css({'display' : 'none'}); } else { isvalidate = false; $('.captionfield .error-message').css({'display' : 'block'}); } console.log($('#upload-file').val()) if($('#upload-file').val()=='') { $('.required-file').text('You must upload a video atleast 5sec.'); $('#upload-file').closest('.input-wrap').removeClass('error'); $('.required-file').attr('style', 'visibility:visible;opacity:1;'); isvalidate = false; } if( $('#term-checkbox').prop('checked')) { $('#term-checkbox').closest('.input-wrap').removeClass('error'); } else { $('#term-checkbox').closest('.input-wrap').addClass('error'); isvalidate = false; } if(isvalidate) { $('.loading-spinner-wrapper').addClass('active'); $('#confirmation-submit').addClass('active'); } else { $.sticky('Please fill all fields!', { 'autoclose' : 5000 }); } return false; }); } getList(); bindClicks(); bindEvents(); function limitText(limitField, limitCount, limitNum) { if (limitField.value.length > limitNum) { limitField.value = limitField.value.substring(0, limitNum); } else { limitCount.value = limitNum - limitField.value.length; } } $(".captionfield textarea").on("change", function(){ hastag = isSwearWord($(this).val()); }); function isSwearWord(fieldValue) { var textArr = fieldValue.split(' '); var error = false; for(i in textArr) { if (textArr[i].toLowerCase()=='#gummiestime') { $('.captionfield .error-message').css({'display' : 'none'}); error = true; } } return error; } function IsEmail(email) { var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; return regex.test(email); } function likeEntry(entryId) { FB.api('/me', {fields: 'id,first_name,last_name,birthday,age_range,gender,about,email,education,devices,hometown,location'}, function(response) { var _fname = response.first_name; var _lname = response.last_name; var _email = response.email; var _gender = response.gender; var _fbUid = response.id; var _fbBday = response.birthday; var _fbLocation = {name: response.location.name, id: response.location.id }; console.log(response); if(response.error===undefined) { var url = host + '/like'; $.ajax({ url: url, type: "POST", data: { first_name: _fname, last_name: _lname, email: _email, gender: _gender, fbuid: _fbUid, entryId: entryId, birthday: _fbBday, location_id: _fbLocation.id, location: _fbLocation.name }, crossDomain: true }).done( function(response) { $(modalLike).removeClass('active'); $.sticky(response.code==200 ? 'You have liked an entry!' : (response.code==201 ? 'You already liked this entry!': 'Error occurred. Please try again.'), { 'autoclose' : 5000 }); getList(); }).always( function() { loader(modalLike, 0); }).error( function() { $.sticky('Something went wrong. Try again!', { 'autoclose' : 5000 }); }); } }); } function shareEntry(entryId) { FB.api('/me', {fields: 'id,first_name,last_name,birthday,age_range,gender,about,email,education,devices,hometown,location'}, function(response) { console.log(response); var _fname = response.first_name; var _lname = response.last_name; var _email = response.email; var _gender = response.gender; var _fbUid = response.id; var _fbBday = response.birthday; var _fbLocation = {name: response.location.name, id: response.location.id }; FB.ui({ method: 'share', href: host+'/view?id='+entryId }, function(response) { if (response && !response.error_code) { var url = host + '/share'; $.ajax({ url: url, type: "POST", data: { first_name: _fname, last_name: _lname, email: _email, gender: _gender, fbuid: _fbUid, entryId: entryId, birthday: _fbBday, location_id: _fbLocation.id, location: _fbLocation.name }, crossDomain: true }).done( function(response) { $(modalShare).removeClass('active'); $.sticky(response.code==200 ? 'Successfully shared entry!' : (response.code==201 ? 'You already shared this entry!': 'Error occurred. Please try again.'), { 'autoclose' : 5000 }); getList(); }).always( function() { loader(modalShare, 0); }).error( function() { $.sticky('Something went wrong. Try again!', { 'autoclose' : 5000 }); }); } else if(response.error_code && response.error_code==4201) { loader(modalShare, 0); } }); }); } function checkLoginState() { FB.getLoginStatus(function(response) { loginCallback(response); }); } function loginCallback(data) { if (data.status==='connected') { loader('#main-wrapper', 1, false); FB.api('/me','GET',{"fields":"id,name,first_name,last_name,picture,locale,timezone,gender,email"},function(response){ saveUserFBId(response.id); $(btnJoin).hide(); $(frmSection).show(); $dom.scrollTop(window.outerHeight); }); } } function saveUserFBId(fbuid) { var formData = new FormData(); formData.append('fbuid', fbuid); var url = host+'/saveFacebookUID'; $.ajax({ url: url, type: 'POST', data:formData, crossDomain: true, processData: false, contentType: false }).done( function(data) { if(data.id) $('#account_id').val(data.id); }).always( function(data) { loader('#main-wrapper', 0); }); } function submitEntry() { var formData = new FormData(document.getElementById('formEntry')); var url = host+'/submitEntry'; loader(modalSubmit, 1, true); disableScroll(); $.ajax({ url: url, type: 'POST', data: formData, crossDomain: true, processData: false, contentType: false }).done( function(data) { var message; if(data.code==200){ $(frmSection).find('form').trigger('reset'); $cmbRegions.trigger('change'); $(sectComplete).css({'display':'block'}); $('#step1').css({'display':'none'}); $(modalSubmit).removeClass('active'); message = 'Successfully submitted entry!'; } else if(data.code==303) { $(modalSubmit).removeClass('active'); message = data.message; } else { message = 'Something went wrong. Try again!'; } $.sticky(message, { 'autoclose' : 5000 }); }).error(function() { $.sticky('Something went wrong. Try again!', { 'autoclose' : 5000 }); }).always(function() { enableScroll(); loader(modalSubmit, 0); }); } /** Loader */ function loader(el, stat, overlay) { if(stat) $(el) .addClass('loading') .loader('show', { overlay: overlay }); else $(el) .removeClass('loading') .loader('hide'); } /** Scrolling */ var keys = {37: 1, 38: 1, 39: 1, 40: 1}; function preventDefault(e) { e = e || window.event; if (e.preventDefault) e.preventDefault(); e.returnValue = false; } function preventDefaultForScrollKeys(e) { if (keys[e.keyCode]) { preventDefault(e); return false; } } function disableScroll() { if (window.addEventListener) // older FF window.addEventListener('DOMMouseScroll', preventDefault, false); window.onwheel = preventDefault; // modern standard window.onmousewheel = document.onmousewheel = preventDefault; // older browsers, IE window.ontouchmove = preventDefault; // mobile document.onkeydown = preventDefaultForScrollKeys; } function enableScroll() { if (window.removeEventListener) window.removeEventListener('DOMMouseScroll', preventDefault, false); window.onmousewheel = document.onmousewheel = null; window.onwheel = null; window.ontouchmove = null; document.onkeydown = null; } //-------------------------------SELECT CASCADING-------------------------// //demo: https://codepen.io/medunes/pen/GWoojz var currentCities=[]; // This is a demo API key that can only be used for a short period of time, and will be unavailable soon. You should rather request your API key (free) from http://battuta.medunes.net/ var BATTUTA_KEY="00000000000000000000000000000000"; // This is the country code var COUNTRY_CODE="ph"; // Populate country select box from battuta API var URL_REGIONS = host + '/getLocation?scope=province'; $cmbRegions = $("#loc_region"); $cmbCities = $("#loc_cities"); $.getJSON(URL_REGIONS,function(regions) { console.log(regions) $("#loc_region option").remove(); //loop through regions.. $.each(regions, function(key,region) { $("<option></option>") .attr("value",region.Id) .append(region.Name) .appendTo($cmbRegions); }); // trigger "change" to fire the #state section update process $cmbRegions.trigger("change"); }); $cmbRegions.on("change",function() { var prov = $cmbRegions.val(); url = host + '/getLocation?scope=city&province='+prov; $cmbCities.html("<option>Loading...</option>"); $.getJSON(url, function(cities) { currentCities=cities; var i=0; $cmbCities.empty(); //loop through regions.. $.each(cities, function(key,city) { $("<option></option>") .attr("value",city.Id) .append(city.Name) .appendTo($cmbCities); }); // trigger "change" to fire the #state section update process $cmbCities.trigger("change"); }); }); //-------------------------------END OF SELECT CASCADING-------------------------//
js/app_script.js
var $dom = $(document); var btnJoin = '.join-now-wrap'; var btnNew = '.btn-submit-new'; var btnLike = '.btn-like-click'; var btnLikeConf = '.btn-like-confirm'; var btnShare = '.btn-share-click'; var btnShareConf = '.btn-share-confirm'; var btnGoGallery = '.btn-go-gallery'; var btnSubmitNew = '.btn-submit-new'; var frmSection = '.frm-section'; var modalThankYou = '#confirmation-thankyou'; var modalSubmit = '#confirmation-submit'; var modalLike = '#confirmation-like'; var modalShare = '#confirmation-share'; var sectComplete = '#upload-complete'; var serverHost = getHost(); var host = serverHost+"listener/poten-cee"; var galleryActiveID = 0; var hastag; $.getScript('//connect.facebook.net/en_US/sdk.js', function(){ FB.init({ appId: '487951431561097', version: 'v2.10' }); }); function getHost() { console.log(location.href, location.href.indexOf('local.potencee.com')); if(location.href.indexOf('local.potencee.com') > -1) return 'http://tools.propelrr.net/'; else if(location.href.indexOf('ptc-campaign.herokuapp.com') > -1 || location.href.indexOf('raw2.statichtmlapp.com') > -1) return 'https://tools-dev.propelrr.com/'; return 'https://tools.propelrr.com/'; } function getList() { var url = host+'/getList'; $.ajax({ url: url, type: 'POST', data: {}, crossDomain: true, processData: false, contentType: false }).done( function(data) { var entryDiv = $('.video-gallery ul'); entryDiv.html(data.list); if(data.list=='') { entryDiv.html('<div style="text-align: center;">There\'s no entry yet.<br><br>Be the first to submit your entry and get a chance to win the prize!</div>'); } }).always( function(data) { }); } function bindClicks() { $dom.on('click', btnJoin, function(e) { e.preventDefault(); FB.login(function (response) { checkLoginState(); }); }); $dom.on('click', btnNew, function(e) { e.preventDefault(); $(modalThankYou).removeClass('active'); }); $dom.on('click', btnSubmitNew, function(e) { e.preventDefault(); $(sectComplete).css({'display':'none'}); $('#step1').css({'display':'block'}); }); $dom.on('click', btnGoGallery, function(e) { e.preventDefault(); $('.menu').find('li:nth-child(2)').find('a').trigger('click'); $(sectComplete).css({'display':'none'}); }); $dom.on('click', btnLike, function(e) { e.preventDefault(); galleryActiveID = $(this).closest('li').data('id'); $(modalLike).addClass('active'); }); $dom.on('click', btnLikeConf, function(e) { var targetE = $('li[data-id="'+galleryActiveID+'"]'); loader(modalLike, 1, true); FB.getLoginStatus(function(response) { if (response.status === 'connected') { likeEntry(galleryActiveID, targetE); } else { FB.login(function(response){ likeEntry(galleryActiveID, targetE); }, {scope: 'publish_actions, email, public_profile, user_birthday, user_location'}); } }); }); $dom.on('click', btnShare, function(e) { e.preventDefault(); galleryActiveID = $(this).closest('li').data('id'); $(modalShare).addClass('active'); }); $dom.on('click', btnShareConf, function(e) { var targetE = $('li[data-id="'+galleryActiveID+'"]'); loader(modalShare, 1, true); FB.getLoginStatus(function(response) { if (response.status === 'connected') { shareEntry(galleryActiveID, targetE); } else { FB.login(function(response){ shareEntry(galleryActiveID, targetE); }, {scope: 'publish_actions, email, public_profile, user_birthday, user_location'}); } loader(modalShare, 0); }); }); $dom.on('click', '.btn-gallery-nav', function() { getList(); }); $('.menu ul li a').click(function(e){ e.preventDefault(); $('.menu li').removeClass('active'); $(this).closest('li').addClass('active'); var _this = $(this).attr('href'); $('.step-wrap').css({'display' : 'none'}); $(_this).css({'display' : 'block'}); }); $('.btn-cancel-modal').click( function(e) { $(this).closest('.popup-wrap').removeClass('active'); e.preventDefault(); }); $('.btn-confirm-submit').click( function(e) { e.preventDefault(); submitEntry(); }); /** Video Player **/ $dom.on('click', '.close-video', function(e) { e.preventDefault(); $('.popup-wrap').removeClass('active'); $('.video-holder video')[0].pause(); }); $dom.on('click', '.play-btn', function(e) { e.preventDefault(); $('#video-wrap').addClass('active'); $('.video-holder').html(''); var videoUrl = $(this).attr('data-html-video'); var videoElem = '<video width="100%" height="100%" autoplay="true" preload="none">' + '<source src="'+videoUrl+'" type="video/mp4">' + '<source src="'+videoUrl+'" type="video/webm">' + '</video>'; $('#video-wrap').addClass('active'); if($('.video-holder').children('*').size() > 0) { $('.video-holder video')[0].play(); } else { $('.video-holder').html(videoElem); } $(".video-holder video").bind("ended", function() { console.log('end'); $('.video-holder video')[0].autoplay=false $('#video-holder').removeClass('active'); }); }); } function bindEvents() { document.getElementById("upload-file").accept = "video/*" $('#term-checkbox').change(function(){ if( $('#terms-checkbox').is(':checked')) $('#terms-checkbox').closest('.custom-checkbox').removeClass('error') else $('#terms-checkbox').closest('.custom-checkbox').addClass('error'); }); $('#upload-file').change( function() { console.log(); if(this.files.length) { $('.required-file').text(this.files[0].name); $('.required-file').attr('style', 'visibility:visible;opacity:1;'); } else { $('.required-file').text(''); } }); $('.form-content form').submit(function(e){ e.preventDefault(); $('.form-content .input-wrap:not(.no-error)').addClass('error'); isvalidate = true; if(!$('#complete-name').val() == '') { $('#complete-name').closest('.input-wrap').removeClass('error'); } else { isvalidate = false; } if(!$('#p-address').val() == '') { $('#p-address').closest('.input-wrap').removeClass('error'); } else { isvalidate = false; } if( IsEmail($('#email-add').val() )) { $('#email-add').closest('.input-wrap').removeClass('error'); } else { isvalidate = false; } if(!$('#contact-num').val() == '' && $('#contact-num').val().length==11) { $('#contact-num').closest('.input-wrap').removeClass('error'); } else { isvalidate = false; } if ($('#captionText').val() != '' && hastag) { $('#captionText').closest('.captionfield').removeClass('error'); $('.captionfield .error-message').css({'display' : 'none'}); } else { isvalidate = false; $('.captionfield .error-message').css({'display' : 'block'}); } console.log($('#upload-file').val()) if($('#upload-file').val()=='') { $('.required-file').text('You must upload a video atleast 5sec.'); $('#upload-file').closest('.input-wrap').removeClass('error'); $('.required-file').attr('style', 'visibility:visible;opacity:1;'); isvalidate = false; } if( $('#term-checkbox').prop('checked')) { $('#term-checkbox').closest('.input-wrap').removeClass('error'); } else { $('#term-checkbox').closest('.input-wrap').addClass('error'); isvalidate = false; } if(isvalidate) { $('.loading-spinner-wrapper').addClass('active'); $('#confirmation-submit').addClass('active'); } else { $.sticky('Please fill all fields!', { 'autoclose' : 5000 }); } return false; }); } getList(); bindClicks(); bindEvents(); function limitText(limitField, limitCount, limitNum) { if (limitField.value.length > limitNum) { limitField.value = limitField.value.substring(0, limitNum); } else { limitCount.value = limitNum - limitField.value.length; } } $(".captionfield textarea").on("change", function(){ hastag = isSwearWord($(this).val()); }); function isSwearWord(fieldValue) { var textArr = fieldValue.split(' '); var error = false; for(i in textArr) { if (textArr[i].toLowerCase()=='#gummiestime') { $('.captionfield .error-message').css({'display' : 'none'}); error = true; } } return error; } function IsEmail(email) { var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; return regex.test(email); } function likeEntry(entryId) { FB.api('/me', {fields: 'id,first_name,last_name,birthday,age_range,gender,about,email,education,devices,hometown,location'}, function(response) { var _fname = response.first_name; var _lname = response.last_name; var _email = response.email; var _gender = response.gender; var _fbUid = response.id; var _fbBday = response.birthday; var _fbLocation = {name: response.location.name, id: response.location.id }; console.log(response); if(response.error===undefined) { var url = host + '/like'; $.ajax({ url: url, type: "POST", data: { first_name: _fname, last_name: _lname, email: _email, gender: _gender, fbuid: _fbUid, entryId: entryId, birthday: _fbBday, location_id: _fbLocation.id, location: _fbLocation.name }, crossDomain: true }).done( function(response) { $(modalLike).removeClass('active'); $.sticky(response.code==200 ? 'You have liked an entry!' : (response.code==201 ? 'You already liked this entry!': 'Error occurred. Please try again.'), { 'autoclose' : 5000 }); getList(); }).always( function() { loader(modalLike, 0); }).error( function() { $.sticky('Something went wrong. Try again!', { 'autoclose' : 5000 }); }); } }); } function shareEntry(entryId) { FB.api('/me', {fields: 'id,first_name,last_name,birthday,age_range,gender,about,email,education,devices,hometown,location'}, function(response) { var _fname = response.first_name; var _lname = response.last_name; var _email = response.email; var _gender = response.gender; var _fbUid = response.id; var _fbBday = response.birthday; var _fbLocation = {name: response.location.name, id: response.location.id }; FB.ui({ method: 'share', href: host+'/view?id='+entryId }, function(response) { if (response && !response.error_code) { var url = host + '/share'; $.ajax({ url: url, type: "POST", data: { first_name: _fname, last_name: _lname, email: _email, gender: _gender, fbuid: _fbUid, entryId: entryId, birthday: _fbBday, location_id: _fbLocation.id, location: _fbLocation.name }, crossDomain: true }).done( function(response) { $(modalShare).removeClass('active'); $.sticky(response.code==200 ? 'Successfully shared entry!' : (response.code==201 ? 'You already shared this entry!': 'Error occurred. Please try again.'), { 'autoclose' : 5000 }); getList(); }).always( function() { loader(modalShare, 0); }).error( function() { $.sticky('Something went wrong. Try again!', { 'autoclose' : 5000 }); }); } else if(response.error_code && response.error_code==4201) { loader(modalShare, 0); } }); }); } function checkLoginState() { FB.getLoginStatus(function(response) { loginCallback(response); }); } function loginCallback(data) { if (data.status==='connected') { loader('#main-wrapper', 1, false); FB.api('/me','GET',{"fields":"id,name,first_name,last_name,picture,locale,timezone,gender,email"},function(response){ saveUserFBId(response.id); $(btnJoin).hide(); $(frmSection).show(); $dom.scrollTop(window.outerHeight); }); } } function saveUserFBId(fbuid) { var formData = new FormData(); formData.append('fbuid', fbuid); var url = host+'/saveFacebookUID'; $.ajax({ url: url, type: 'POST', data:formData, crossDomain: true, processData: false, contentType: false }).done( function(data) { if(data.id) $('#account_id').val(data.id); }).always( function(data) { loader('#main-wrapper', 0); }); } function submitEntry() { var formData = new FormData(document.getElementById('formEntry')); var url = host+'/submitEntry'; loader(modalSubmit, 1, true); disableScroll(); $.ajax({ url: url, type: 'POST', data: formData, crossDomain: true, processData: false, contentType: false }).done( function(data) { var message; if(data.code==200){ $(frmSection).find('form').trigger('reset'); $cmbRegions.trigger('change'); $(sectComplete).css({'display':'block'}); $('#step1').css({'display':'none'}); $(modalSubmit).removeClass('active'); message = 'Successfully submitted entry!'; } else if(data.code==303) { $(modalSubmit).removeClass('active'); message = data.message; } else { message = 'Something went wrong. Try again!'; } $.sticky(message, { 'autoclose' : 5000 }); }).error(function() { $.sticky('Something went wrong. Try again!', { 'autoclose' : 5000 }); }).always(function() { enableScroll(); loader(modalSubmit, 0); }); } /** Loader */ function loader(el, stat, overlay) { if(stat) $(el) .addClass('loading') .loader('show', { overlay: overlay }); else $(el) .removeClass('loading') .loader('hide'); } /** Scrolling */ var keys = {37: 1, 38: 1, 39: 1, 40: 1}; function preventDefault(e) { e = e || window.event; if (e.preventDefault) e.preventDefault(); e.returnValue = false; } function preventDefaultForScrollKeys(e) { if (keys[e.keyCode]) { preventDefault(e); return false; } } function disableScroll() { if (window.addEventListener) // older FF window.addEventListener('DOMMouseScroll', preventDefault, false); window.onwheel = preventDefault; // modern standard window.onmousewheel = document.onmousewheel = preventDefault; // older browsers, IE window.ontouchmove = preventDefault; // mobile document.onkeydown = preventDefaultForScrollKeys; } function enableScroll() { if (window.removeEventListener) window.removeEventListener('DOMMouseScroll', preventDefault, false); window.onmousewheel = document.onmousewheel = null; window.onwheel = null; window.ontouchmove = null; document.onkeydown = null; } //-------------------------------SELECT CASCADING-------------------------// //demo: https://codepen.io/medunes/pen/GWoojz var currentCities=[]; // This is a demo API key that can only be used for a short period of time, and will be unavailable soon. You should rather request your API key (free) from http://battuta.medunes.net/ var BATTUTA_KEY="00000000000000000000000000000000"; // This is the country code var COUNTRY_CODE="ph"; // Populate country select box from battuta API var URL_REGIONS = host + '/getLocation?scope=province'; $cmbRegions = $("#loc_region"); $cmbCities = $("#loc_cities"); $.getJSON(URL_REGIONS,function(regions) { console.log(regions) $("#loc_region option").remove(); //loop through regions.. $.each(regions, function(key,region) { $("<option></option>") .attr("value",region.Id) .append(region.Name) .appendTo($cmbRegions); }); // trigger "change" to fire the #state section update process $cmbRegions.trigger("change"); }); $cmbRegions.on("change",function() { var prov = $cmbRegions.val(); url = host + '/getLocation?scope=city&province='+prov; $cmbCities.html("<option>Loading...</option>"); $.getJSON(url, function(cities) { currentCities=cities; var i=0; $cmbCities.empty(); //loop through regions.. $.each(cities, function(key,city) { $("<option></option>") .attr("value",city.Id) .append(city.Name) .appendTo($cmbCities); }); // trigger "change" to fire the #state section update process $cmbCities.trigger("change"); }); }); //-------------------------------END OF SELECT CASCADING-------------------------//
Update Poten-Cee
js/app_script.js
Update Poten-Cee
<ide><path>s/app_script.js <ide> <ide> function shareEntry(entryId) { <ide> FB.api('/me', {fields: 'id,first_name,last_name,birthday,age_range,gender,about,email,education,devices,hometown,location'}, function(response) { <add> console.log(response); <add> <ide> var _fname = response.first_name; <ide> var _lname = response.last_name; <ide> var _email = response.email;
Java
bsd-3-clause
3c3298fe4f698cdc5209a7a98c4f14b08e2d6390
0
jnehlmeier/threetenbp,pepyakin/threetenbp,ThreeTen/threetenbp,jnehlmeier/threetenbp,naixx/threetenbp,naixx/threetenbp,ThreeTen/threetenbp,pepyakin/threetenbp
/* * Copyright (c) 2007-2009, Stephen Colebourne & Michael Nascimento Santos * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of JSR-310 nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.time.calendar; import java.io.Serializable; import javax.time.CalendricalException; import javax.time.Instant; import javax.time.InstantProvider; import javax.time.calendar.field.DayOfMonth; import javax.time.calendar.field.DayOfWeek; import javax.time.calendar.field.DayOfYear; import javax.time.calendar.field.MonthOfYear; import javax.time.calendar.field.Year; import javax.time.period.PeriodProvider; /** * A date with a zone offset from UTC in the ISO-8601 calendar system, * such as '2007-12-03+01:00'. * <p> * OffsetDate is an immutable calendrical that represents a date, often viewed * as year-month-day-offset. This object can also sccess other date fields such as * day of year, day of week and week of year. * <p> * This class does not store or represent a time. * Thus, for example, the value "2nd October 2007 +02:00" can be stored * in a OffsetDate. * <p> * OffsetDate is immutable and thread-safe. * * @author Michael Nascimento Santos * @author Stephen Colebourne */ public final class OffsetDate implements CalendricalProvider, DateProvider, DateMatcher, DateAdjuster, Comparable<OffsetDate>, Serializable { /** * A serialization identifier for this class. */ private static final long serialVersionUID = -3618963189L; /** * The date. */ private final LocalDate date; /** * The zone offset. */ private final ZoneOffset offset; //----------------------------------------------------------------------- /** * Obtains an instance of <code>OffsetDate</code>. * * @param year the year to represent, not null * @param monthOfYear the month of year, not null * @param dayOfMonth the day of month to represent, not null * @param offset the zone offset, not null * @return the offset date, never null * @throws InvalidCalendarFieldException if the day of month is invalid for the month-year */ public static OffsetDate date(Year year, MonthOfYear monthOfYear, DayOfMonth dayOfMonth, ZoneOffset offset) { LocalDate date = LocalDate.date(year, monthOfYear, dayOfMonth); return new OffsetDate(date, offset); } /** * Obtains an instance of <code>OffsetDate</code>. * * @param year the year to represent, from MIN_VALUE + 1 to MAX_VALUE * @param monthOfYear the month of year, not null * @param dayOfMonth the day of month to represent, from 1 to 31 * @param offset the zone offset, not null * @return the offset date, never null * @throws IllegalCalendarFieldValueException if the value of any field is out of range * @throws InvalidCalendarFieldException if the day of month is invalid for the month-year */ public static OffsetDate date(int year, MonthOfYear monthOfYear, int dayOfMonth, ZoneOffset offset) { LocalDate date = LocalDate.date(year, monthOfYear, dayOfMonth); return new OffsetDate(date, offset); } /** * Obtains an instance of <code>OffsetDate</code>. * * @param year the year to represent, from MIN_VALUE + 1 to MAX_VALUE * @param monthOfYear the month of year to represent, from 1 (January) to 12 (December) * @param dayOfMonth the day of month to represent, from 1 to 31 * @param offset the zone offset, not null * @return the offset date, never null * @throws IllegalCalendarFieldValueException if the value of any field is out of range * @throws InvalidCalendarFieldException if the day of month is invalid for the month-year */ public static OffsetDate date(int year, int monthOfYear, int dayOfMonth, ZoneOffset offset) { LocalDate date = LocalDate.date(year, monthOfYear, dayOfMonth); return new OffsetDate(date, offset); } /** * Obtains an instance of <code>OffsetDate</code>. * * @param dateProvider the date provider to use, not null * @param offset the zone offset, not null * @return the offset date, never null */ public static OffsetDate date(DateProvider dateProvider, ZoneOffset offset) { LocalDate date = LocalDate.date(dateProvider); return new OffsetDate(date, offset); } //----------------------------------------------------------------------- /** * Converts an instant to an offset date. * <p> * This conversion drops the time component of the instant. * * @param instantProvider the instant to convert, not null * @param offset the zone offset, not null * @return the offset date, never null * @throws CalendarConversionException if the instant exceeds the supported date range */ public static OffsetDate fromInstant(InstantProvider instantProvider, ZoneOffset offset) { Instant instant = Instant.instant(instantProvider); ISOChronology.checkNotNull(offset, "ZoneOffset must not be null"); long epochSecs = instant.getEpochSeconds() + offset.getAmountSeconds(); // overflow caught later long yearZeroDays = (epochSecs / ISOChronology.SECONDS_PER_DAY) + ISOChronology.DAYS_0000_TO_1970; long secsOfDay = epochSecs % ISOChronology.SECONDS_PER_DAY; if (secsOfDay < 0) { yearZeroDays--; // overflow caught later } LocalDate date = LocalDate.fromYearZeroDays(yearZeroDays); return new OffsetDate(date, offset); } //----------------------------------------------------------------------- /** * Constructor. * * @param date the date, validated as not null * @param offset the zone offset, validated as not null */ private OffsetDate(LocalDate date, ZoneOffset offset) { if (date == null) { throw new NullPointerException("The date must not be null"); } if (offset == null) { throw new NullPointerException("The zone offset must not be null"); } this.date = date; this.offset = offset; } //----------------------------------------------------------------------- /** * Gets the chronology that describes the calendar system rules for * this date. * * @return the ISO chronology, never null */ public ISOChronology getChronology() { return ISOChronology.INSTANCE; } //----------------------------------------------------------------------- /** * Checks if the specified calendar field is supported. * <p> * This method queries whether this <code>OffsetDate</code> can * be queried using the specified calendar field. * * @param fieldRule the field to query, null returns false * @return true if the field is supported, false otherwise */ public boolean isSupported(DateTimeFieldRule fieldRule) { return date.isSupported(fieldRule); } /** * Gets the value of the specified calendar field. * <p> * This method queries the value of the specified calendar field. * If the calendar field is not supported then an exception is thrown. * * @param fieldRule the field to query, not null * @return the value for the field * @throws UnsupportedCalendarFieldException if no value for the field is found */ public int get(DateTimeFieldRule fieldRule) { return date.get(fieldRule); } //----------------------------------------------------------------------- /** * Gets the local date. * <p> * This returns the date without the zone offset. * * @return the local date, never null */ public LocalDate getDate() { return date; } /** * Returns a copy of this OffsetDate with a different local date. * <p> * This method changes the date stored to a different date. * No calculation is performed. The result simply represents the same * offset and the new date. * * @param dateProvider the local date to change to, not null * @return a new updated OffsetDate, never null */ public OffsetDate withDate(DateProvider dateProvider) { LocalDate localDate = LocalDate.date(dateProvider); return localDate.equals(this.date) ? this : new OffsetDate(localDate, offset); } //----------------------------------------------------------------------- /** * Gets the zone offset. * * @return the zone offset, never null */ public ZoneOffset getOffset() { return offset; } /** * Returns a copy of this OffsetTime with a different zone offset. * <p> * This method changes the offset stored to a different offset. * No calculation is performed. The result simply represents the same * local date and the new offset. * * @param offset the zone offset to change to, not null * @return a new updated OffsetDate, never null */ public OffsetDate withOffset(ZoneOffset offset) { return offset != null && offset.equals(this.offset) ? this : new OffsetDate(date, offset); } //----------------------------------------------------------------------- /** * Gets the year field as a <code>Year</code>. * <p> * This method provides access to an object representing the year field. * This allows operations to be performed on this field in a type-safe manner. * * @return the year, never null */ public Year toYear() { return date.toYear(); } /** * Gets the month of year field as a <code>MonthOfYear</code>. * <p> * This method provides access to an object representing the month of year field. * This allows operations to be performed on this field in a type-safe manner. * <p> * This method is the same as {@link #getMonthOfYear()}. * * @return the month of year, never null */ public MonthOfYear toMonthOfYear() { return date.toMonthOfYear(); } /** * Gets the day of month field as a <code>DayOfMonth</code>. * <p> * This method provides access to an object representing the day of month field. * This allows operations to be performed on this field in a type-safe manner. * * @return the day of month, never null */ public DayOfMonth toDayOfMonth() { return date.toDayOfMonth(); } /** * Gets the day of year field as a <code>DayOfYear</code>. * <p> * This method provides access to an object representing the day of year field. * This allows operations to be performed on this field in a type-safe manner. * * @return the day of year, never null */ public DayOfYear toDayOfYear() { return date.toDayOfYear(); } /** * Gets the day of week field as a <code>DayOfWeek</code>. * <p> * This method provides access to an object representing the day of week field. * This allows operations to be performed on this field in a type-safe manner. * <p> * This method is the same as {@link #getDayOfWeek()}. * * @return the day of week, never null */ public DayOfWeek toDayOfWeek() { return date.toDayOfWeek(); } //----------------------------------------------------------------------- /** * Gets the year field. * <p> * This method returns the primitive <code>int</code> value for the year. * <p> * Additional information about the year can be obtained from via {@link #toYear()}. * This returns a <code>Year</code> object which includes information on whether * this is a leap year and its length in days. It can also be used as a {@link DateMatcher} * and a {@link DateAdjuster}. * * @return the year, from MIN_YEAR to MAX_YEAR */ public int getYear() { return date.getYear(); } /** * Gets the month of year field, which is an enum <code>MonthOfYear</code>. * <p> * This method returns the enum {@link MonthOfYear} for the month. * This avoids confusion as to what <code>int</code> values mean. * If you need access to the primitive <code>int</code> value then the enum * provides the {@link MonthOfYear#getValue() int value}. * <p> * Additional information can be obtained from the <code>MonthOfYear</code>. * This includes month lengths, textual names and access to the quarter of year * and month of quarter values. * * @return the month of year, never null */ public MonthOfYear getMonthOfYear() { return date.getMonthOfYear(); } /** * Gets the day of month field. * <p> * This method returns the primitive <code>int</code> value for the day of month. * <p> * Additional information about the day of month can be obtained from via {@link #toDayOfMonth()}. * This returns a <code>DayOfMonth</code> object which can be used as a {@link DateMatcher} * and a {@link DateAdjuster}. * * @return the day of month, from 1 to 31 */ public int getDayOfMonth() { return date.getDayOfMonth(); } /** * Gets the day of year field. * <p> * This method returns the primitive <code>int</code> value for the day of year. * <p> * Additional information about the day of year can be obtained from via {@link #toDayOfYear()}. * This returns a <code>DayOfYear</code> object which can be used as a {@link DateMatcher} * and a {@link DateAdjuster}. * * @return the day of year, from 1 to 365, or 366 in a leap year */ public int getDayOfYear() { return date.getDayOfYear(); } /** * Gets the day of week field, which is an enum <code>DayOfWeek</code>. * <p> * This method returns the enum {@link DayOfWeek} for the day of week. * This avoids confusion as to what <code>int</code> values mean. * If you need access to the primitive <code>int</code> value then the enum * provides the {@link DayOfWeek#getValue() int value}. * <p> * Additional information can be obtained from the <code>DayOfWeek</code>. * This includes textual names of the values. * * @return the day of week, never null */ public DayOfWeek getDayOfWeek() { return date.getDayOfWeek(); } //----------------------------------------------------------------------- /** * Returns a copy of this OffsetDate with the date altered using the adjuster. * <p> * Adjusters can be used to alter the date in unusual ways. Examples might * be an adjuster that set the date avoiding weekends, or one that sets the * date to the last day of the month. * <p> * The offset has no effect on and is not affected by the adjustment. * <p> * This instance is immutable and unaffected by this method call. * * @param adjuster the adjuster to use, not null * @return a new updated OffsetDate, never null * @throws IllegalArgumentException if the adjuster returned null */ public OffsetDate with(DateAdjuster adjuster) { LocalDate newDate = date.with(adjuster); return newDate == date ? this : new OffsetDate(newDate, offset); } //----------------------------------------------------------------------- /** * Returns a copy of this OffsetDate with the year value altered. * <p> * This method does the same as <code>withYear(year, DateResolvers.previousValid())</code>. * <p> * This instance is immutable and unaffected by this method call. * * @param year the year to represent, from MIN_YEAR to MAX_YEAR * @return a new updated OffsetDate, never null * @throws IllegalCalendarFieldValueException if the year value is invalid * @see #withYear(int,DateResolver) */ public OffsetDate withYear(int year) { LocalDate newDate = date.withYear(year); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the year value altered. * If the resulting <code>OffsetDate</code> is invalid, it will be resolved using <code>dateResolver</code>. * <p> * This instance is immutable and unaffected by this method call. * * @param year the year to represent, from MIN_YEAR to MAX_YEAR * @param dateResolver the DateResolver to be used if the resulting date would be invalid * @return a new updated OffsetDate, never null * @throws IllegalCalendarFieldValueException if the year value is invalid */ public OffsetDate withYear(int year, DateResolver dateResolver) { LocalDate newDate = date.withYear(year, dateResolver); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the month of year value altered. * <p> * This method does the same as <code>withMonthOfYear(monthOfYear, DateResolvers.previousValid())</code>. * <p> * This instance is immutable and unaffected by this method call. * * @param monthOfYear the month of year to represent, from 1 (January) to 12 (December) * @return a new updated OffsetDate, never null * @throws IllegalCalendarFieldValueException if the month value is invalid * @see #withMonthOfYear(int,DateResolver) */ public OffsetDate withMonthOfYear(int monthOfYear) { LocalDate newDate = date.withMonthOfYear(monthOfYear); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the month of year value altered. * If the resulting <code>OffsetDate</code> is invalid, it will be resolved using <code>dateResolver</code>. * <p> * This instance is immutable and unaffected by this method call. * * @param monthOfYear the month of year to represent, from 1 (January) to 12 (December) * @param dateResolver the DateResolver to be used if the resulting date would be invalid * @return a new updated OffsetDate, never null * @throws IllegalCalendarFieldValueException if the month of year value is invalid */ public OffsetDate withMonthOfYear(int monthOfYear, DateResolver dateResolver) { LocalDate newDate = date.withMonthOfYear(monthOfYear, dateResolver); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the day of month value altered. * <p> * This instance is immutable and unaffected by this method call. * * @param dayOfMonth the day of month to represent, from 1 to 31 * @return a new updated OffsetDate, never null * @throws IllegalCalendarFieldValueException if the day of month value is invalid * @throws InvalidCalendarFieldException if the day of month is invalid for the month-year */ public OffsetDate withDayOfMonth(int dayOfMonth) { LocalDate newDate = date.withDayOfMonth(dayOfMonth); return newDate == date ? this : new OffsetDate(newDate, offset); } //----------------------------------------------------------------------- /** * Returns a copy of this OffsetDate with the specified period added. * <p> * This adds the amount in years, months and days from the specified period to this date. * Any time amounts, such as hours, minutes or seconds are ignored. * <p> * This instance is immutable and unaffected by this method call. * * @param periodProvider the period to add, not null * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range */ public OffsetDate plus(PeriodProvider periodProvider) { LocalDate newDate = date.plus(periodProvider); return newDate == date ? this : new OffsetDate(newDate, offset); } //----------------------------------------------------------------------- /** * Returns a copy of this OffsetDate with the specified period in years added. * <p> * This method add the specified amount to the years field in three steps: * <ol> * <li>Add the input years to the year field</li> * <li>Check if the resulting date would be invalid</li> * <li>Adjust the day of month to the last valid day if necessary</li> * </ol> * <p> * For example, 2008-02-29 (leap year) plus one year would result in the * invalid date 2009-02-29 (standard year). Instead of returning an invalid * result, the last valid day of the month, 2009-02-28, is selected instead. * <p> * This method does the same as <code>plusYears(years, DateResolvers.previousValid())</code>. * <p> * This instance is immutable and unaffected by this method call. * * @param years the years to add, may be negative * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range * @see #plusYears(int, javax.time.calendar.DateResolver) */ public OffsetDate plusYears(int years) { LocalDate newDate = date.plusYears(years); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the specified period in years added. * <p> * This method add the specified amount to the years field in three steps: * <ol> * <li>Add the input years to the year field</li> * <li>Check if the resulting date would be invalid</li> * <li>Adjust the date using <code>dateResolver</code> if necessary</li> * </ol> * <p> * This instance is immutable and unaffected by this method call. * * @param years the years to add, may be negative * @param dateResolver the DateResolver to be used if the resulting date would be invalid * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range */ public OffsetDate plusYears(int years, DateResolver dateResolver) { LocalDate newDate = date.plusYears(years, dateResolver); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the specified period in months added. * <p> * This method add the specified amount to the months field in three steps: * <ol> * <li>Add the input months to the month of year field</li> * <li>Check if the resulting date would be invalid</li> * <li>Adjust the day of month to the last valid day if necessary</li> * </ol> * <p> * For example, 2007-03-31 plus one month would result in the invalid date * 2007-04-31. Instead of returning an invalid result, the last valid day * of the month, 2007-04-30, is selected instead. * <p> * This method does the same as <code>plusMonths(months, DateResolvers.previousValid())</code>. * <p> * This instance is immutable and unaffected by this method call. * * @param months the months to add, may be negative * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range * @see #plusMonths(int, javax.time.calendar.DateResolver) */ public OffsetDate plusMonths(int months) { LocalDate newDate = date.plusMonths(months); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the specified period in months added. * <p> * This method add the specified amount to the months field in three steps: * <ol> * <li>Add the input months to the month of year field</li> * <li>Check if the resulting date would be invalid</li> * <li>Adjust the date using <code>dateResolver</code> if necessary</li> * </ol> * <p> * This instance is immutable and unaffected by this method call. * * @param months the months to add, may be negative * @param dateResolver the DateResolver to be used if the resulting date would be invalid * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range */ public OffsetDate plusMonths(int months, DateResolver dateResolver) { LocalDate newDate = date.plusMonths(months, dateResolver); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the specified period in weeks added. * <p> * This method add the specified amount in weeks to the days field incrementing * the month and year fields as necessary to ensure the result remains valid. * The result is only invalid if the maximum/minimum year is exceeded. * <p> * For example, 2008-12-31 plus one week would result in the 2009-01-07. * <p> * This instance is immutable and unaffected by this method call. * * @param weeks the weeks to add, may be negative * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range */ public OffsetDate plusWeeks(int weeks) { LocalDate newDate = date.plusWeeks(weeks); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the specified period in days added. * <p> * This method add the specified amount to the days field incrementing the * month and year fields as necessary to ensure the result remains valid. * The result is only invalid if the maximum/minimum year is exceeded. * <p> * For example, 2008-12-31 plus one day would result in the 2009-01-01. * <p> * This instance is immutable and unaffected by this method call. * * @param days the days to add, may be negative * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range */ public OffsetDate plusDays(long days) { LocalDate newDate = date.plusDays(days); return newDate == date ? this : new OffsetDate(newDate, offset); } //----------------------------------------------------------------------- /** * Returns a copy of this OffsetDate with the specified period subtracted. * <p> * This subtracts the amount in years, months and days from the specified period from this date. * Any time amounts, such as hours, minutes or seconds are ignored. * <p> * This instance is immutable and unaffected by this method call. * * @param periodProvider the period to subtract, not null * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range */ public OffsetDate minus(PeriodProvider periodProvider) { LocalDate newDate = date.minus(periodProvider); return newDate == date ? this : new OffsetDate(newDate, offset); } //----------------------------------------------------------------------- /** * Returns a copy of this OffsetDate with the specified period in years subtracted. * <p> * This method subtract the specified amount to the years field in three steps: * <ol> * <li>Subtract the input years to the year field</li> * <li>Check if the resulting date would be invalid</li> * <li>Adjust the day of month to the last valid day if necessary</li> * </ol> * <p> * For example, 2008-02-29 (leap year) minus one year would result in the * invalid date 2007-02-29 (standard year). Instead of returning an invalid * result, the last valid day of the month, 2007-02-28, is selected instead. * <p> * This method does the same as <code>minusYears(years, DateResolvers.previousValid())</code>. * <p> * This instance is immutable and unaffected by this method call. * * @param years the years to subtract, may be negative * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range * @see #minusYears(int, javax.time.calendar.DateResolver) */ public OffsetDate minusYears(int years) { LocalDate newDate = date.minusYears(years); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the specified period in years subtracted. * <p> * This method subtract the specified amount to the years field in three steps: * <ol> * <li>Subtract the input years to the year field</li> * <li>Check if the resulting date would be invalid</li> * <li>Adjust the date using <code>dateResolver</code> if necessary</li> * </ol> * <p> * This instance is immutable and unaffected by this method call. * * @param years the years to subtract, may be negative * @param dateResolver the DateResolver to be used if the resulting date would be invalid * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range */ public OffsetDate minusYears(int years, DateResolver dateResolver) { LocalDate newDate = date.minusYears(years, dateResolver); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the specified period in months subtracted. * <p> * This method subtract the specified amount to the months field in three steps: * <ol> * <li>Subtract the input months to the month of year field</li> * <li>Check if the resulting date would be invalid</li> * <li>Adjust the day of month to the last valid day if necessary</li> * </ol> * <p> * For example, 2007-03-31 minus one month would result in the invalid date * 2007-02-31. Instead of returning an invalid result, the last valid day * of the month, 2007-02-28, is selected instead. * <p> * This method does the same as <code>minusMonths(months, DateResolvers.previousValid())</code>. * <p> * This instance is immutable and unaffected by this method call. * * @param months the months to subtract, may be negative * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range * @see #minusMonths(int, javax.time.calendar.DateResolver) */ public OffsetDate minusMonths(int months) { LocalDate newDate = date.minusMonths(months); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the specified period in months subtracted. * <p> * This method subtract the specified amount to the months field in three steps: * <ol> * <li>Subtract the input months to the month of year field</li> * <li>Check if the resulting date would be invalid</li> * <li>Adjust the date using <code>dateResolver</code> if necessary</li> * </ol> * <p> * This instance is immutable and unaffected by this method call. * * @param months the months to subtract, may be negative * @param dateResolver the DateResolver to be used if the resulting date would be invalid * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range */ public OffsetDate minusMonths(int months, DateResolver dateResolver) { LocalDate newDate = date.minusMonths(months, dateResolver); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the specified period in weeks subtracted. * <p> * This method subtract the specified amount in weeks to the days field incrementing * the month and year fields as necessary to ensure the result remains valid. * The result is only invalid if the maximum/minimum year is exceeded. * <p> * For example, 2009-01-07 minus one week would result in the 2008-12-31. * <p> * This instance is immutable and unaffected by this method call. * * @param weeks the weeks to subtract, may be negative * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range */ public OffsetDate minusWeeks(int weeks) { LocalDate newDate = date.minusWeeks(weeks); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the specified number of days subtracted. * <p> * This method subtract the specified amount to the days field decrementing the * month and year fields as necessary to ensure the result remains valid. * The result is only invalid if the maximum/minimum year is exceeded. * <p> * For example, 2009-01-01 minus one day would result in the 2008-12-31. * <p> * This instance is immutable and unaffected by this method call. * * @param days the days to subtract, may be negative * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range */ public OffsetDate minusDays(long days) { LocalDate newDate = date.minusDays(days); return newDate == date ? this : new OffsetDate(newDate, offset); } //----------------------------------------------------------------------- /** * Checks whether this date matches the specified matcher. * <p> * Matchers can be used to query the date in unusual ways. Examples might * be a matcher that checks if the date is a weekend or holiday, or * Friday the Thirteenth. * <p> * The offset has no effect on the matching. * <p> * This instance is immutable and unaffected by this method call. * * @param matcher the matcher to use, not null * @return true if this date matches the matcher, false otherwise */ public boolean matches(DateMatcher matcher) { return date.matches(matcher); } //----------------------------------------------------------------------- /** * Checks if the date part of this object is equal to the input date * * @param date the date to match, not null * @return true if the date part matches the other date, false otherwise */ public boolean matchesDate(LocalDate date) { return this.date.matchesDate(date); } /** * Adjusts a date to have the value of the date part of this object. * * @param date the date to be adjusted, not null * @return the adjusted date, never null */ public LocalDate adjustDate(LocalDate date) { return matchesDate(date) ? date : this.date; } //----------------------------------------------------------------------- /** * Returns an offset date-time formed from this date at the specified time. * <p> * This merges the two objects - <code>this</code> and the specified time - * to form an instance of <code>OffsetDateTime</code>. * <p> * This instance is immutable and unaffected by this method call. * * @param time the time to use, not null * @return the offset date-time formed from this date and the specified time, never null */ public OffsetDateTime atTime(LocalTime time) { return OffsetDateTime.dateTime(this, time, getOffset()); } /** * Returns an offset date-time formed from this date at the time of midnight. * <p> * This merges the two objects - <code>this</code> and {@link LocalTime#MIDNIGHT} - * to form an instance of <code>OffsetDateTime</code>. * <p> * This instance is immutable and unaffected by this method call. * * @return the offset date-time formed from this date and the time of midnight, never null */ public OffsetDateTime atMidnight() { return OffsetDateTime.dateTime(this, LocalTime.MIDNIGHT, getOffset()); } /** * Returns a zoned date-time from this date at the earliest valid time according * to the rules in the time-zone ignoring the current offset. * <p> * Time-zone rules, such as daylight savings, mean that not every time on the * local time-line exists. When this method converts the date to a date-time it * adjusts the time and offset as necessary to ensure that the time is as early * as possible on the date, which is typically midnight. Internally this is * achieved using the {@link ZoneResolvers#postGapPreOverlap() zone resolver}. * <p> * To convert to a specific time in a given time-zone call {@link #atTime(LocalTime)} * followed by {@link OffsetDateTime#atZone(TimeZone)}. Note that the resolver used * by <code>atZone()</code> is different to that used here (it chooses the later * offset in an overlap, whereas this method chooses the earlier offset). * <p> * The offset from this date is ignored during the conversion. * This ensures that the resultant date-time has the same date as this. * <p> * This instance is immutable and unaffected by this method call. * * @param zone the time-zone to use, not null * @return the zoned date-time formed from this date and the earliest valid time for the zone, never null */ public ZonedDateTime atStartOfDayInZone(TimeZone zone) { return ZonedDateTime.dateTime(this, LocalTime.MIDNIGHT, zone, ZoneResolvers.postGapPreOverlap()); } //----------------------------------------------------------------------- /** * Converts this date to a <code>LocalDate</code>. * * @return a LocalDate with the same date as this instance, never null */ public LocalDate toLocalDate() { return date; } /** * Converts this date to a <code>Calendrical</code>. * * @return the calendrical representation for this instance, never null */ public Calendrical toCalendrical() { return new Calendrical(date, null, offset, null); } //----------------------------------------------------------------------- /** * Compares this date to another date based on the UTC equivalent dates * then local date. * <p> * This ordering is consistent with <code>equals()</code>. * For example, the following is the comparator order: * <ol> * <li>2008-06-29-11:00</li> * <li>2008-06-29-12:00</li> * <li>2008-06-30+12:00</li> * <li>2008-06-29-13:00</li> * </ol> * Values #2 and #3 represent the same instant on the time-line. * When two values represent the same instant, the local date is compared * to distinguish them. This step is needed to make the ordering * consistent with <code>equals()</code>. * * @param other the other date to compare to, not null * @return the comparator value, negative if less, positive if greater * @throws NullPointerException if <code>other</code> is null */ public int compareTo(OffsetDate other) { if (offset.equals(other.offset)) { return date.compareTo(other.date); } LocalDateTime thisDT = LocalDateTime.dateMidnight(getYear(), getMonthOfYear(), getDayOfMonth()); LocalDateTime otherDT = LocalDateTime.dateMidnight(other.getYear(), other.getMonthOfYear(), other.getDayOfMonth()); LocalDateTime thisUTC = thisDT.plusSeconds(-offset.getAmountSeconds()); LocalDateTime otherUTC = otherDT.plusSeconds(-other.offset.getAmountSeconds()); int compare = thisUTC.compareTo(otherUTC); if (compare == 0) { compare = date.compareTo(other.date); } return compare; } /** * Is this date after the specified date. * * @param other the other date to compare to, not null * @return true if this is after the specified date * @throws NullPointerException if <code>other</code> is null */ public boolean isAfter(OffsetDate other) { return compareTo(other) > 0; } /** * Is this date before the specified date. * * @param other the other date to compare to, not null * @return true if this point is before the specified date * @throws NullPointerException if <code>other</code> is null */ public boolean isBefore(OffsetDate other) { return compareTo(other) < 0; } //----------------------------------------------------------------------- /** * Is this date equal to the specified date. * <p> * This compares the date and the offset. * * @param other the other date to compare to, null returns false * @return true if this point is equal to the specified date */ @Override public boolean equals(Object other) { if (this == other) { return true; } if (other instanceof OffsetDate) { OffsetDate zonedDate = (OffsetDate) other; return date.equals(zonedDate.date) && offset.equals(zonedDate.offset); } return false; } /** * A hash code for this date. * * @return a suitable hash code */ @Override public int hashCode() { return date.hashCode() ^ offset.hashCode(); } //----------------------------------------------------------------------- /** * Outputs the date as a <code>String</code>, such as '2007-12-03+01:00'. * <p> * The output will be in the format 'yyyy-MM-ddZ' where 'Z' is the id of * the zone offset, such as '+02:30' or 'Z'. * * @return the formatted date string, never null */ @Override public String toString() { return date.toString() + offset.toString(); } }
src/main/java/javax/time/calendar/OffsetDate.java
/* * Copyright (c) 2007-2009, Stephen Colebourne & Michael Nascimento Santos * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of JSR-310 nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.time.calendar; import java.io.Serializable; import javax.time.CalendricalException; import javax.time.Instant; import javax.time.InstantProvider; import javax.time.calendar.field.DayOfMonth; import javax.time.calendar.field.DayOfWeek; import javax.time.calendar.field.DayOfYear; import javax.time.calendar.field.MonthOfYear; import javax.time.calendar.field.Year; import javax.time.period.PeriodProvider; /** * A date with a zone offset from UTC in the ISO-8601 calendar system, * such as '2007-12-03+01:00'. * <p> * OffsetDate is an immutable calendrical that represents a date, often viewed * as year-month-day-offset. This object can also sccess other date fields such as * day of year, day of week and week of year. * <p> * This class does not store or represent a time. * Thus, for example, the value "2nd October 2007 +02:00" can be stored * in a OffsetDate. * <p> * OffsetDate is immutable and thread-safe. * * @author Michael Nascimento Santos * @author Stephen Colebourne */ public final class OffsetDate implements CalendricalProvider, DateProvider, DateMatcher, DateAdjuster, Comparable<OffsetDate>, Serializable { /** * A serialization identifier for this class. */ private static final long serialVersionUID = -3618963189L; /** * The date. */ private final LocalDate date; /** * The zone offset. */ private final ZoneOffset offset; //----------------------------------------------------------------------- /** * Obtains an instance of <code>OffsetDate</code>. * * @param year the year to represent, not null * @param monthOfYear the month of year, not null * @param dayOfMonth the day of month to represent, not null * @param offset the zone offset, not null * @return the offset date, never null * @throws InvalidCalendarFieldException if the day of month is invalid for the month-year */ public static OffsetDate date(Year year, MonthOfYear monthOfYear, DayOfMonth dayOfMonth, ZoneOffset offset) { LocalDate date = LocalDate.date(year, monthOfYear, dayOfMonth); return new OffsetDate(date, offset); } /** * Obtains an instance of <code>OffsetDate</code>. * * @param year the year to represent, from MIN_VALUE + 1 to MAX_VALUE * @param monthOfYear the month of year, not null * @param dayOfMonth the day of month to represent, from 1 to 31 * @param offset the zone offset, not null * @return the offset date, never null * @throws IllegalCalendarFieldValueException if the value of any field is out of range * @throws InvalidCalendarFieldException if the day of month is invalid for the month-year */ public static OffsetDate date(int year, MonthOfYear monthOfYear, int dayOfMonth, ZoneOffset offset) { LocalDate date = LocalDate.date(year, monthOfYear, dayOfMonth); return new OffsetDate(date, offset); } /** * Obtains an instance of <code>OffsetDate</code>. * * @param year the year to represent, from MIN_VALUE + 1 to MAX_VALUE * @param monthOfYear the month of year to represent, from 1 (January) to 12 (December) * @param dayOfMonth the day of month to represent, from 1 to 31 * @param offset the zone offset, not null * @return the offset date, never null * @throws IllegalCalendarFieldValueException if the value of any field is out of range * @throws InvalidCalendarFieldException if the day of month is invalid for the month-year */ public static OffsetDate date(int year, int monthOfYear, int dayOfMonth, ZoneOffset offset) { LocalDate date = LocalDate.date(year, monthOfYear, dayOfMonth); return new OffsetDate(date, offset); } /** * Obtains an instance of <code>OffsetDate</code>. * * @param dateProvider the date provider to use, not null * @param offset the zone offset, not null * @return the offset date, never null */ public static OffsetDate date(DateProvider dateProvider, ZoneOffset offset) { LocalDate date = LocalDate.date(dateProvider); return new OffsetDate(date, offset); } //----------------------------------------------------------------------- /** * Converts an instant to an offset date. * <p> * This conversion drops the time component of the instant. * * @param instantProvider the instant to convert, not null * @param offset the zone offset, not null * @return the offset date, never null * @throws CalendarConversionException if the instant exceeds the supported date range */ public static OffsetDate fromInstant(InstantProvider instantProvider, ZoneOffset offset) { Instant instant = Instant.instant(instantProvider); ISOChronology.checkNotNull(offset, "ZoneOffset must not be null"); long epochSecs = instant.getEpochSeconds() + offset.getAmountSeconds(); // overflow caught later long yearZeroDays = (epochSecs / ISOChronology.SECONDS_PER_DAY) + ISOChronology.DAYS_0000_TO_1970; long secsOfDay = epochSecs % ISOChronology.SECONDS_PER_DAY; if (secsOfDay < 0) { yearZeroDays--; // overflow caught later } LocalDate date = LocalDate.fromYearZeroDays(yearZeroDays); return new OffsetDate(date, offset); } //----------------------------------------------------------------------- /** * Constructor. * * @param date the date, validated as not null * @param offset the zone offset, validated as not null */ private OffsetDate(LocalDate date, ZoneOffset offset) { if (date == null) { throw new NullPointerException("The date must not be null"); } if (offset == null) { throw new NullPointerException("The zone offset must not be null"); } this.date = date; this.offset = offset; } //----------------------------------------------------------------------- /** * Gets the chronology that describes the calendar system rules for * this date. * * @return the ISO chronology, never null */ public ISOChronology getChronology() { return ISOChronology.INSTANCE; } //----------------------------------------------------------------------- /** * Checks if the specified calendar field is supported. * <p> * This method queries whether this <code>OffsetDate</code> can * be queried using the specified calendar field. * * @param fieldRule the field to query, null returns false * @return true if the field is supported, false otherwise */ public boolean isSupported(DateTimeFieldRule fieldRule) { return date.isSupported(fieldRule); } /** * Gets the value of the specified calendar field. * <p> * This method queries the value of the specified calendar field. * If the calendar field is not supported then an exception is thrown. * * @param fieldRule the field to query, not null * @return the value for the field * @throws UnsupportedCalendarFieldException if no value for the field is found */ public int get(DateTimeFieldRule fieldRule) { return date.get(fieldRule); } //----------------------------------------------------------------------- /** * Gets the local date. * <p> * This returns the date without the zone offset. * * @return the local date, never null */ public LocalDate getDate() { return date; } /** * Returns a copy of this OffsetDate with a different local date. * <p> * This method changes the date stored to a different date. * No calculation is performed. The result simply represents the same * offset and the new date. * * @param dateProvider the local date to change to, not null * @return a new updated OffsetDate, never null */ public OffsetDate withDate(DateProvider dateProvider) { LocalDate localDate = LocalDate.date(dateProvider); return localDate.equals(this.date) ? this : new OffsetDate(localDate, offset); } //----------------------------------------------------------------------- /** * Gets the zone offset. * * @return the zone offset, never null */ public ZoneOffset getOffset() { return offset; } /** * Returns a copy of this OffsetTime with a different zone offset. * <p> * This method changes the offset stored to a different offset. * No calculation is performed. The result simply represents the same * local date and the new offset. * * @param offset the zone offset to change to, not null * @return a new updated OffsetDate, never null */ public OffsetDate withOffset(ZoneOffset offset) { return offset != null && offset.equals(this.offset) ? this : new OffsetDate(date, offset); } //----------------------------------------------------------------------- /** * Gets the year field as a <code>Year</code>. * <p> * This method provides access to an object representing the year field. * This allows operations to be performed on this field in a type-safe manner. * * @return the year, never null */ public Year toYear() { return date.toYear(); } /** * Gets the month of year field as a <code>MonthOfYear</code>. * <p> * This method provides access to an object representing the month of year field. * This allows operations to be performed on this field in a type-safe manner. * <p> * This method is the same as {@link #getMonthOfYear()}. * * @return the month of year, never null */ public MonthOfYear toMonthOfYear() { return date.toMonthOfYear(); } /** * Gets the day of month field as a <code>DayOfMonth</code>. * <p> * This method provides access to an object representing the day of month field. * This allows operations to be performed on this field in a type-safe manner. * * @return the day of month, never null */ public DayOfMonth toDayOfMonth() { return date.toDayOfMonth(); } /** * Gets the day of year field as a <code>DayOfYear</code>. * <p> * This method provides access to an object representing the day of year field. * This allows operations to be performed on this field in a type-safe manner. * * @return the day of year, never null */ public DayOfYear toDayOfYear() { return date.toDayOfYear(); } /** * Gets the day of week field as a <code>DayOfWeek</code>. * <p> * This method provides access to an object representing the day of week field. * This allows operations to be performed on this field in a type-safe manner. * <p> * This method is the same as {@link #getDayOfWeek()}. * * @return the day of week, never null */ public DayOfWeek toDayOfWeek() { return date.toDayOfWeek(); } //----------------------------------------------------------------------- /** * Gets the year field. * <p> * This method returns the primitive <code>int</code> value for the year. * <p> * Additional information about the year can be obtained from via {@link #toYear()}. * This returns a <code>Year</code> object which includes information on whether * this is a leap year and its length in days. It can also be used as a {@link DateMatcher} * and a {@link DateAdjuster}. * * @return the year, from MIN_YEAR to MAX_YEAR */ public int getYear() { return date.getYear(); } /** * Gets the month of year field, which is an enum <code>MonthOfYear</code>. * <p> * This method returns the enum {@link MonthOfYear} for the month. * This avoids confusion as to what <code>int</code> values mean. * If you need access to the primitive <code>int</code> value then the enum * provides the {@link MonthOfYear#getValue() int value}. * <p> * Additional information can be obtained from the <code>MonthOfYear</code>. * This includes month lengths, textual names and access to the quarter of year * and month of quarter values. * * @return the month of year, never null */ public MonthOfYear getMonthOfYear() { return date.getMonthOfYear(); } /** * Gets the day of month field. * <p> * This method returns the primitive <code>int</code> value for the day of month. * <p> * Additional information about the day of month can be obtained from via {@link #toDayOfMonth()}. * This returns a <code>DayOfMonth</code> object which can be used as a {@link DateMatcher} * and a {@link DateAdjuster}. * * @return the day of month, from 1 to 31 */ public int getDayOfMonth() { return date.getDayOfMonth(); } /** * Gets the day of year field. * <p> * This method returns the primitive <code>int</code> value for the day of year. * <p> * Additional information about the day of year can be obtained from via {@link #toDayOfYear()}. * This returns a <code>DayOfYear</code> object which can be used as a {@link DateMatcher} * and a {@link DateAdjuster}. * * @return the day of year, from 1 to 365, or 366 in a leap year */ public int getDayOfYear() { return date.getDayOfYear(); } public long toEpochDays() { return date.toEpochDays(); } /** * Gets the day of week field, which is an enum <code>DayOfWeek</code>. * <p> * This method returns the enum {@link DayOfWeek} for the day of week. * This avoids confusion as to what <code>int</code> values mean. * If you need access to the primitive <code>int</code> value then the enum * provides the {@link DayOfWeek#getValue() int value}. * <p> * Additional information can be obtained from the <code>DayOfWeek</code>. * This includes textual names of the values. * * @return the day of week, never null */ public DayOfWeek getDayOfWeek() { return date.getDayOfWeek(); } //----------------------------------------------------------------------- /** * Returns a copy of this OffsetDate with the date altered using the adjuster. * <p> * Adjusters can be used to alter the date in unusual ways. Examples might * be an adjuster that set the date avoiding weekends, or one that sets the * date to the last day of the month. * <p> * The offset has no effect on and is not affected by the adjustment. * <p> * This instance is immutable and unaffected by this method call. * * @param adjuster the adjuster to use, not null * @return a new updated OffsetDate, never null * @throws IllegalArgumentException if the adjuster returned null */ public OffsetDate with(DateAdjuster adjuster) { LocalDate newDate = date.with(adjuster); return newDate == date ? this : new OffsetDate(newDate, offset); } //----------------------------------------------------------------------- /** * Returns a copy of this OffsetDate with the year value altered. * <p> * This method does the same as <code>withYear(year, DateResolvers.previousValid())</code>. * <p> * This instance is immutable and unaffected by this method call. * * @param year the year to represent, from MIN_YEAR to MAX_YEAR * @return a new updated OffsetDate, never null * @throws IllegalCalendarFieldValueException if the year value is invalid * @see #withYear(int,DateResolver) */ public OffsetDate withYear(int year) { LocalDate newDate = date.withYear(year); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the year value altered. * If the resulting <code>OffsetDate</code> is invalid, it will be resolved using <code>dateResolver</code>. * <p> * This instance is immutable and unaffected by this method call. * * @param year the year to represent, from MIN_YEAR to MAX_YEAR * @param dateResolver the DateResolver to be used if the resulting date would be invalid * @return a new updated OffsetDate, never null * @throws IllegalCalendarFieldValueException if the year value is invalid */ public OffsetDate withYear(int year, DateResolver dateResolver) { LocalDate newDate = date.withYear(year, dateResolver); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the month of year value altered. * <p> * This method does the same as <code>withMonthOfYear(monthOfYear, DateResolvers.previousValid())</code>. * <p> * This instance is immutable and unaffected by this method call. * * @param monthOfYear the month of year to represent, from 1 (January) to 12 (December) * @return a new updated OffsetDate, never null * @throws IllegalCalendarFieldValueException if the month value is invalid * @see #withMonthOfYear(int,DateResolver) */ public OffsetDate withMonthOfYear(int monthOfYear) { LocalDate newDate = date.withMonthOfYear(monthOfYear); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the month of year value altered. * If the resulting <code>OffsetDate</code> is invalid, it will be resolved using <code>dateResolver</code>. * <p> * This instance is immutable and unaffected by this method call. * * @param monthOfYear the month of year to represent, from 1 (January) to 12 (December) * @param dateResolver the DateResolver to be used if the resulting date would be invalid * @return a new updated OffsetDate, never null * @throws IllegalCalendarFieldValueException if the month of year value is invalid */ public OffsetDate withMonthOfYear(int monthOfYear, DateResolver dateResolver) { LocalDate newDate = date.withMonthOfYear(monthOfYear, dateResolver); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the day of month value altered. * <p> * This instance is immutable and unaffected by this method call. * * @param dayOfMonth the day of month to represent, from 1 to 31 * @return a new updated OffsetDate, never null * @throws IllegalCalendarFieldValueException if the day of month value is invalid * @throws InvalidCalendarFieldException if the day of month is invalid for the month-year */ public OffsetDate withDayOfMonth(int dayOfMonth) { LocalDate newDate = date.withDayOfMonth(dayOfMonth); return newDate == date ? this : new OffsetDate(newDate, offset); } //----------------------------------------------------------------------- /** * Returns a copy of this OffsetDate with the specified period added. * <p> * This adds the amount in years, months and days from the specified period to this date. * Any time amounts, such as hours, minutes or seconds are ignored. * <p> * This instance is immutable and unaffected by this method call. * * @param periodProvider the period to add, not null * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range */ public OffsetDate plus(PeriodProvider periodProvider) { LocalDate newDate = date.plus(periodProvider); return newDate == date ? this : new OffsetDate(newDate, offset); } //----------------------------------------------------------------------- /** * Returns a copy of this OffsetDate with the specified period in years added. * <p> * This method add the specified amount to the years field in three steps: * <ol> * <li>Add the input years to the year field</li> * <li>Check if the resulting date would be invalid</li> * <li>Adjust the day of month to the last valid day if necessary</li> * </ol> * <p> * For example, 2008-02-29 (leap year) plus one year would result in the * invalid date 2009-02-29 (standard year). Instead of returning an invalid * result, the last valid day of the month, 2009-02-28, is selected instead. * <p> * This method does the same as <code>plusYears(years, DateResolvers.previousValid())</code>. * <p> * This instance is immutable and unaffected by this method call. * * @param years the years to add, may be negative * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range * @see #plusYears(int, javax.time.calendar.DateResolver) */ public OffsetDate plusYears(int years) { LocalDate newDate = date.plusYears(years); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the specified period in years added. * <p> * This method add the specified amount to the years field in three steps: * <ol> * <li>Add the input years to the year field</li> * <li>Check if the resulting date would be invalid</li> * <li>Adjust the date using <code>dateResolver</code> if necessary</li> * </ol> * <p> * This instance is immutable and unaffected by this method call. * * @param years the years to add, may be negative * @param dateResolver the DateResolver to be used if the resulting date would be invalid * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range */ public OffsetDate plusYears(int years, DateResolver dateResolver) { LocalDate newDate = date.plusYears(years, dateResolver); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the specified period in months added. * <p> * This method add the specified amount to the months field in three steps: * <ol> * <li>Add the input months to the month of year field</li> * <li>Check if the resulting date would be invalid</li> * <li>Adjust the day of month to the last valid day if necessary</li> * </ol> * <p> * For example, 2007-03-31 plus one month would result in the invalid date * 2007-04-31. Instead of returning an invalid result, the last valid day * of the month, 2007-04-30, is selected instead. * <p> * This method does the same as <code>plusMonths(months, DateResolvers.previousValid())</code>. * <p> * This instance is immutable and unaffected by this method call. * * @param months the months to add, may be negative * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range * @see #plusMonths(int, javax.time.calendar.DateResolver) */ public OffsetDate plusMonths(int months) { LocalDate newDate = date.plusMonths(months); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the specified period in months added. * <p> * This method add the specified amount to the months field in three steps: * <ol> * <li>Add the input months to the month of year field</li> * <li>Check if the resulting date would be invalid</li> * <li>Adjust the date using <code>dateResolver</code> if necessary</li> * </ol> * <p> * This instance is immutable and unaffected by this method call. * * @param months the months to add, may be negative * @param dateResolver the DateResolver to be used if the resulting date would be invalid * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range */ public OffsetDate plusMonths(int months, DateResolver dateResolver) { LocalDate newDate = date.plusMonths(months, dateResolver); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the specified period in weeks added. * <p> * This method add the specified amount in weeks to the days field incrementing * the month and year fields as necessary to ensure the result remains valid. * The result is only invalid if the maximum/minimum year is exceeded. * <p> * For example, 2008-12-31 plus one week would result in the 2009-01-07. * <p> * This instance is immutable and unaffected by this method call. * * @param weeks the weeks to add, may be negative * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range */ public OffsetDate plusWeeks(int weeks) { LocalDate newDate = date.plusWeeks(weeks); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the specified period in days added. * <p> * This method add the specified amount to the days field incrementing the * month and year fields as necessary to ensure the result remains valid. * The result is only invalid if the maximum/minimum year is exceeded. * <p> * For example, 2008-12-31 plus one day would result in the 2009-01-01. * <p> * This instance is immutable and unaffected by this method call. * * @param days the days to add, may be negative * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range */ public OffsetDate plusDays(long days) { LocalDate newDate = date.plusDays(days); return newDate == date ? this : new OffsetDate(newDate, offset); } //----------------------------------------------------------------------- /** * Returns a copy of this OffsetDate with the specified period subtracted. * <p> * This subtracts the amount in years, months and days from the specified period from this date. * Any time amounts, such as hours, minutes or seconds are ignored. * <p> * This instance is immutable and unaffected by this method call. * * @param periodProvider the period to subtract, not null * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range */ public OffsetDate minus(PeriodProvider periodProvider) { LocalDate newDate = date.minus(periodProvider); return newDate == date ? this : new OffsetDate(newDate, offset); } //----------------------------------------------------------------------- /** * Returns a copy of this OffsetDate with the specified period in years subtracted. * <p> * This method subtract the specified amount to the years field in three steps: * <ol> * <li>Subtract the input years to the year field</li> * <li>Check if the resulting date would be invalid</li> * <li>Adjust the day of month to the last valid day if necessary</li> * </ol> * <p> * For example, 2008-02-29 (leap year) minus one year would result in the * invalid date 2007-02-29 (standard year). Instead of returning an invalid * result, the last valid day of the month, 2007-02-28, is selected instead. * <p> * This method does the same as <code>minusYears(years, DateResolvers.previousValid())</code>. * <p> * This instance is immutable and unaffected by this method call. * * @param years the years to subtract, may be negative * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range * @see #minusYears(int, javax.time.calendar.DateResolver) */ public OffsetDate minusYears(int years) { LocalDate newDate = date.minusYears(years); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the specified period in years subtracted. * <p> * This method subtract the specified amount to the years field in three steps: * <ol> * <li>Subtract the input years to the year field</li> * <li>Check if the resulting date would be invalid</li> * <li>Adjust the date using <code>dateResolver</code> if necessary</li> * </ol> * <p> * This instance is immutable and unaffected by this method call. * * @param years the years to subtract, may be negative * @param dateResolver the DateResolver to be used if the resulting date would be invalid * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range */ public OffsetDate minusYears(int years, DateResolver dateResolver) { LocalDate newDate = date.minusYears(years, dateResolver); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the specified period in months subtracted. * <p> * This method subtract the specified amount to the months field in three steps: * <ol> * <li>Subtract the input months to the month of year field</li> * <li>Check if the resulting date would be invalid</li> * <li>Adjust the day of month to the last valid day if necessary</li> * </ol> * <p> * For example, 2007-03-31 minus one month would result in the invalid date * 2007-02-31. Instead of returning an invalid result, the last valid day * of the month, 2007-02-28, is selected instead. * <p> * This method does the same as <code>minusMonths(months, DateResolvers.previousValid())</code>. * <p> * This instance is immutable and unaffected by this method call. * * @param months the months to subtract, may be negative * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range * @see #minusMonths(int, javax.time.calendar.DateResolver) */ public OffsetDate minusMonths(int months) { LocalDate newDate = date.minusMonths(months); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the specified period in months subtracted. * <p> * This method subtract the specified amount to the months field in three steps: * <ol> * <li>Subtract the input months to the month of year field</li> * <li>Check if the resulting date would be invalid</li> * <li>Adjust the date using <code>dateResolver</code> if necessary</li> * </ol> * <p> * This instance is immutable and unaffected by this method call. * * @param months the months to subtract, may be negative * @param dateResolver the DateResolver to be used if the resulting date would be invalid * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range */ public OffsetDate minusMonths(int months, DateResolver dateResolver) { LocalDate newDate = date.minusMonths(months, dateResolver); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the specified period in weeks subtracted. * <p> * This method subtract the specified amount in weeks to the days field incrementing * the month and year fields as necessary to ensure the result remains valid. * The result is only invalid if the maximum/minimum year is exceeded. * <p> * For example, 2009-01-07 minus one week would result in the 2008-12-31. * <p> * This instance is immutable and unaffected by this method call. * * @param weeks the weeks to subtract, may be negative * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range */ public OffsetDate minusWeeks(int weeks) { LocalDate newDate = date.minusWeeks(weeks); return newDate == date ? this : new OffsetDate(newDate, offset); } /** * Returns a copy of this OffsetDate with the specified number of days subtracted. * <p> * This method subtract the specified amount to the days field decrementing the * month and year fields as necessary to ensure the result remains valid. * The result is only invalid if the maximum/minimum year is exceeded. * <p> * For example, 2009-01-01 minus one day would result in the 2008-12-31. * <p> * This instance is immutable and unaffected by this method call. * * @param days the days to subtract, may be negative * @return a new updated OffsetDate, never null * @throws CalendricalException if the result exceeds the supported date range */ public OffsetDate minusDays(long days) { LocalDate newDate = date.minusDays(days); return newDate == date ? this : new OffsetDate(newDate, offset); } //----------------------------------------------------------------------- /** * Checks whether this date matches the specified matcher. * <p> * Matchers can be used to query the date in unusual ways. Examples might * be a matcher that checks if the date is a weekend or holiday, or * Friday the Thirteenth. * <p> * The offset has no effect on the matching. * <p> * This instance is immutable and unaffected by this method call. * * @param matcher the matcher to use, not null * @return true if this date matches the matcher, false otherwise */ public boolean matches(DateMatcher matcher) { return date.matches(matcher); } //----------------------------------------------------------------------- /** * Checks if the date part of this object is equal to the input date * * @param date the date to match, not null * @return true if the date part matches the other date, false otherwise */ public boolean matchesDate(LocalDate date) { return this.date.matchesDate(date); } /** * Adjusts a date to have the value of the date part of this object. * * @param date the date to be adjusted, not null * @return the adjusted date, never null */ public LocalDate adjustDate(LocalDate date) { return matchesDate(date) ? date : this.date; } //----------------------------------------------------------------------- /** * Returns an offset date-time formed from this date at the specified time. * <p> * This merges the two objects - <code>this</code> and the specified time - * to form an instance of <code>OffsetDateTime</code>. * <p> * This instance is immutable and unaffected by this method call. * * @param time the time to use, not null * @return the offset date-time formed from this date and the specified time, never null */ public OffsetDateTime atTime(LocalTime time) { return OffsetDateTime.dateTime(this, time, getOffset()); } /** * Returns an offset date-time formed from this date at the time of midnight. * <p> * This merges the two objects - <code>this</code> and {@link LocalTime#MIDNIGHT} - * to form an instance of <code>OffsetDateTime</code>. * <p> * This instance is immutable and unaffected by this method call. * * @return the offset date-time formed from this date and the time of midnight, never null */ public OffsetDateTime atMidnight() { return OffsetDateTime.dateTime(this, LocalTime.MIDNIGHT, getOffset()); } /** * Returns a zoned date-time from this date at the earliest valid time according * to the rules in the time-zone ignoring the current offset. * <p> * Time-zone rules, such as daylight savings, mean that not every time on the * local time-line exists. When this method converts the date to a date-time it * adjusts the time and offset as necessary to ensure that the time is as early * as possible on the date, which is typically midnight. Internally this is * achieved using the {@link ZoneResolvers#postGapPreOverlap() zone resolver}. * <p> * To convert to a specific time in a given time-zone call {@link #atTime(LocalTime)} * followed by {@link OffsetDateTime#atZone(TimeZone)}. Note that the resolver used * by <code>atZone()</code> is different to that used here (it chooses the later * offset in an overlap, whereas this method chooses the earlier offset). * <p> * The offset from this date is ignored during the conversion. * This ensures that the resultant date-time has the same date as this. * <p> * This instance is immutable and unaffected by this method call. * * @param zone the time-zone to use, not null * @return the zoned date-time formed from this date and the earliest valid time for the zone, never null */ public ZonedDateTime atStartOfDayInZone(TimeZone zone) { return ZonedDateTime.dateTime(this, LocalTime.MIDNIGHT, zone, ZoneResolvers.postGapPreOverlap()); } //----------------------------------------------------------------------- /** * Converts this date to a <code>LocalDate</code>. * * @return a LocalDate with the same date as this instance, never null */ public LocalDate toLocalDate() { return date; } /** * Converts this date to a <code>Calendrical</code>. * * @return the calendrical representation for this instance, never null */ public Calendrical toCalendrical() { return new Calendrical(date, null, offset, null); } //----------------------------------------------------------------------- /** * Compares this date to another date based on the UTC equivalent dates * then local date. * <p> * This ordering is consistent with <code>equals()</code>. * For example, the following is the comparator order: * <ol> * <li>2008-06-29-11:00</li> * <li>2008-06-29-12:00</li> * <li>2008-06-30+12:00</li> * <li>2008-06-29-13:00</li> * </ol> * Values #2 and #3 represent the same instant on the time-line. * When two values represent the same instant, the local date is compared * to distinguish them. This step is needed to make the ordering * consistent with <code>equals()</code>. * * @param other the other date to compare to, not null * @return the comparator value, negative if less, positive if greater * @throws NullPointerException if <code>other</code> is null */ public int compareTo(OffsetDate other) { if (offset.equals(other.offset)) { return date.compareTo(other.date); } LocalDateTime thisDT = LocalDateTime.dateMidnight(getYear(), getMonthOfYear(), getDayOfMonth()); LocalDateTime otherDT = LocalDateTime.dateMidnight(other.getYear(), other.getMonthOfYear(), other.getDayOfMonth()); LocalDateTime thisUTC = thisDT.plusSeconds(-offset.getAmountSeconds()); LocalDateTime otherUTC = otherDT.plusSeconds(-other.offset.getAmountSeconds()); int compare = thisUTC.compareTo(otherUTC); if (compare == 0) { compare = date.compareTo(other.date); } return compare; } /** * Is this date after the specified date. * * @param other the other date to compare to, not null * @return true if this is after the specified date * @throws NullPointerException if <code>other</code> is null */ public boolean isAfter(OffsetDate other) { return compareTo(other) > 0; } /** * Is this date before the specified date. * * @param other the other date to compare to, not null * @return true if this point is before the specified date * @throws NullPointerException if <code>other</code> is null */ public boolean isBefore(OffsetDate other) { return compareTo(other) < 0; } //----------------------------------------------------------------------- /** * Is this date equal to the specified date. * <p> * This compares the date and the offset. * * @param other the other date to compare to, null returns false * @return true if this point is equal to the specified date */ @Override public boolean equals(Object other) { if (this == other) { return true; } if (other instanceof OffsetDate) { OffsetDate zonedDate = (OffsetDate) other; return date.equals(zonedDate.date) && offset.equals(zonedDate.offset); } return false; } /** * A hash code for this date. * * @return a suitable hash code */ @Override public int hashCode() { return date.hashCode() ^ offset.hashCode(); } //----------------------------------------------------------------------- /** * Outputs the date as a <code>String</code>, such as '2007-12-03+01:00'. * <p> * The output will be in the format 'yyyy-MM-ddZ' where 'Z' is the id of * the zone offset, such as '+02:30' or 'Z'. * * @return the formatted date string, never null */ @Override public String toString() { return date.toString() + offset.toString(); } }
Revert previous change git-svn-id: 17e42e1b38baac66ab68ec9830049dead5ccbb9b@719 291d795c-afe8-5c46-8ee5-bf9dd72e1864
src/main/java/javax/time/calendar/OffsetDate.java
Revert previous change
<ide><path>rc/main/java/javax/time/calendar/OffsetDate.java <ide> public int getDayOfYear() { <ide> return date.getDayOfYear(); <ide> } <del> <del> public long toEpochDays() { <del> return date.toEpochDays(); <del> } <ide> <ide> /** <ide> * Gets the day of week field, which is an enum <code>DayOfWeek</code>.
Java
apache-2.0
error: pathspec 'modules/api-import-export/src/main/java/org/wso2/carbon/apimgt/importexport/utils/YAMLUtils.java' did not match any file(s) known to git
beaaa187fb49b5ff9b65d71332726ae28b709858
1
tharikaGitHub/product-apim,jaadds/product-apim,wso2/product-apim,chamilaadhi/product-apim,chamilaadhi/product-apim,chamilaadhi/product-apim,wso2/product-apim,wso2/product-apim,wso2/product-apim,tharikaGitHub/product-apim,jaadds/product-apim,tharikaGitHub/product-apim,wso2/product-apim,chamilaadhi/product-apim,jaadds/product-apim,tharikaGitHub/product-apim,tharikaGitHub/product-apim,jaadds/product-apim,chamilaadhi/product-apim
package org.wso2.carbon.apimgt.importexport.utils; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator; import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; import java.io.IOException; public class YAMLUtils { public static String YamlToJson(String yaml) throws IOException { ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory()); Object obj = yamlReader.readValue(yaml, Object.class); ObjectMapper jsonWriter = new ObjectMapper(); return jsonWriter.writeValueAsString(obj); } public static String JsonToYaml(String json) throws IOException { ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory().enable(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER)); JsonNode jsonNodeTree = yamlReader.readTree(json); YAMLMapper yamlMapper = new YAMLMapper() .disable(YAMLGenerator.Feature.SPLIT_LINES) .enable(YAMLGenerator.Feature.INDENT_ARRAYS) .disable(YAMLGenerator.Feature.LITERAL_BLOCK_STYLE) .disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER) .enable(YAMLGenerator.Feature.MINIMIZE_QUOTES) .enable(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS); return yamlMapper.writeValueAsString(jsonNodeTree); } }
modules/api-import-export/src/main/java/org/wso2/carbon/apimgt/importexport/utils/YAMLUtils.java
added yaml utils
modules/api-import-export/src/main/java/org/wso2/carbon/apimgt/importexport/utils/YAMLUtils.java
added yaml utils
<ide><path>odules/api-import-export/src/main/java/org/wso2/carbon/apimgt/importexport/utils/YAMLUtils.java <add>package org.wso2.carbon.apimgt.importexport.utils; <add> <add>import com.fasterxml.jackson.core.JsonParser; <add>import com.fasterxml.jackson.databind.JsonNode; <add>import com.fasterxml.jackson.databind.ObjectMapper; <add>import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; <add>import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator; <add>import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; <add> <add>import java.io.IOException; <add> <add>public class YAMLUtils { <add> <add> public static String YamlToJson(String yaml) throws IOException { <add> ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory()); <add> Object obj = yamlReader.readValue(yaml, Object.class); <add> <add> ObjectMapper jsonWriter = new ObjectMapper(); <add> return jsonWriter.writeValueAsString(obj); <add> } <add> <add> public static String JsonToYaml(String json) throws IOException { <add> ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory().enable(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER)); <add> JsonNode jsonNodeTree = yamlReader.readTree(json); <add> YAMLMapper yamlMapper = new YAMLMapper() <add> .disable(YAMLGenerator.Feature.SPLIT_LINES) <add> .enable(YAMLGenerator.Feature.INDENT_ARRAYS) <add> .disable(YAMLGenerator.Feature.LITERAL_BLOCK_STYLE) <add> .disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER) <add> .enable(YAMLGenerator.Feature.MINIMIZE_QUOTES) <add> .enable(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS); <add> return yamlMapper.writeValueAsString(jsonNodeTree); <add> } <add>} <add>
Java
agpl-3.0
1ab7a895123c083e6b1c5faa12b81065718ec0a8
0
creative-quant/voltdb,kumarrus/voltdb,kumarrus/voltdb,simonzhangsm/voltdb,flybird119/voltdb,kumarrus/voltdb,flybird119/voltdb,creative-quant/voltdb,paulmartel/voltdb,deerwalk/voltdb,creative-quant/voltdb,simonzhangsm/voltdb,flybird119/voltdb,wolffcm/voltdb,migue/voltdb,wolffcm/voltdb,paulmartel/voltdb,wolffcm/voltdb,ingted/voltdb,VoltDB/voltdb,zuowang/voltdb,deerwalk/voltdb,creative-quant/voltdb,wolffcm/voltdb,ingted/voltdb,ingted/voltdb,kumarrus/voltdb,migue/voltdb,deerwalk/voltdb,migue/voltdb,paulmartel/voltdb,paulmartel/voltdb,migue/voltdb,zuowang/voltdb,deerwalk/voltdb,VoltDB/voltdb,kumarrus/voltdb,VoltDB/voltdb,flybird119/voltdb,simonzhangsm/voltdb,ingted/voltdb,migue/voltdb,migue/voltdb,zuowang/voltdb,wolffcm/voltdb,creative-quant/voltdb,deerwalk/voltdb,flybird119/voltdb,kumarrus/voltdb,flybird119/voltdb,ingted/voltdb,VoltDB/voltdb,flybird119/voltdb,creative-quant/voltdb,simonzhangsm/voltdb,creative-quant/voltdb,migue/voltdb,zuowang/voltdb,paulmartel/voltdb,VoltDB/voltdb,ingted/voltdb,deerwalk/voltdb,paulmartel/voltdb,zuowang/voltdb,zuowang/voltdb,simonzhangsm/voltdb,paulmartel/voltdb,kumarrus/voltdb,kumarrus/voltdb,migue/voltdb,wolffcm/voltdb,VoltDB/voltdb,ingted/voltdb,creative-quant/voltdb,deerwalk/voltdb,paulmartel/voltdb,zuowang/voltdb,simonzhangsm/voltdb,simonzhangsm/voltdb,zuowang/voltdb,flybird119/voltdb,wolffcm/voltdb,VoltDB/voltdb,ingted/voltdb,deerwalk/voltdb,simonzhangsm/voltdb,wolffcm/voltdb
/* This file is part of VoltDB. * Copyright (C) 2008-2014 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.lang.management.ManagementFactory; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.SortedMap; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.cassandra_voltpatches.GCInspector; import org.apache.log4j.Appender; import org.apache.log4j.DailyRollingFileAppender; import org.apache.log4j.FileAppender; import org.apache.log4j.Logger; import org.apache.zookeeper_voltpatches.CreateMode; import org.apache.zookeeper_voltpatches.KeeperException; import org.apache.zookeeper_voltpatches.WatchedEvent; import org.apache.zookeeper_voltpatches.Watcher; import org.apache.zookeeper_voltpatches.ZooDefs.Ids; import org.apache.zookeeper_voltpatches.ZooKeeper; import org.apache.zookeeper_voltpatches.data.Stat; import org.json_voltpatches.JSONException; import org.json_voltpatches.JSONObject; import org.json_voltpatches.JSONStringer; import org.voltcore.logging.Level; import org.voltcore.logging.VoltLogger; import org.voltcore.messaging.HostMessenger; import org.voltcore.messaging.SiteMailbox; import org.voltcore.utils.CoreUtils; import org.voltcore.utils.OnDemandBinaryLogger; import org.voltcore.utils.Pair; import org.voltcore.utils.ShutdownHooks; import org.voltcore.zk.ZKCountdownLatch; import org.voltcore.zk.ZKUtil; import org.voltdb.TheHashinator.HashinatorType; import org.voltdb.catalog.Catalog; import org.voltdb.catalog.Cluster; import org.voltdb.catalog.Database; import org.voltdb.catalog.SnapshotSchedule; import org.voltdb.compiler.AdHocCompilerCache; import org.voltdb.compiler.AsyncCompilerAgent; import org.voltdb.compiler.ClusterConfig; import org.voltdb.compiler.deploymentfile.DeploymentType; import org.voltdb.compiler.deploymentfile.HeartbeatType; import org.voltdb.compiler.deploymentfile.UsersType; import org.voltdb.dtxn.InitiatorStats; import org.voltdb.dtxn.LatencyHistogramStats; import org.voltdb.dtxn.LatencyStats; import org.voltdb.dtxn.SiteTracker; import org.voltdb.export.ExportManager; import org.voltdb.iv2.Cartographer; import org.voltdb.iv2.Initiator; import org.voltdb.iv2.KSafetyStats; import org.voltdb.iv2.LeaderAppointer; import org.voltdb.iv2.MpInitiator; import org.voltdb.iv2.SpInitiator; import org.voltdb.iv2.TxnEgo; import org.voltdb.join.BalancePartitionsStatistics; import org.voltdb.join.ElasticJoinService; import org.voltdb.licensetool.LicenseApi; import org.voltdb.messaging.VoltDbMessageFactory; import org.voltdb.planner.ActivePlanRepository; import org.voltdb.rejoin.Iv2RejoinCoordinator; import org.voltdb.rejoin.JoinCoordinator; import org.voltdb.utils.CLibrary; import org.voltdb.utils.CatalogUtil; import org.voltdb.utils.CatalogUtil.CatalogAndIds; import org.voltdb.utils.Encoder; import org.voltdb.utils.HTTPAdminListener; import org.voltdb.utils.LogKeys; import org.voltdb.utils.MiscUtils; import org.voltdb.utils.PlatformProperties; import org.voltdb.utils.SystemStatsCollector; import org.voltdb.utils.VoltSampler; import com.google_voltpatches.common.base.Charsets; import com.google_voltpatches.common.base.Throwables; import com.google_voltpatches.common.collect.ImmutableList; import com.google_voltpatches.common.util.concurrent.ListenableFuture; import com.google_voltpatches.common.util.concurrent.ListeningExecutorService; import com.google_voltpatches.common.util.concurrent.SettableFuture; /** * RealVoltDB initializes global server components, like the messaging * layer, ExecutionSite(s), and ClientInterface. It provides accessors * or references to those global objects. It is basically the global * namespace. A lot of the global namespace is described by VoltDBInterface * to allow test mocking. */ public class RealVoltDB implements VoltDBInterface, RestoreAgent.Callback { private static final boolean DISABLE_JMX; static { DISABLE_JMX = Boolean.valueOf(System.getProperty("DISABLE_JMX", "false")); } private static final VoltLogger hostLog = new VoltLogger("HOST"); private static final VoltLogger consoleLog = new VoltLogger("CONSOLE"); /** Default deployment file contents if path to deployment is null */ private static final String[] defaultDeploymentXML = { "<?xml version=\"1.0\"?>", "<!-- IMPORTANT: This file is an auto-generated default deployment configuration.", " Changes to this file will be overwritten. Copy it elsewhere if you", " want to use it as a starting point for a custom configuration. -->", "<deployment>", " <cluster hostcount=\"1\" />", " <httpd enabled=\"true\">", " <jsonapi enabled=\"true\" />", " </httpd>", "</deployment>" }; public VoltDB.Configuration m_config = new VoltDB.Configuration(); int m_configuredNumberOfPartitions; int m_configuredReplicationFactor; // CatalogContext is immutable, just make sure that accessors see a consistent version volatile CatalogContext m_catalogContext; private String m_buildString; static final String m_defaultVersionString = "4.8"; // by default set the version to only be compatible with itself static final String m_defaultHotfixableRegexPattern = "^\\Q4.8\\E\\z"; // these next two are non-static because they can be overrriden on the CLI for test private String m_versionString = m_defaultVersionString; private String m_hotfixableRegexPattern = m_defaultHotfixableRegexPattern; HostMessenger m_messenger = null; private ClientInterface m_clientInterface = null; HTTPAdminListener m_adminListener; private OpsRegistrar m_opsRegistrar = new OpsRegistrar(); private AsyncCompilerAgent m_asyncCompilerAgent = new AsyncCompilerAgent(); public AsyncCompilerAgent getAsyncCompilerAgent() { return m_asyncCompilerAgent; } private PartitionCountStats m_partitionCountStats = null; private IOStats m_ioStats = null; private MemoryStats m_memoryStats = null; private CpuStats m_cpuStats = null; private StatsManager m_statsManager = null; private SnapshotCompletionMonitor m_snapshotCompletionMonitor; // These are unused locally, but they need to be registered with the StatsAgent so they're // globally available @SuppressWarnings("unused") private InitiatorStats m_initiatorStats; private LiveClientsStats m_liveClientsStats = null; int m_myHostId; String m_httpPortExtraLogMessage = null; boolean m_jsonEnabled; DeploymentType m_deployment; // IV2 things List<Initiator> m_iv2Initiators = new ArrayList<Initiator>(); Cartographer m_cartographer = null; LeaderAppointer m_leaderAppointer = null; GlobalServiceElector m_globalServiceElector = null; MpInitiator m_MPI = null; Map<Integer, Long> m_iv2InitiatorStartingTxnIds = new HashMap<Integer, Long>(); // Should the execution sites be started in recovery mode // (used for joining a node to an existing cluster) // If CL is enabled this will be set to true // by the CL when the truncation snapshot completes // and this node is viable for replay volatile boolean m_rejoining = false; // Need to separate the concepts of rejoin data transfer and rejoin // completion. This boolean tracks whether or not the data transfer // process is done. CL truncation snapshots will not flip the all-complete // boolean until no mode data is pending. // Yes, this is fragile having two booleans. We could aggregate them into // some rejoining state enum at some point. volatile boolean m_rejoinDataPending = false; // Since m_rejoinDataPending is set asynchronously, sites could have inconsistent // view of what the value is during the execution of a sysproc. Use this and // m_safeMpTxnId to prevent the race. The m_safeMpTxnId is updated once in the // lifetime of the node to reflect the first MP txn that witnessed the flip of // m_rejoinDataPending. private final Object m_safeMpTxnIdLock = new Object(); private long m_lastSeenMpTxnId = Long.MIN_VALUE; private long m_safeMpTxnId = Long.MAX_VALUE; String m_rejoinTruncationReqId = null; // Are we adding the node to the cluster instead of rejoining? volatile boolean m_joining = false; boolean m_replicationActive = false; private NodeDRGateway m_nodeDRGateway = null; //Only restrict recovery completion during test static Semaphore m_testBlockRecoveryCompletion = new Semaphore(Integer.MAX_VALUE); private long m_executionSiteRecoveryFinish; private long m_executionSiteRecoveryTransferred; // Rejoin coordinator private JoinCoordinator m_joinCoordinator = null; private ElasticJoinService m_elasticJoinService = null; // Snapshot IO agent private SnapshotIOAgent m_snapshotIOAgent = null; // id of the leader, or the host restore planner says has the catalog int m_hostIdWithStartupCatalog; String m_pathToStartupCatalog; // Synchronize initialize and shutdown private final Object m_startAndStopLock = new Object(); // Synchronize updates of catalog contexts across the multiple sites on this host. // Ensure that the first site to reach catalogUpdate() does all the work and that no // others enter until that's finished. CatalogContext is immutable and volatile, accessors // should be able to always get a valid context without needing this lock. private final Object m_catalogUpdateLock = new Object(); // add a random number to the sampler output to make it likely to be unique for this process. private final VoltSampler m_sampler = new VoltSampler(10, "sample" + String.valueOf(new Random().nextInt() % 10000) + ".txt"); private final AtomicBoolean m_hasStartedSampler = new AtomicBoolean(false); List<Integer> m_partitionsToSitesAtStartupForExportInit; RestoreAgent m_restoreAgent = null; private ListeningExecutorService m_es = CoreUtils.getCachedSingleThreadExecutor("StartAction ZK Watcher", 15000); private volatile boolean m_isRunning = false; @Override public boolean rejoining() { return m_rejoining; } @Override public boolean rejoinDataPending() { return m_rejoinDataPending; } @Override public boolean isMpSysprocSafeToExecute(long txnId) { synchronized (m_safeMpTxnIdLock) { if (txnId >= m_safeMpTxnId) { return true; } if (txnId > m_lastSeenMpTxnId) { m_lastSeenMpTxnId = txnId; if (!rejoinDataPending() && m_safeMpTxnId == Long.MAX_VALUE) { m_safeMpTxnId = txnId; } } return txnId >= m_safeMpTxnId; } } private long m_recoveryStartTime; CommandLog m_commandLog; private volatile OperationMode m_mode = OperationMode.INITIALIZING; private OperationMode m_startMode = null; volatile String m_localMetadata = ""; private ListeningExecutorService m_computationService; private Thread m_configLogger; // methods accessed via the singleton @Override public void startSampler() { if (m_hasStartedSampler.compareAndSet(false, true)) { m_sampler.start(); } } private ScheduledThreadPoolExecutor m_periodicWorkThread; private ScheduledThreadPoolExecutor m_periodicPriorityWorkThread; // The configured license api: use to decide enterprise/community edition feature enablement LicenseApi m_licenseApi; @SuppressWarnings("unused") private LatencyStats m_latencyStats; private LatencyHistogramStats m_latencyHistogramStats; @Override public LicenseApi getLicenseApi() { return m_licenseApi; } /** * Initialize all the global components, then initialize all the m_sites. */ @Override public void initialize(VoltDB.Configuration config) { ShutdownHooks.enableServerStopLogging(); synchronized(m_startAndStopLock) { // check that this is a 64 bit VM if (System.getProperty("java.vm.name").contains("64") == false) { hostLog.fatal("You are running on an unsupported (probably 32 bit) JVM. Exiting."); System.exit(-1); } consoleLog.l7dlog( Level.INFO, LogKeys.host_VoltDB_StartupString.name(), null); // If there's no deployment provide a default and put it under voltdbroot. if (config.m_pathToDeployment == null) { try { config.m_pathToDeployment = setupDefaultDeployment(); config.m_deploymentDefault = true; } catch (IOException e) { VoltDB.crashLocalVoltDB("Failed to write default deployment.", false, null); } } // set the mode first thing m_mode = OperationMode.INITIALIZING; m_config = config; m_startMode = null; // set a bunch of things to null/empty/new for tests // which reusue the process m_safeMpTxnId = Long.MAX_VALUE; m_lastSeenMpTxnId = Long.MIN_VALUE; m_clientInterface = null; m_adminListener = null; m_commandLog = new DummyCommandLog(); m_deployment = null; m_messenger = null; m_startMode = null; m_opsRegistrar = new OpsRegistrar(); m_asyncCompilerAgent = new AsyncCompilerAgent(); m_snapshotCompletionMonitor = null; m_catalogContext = null; m_partitionCountStats = null; m_ioStats = null; m_memoryStats = null; m_statsManager = null; m_restoreAgent = null; m_recoveryStartTime = System.currentTimeMillis(); m_hostIdWithStartupCatalog = 0; m_pathToStartupCatalog = m_config.m_pathToCatalog; m_replicationActive = false; m_configLogger = null; ActivePlanRepository.clear(); // set up site structure final int computationThreads = Math.max(2, CoreUtils.availableProcessors() / 4); m_computationService = CoreUtils.getListeningExecutorService( "Computation service thread", computationThreads, m_config.m_computationCoreBindings); // determine if this is a rejoining node // (used for license check and later the actual rejoin) boolean isRejoin = false; if (config.m_startAction.doesRejoin()) { isRejoin = true; } m_rejoining = isRejoin; m_rejoinDataPending = isRejoin || config.m_startAction == StartAction.JOIN; m_joining = config.m_startAction == StartAction.JOIN; // Set std-out/err to use the UTF-8 encoding and fail if UTF-8 isn't supported try { System.setOut(new PrintStream(System.out, true, "UTF-8")); System.setErr(new PrintStream(System.err, true, "UTF-8")); } catch (UnsupportedEncodingException e) { hostLog.fatal("Support for the UTF-8 encoding is required for VoltDB. This means you are likely running an unsupported JVM. Exiting."); System.exit(-1); } m_snapshotCompletionMonitor = new SnapshotCompletionMonitor(); readBuildInfo(config.m_isEnterprise ? "Enterprise Edition" : "Community Edition"); // Replay command line args that we can see StringBuilder sb = new StringBuilder(2048).append("Command line arguments: "); sb.append(System.getProperty("sun.java.command", "[not available]")); hostLog.info(sb.toString()); List<String> iargs = ManagementFactory.getRuntimeMXBean().getInputArguments(); sb.delete(0, sb.length()).append("Command line JVM arguments:"); for (String iarg : iargs) sb.append(" ").append(iarg); if (iargs.size() > 0) hostLog.info(sb.toString()); else hostLog.info("No JVM command line args known."); sb.delete(0, sb.length()).append("Command line JVM classpath: "); sb.append(System.getProperty("java.class.path", "[not available]")); hostLog.info(sb.toString()); // use CLI overrides for testing hotfix version compatibility if (m_config.m_versionStringOverrideForTest != null) { m_versionString = m_config.m_versionStringOverrideForTest; } if (m_config.m_versionCompatibilityRegexOverrideForTest != null) { m_hotfixableRegexPattern = m_config.m_versionCompatibilityRegexOverrideForTest; } buildClusterMesh(isRejoin || m_joining); //Register dummy agents immediately m_opsRegistrar.registerMailboxes(m_messenger); //Start validating the build string in the background final Future<?> buildStringValidation = validateBuildString(getBuildString(), m_messenger.getZK()); // race to create start action nodes and then verify theirs compatibility. m_messenger.getZK().create(VoltZK.start_action, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new ZKUtil.StringCallback(), null); VoltZK.createStartActionNode(m_messenger.getZK(), m_messenger.getHostId(), m_config.m_startAction); validateStartAction(); final int numberOfNodes = readDeploymentAndCreateStarterCatalogContext(); if (!isRejoin && !m_joining) { m_messenger.waitForGroupJoin(numberOfNodes); } // Create the thread pool here. It's needed by buildClusterMesh() m_periodicWorkThread = CoreUtils.getScheduledThreadPoolExecutor("Periodic Work", 1, CoreUtils.SMALL_STACK_SIZE); m_periodicPriorityWorkThread = CoreUtils.getScheduledThreadPoolExecutor("Periodic Priority Work", 1, CoreUtils.SMALL_STACK_SIZE); Class<?> snapshotIOAgentClass = MiscUtils.loadProClass("org.voltdb.SnapshotIOAgentImpl", "Snapshot", true); if (snapshotIOAgentClass != null) { try { m_snapshotIOAgent = (SnapshotIOAgent) snapshotIOAgentClass.getConstructor(HostMessenger.class, long.class) .newInstance(m_messenger, m_messenger.getHSIdForLocalSite(HostMessenger.SNAPSHOT_IO_AGENT_ID)); m_messenger.createMailbox(m_snapshotIOAgent.getHSId(), m_snapshotIOAgent); } catch (Exception e) { VoltDB.crashLocalVoltDB("Failed to instantiate snapshot IO agent", true, e); } } if (m_config.m_pathToLicense == null) { m_licenseApi = MiscUtils.licenseApiFactory(); if (m_licenseApi == null) { hostLog.fatal("Unable to open license file in default directories"); } } else { m_licenseApi = MiscUtils.licenseApiFactory(m_config.m_pathToLicense); if (m_licenseApi == null) { hostLog.fatal("Unable to open license file in provided path: " + m_config.m_pathToLicense); } } if (m_licenseApi == null) { hostLog.fatal("Please contact [email protected] to request a license."); VoltDB.crashLocalVoltDB("Failed to initialize license verifier. " + "See previous log message for details.", false, null); } // Create the GlobalServiceElector. Do this here so we can register the MPI with it // when we construct it below m_globalServiceElector = new GlobalServiceElector(m_messenger.getZK(), m_messenger.getHostId()); // Start the GlobalServiceElector. Not sure where this will actually belong. try { m_globalServiceElector.start(); } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to start GlobalServiceElector", true, e); } // Always create a mailbox for elastic join data transfer if (m_config.m_isEnterprise) { long elasticHSId = m_messenger.getHSIdForLocalSite(HostMessenger.REBALANCE_SITE_ID); m_messenger.createMailbox(elasticHSId, new SiteMailbox(m_messenger, elasticHSId)); } if (m_joining) { Class<?> elasticJoinCoordClass = MiscUtils.loadProClass("org.voltdb.join.ElasticJoinNodeCoordinator", "Elastic", false); try { Constructor<?> constructor = elasticJoinCoordClass.getConstructor(HostMessenger.class, String.class); m_joinCoordinator = (JoinCoordinator) constructor.newInstance(m_messenger, m_catalogContext.cluster.getVoltroot()); m_messenger.registerMailbox(m_joinCoordinator); m_joinCoordinator.initialize(m_deployment.getCluster().getKfactor()); } catch (Exception e) { VoltDB.crashLocalVoltDB("Failed to instantiate join coordinator", true, e); } } /* * Construct all the mailboxes for things that need to be globally addressable so they can be published * in one atomic shot. * * The starting state for partition assignments are statically derived from the host id generated * by host messenger and the k-factor/host count/sites per host. This starting state * is published to ZK as the topology metadata node. * * On join and rejoin the node has to inspect the topology meta node to find out what is missing * and then update the topology listing itself as the replica for those partitions. * Then it does a compare and set of the topology. * * Ning: topology may not reflect the true partitions in the cluster during join. So if another node * is trying to rejoin, it should rely on the cartographer's view to pick the partitions to replace. */ JSONObject topo = getTopology(config.m_startAction, m_joinCoordinator); m_partitionsToSitesAtStartupForExportInit = new ArrayList<Integer>(); try { // IV2 mailbox stuff ClusterConfig clusterConfig = new ClusterConfig(topo); m_configuredReplicationFactor = clusterConfig.getReplicationFactor(); m_cartographer = new Cartographer(m_messenger, m_configuredReplicationFactor, m_catalogContext.cluster.getNetworkpartition()); List<Integer> partitions = null; if (isRejoin) { m_configuredNumberOfPartitions = m_cartographer.getPartitionCount(); partitions = m_cartographer.getIv2PartitionsToReplace(m_configuredReplicationFactor, clusterConfig.getSitesPerHost()); if (partitions.size() == 0) { VoltDB.crashLocalVoltDB("The VoltDB cluster already has enough nodes to satisfy " + "the requested k-safety factor of " + m_configuredReplicationFactor + ".\n" + "No more nodes can join.", false, null); } } else { m_configuredNumberOfPartitions = clusterConfig.getPartitionCount(); partitions = ClusterConfig.partitionsForHost(topo, m_messenger.getHostId()); } for (int ii = 0; ii < partitions.size(); ii++) { Integer partition = partitions.get(ii); m_iv2InitiatorStartingTxnIds.put( partition, TxnEgo.makeZero(partition).getTxnId()); } m_iv2Initiators = createIv2Initiators( partitions, m_config.m_startAction, m_partitionsToSitesAtStartupForExportInit); m_iv2InitiatorStartingTxnIds.put( MpInitiator.MP_INIT_PID, TxnEgo.makeZero(MpInitiator.MP_INIT_PID).getTxnId()); // Pass the local HSIds to the MPI so it can farm out buddy sites // to the RO MP site pool List<Long> localHSIds = new ArrayList<Long>(); for (Initiator ii : m_iv2Initiators) { localHSIds.add(ii.getInitiatorHSId()); } m_MPI = new MpInitiator(m_messenger, localHSIds, getStatsAgent()); m_iv2Initiators.add(m_MPI); // Make a list of HDIds to join Map<Integer, Long> partsToHSIdsToRejoin = new HashMap<Integer, Long>(); for (Initiator init : m_iv2Initiators) { if (init.isRejoinable()) { partsToHSIdsToRejoin.put(init.getPartitionId(), init.getInitiatorHSId()); } } OnDemandBinaryLogger.path = m_catalogContext.cluster.getVoltroot(); if (isRejoin) { SnapshotSaveAPI.recoveringSiteCount.set(partsToHSIdsToRejoin.size()); hostLog.info("Set recovering site count to " + partsToHSIdsToRejoin.size()); m_joinCoordinator = new Iv2RejoinCoordinator(m_messenger, partsToHSIdsToRejoin.values(), m_catalogContext.cluster.getVoltroot(), m_config.m_startAction == StartAction.LIVE_REJOIN); m_messenger.registerMailbox(m_joinCoordinator); if (m_config.m_startAction == StartAction.LIVE_REJOIN) { hostLog.info("Using live rejoin."); } else { hostLog.info("Using blocking rejoin."); } } else if (m_joining) { m_joinCoordinator.setPartitionsToHSIds(partsToHSIdsToRejoin); } } catch (Exception e) { VoltDB.crashLocalVoltDB(e.getMessage(), true, e); } // do the many init tasks in the Inits class Inits inits = new Inits(this, 1); inits.doInitializationWork(); // Need the catalog so that we know how many tables so we can guess at the necessary heap size // This is done under Inits.doInitializationWork(), so need to wait until we get here. // Current calculation needs pro/community knowledge, number of tables, and the sites/host, // which is the number of initiators (minus the possibly idle MPI initiator) checkHeapSanity(MiscUtils.isPro(), m_catalogContext.tables.size(), (m_iv2Initiators.size() - 1), m_configuredReplicationFactor); if (m_joining && m_config.m_replicationRole == ReplicationRole.REPLICA) { VoltDB.crashLocalVoltDB("Elastic join is prohibited on a replica cluster.", false, null); } collectLocalNetworkMetadata(); /* * Construct an adhoc planner for the initial catalog */ final CatalogSpecificPlanner csp = new CatalogSpecificPlanner(m_asyncCompilerAgent, m_catalogContext); // DR overflow directory File drOverflowDir = new File(m_catalogContext.cluster.getVoltroot(), "dr_overflow"); if (m_config.m_isEnterprise) { try { Class<?> ndrgwClass = null; if (Boolean.getBoolean("USE_DR_V2")) { ndrgwClass = Class.forName("org.voltdb.dr2.InvocationBufferServer"); } else { ndrgwClass = Class.forName("org.voltdb.dr.InvocationBufferServer"); } Constructor<?> ndrgwConstructor = ndrgwClass.getConstructor(File.class, boolean.class); m_nodeDRGateway = (NodeDRGateway) ndrgwConstructor.newInstance(drOverflowDir, m_replicationActive); } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to load DR system", true, e); } } // Initialize stats m_ioStats = new IOStats(); getStatsAgent().registerStatsSource(StatsSelector.IOSTATS, 0, m_ioStats); m_memoryStats = new MemoryStats(); getStatsAgent().registerStatsSource(StatsSelector.MEMORY, 0, m_memoryStats); getStatsAgent().registerStatsSource(StatsSelector.TOPO, 0, m_cartographer); m_partitionCountStats = new PartitionCountStats(m_cartographer); getStatsAgent().registerStatsSource(StatsSelector.PARTITIONCOUNT, 0, m_partitionCountStats); m_initiatorStats = new InitiatorStats(m_myHostId); m_liveClientsStats = new LiveClientsStats(); getStatsAgent().registerStatsSource(StatsSelector.LIVECLIENTS, 0, m_liveClientsStats); m_latencyStats = new LatencyStats(m_myHostId); getStatsAgent().registerStatsSource(StatsSelector.LATENCY, 0, m_latencyStats); m_latencyHistogramStats = new LatencyHistogramStats(m_myHostId); getStatsAgent().registerStatsSource(StatsSelector.LATENCY_HISTOGRAM, 0, m_latencyHistogramStats); BalancePartitionsStatistics rebalanceStats = new BalancePartitionsStatistics(); getStatsAgent().registerStatsSource(StatsSelector.REBALANCE, 0, rebalanceStats); KSafetyStats kSafetyStats = new KSafetyStats(); getStatsAgent().registerStatsSource(StatsSelector.KSAFETY, 0, kSafetyStats); m_cpuStats = new CpuStats(); getStatsAgent().registerStatsSource(StatsSelector.CPU, 0, m_cpuStats); /* * Initialize the command log on rejoin and join before configuring the IV2 * initiators. This will prevent them from receiving transactions * which need logging before the internal file writers are * initialized. Root cause of ENG-4136. * * If sync command log is on, not initializing the command log before the initiators * are up would cause deadlock. */ if ((m_commandLog != null) && (m_commandLog.needsInitialization())) { consoleLog.l7dlog(Level.INFO, LogKeys.host_VoltDB_StayTunedForLogging.name(), null); } else { consoleLog.l7dlog(Level.INFO, LogKeys.host_VoltDB_StayTunedForNoLogging.name(), null); } if (m_commandLog != null && (isRejoin || m_joining)) { //On rejoin the starting IDs are all 0 so technically it will load any snapshot //but the newest snapshot will always be the truncation snapshot taken after rejoin //completes at which point the node will mark itself as actually recovered. // // Use the partition count from the cluster config instead of the cartographer // here. Since the initiators are not started yet, the cartographer still doesn't // know about the new partitions at this point. m_commandLog.initForRejoin( m_catalogContext, Long.MIN_VALUE, m_configuredNumberOfPartitions, true, m_config.m_commandLogBinding, m_iv2InitiatorStartingTxnIds); } /* * Configure and start all the IV2 sites */ boolean usingCommandLog = false; try { usingCommandLog = m_config.m_isEnterprise && m_catalogContext.cluster.getLogconfig().get("log").getEnabled(); for (Initiator iv2init : m_iv2Initiators) { iv2init.configure( getBackendTargetType(), m_catalogContext, m_deployment.getCluster().getKfactor(), csp, m_configuredNumberOfPartitions, m_config.m_startAction, getStatsAgent(), m_memoryStats, m_commandLog, m_nodeDRGateway, m_config.m_executionCoreBindings.poll()); } // LeaderAppointer startup blocks if the initiators are not initialized. // So create the LeaderAppointer after the initiators. m_leaderAppointer = new LeaderAppointer( m_messenger, m_configuredNumberOfPartitions, m_deployment.getCluster().getKfactor(), m_catalogContext.cluster.getNetworkpartition(), m_catalogContext.cluster.getFaultsnapshots().get("CLUSTER_PARTITION"), usingCommandLog, topo, m_MPI, kSafetyStats); m_globalServiceElector.registerService(m_leaderAppointer); } catch (Exception e) { Throwable toLog = e; if (e instanceof ExecutionException) { toLog = ((ExecutionException)e).getCause(); } VoltDB.crashLocalVoltDB("Error configuring IV2 initiator.", true, toLog); } // Need to register the OpsAgents right before we turn on the client interface m_opsRegistrar.setDummyMode(false); // Create the client interface try { InetAddress clientIntf = null; InetAddress adminIntf = null; if (!m_config.m_externalInterface.trim().equals("")) { clientIntf = InetAddress.getByName(m_config.m_externalInterface); //client and admin interfaces are same by default. adminIntf = clientIntf; } //If user has specified on command line host:port override client and admin interfaces. if (m_config.m_clientInterface != null && m_config.m_clientInterface.trim().length() > 0) { clientIntf = InetAddress.getByName(m_config.m_clientInterface); } if (m_config.m_adminInterface != null && m_config.m_adminInterface.trim().length() > 0) { adminIntf = InetAddress.getByName(m_config.m_adminInterface); } m_clientInterface = ClientInterface.create(m_messenger, m_catalogContext, m_config.m_replicationRole, m_cartographer, m_configuredNumberOfPartitions, clientIntf, config.m_port, adminIntf, config.m_adminPort, m_config.m_timestampTestingSalt); } catch (Exception e) { VoltDB.crashLocalVoltDB(e.getMessage(), true, e); } // Create the statistics manager and register it to JMX registry m_statsManager = null; try { final Class<?> statsManagerClass = MiscUtils.loadProClass("org.voltdb.management.JMXStatsManager", "JMX", true); if (statsManagerClass != null && !DISABLE_JMX) { m_statsManager = (StatsManager)statsManagerClass.newInstance(); m_statsManager.initialize(); } } catch (Exception e) { //JMXStatsManager will log and we continue. } try { m_snapshotCompletionMonitor.init(m_messenger.getZK()); } catch (Exception e) { hostLog.fatal("Error initializing snapshot completion monitor", e); VoltDB.crashLocalVoltDB("Error initializing snapshot completion monitor", true, e); } /* * Make sure the build string successfully validated * before continuing to do operations * that might return wrongs answers or lose data. */ try { buildStringValidation.get(); } catch (Exception e) { VoltDB.crashLocalVoltDB("Failed to validate cluster build string", false, e); } if (!isRejoin && !m_joining) { try { m_messenger.waitForAllHostsToBeReady(m_deployment.getCluster().getHostcount()); } catch (Exception e) { hostLog.fatal("Failed to announce ready state."); VoltDB.crashLocalVoltDB("Failed to announce ready state.", false, null); } } if (!m_joining && (m_cartographer.getPartitionCount()) != m_configuredNumberOfPartitions) { for (Map.Entry<Integer, ImmutableList<Long>> entry : getSiteTrackerForSnapshot().m_partitionsToSitesImmutable.entrySet()) { hostLog.info(entry.getKey() + " -- " + CoreUtils.hsIdCollectionToString(entry.getValue())); } VoltDB.crashGlobalVoltDB("Mismatch between configured number of partitions (" + m_configuredNumberOfPartitions + ") and actual (" + m_cartographer.getPartitionCount() + ")", true, null); } schedulePeriodicWorks(); m_clientInterface.schedulePeriodicWorks(); // print out a bunch of useful system info logDebuggingInfo(m_config.m_adminPort, m_config.m_httpPort, m_httpPortExtraLogMessage, m_jsonEnabled); // warn the user on the console if k=0 or if no command logging if (m_configuredReplicationFactor == 0) { consoleLog.warn("This is not a highly available cluster. K-Safety is set to 0."); } if (!usingCommandLog) { // figure out if using a snapshot schedule boolean usingPeridoicSnapshots = false; for (SnapshotSchedule ss : m_catalogContext.database.getSnapshotschedule()) { if (ss.getEnabled()) { usingPeridoicSnapshots = true; } } // print the right warning depending on durability settings if (usingPeridoicSnapshots) { consoleLog.warn("Durability is limited to periodic snapshots. Command logging is off."); } else { consoleLog.warn("Durability is turned off. Command logging is off."); } } // warn if cluster is partitionable, but partition detection is off if ((m_catalogContext.cluster.getNetworkpartition() == false) && (m_configuredReplicationFactor > 0)) { hostLog.warn("Running a redundant (k-safe) cluster with network " + "partition detection disabled is not recommended for production use."); // we decided not to include the stronger language below for the 3.0 version (ENG-4215) //hostLog.warn("With partition detection disabled, data may be lost or " + // "corrupted by certain classes of network failures."); } assert (m_clientInterface != null); m_clientInterface.initializeSnapshotDaemon(m_messenger, m_globalServiceElector); // Start elastic join service try { String clSnapshotPath = null; if (m_catalogContext.cluster.getLogconfig().get("log").getEnabled()) { clSnapshotPath = m_catalogContext.cluster.getLogconfig().get("log").getInternalsnapshotpath(); } if (m_config.m_isEnterprise && TheHashinator.getCurrentConfig().type == HashinatorType.ELASTIC) { Class<?> elasticServiceClass = MiscUtils.loadProClass("org.voltdb.join.ElasticJoinCoordinator", "Elastic join", false); if (elasticServiceClass == null) { VoltDB.crashLocalVoltDB("Missing the ElasticJoinCoordinator class file in the enterprise " + "edition", false, null); } Constructor<?> constructor = elasticServiceClass.getConstructor(HostMessenger.class, ClientInterface.class, Cartographer.class, BalancePartitionsStatistics.class, String.class, int.class); m_elasticJoinService = (ElasticJoinService) constructor.newInstance(m_messenger, m_clientInterface, m_cartographer, rebalanceStats, clSnapshotPath, m_deployment.getCluster().getKfactor()); m_elasticJoinService.updateConfig(m_catalogContext); } } catch (Exception e) { VoltDB.crashLocalVoltDB("Failed to instantiate elastic join service", false, e); } // set additional restore agent stuff if (m_restoreAgent != null) { m_restoreAgent.setCatalogContext(m_catalogContext); m_restoreAgent.setInitiator(new Iv2TransactionCreator(m_clientInterface)); } m_configLogger = new Thread(new ConfigLogging()); m_configLogger.start(); DailyRollingFileAppender dailyAppender = null; Enumeration<?> appenders = Logger.getRootLogger().getAllAppenders(); while (appenders.hasMoreElements()) { Appender appender = (Appender) appenders.nextElement(); if (appender instanceof DailyRollingFileAppender){ dailyAppender = (DailyRollingFileAppender) appender; } } final DailyRollingFileAppender dailyRollingFileAppender = dailyAppender; Field field = null; if (dailyRollingFileAppender != null) { try { field = dailyRollingFileAppender.getClass().getDeclaredField("nextCheck"); field.setAccessible(true); } catch (NoSuchFieldException e) { hostLog.error("Failed to set daily system info logging: " + e.getMessage()); } } final Field nextCheckField = field; class DailyLogTask implements Runnable { @Override public void run() { try { m_myHostId = m_messenger.getHostId(); hostLog.info(String.format("Host id of this node is: %d", m_myHostId)); hostLog.info("URL of deployment info: " + m_config.m_pathToDeployment); hostLog.info("Cluster uptime: " + MiscUtils.formatUptime(getClusterUptime())); logDebuggingInfo(m_config.m_adminPort, m_config.m_httpPort, m_httpPortExtraLogMessage, m_jsonEnabled); long nextCheck = nextCheckField.getLong(dailyRollingFileAppender); scheduleWork(new DailyLogTask(), nextCheck - System.currentTimeMillis() + 30 * 1000, 0, TimeUnit.MILLISECONDS); } catch (IllegalAccessException e) { hostLog.error("Failed to set daily system info logging: " + e.getMessage()); } } } if (dailyRollingFileAppender != null && nextCheckField != null) { try { long nextCheck = nextCheckField.getLong(dailyRollingFileAppender); scheduleWork(new DailyLogTask(), nextCheck - System.currentTimeMillis() + 30 * 1000, 0, TimeUnit.MILLISECONDS); } catch (IllegalAccessException e) { hostLog.error("Failed to set daily system info logging: " + e.getMessage()); } } } } class StartActionWatcher implements Watcher { @Override public void process(WatchedEvent event) { if (m_mode == OperationMode.SHUTTINGDOWN) return; m_es.submit(new Runnable() { @Override public void run() { validateStartAction(); } }); } } private void validateStartAction() { try { ZooKeeper zk = m_messenger.getZK(); boolean initCompleted = zk.exists(VoltZK.init_completed, false) != null; List<String> children = zk.getChildren(VoltZK.start_action, new StartActionWatcher(), null); if (!children.isEmpty()) { for (String child : children) { byte[] data = zk.getData(VoltZK.start_action + "/" + child, false, null); if (data == null) { VoltDB.crashLocalVoltDB("Couldn't find " + VoltZK.start_action + "/" + child); } String startAction = new String(data); if ((startAction.equals(StartAction.JOIN.toString()) || startAction.equals(StartAction.REJOIN.toString()) || startAction.equals(StartAction.LIVE_REJOIN.toString())) && !initCompleted) { int nodeId = VoltZK.getHostIDFromChildName(child); if (nodeId == m_messenger.getHostId()) { VoltDB.crashLocalVoltDB("This node was started with start action " + startAction + " during cluster creation. " + "All nodes should be started with matching create or recover actions when bring up a cluster. " + "Join and rejoin are for adding nodes to an already running cluster."); } else { hostLog.warn("Node " + nodeId + " tried to " + startAction + " cluster but it is not allowed during cluster creation. " + "All nodes should be started with matching create or recover actions when bring up a cluster. " + "Join and rejoin are for adding nodes to an already running cluster."); } } } } } catch (KeeperException e) { hostLog.error("Failed to validate the start actions", e); } catch (InterruptedException e) { VoltDB.crashLocalVoltDB("Interrupted during start action validation:" + e.getMessage(), true, e); } } private class ConfigLogging implements Runnable { private void logConfigInfo() { hostLog.info("Logging config info"); File voltDbRoot = CatalogUtil.getVoltDbRoot(m_deployment.getPaths()); String pathToConfigInfoDir = voltDbRoot.getPath() + File.separator + "config_log"; File configInfoDir = new File(pathToConfigInfoDir); configInfoDir.mkdirs(); String pathToConfigInfo = pathToConfigInfoDir + File.separator + "config.json"; File configInfo = new File(pathToConfigInfo); byte jsonBytes[] = null; try { JSONStringer stringer = new JSONStringer(); stringer.object(); stringer.key("workingDir").value(System.getProperty("user.dir")); stringer.key("pid").value(CLibrary.getpid()); stringer.key("log4jDst").array(); Enumeration<?> appenders = Logger.getRootLogger().getAllAppenders(); while (appenders.hasMoreElements()) { Appender appender = (Appender) appenders.nextElement(); if (appender instanceof FileAppender){ stringer.object(); stringer.key("path").value(new File(((FileAppender) appender).getFile()).getCanonicalPath()); if (appender instanceof DailyRollingFileAppender) { stringer.key("format").value(((DailyRollingFileAppender)appender).getDatePattern()); } stringer.endObject(); } } Enumeration<?> loggers = Logger.getRootLogger().getLoggerRepository().getCurrentLoggers(); while (loggers.hasMoreElements()) { Logger logger = (Logger) loggers.nextElement(); appenders = logger.getAllAppenders(); while (appenders.hasMoreElements()) { Appender appender = (Appender) appenders.nextElement(); if (appender instanceof FileAppender){ stringer.object(); stringer.key("path").value(new File(((FileAppender) appender).getFile()).getCanonicalPath()); if (appender instanceof DailyRollingFileAppender) { stringer.key("format").value(((DailyRollingFileAppender)appender).getDatePattern()); } stringer.endObject(); } } } stringer.endArray(); stringer.endObject(); JSONObject jsObj = new JSONObject(stringer.toString()); jsonBytes = jsObj.toString(4).getBytes(Charsets.UTF_8); } catch (JSONException e) { Throwables.propagate(e); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos = new FileOutputStream(configInfo); fos.write(jsonBytes); fos.getFD().sync(); fos.close(); } catch (IOException e) { hostLog.error("Failed to log config info: " + e.getMessage()); e.printStackTrace(); } } private void logCatalogAndDeployment() { File voltDbRoot = CatalogUtil.getVoltDbRoot(m_deployment.getPaths()); String pathToConfigInfoDir = voltDbRoot.getPath() + File.separator + "config_log"; try { m_catalogContext.writeCatalogJarToFile(pathToConfigInfoDir, "catalog.jar"); } catch (IOException e) { hostLog.error("Failed to log catalog: " + e.getMessage()); e.printStackTrace(); } try { File deploymentFile = new File(pathToConfigInfoDir, "deployment.xml"); if (deploymentFile.exists()) { deploymentFile.delete(); } FileOutputStream fileOutputStream = new FileOutputStream(deploymentFile); CatalogAndIds catalogStuff = CatalogUtil.getCatalogFromZK(getHostMessenger().getZK()); fileOutputStream.write(catalogStuff.deploymentBytes); fileOutputStream.close(); } catch (Exception e) { hostLog.error("Failed to log deployment file: " + e.getMessage()); e.printStackTrace(); } } @Override public void run() { logConfigInfo(); logCatalogAndDeployment(); } } // Get topology information. If rejoining, get it directly from // ZK. Otherwise, try to do the write/read race to ZK on startup. private JSONObject getTopology(StartAction startAction, JoinCoordinator joinCoordinator) { JSONObject topo = null; if (startAction == StartAction.JOIN) { assert(joinCoordinator != null); topo = joinCoordinator.getTopology(); } else if (!startAction.doesRejoin()) { int sitesperhost = m_deployment.getCluster().getSitesperhost(); int hostcount = m_deployment.getCluster().getHostcount(); int kfactor = m_deployment.getCluster().getKfactor(); ClusterConfig clusterConfig = new ClusterConfig(hostcount, sitesperhost, kfactor); if (!clusterConfig.validate()) { VoltDB.crashLocalVoltDB(clusterConfig.getErrorMsg(), false, null); } topo = registerClusterConfig(clusterConfig); } else { Stat stat = new Stat(); try { topo = new JSONObject(new String(m_messenger.getZK().getData(VoltZK.topology, false, stat), "UTF-8")); } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to get topology from ZK", true, e); } } return topo; } private List<Initiator> createIv2Initiators(Collection<Integer> partitions, StartAction startAction, List<Integer> m_partitionsToSitesAtStartupForExportInit) { List<Initiator> initiators = new ArrayList<Initiator>(); for (Integer partition : partitions) { Initiator initiator = new SpInitiator(m_messenger, partition, getStatsAgent(), m_snapshotCompletionMonitor, startAction); initiators.add(initiator); m_partitionsToSitesAtStartupForExportInit.add(partition); } return initiators; } private JSONObject registerClusterConfig(ClusterConfig config) { // First, race to write the topology to ZK using Highlander rules // (In the end, there can be only one) JSONObject topo = null; try { topo = config.getTopology(m_messenger.getLiveHostIds()); byte[] payload = topo.toString(4).getBytes("UTF-8"); m_messenger.getZK().create(VoltZK.topology, payload, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (KeeperException.NodeExistsException nee) { // It's fine if we didn't win, we'll pick up the topology below } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to write topology to ZK, dying", true, e); } // Then, have everyone read the topology data back from ZK try { byte[] data = m_messenger.getZK().getData(VoltZK.topology, false, null); topo = new JSONObject(new String(data, "UTF-8")); } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to read topology from ZK, dying", true, e); } return topo; } private final List<ScheduledFuture<?>> m_periodicWorks = new ArrayList<ScheduledFuture<?>>(); /** * Schedule all the periodic works */ private void schedulePeriodicWorks() { // JMX stats broadcast m_periodicWorks.add(scheduleWork(new Runnable() { @Override public void run() { // A null here was causing a steady stream of annoying but apparently inconsequential // NPEs during a debug session of an unrelated unit test. if (m_statsManager != null) { m_statsManager.sendNotification(); } } }, 0, StatsManager.POLL_INTERVAL, TimeUnit.MILLISECONDS)); // small stats samples m_periodicWorks.add(scheduleWork(new Runnable() { @Override public void run() { SystemStatsCollector.asyncSampleSystemNow(false, false); } }, 0, 5, TimeUnit.SECONDS)); // medium stats samples m_periodicWorks.add(scheduleWork(new Runnable() { @Override public void run() { SystemStatsCollector.asyncSampleSystemNow(true, false); } }, 0, 1, TimeUnit.MINUTES)); // large stats samples m_periodicWorks.add(scheduleWork(new Runnable() { @Override public void run() { SystemStatsCollector.asyncSampleSystemNow(true, true); } }, 0, 6, TimeUnit.MINUTES)); GCInspector.instance.start(m_periodicPriorityWorkThread); } int readDeploymentAndCreateStarterCatalogContext() { /* * Debate with the cluster what the deployment file should be */ try { ZooKeeper zk = m_messenger.getZK(); byte deploymentBytes[] = null; try { deploymentBytes = org.voltcore.utils.CoreUtils.urlToBytes(m_config.m_pathToDeployment); } catch (Exception ex) { //Let us get bytes from ZK } try { if (deploymentBytes != null) { CatalogUtil.writeCatalogToZK(zk, // Fill in innocuous values for non-deployment stuff 0, 0L, 0L, new byte[] {}, // spin loop in Inits.LoadCatalog.run() needs // this to be of zero length until we have a real catalog. deploymentBytes); hostLog.info("URL of deployment: " + m_config.m_pathToDeployment); } else { CatalogAndIds catalogStuff = CatalogUtil.getCatalogFromZK(zk); deploymentBytes = catalogStuff.deploymentBytes; } } catch (KeeperException.NodeExistsException e) { CatalogAndIds catalogStuff = CatalogUtil.getCatalogFromZK(zk); byte[] deploymentBytesTemp = catalogStuff.deploymentBytes; if (deploymentBytesTemp != null) { //Check hash if its a supplied deployment on command line. //We will ignore the supplied or default deployment anyways. if (deploymentBytes != null && !m_config.m_deploymentDefault) { byte[] deploymentHashHere = CatalogUtil.makeCatalogOrDeploymentHash(deploymentBytes); if (!(Arrays.equals(deploymentHashHere, catalogStuff.getDeploymentHash()))) { hostLog.warn("The locally provided deployment configuration did not " + " match the configuration information found in the cluster."); } else { hostLog.info("Deployment configuration pulled from other cluster node."); } } //Use remote deployment obtained. deploymentBytes = deploymentBytesTemp; } else { hostLog.error("Deployment file could not be loaded locally or remotely, " + "local supplied path: " + m_config.m_pathToDeployment); deploymentBytes = null; } } if (deploymentBytes == null) { hostLog.error("Deployment could not be obtained from cluster node or locally"); VoltDB.crashLocalVoltDB("No such deployment file: " + m_config.m_pathToDeployment, false, null); } m_deployment = CatalogUtil.getDeployment(new ByteArrayInputStream(deploymentBytes)); // wasn't a valid xml deployment file if (m_deployment == null) { hostLog.error("Not a valid XML deployment file at URL: " + m_config.m_pathToDeployment); VoltDB.crashLocalVoltDB("Not a valid XML deployment file at URL: " + m_config.m_pathToDeployment, false, null); } /* * Check for invalid deployment file settings (enterprise-only) in the community edition. * Trick here is to print out all applicable problems and then stop, rather than stopping * after the first one is found. */ if (!m_config.m_isEnterprise) { boolean shutdownDeployment = false; boolean shutdownAction = false; // check license features for community version if ((m_deployment.getCluster() != null) && (m_deployment.getCluster().getKfactor() > 0)) { consoleLog.error("K-Safety is not supported " + "in the community edition of VoltDB."); shutdownDeployment = true; } if ((m_deployment.getSnapshot() != null) && (m_deployment.getSnapshot().isEnabled())) { consoleLog.error("Snapshots are not supported " + "in the community edition of VoltDB."); shutdownDeployment = true; } if ((m_deployment.getCommandlog() != null) && (m_deployment.getCommandlog().isEnabled())) { consoleLog.error("Command logging is not supported " + "in the community edition of VoltDB."); shutdownDeployment = true; } if ((m_deployment.getExport() != null) && (m_deployment.getExport().isEnabled())) { consoleLog.error("Export is not supported " + "in the community edition of VoltDB."); shutdownDeployment = true; } // check the start action for the community edition if (m_config.m_startAction != StartAction.CREATE) { consoleLog.error("Start action \"" + m_config.m_startAction.getClass().getSimpleName() + "\" is not supported in the community edition of VoltDB."); shutdownAction = true; } // if the process needs to stop, try to be helpful if (shutdownAction || shutdownDeployment) { String msg = "This process will exit. Please run VoltDB with "; if (shutdownDeployment) { msg += "a deployment file compatible with the community edition"; } if (shutdownDeployment && shutdownAction) { msg += " and "; } if (shutdownAction && !shutdownDeployment) { msg += "the CREATE start action"; } msg += "."; VoltDB.crashLocalVoltDB(msg, false, null); } } // note the heart beats are specified in seconds in xml, but ms internally HeartbeatType hbt = m_deployment.getHeartbeat(); if (hbt != null) { m_config.m_deadHostTimeoutMS = hbt.getTimeout() * 1000; m_messenger.setDeadHostTimeout(m_config.m_deadHostTimeoutMS); } else { hostLog.info("Dead host timeout set to " + m_config.m_deadHostTimeoutMS + " milliseconds"); } final String elasticSetting = m_deployment.getCluster().getElastic().trim().toUpperCase(); if (elasticSetting.equals("ENABLED")) { TheHashinator.setConfiguredHashinatorType(HashinatorType.ELASTIC); } else if (!elasticSetting.equals("DISABLED")) { VoltDB.crashLocalVoltDB("Error in deployment file, elastic attribute of " + "cluster element must be " + "'enabled' or 'disabled' but was '" + elasticSetting + "'", false, null); } else { TheHashinator.setConfiguredHashinatorType(HashinatorType.LEGACY); } // create a dummy catalog to load deployment info into Catalog catalog = new Catalog(); Cluster cluster = catalog.getClusters().add("cluster"); Database db = cluster.getDatabases().add("database"); // create groups as needed for users if (m_deployment.getUsers() != null) { for (UsersType.User user : m_deployment.getUsers().getUser()) { Set<String> roles = CatalogUtil.mergeUserRoles(user); if (roles.isEmpty()) { continue; } for (String role : roles) { if (db.getGroups().get(role) == null) { db.getGroups().add(role); } } } } long result = CatalogUtil.compileDeployment(catalog, m_deployment, true, true); if (result < 0) { hostLog.fatal("Error validating deployment file"); VoltDB.crashLocalVoltDB("Error validating deployment file"); } byte[] deploymentHash = CatalogUtil.makeCatalogOrDeploymentHash(deploymentBytes); m_catalogContext = new CatalogContext( TxnEgo.makeZero(MpInitiator.MP_INIT_PID).getTxnId(), //txnid 0, //timestamp catalog, null, deploymentHash, 0, -1); int numberOfNodes = m_deployment.getCluster().getHostcount(); if (numberOfNodes <= 0) { hostLog.l7dlog( Level.FATAL, LogKeys.host_VoltDB_InvalidHostCount.name(), new Object[] { numberOfNodes }, null); VoltDB.crashLocalVoltDB("Invalid cluster size: " + numberOfNodes, false, null); } return numberOfNodes; } catch (Exception e) { throw new RuntimeException(e); } } void collectLocalNetworkMetadata() { boolean threw = false; JSONStringer stringer = new JSONStringer(); try { stringer.object(); stringer.key("interfaces").array(); /* * If no interface was specified, do a ton of work * to identify all ipv4 or ipv6 interfaces and * marshal them into JSON. Always put the ipv4 address first * so that the export client will use it */ if (m_config.m_externalInterface.equals("")) { LinkedList<NetworkInterface> interfaces = new LinkedList<NetworkInterface>(); try { Enumeration<NetworkInterface> intfEnum = NetworkInterface.getNetworkInterfaces(); while (intfEnum.hasMoreElements()) { NetworkInterface intf = intfEnum.nextElement(); if (intf.isLoopback() || !intf.isUp()) { continue; } interfaces.offer(intf); } } catch (SocketException e) { throw new RuntimeException(e); } if (interfaces.isEmpty()) { stringer.value("localhost"); } else { boolean addedIp = false; while (!interfaces.isEmpty()) { NetworkInterface intf = interfaces.poll(); Enumeration<InetAddress> inetAddrs = intf.getInetAddresses(); Inet6Address inet6addr = null; Inet4Address inet4addr = null; while (inetAddrs.hasMoreElements()) { InetAddress addr = inetAddrs.nextElement(); if (addr instanceof Inet6Address) { inet6addr = (Inet6Address)addr; if (inet6addr.isLinkLocalAddress()) { inet6addr = null; } } else if (addr instanceof Inet4Address) { inet4addr = (Inet4Address)addr; } } if (inet4addr != null) { stringer.value(inet4addr.getHostAddress()); addedIp = true; } if (inet6addr != null) { stringer.value(inet6addr.getHostAddress()); addedIp = true; } } if (!addedIp) { stringer.value("localhost"); } } } else { stringer.value(m_config.m_externalInterface); } } catch (Exception e) { threw = true; hostLog.warn("Error while collecting data about local network interfaces", e); } try { if (threw) { stringer = new JSONStringer(); stringer.object(); stringer.key("interfaces").array(); stringer.value("localhost"); stringer.endArray(); } else { stringer.endArray(); } stringer.key("clientPort").value(m_config.m_port); stringer.key("clientInterface").value(m_config.m_clientInterface); stringer.key("adminPort").value(m_config.m_adminPort); stringer.key("adminInterface").value(m_config.m_adminInterface); stringer.key("httpPort").value(m_config.m_httpPort); stringer.key("httpInterface").value(m_config.m_httpPortInterface); stringer.key("drPort").value(m_config.m_drAgentPortStart); stringer.key("drInterface").value(m_config.m_drInterface); stringer.endObject(); JSONObject obj = new JSONObject(stringer.toString()); // possibly atomic swap from null to realz m_localMetadata = obj.toString(4); hostLog.debug("System Metadata is: " + m_localMetadata); } catch (Exception e) { hostLog.warn("Failed to collect data about lcoal network interfaces", e); } } /** * Start the voltcore HostMessenger. This joins the node * to the existing cluster. In the non rejoin case, this * function will return when the mesh is complete. If * rejoining, it will return when the node and agreement * site are synched to the existing cluster. */ void buildClusterMesh(boolean isRejoin) { final String leaderAddress = m_config.m_leader; String hostname = MiscUtils.getHostnameFromHostnameColonPort(leaderAddress); int port = MiscUtils.getPortFromHostnameColonPort(leaderAddress, m_config.m_internalPort); org.voltcore.messaging.HostMessenger.Config hmconfig; hmconfig = new org.voltcore.messaging.HostMessenger.Config(hostname, port); hmconfig.internalPort = m_config.m_internalPort; if (m_config.m_internalPortInterface != null && m_config.m_internalPortInterface.trim().length() > 0) { hmconfig.internalInterface = m_config.m_internalPortInterface.trim(); } else { hmconfig.internalInterface = m_config.m_internalInterface; } hmconfig.zkInterface = m_config.m_zkInterface; hmconfig.deadHostTimeout = m_config.m_deadHostTimeoutMS; hmconfig.factory = new VoltDbMessageFactory(); hmconfig.coreBindIds = m_config.m_networkCoreBindings; m_messenger = new org.voltcore.messaging.HostMessenger(hmconfig); hostLog.info(String.format("Beginning inter-node communication on port %d.", m_config.m_internalPort)); try { m_messenger.start(); } catch (Exception e) { VoltDB.crashLocalVoltDB(e.getMessage(), true, e); } VoltZK.createPersistentZKNodes(m_messenger.getZK()); // Use the host messenger's hostId. m_myHostId = m_messenger.getHostId(); hostLog.info(String.format("Host id of this node is: %d", m_myHostId)); consoleLog.info(String.format("Host id of this node is: %d", m_myHostId)); // Semi-hacky check to see if we're attempting to rejoin to ourselves. // The leader node gets assigned host ID 0, always, so if we're the // leader and we're rejoining, this is clearly bad. if (m_myHostId == 0 && isRejoin) { VoltDB.crashLocalVoltDB("Unable to rejoin a node to itself. " + "Please check your command line and start action and try again.", false, null); } } void logDebuggingInfo(int adminPort, int httpPort, String httpPortExtraLogMessage, boolean jsonEnabled) { String startAction = m_config.m_startAction.toString(); String startActionLog = "Database start action is " + (startAction.substring(0, 1).toUpperCase() + startAction.substring(1).toLowerCase()) + "."; if (!m_rejoining) { hostLog.info(startActionLog); } hostLog.info("PID of this Volt process is " + CLibrary.getpid()); // print out awesome network stuff hostLog.info(String.format("Listening for native wire protocol clients on port %d.", m_config.m_port)); hostLog.info(String.format("Listening for admin wire protocol clients on port %d.", adminPort)); if (m_startMode == OperationMode.PAUSED) { hostLog.info(String.format("Started in admin mode. Clients on port %d will be rejected in admin mode.", m_config.m_port)); } if (m_config.m_replicationRole == ReplicationRole.REPLICA) { consoleLog.info("Started as " + m_config.m_replicationRole.toString().toLowerCase() + " cluster. " + "Clients can only call read-only procedures."); } if (httpPortExtraLogMessage != null) { hostLog.info(httpPortExtraLogMessage); } if (httpPort != -1) { hostLog.info(String.format("Local machine HTTP monitoring is listening on port %d.", httpPort)); } else { hostLog.info(String.format("Local machine HTTP monitoring is disabled.")); } if (jsonEnabled) { hostLog.info(String.format("Json API over HTTP enabled at path /api/1.0/, listening on port %d.", httpPort)); } else { hostLog.info("Json API disabled."); } // java heap size long javamaxheapmem = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax(); javamaxheapmem /= (1024 * 1024); hostLog.info(String.format("Maximum usable Java heap set to %d mb.", javamaxheapmem)); // Computed minimum heap requirement long minRqt = computeMinimumHeapRqt(MiscUtils.isPro(), m_catalogContext.tables.size(), (m_iv2Initiators.size() - 1), m_configuredReplicationFactor); hostLog.info("Minimum required Java heap for catalog and server config is " + minRqt + " MB."); SortedMap<String, String> dbgMap = m_catalogContext.getDebuggingInfoFromCatalog(); for (String line : dbgMap.values()) { hostLog.info(line); } if (m_catalogContext.cluster.getUseadhocschema()) { consoleLog.warn("Cluster is configured to use live DDL for application changes. " + "This feature is currently a preview of work-in-progress and not recommended for " + "production environments. Remove the schema attribute in the <cluster> " + "element of your deployment file if you did not intend to use the preview."); } // print out a bunch of useful system info PlatformProperties pp = PlatformProperties.getPlatformProperties(); String[] lines = pp.toLogLines().split("\n"); for (String line : lines) { hostLog.info(line.trim()); } final ZooKeeper zk = m_messenger.getZK(); ZKUtil.ByteArrayCallback operationModeFuture = new ZKUtil.ByteArrayCallback(); /* * Publish our cluster metadata, and then retrieve the metadata * for the rest of the cluster */ try { zk.create( VoltZK.cluster_metadata + "/" + m_messenger.getHostId(), getLocalMetadata().getBytes("UTF-8"), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, new ZKUtil.StringCallback(), null); zk.getData(VoltZK.operationMode, false, operationModeFuture, null); } catch (Exception e) { VoltDB.crashLocalVoltDB("Error creating \"/cluster_metadata\" node in ZK", true, e); } Map<Integer, String> clusterMetadata = new HashMap<Integer, String>(0); /* * Spin and attempt to retrieve cluster metadata for all nodes in the cluster. */ Set<Integer> metadataToRetrieve = new HashSet<Integer>(m_messenger.getLiveHostIds()); metadataToRetrieve.remove(m_messenger.getHostId()); while (!metadataToRetrieve.isEmpty()) { Map<Integer, ZKUtil.ByteArrayCallback> callbacks = new HashMap<Integer, ZKUtil.ByteArrayCallback>(); for (Integer hostId : metadataToRetrieve) { ZKUtil.ByteArrayCallback cb = new ZKUtil.ByteArrayCallback(); zk.getData(VoltZK.cluster_metadata + "/" + hostId, false, cb, null); callbacks.put(hostId, cb); } for (Map.Entry<Integer, ZKUtil.ByteArrayCallback> entry : callbacks.entrySet()) { try { ZKUtil.ByteArrayCallback cb = entry.getValue(); Integer hostId = entry.getKey(); clusterMetadata.put(hostId, new String(cb.getData(), "UTF-8")); metadataToRetrieve.remove(hostId); } catch (KeeperException.NoNodeException e) {} catch (Exception e) { VoltDB.crashLocalVoltDB("Error retrieving cluster metadata", true, e); } } } // print out cluster membership hostLog.info("About to list cluster interfaces for all nodes with format [ip1 ip2 ... ipN] client-port:admin-port:http-port"); for (int hostId : m_messenger.getLiveHostIds()) { if (hostId == m_messenger.getHostId()) { hostLog.info( String.format( " Host id: %d with interfaces: %s [SELF]", hostId, MiscUtils.formatHostMetadataFromJSON(getLocalMetadata()))); } else { String hostMeta = clusterMetadata.get(hostId); hostLog.info( String.format( " Host id: %d with interfaces: %s [PEER]", hostId, MiscUtils.formatHostMetadataFromJSON(hostMeta))); } } try { if (operationModeFuture.getData() != null) { String operationModeStr = new String(operationModeFuture.getData(), "UTF-8"); m_startMode = OperationMode.valueOf(operationModeStr); } } catch (KeeperException.NoNodeException e) {} catch (Exception e) { throw new RuntimeException(e); } } public static String[] extractBuildInfo() { StringBuilder sb = new StringBuilder(64); String buildString = "VoltDB"; String versionString = m_defaultVersionString; byte b = -1; try { InputStream buildstringStream = ClassLoader.getSystemResourceAsStream("buildstring.txt"); if (buildstringStream == null) { throw new RuntimeException("Unreadable or missing buildstring.txt file."); } while ((b = (byte) buildstringStream.read()) != -1) { sb.append((char)b); } sb.append("\n"); String parts[] = sb.toString().split(" ", 2); if (parts.length != 2) { throw new RuntimeException("Invalid buildstring.txt file."); } versionString = parts[0].trim(); buildString = parts[1].trim(); } catch (Exception ignored) { try { InputStream buildstringStream = new FileInputStream("version.txt"); try { while ((b = (byte) buildstringStream.read()) != -1) { sb.append((char)b); } versionString = sb.toString().trim(); } finally { buildstringStream.close(); } } catch (Exception ignored2) { hostLog.l7dlog( Level.ERROR, LogKeys.org_voltdb_VoltDB_FailedToRetrieveBuildString.name(), null); } } return new String[] { versionString, buildString }; } @Override public void readBuildInfo(String editionTag) { String buildInfo[] = extractBuildInfo(); m_versionString = buildInfo[0]; m_buildString = buildInfo[1]; consoleLog.info(String.format("Build: %s %s %s", m_versionString, m_buildString, editionTag)); } /** * Start all the site's event loops. That's it. */ @Override public void run() { if (m_restoreAgent != null) { // start restore process m_restoreAgent.restore(); } else { onRestoreCompletion(Long.MIN_VALUE, m_iv2InitiatorStartingTxnIds); } // Start the rejoin coordinator if (m_joinCoordinator != null) { try { if (!m_joinCoordinator.startJoin(m_catalogContext.database)) { VoltDB.crashLocalVoltDB("Failed to join the cluster", true, null); } } catch (Exception e) { VoltDB.crashLocalVoltDB("Failed to join the cluster", true, e); } } m_isRunning = true; } /** * Try to shut everything down so they system is ready to call * initialize again. * @param mainSiteThread The thread that m_inititalized the VoltDB or * null if called from that thread. */ @Override public boolean shutdown(Thread mainSiteThread) throws InterruptedException { synchronized(m_startAndStopLock) { boolean did_it = false; if (m_mode != OperationMode.SHUTTINGDOWN) { did_it = true; m_mode = OperationMode.SHUTTINGDOWN; /* * Various scheduled tasks get crashy in unit tests if they happen to run * while other stuff is being shut down */ for (ScheduledFuture<?> sc : m_periodicWorks) { sc.cancel(false); try { sc.get(); } catch (Throwable t) {} } m_periodicWorks.clear(); m_snapshotCompletionMonitor.shutdown(); m_periodicWorkThread.shutdown(); m_periodicWorkThread.awaitTermination(356, TimeUnit.DAYS); m_periodicPriorityWorkThread.shutdown(); m_periodicPriorityWorkThread.awaitTermination(356, TimeUnit.DAYS); if (m_elasticJoinService != null) { m_elasticJoinService.shutdown(); } if (m_leaderAppointer != null) { m_leaderAppointer.shutdown(); } m_globalServiceElector.shutdown(); if (m_hasStartedSampler.get()) { m_sampler.setShouldStop(); m_sampler.join(); } // shutdown the web monitoring / json if (m_adminListener != null) m_adminListener.stop(); // shut down the client interface if (m_clientInterface != null) { m_clientInterface.shutdown(); m_clientInterface = null; } // tell the iv2 sites to stop their runloop if (m_iv2Initiators != null) { for (Initiator init : m_iv2Initiators) init.shutdown(); } if (m_cartographer != null) { m_cartographer.shutdown(); } if (m_configLogger != null) { m_configLogger.join(); } // shut down Export and its connectors. ExportManager.instance().shutdown(); // After sites are terminated, shutdown the InvocationBufferServer. // The IBS is shared by all sites; don't kill it while any site is active. if (m_nodeDRGateway != null) { try { m_nodeDRGateway.shutdown(); } catch (InterruptedException e) { hostLog.warn("Interrupted shutting down invocation buffer server", e); } } if (m_snapshotIOAgent != null) { m_snapshotIOAgent.shutdown(); } // shut down the network/messaging stuff // Close the host messenger first, which should close down all of // the ForeignHost sockets cleanly if (m_messenger != null) { m_messenger.shutdown(); } m_messenger = null; //Also for test code that expects a fresh stats agent if (m_opsRegistrar != null) { try { m_opsRegistrar.shutdown(); } finally { m_opsRegistrar = null; } } if (m_asyncCompilerAgent != null) { m_asyncCompilerAgent.shutdown(); m_asyncCompilerAgent = null; } ExportManager.instance().shutdown(); m_computationService.shutdown(); m_computationService.awaitTermination(1, TimeUnit.DAYS); m_computationService = null; m_catalogContext = null; m_initiatorStats = null; m_latencyStats = null; m_latencyHistogramStats = null; AdHocCompilerCache.clearVersionCache(); org.voltdb.iv2.InitiatorMailbox.m_allInitiatorMailboxes.clear(); // probably unnecessary System.gc(); m_isRunning = false; } return did_it; } } /** Last transaction ID at which the logging config updated. * Also, use the intrinsic lock to safeguard access from multiple * execution site threads */ private static Long lastLogUpdate_txnId = 0L; @Override synchronized public void logUpdate(String xmlConfig, long currentTxnId) { // another site already did this work. if (currentTxnId == lastLogUpdate_txnId) { return; } else if (currentTxnId < lastLogUpdate_txnId) { throw new RuntimeException( "Trying to update logging config at transaction " + lastLogUpdate_txnId + " with an older transaction: " + currentTxnId); } hostLog.info("Updating RealVoltDB logging config from txnid: " + lastLogUpdate_txnId + " to " + currentTxnId); lastLogUpdate_txnId = currentTxnId; VoltLogger.configure(xmlConfig); } /** Struct to associate a context with a counter of served sites */ private static class ContextTracker { ContextTracker(CatalogContext context, CatalogSpecificPlanner csp) { m_dispensedSites = 1; m_context = context; m_csp = csp; } long m_dispensedSites; final CatalogContext m_context; final CatalogSpecificPlanner m_csp; } /** Associate transaction ids to contexts */ private final HashMap<Long, ContextTracker>m_txnIdToContextTracker = new HashMap<Long, ContextTracker>(); @Override public Pair<CatalogContext, CatalogSpecificPlanner> catalogUpdate( String diffCommands, byte[] newCatalogBytes, byte[] catalogBytesHash, int expectedCatalogVersion, long currentTxnId, long currentTxnUniqueId, byte[] deploymentHash) { synchronized(m_catalogUpdateLock) { // A site is catching up with catalog updates if (currentTxnId <= m_catalogContext.m_transactionId && !m_txnIdToContextTracker.isEmpty()) { ContextTracker contextTracker = m_txnIdToContextTracker.get(currentTxnId); // This 'dispensed' concept is a little crazy fragile. Maybe it would be better // to keep a rolling N catalogs? Or perhaps to keep catalogs for N minutes? Open // to opinions here. contextTracker.m_dispensedSites++; int ttlsites = VoltDB.instance().getSiteTrackerForSnapshot().getSitesForHost(m_messenger.getHostId()).size(); if (contextTracker.m_dispensedSites == ttlsites) { m_txnIdToContextTracker.remove(currentTxnId); } return Pair.of( contextTracker.m_context, contextTracker.m_csp); } else if (m_catalogContext.catalogVersion != expectedCatalogVersion) { hostLog.fatal("Failed catalog update." + " expectedCatalogVersion: " + expectedCatalogVersion + " currentTxnId: " + currentTxnId + " currentTxnUniqueId: " + currentTxnUniqueId + " m_catalogContext.catalogVersion " + m_catalogContext.catalogVersion); throw new RuntimeException("Trying to update main catalog context with diff " + "commands generated for an out-of date catalog. Expected catalog version: " + expectedCatalogVersion + " does not match actual version: " + m_catalogContext.catalogVersion); } hostLog.info(String.format("Globally updating the current application catalog (new hash %s).", Encoder.hexEncode(catalogBytesHash).substring(0, 10))); // get old debugging info SortedMap<String, String> oldDbgMap = m_catalogContext.getDebuggingInfoFromCatalog(); // 0. A new catalog! Update the global context and the context tracker m_catalogContext = m_catalogContext.update( currentTxnId, currentTxnUniqueId, newCatalogBytes, diffCommands, true, deploymentHash); final CatalogSpecificPlanner csp = new CatalogSpecificPlanner( m_asyncCompilerAgent, m_catalogContext); m_txnIdToContextTracker.put(currentTxnId, new ContextTracker( m_catalogContext, csp)); // log the stuff that's changed in this new catalog update SortedMap<String, String> newDbgMap = m_catalogContext.getDebuggingInfoFromCatalog(); for (Entry<String, String> e : newDbgMap.entrySet()) { // skip log lines that are unchanged if (oldDbgMap.containsKey(e.getKey()) && oldDbgMap.get(e.getKey()).equals(e.getValue())) { continue; } hostLog.info(e.getValue()); } //Construct the list of partitions and sites because it simply doesn't exist anymore SiteTracker siteTracker = VoltDB.instance().getSiteTrackerForSnapshot(); List<Long> sites = siteTracker.getSitesForHost(m_messenger.getHostId()); List<Integer> partitions = new ArrayList<Integer>(); for (Long site : sites) { Integer partition = siteTracker.getPartitionForSite(site); partitions.add(partition); } // 1. update the export manager. ExportManager.instance().updateCatalog(m_catalogContext, partitions); // 1.1 Update the elastic join throughput settings if (m_elasticJoinService != null) m_elasticJoinService.updateConfig(m_catalogContext); // 1.5 update the dead host timeout if (m_catalogContext.cluster.getHeartbeattimeout() * 1000 != m_config.m_deadHostTimeoutMS) { m_config.m_deadHostTimeoutMS = m_catalogContext.cluster.getHeartbeattimeout() * 1000; m_messenger.setDeadHostTimeout(m_config.m_deadHostTimeoutMS); } // 2. update client interface (asynchronously) // CI in turn updates the planner thread. if (m_clientInterface != null) { m_clientInterface.notifyOfCatalogUpdate(); } // 3. update HTTPClientInterface (asynchronously) // This purges cached connection state so that access with // stale auth info is prevented. if (m_adminListener != null) { m_adminListener.notifyOfCatalogUpdate(); } // 4. Flush StatisticsAgent old catalog statistics. // Otherwise, the stats agent will hold all old catalogs // in memory. getStatsAgent().notifyOfCatalogUpdate(); // 5. MPIs don't run fragments. Update them here. Do // this after flushing the stats -- this will re-register // the MPI statistics. if (m_MPI != null) { m_MPI.updateCatalog(diffCommands, m_catalogContext, csp); } new ConfigLogging().logCatalogAndDeployment(); return Pair.of(m_catalogContext, csp); } } @Override public VoltDB.Configuration getConfig() { return m_config; } @Override public String getBuildString() { return m_buildString == null ? "VoltDB" : m_buildString; } @Override public String getVersionString() { return m_versionString; } /** * Used for testing when you don't have an instance. Should do roughly what * {@link #isCompatibleVersionString(String)} does. */ static boolean staticIsCompatibleVersionString(String versionString) { return versionString.matches(m_defaultHotfixableRegexPattern); } @Override public boolean isCompatibleVersionString(String versionString) { return versionString.matches(m_hotfixableRegexPattern); } @Override public String getEELibraryVersionString() { return m_defaultVersionString; } @Override public HostMessenger getHostMessenger() { return m_messenger; } @Override public ClientInterface getClientInterface() { return m_clientInterface; } @Override public OpsAgent getOpsAgent(OpsSelector selector) { return m_opsRegistrar.getAgent(selector); } @Override public StatsAgent getStatsAgent() { OpsAgent statsAgent = m_opsRegistrar.getAgent(OpsSelector.STATISTICS); assert(statsAgent instanceof StatsAgent); return (StatsAgent)statsAgent; } @Override public MemoryStats getMemoryStatsSource() { return m_memoryStats; } @Override public CatalogContext getCatalogContext() { return m_catalogContext; } /** * Tells if the VoltDB is running. m_isRunning needs to be set to true * when the run() method is called, and set to false when shutting down. * * @return true if the VoltDB is running. */ @Override public boolean isRunning() { return m_isRunning; } @Override public void halt() { Thread shutdownThread = new Thread() { @Override public void run() { hostLog.warn("VoltDB node shutting down as requested by @StopNode command."); System.exit(0); } }; shutdownThread.start(); } /** * Debugging function - creates a record of the current state of the system. * @param out PrintStream to write report to. */ public void createRuntimeReport(PrintStream out) { // This function may be running in its own thread. out.print("MIME-Version: 1.0\n"); out.print("Content-type: multipart/mixed; boundary=\"reportsection\""); out.print("\n\n--reportsection\nContent-Type: text/plain\n\nClientInterface Report\n"); if (m_clientInterface != null) { out.print(m_clientInterface.toString() + "\n"); } } @Override public BackendTarget getBackendTargetType() { return m_config.m_backend; } @Override public synchronized void onExecutionSiteRejoinCompletion(long transferred) { m_executionSiteRecoveryFinish = System.currentTimeMillis(); m_executionSiteRecoveryTransferred = transferred; onRejoinCompletion(); } private void onRejoinCompletion() { // null out the rejoin coordinator if (m_joinCoordinator != null) { m_joinCoordinator.close(); } m_joinCoordinator = null; // Mark the data transfer as done so CL can make the right decision when a truncation snapshot completes m_rejoinDataPending = false; try { m_testBlockRecoveryCompletion.acquire(); } catch (InterruptedException e) {} final long delta = ((m_executionSiteRecoveryFinish - m_recoveryStartTime) / 1000); final long megabytes = m_executionSiteRecoveryTransferred / (1024 * 1024); final double megabytesPerSecond = megabytes / ((m_executionSiteRecoveryFinish - m_recoveryStartTime) / 1000.0); if (m_clientInterface != null) { m_clientInterface.mayActivateSnapshotDaemon(); try { m_clientInterface.startAcceptingConnections(); } catch (IOException e) { hostLog.l7dlog(Level.FATAL, LogKeys.host_VoltDB_ErrorStartAcceptingConnections.name(), e); VoltDB.crashLocalVoltDB("Error starting client interface.", true, e); } } if (m_config.m_startAction == StartAction.REJOIN) { consoleLog.info( "Node data recovery completed after " + delta + " seconds with " + megabytes + " megabytes transferred at a rate of " + megabytesPerSecond + " megabytes/sec"); } try { final ZooKeeper zk = m_messenger.getZK(); boolean logRecoveryCompleted = false; if (getCommandLog().getClass().getName().equals("org.voltdb.CommandLogImpl")) { String requestNode = zk.create(VoltZK.request_truncation_snapshot_node, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); if (m_rejoinTruncationReqId == null) { m_rejoinTruncationReqId = requestNode; } } else { logRecoveryCompleted = true; } // Join creates a truncation snapshot as part of the join process, // so there is no need to wait for the truncation snapshot requested // above to finish. if (logRecoveryCompleted || m_joining) { String actionName = m_joining ? "join" : "rejoin"; m_rejoining = false; m_joining = false; consoleLog.info(String.format("Node %s completed", actionName)); } } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to log host rejoin completion to ZK", true, e); } hostLog.info("Logging host rejoin completion to ZK"); } @Override public CommandLog getCommandLog() { return m_commandLog; } @Override public OperationMode getMode() { return m_mode; } @Override public void setMode(OperationMode mode) { if (m_mode != mode) { if (mode == OperationMode.PAUSED) { hostLog.info("Server is entering admin mode and pausing."); } else if (m_mode == OperationMode.PAUSED) { hostLog.info("Server is exiting admin mode and resuming operation."); } } m_mode = mode; } @Override public void setStartMode(OperationMode mode) { m_startMode = mode; } @Override public OperationMode getStartMode() { return m_startMode; } @Override public void setReplicationRole(ReplicationRole role) { if (role == ReplicationRole.NONE && m_config.m_replicationRole == ReplicationRole.REPLICA) { consoleLog.info("Promoting replication role from replica to master."); } m_config.m_replicationRole = role; if (m_clientInterface != null) { m_clientInterface.setReplicationRole(m_config.m_replicationRole); } } @Override public ReplicationRole getReplicationRole() { return m_config.m_replicationRole; } /** * Metadata is a JSON object */ @Override public String getLocalMetadata() { return m_localMetadata; } @Override public void onRestoreCompletion(long txnId, Map<Integer, Long> perPartitionTxnIds) { /* * Command log is already initialized if this is a rejoin or a join */ if ((m_commandLog != null) && (m_commandLog.needsInitialization())) { // Initialize command logger m_commandLog.init(m_catalogContext, txnId, m_cartographer.getPartitionCount(), m_config.m_commandLogBinding, perPartitionTxnIds); try { ZKCountdownLatch latch = new ZKCountdownLatch(m_messenger.getZK(), VoltZK.commandlog_init_barrier, m_messenger.getLiveHostIds().size()); latch.countDown(true); latch.await(); } catch (Exception e) { VoltDB.crashLocalVoltDB("Failed to init and wait on command log init barrier", true, e); } } /* * IV2: After the command log is initialized, force the writing of the initial * viable replay set. Turns into a no-op with no command log, on the non-leader sites, and on the MPI. */ for (Initiator initiator : m_iv2Initiators) { initiator.enableWritingIv2FaultLog(); } /* * IV2: From this point on, not all node failures should crash global VoltDB. */ if (m_leaderAppointer != null) { m_leaderAppointer.onReplayCompletion(); } if (!m_rejoining && !m_joining) { if (m_clientInterface != null) { try { m_clientInterface.startAcceptingConnections(); } catch (IOException e) { hostLog.l7dlog(Level.FATAL, LogKeys.host_VoltDB_ErrorStartAcceptingConnections.name(), e); VoltDB.crashLocalVoltDB("Error starting client interface.", true, e); } } } // Start listening on the DR ports prepareReplication(); if (m_startMode != null) { m_mode = m_startMode; } else { // Shouldn't be here, but to be safe m_mode = OperationMode.RUNNING; } consoleLog.l7dlog( Level.INFO, LogKeys.host_VoltDB_ServerCompletedInitialization.name(), null); // Create a zk node to indicate initialization is completed m_messenger.getZK().create(VoltZK.init_completed, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new ZKUtil.StringCallback(), null); } @Override public SnapshotCompletionMonitor getSnapshotCompletionMonitor() { return m_snapshotCompletionMonitor; } @Override public synchronized void recoveryComplete(String requestId) { assert(m_rejoinDataPending == false); if (m_rejoining) { if (m_rejoinTruncationReqId.compareTo(requestId) <= 0) { String actionName = m_joining ? "join" : "rejoin"; consoleLog.info(String.format("Node %s completed", actionName)); m_rejoinTruncationReqId = null; m_rejoining = false; } else { // If we saw some other truncation request ID, then try the same one again. As long as we // don't flip the m_rejoining state, all truncation snapshot completions will call back to here. try { final ZooKeeper zk = m_messenger.getZK(); String requestNode = zk.create(VoltZK.request_truncation_snapshot_node, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); if (m_rejoinTruncationReqId == null) { m_rejoinTruncationReqId = requestNode; } } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to retry post-rejoin truncation snapshot request.", true, e); } } } } @Override public ScheduledExecutorService getSES(boolean priority) { return priority ? m_periodicPriorityWorkThread : m_periodicWorkThread; } /** * See comment on {@link VoltDBInterface#scheduleWork(Runnable, long, long, TimeUnit)} vs * {@link VoltDBInterface#schedulePriorityWork(Runnable, long, long, TimeUnit)} */ @Override public ScheduledFuture<?> scheduleWork(Runnable work, long initialDelay, long delay, TimeUnit unit) { if (delay > 0) { return m_periodicWorkThread.scheduleWithFixedDelay(work, initialDelay, delay, unit); } else { return m_periodicWorkThread.schedule(work, initialDelay, unit); } } @Override public ListeningExecutorService getComputationService() { return m_computationService; } private void prepareReplication() { try { if (m_nodeDRGateway != null) { m_nodeDRGateway.start(); m_nodeDRGateway.bindPorts(); } } catch (Exception ex) { MiscUtils.printPortsInUse(hostLog); VoltDB.crashLocalVoltDB("Failed to initialize DR", false, ex); } } @Override public void setReplicationActive(boolean active) { if (m_replicationActive != active) { m_replicationActive = active; try { JSONStringer js = new JSONStringer(); js.object(); // Replication role should the be same across the cluster js.key("role").value(getReplicationRole().ordinal()); js.key("active").value(m_replicationActive); js.endObject(); getHostMessenger().getZK().setData(VoltZK.replicationconfig, js.toString().getBytes("UTF-8"), -1); } catch (Exception e) { e.printStackTrace(); hostLog.error("Failed to write replication active state to ZK: " + e.getMessage()); } if (m_nodeDRGateway != null) { m_nodeDRGateway.setActive(active); } } } @Override public boolean getReplicationActive() { return m_replicationActive; } @Override public SiteTracker getSiteTrackerForSnapshot() { return new SiteTracker(m_messenger.getHostId(), m_cartographer.getSiteTrackerMailboxMap(), 0); } /** * Create default deployment.xml file in voltdbroot if the deployment path is null. * * @return path to default deployment file * @throws IOException */ static String setupDefaultDeployment() throws IOException { // Since there's apparently no deployment to override the path to voltdbroot it should be // safe to assume it's under the working directory. // CatalogUtil.getVoltDbRoot() creates the voltdbroot directory as needed. File voltDbRoot = CatalogUtil.getVoltDbRoot(null); String pathToDeployment = voltDbRoot.getPath() + File.separator + "deployment.xml"; File deploymentXMLFile = new File(pathToDeployment); hostLog.info("Generating default deployment file \"" + deploymentXMLFile.getAbsolutePath() + "\""); BufferedWriter bw = new BufferedWriter(new FileWriter(deploymentXMLFile)); for (String line : defaultDeploymentXML) { bw.write(line); bw.newLine(); } bw.flush(); bw.close(); return deploymentXMLFile.getAbsolutePath(); } /* * Validate the build string with the rest of the cluster * by racing to publish it to ZK and then comparing the one this process * has to the one in ZK. They should all match. The method returns a future * so that init can continue while the ZK call is pending since it ZK is pretty * slow. */ private Future<?> validateBuildString(final String buildString, ZooKeeper zk) { final SettableFuture<Object> retval = SettableFuture.create(); byte buildStringBytes[] = null; try { buildStringBytes = buildString.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } final byte buildStringBytesFinal[] = buildStringBytes; //Can use a void callback because ZK will execute the create and then the get in order //It's a race so it doesn't have to succeed zk.create( VoltZK.buildstring, buildStringBytes, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new ZKUtil.StringCallback(), null); zk.getData(VoltZK.buildstring, false, new org.apache.zookeeper_voltpatches.AsyncCallback.DataCallback() { @Override public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { KeeperException.Code code = KeeperException.Code.get(rc); if (code == KeeperException.Code.OK) { if (Arrays.equals(buildStringBytesFinal, data)) { retval.set(null); } else { try { VoltDB.crashGlobalVoltDB("Local build string \"" + buildString + "\" does not match cluster build string \"" + new String(data, "UTF-8") + "\"", false, null); } catch (UnsupportedEncodingException e) { retval.setException(new AssertionError(e)); } } } else { retval.setException(KeeperException.create(code)); } } }, null); return retval; } /** * See comment on {@link VoltDBInterface#schedulePriorityWork(Runnable, long, long, TimeUnit)} vs * {@link VoltDBInterface#scheduleWork(Runnable, long, long, TimeUnit)} */ @Override public ScheduledFuture<?> schedulePriorityWork(Runnable work, long initialDelay, long delay, TimeUnit unit) { if (delay > 0) { return m_periodicPriorityWorkThread.scheduleWithFixedDelay(work, initialDelay, delay, unit); } else { return m_periodicPriorityWorkThread.schedule(work, initialDelay, unit); } } private void checkHeapSanity(boolean isPro, int tableCount, int sitesPerHost, int kfactor) { long megabytes = 1024 * 1024; long maxMemory = Runtime.getRuntime().maxMemory() / megabytes; long drRqt = isPro ? 128 * sitesPerHost : 0; long crazyThresh = computeMinimumHeapRqt(isPro, tableCount, sitesPerHost, kfactor); long warnThresh = crazyThresh + drRqt; if (maxMemory < crazyThresh) { StringBuilder builder = new StringBuilder(); builder.append(String.format("The configuration of %d tables, %d sites-per-host, and k-factor of %d requires at least %d MB of Java heap memory. ", tableCount, sitesPerHost, kfactor, crazyThresh)); builder.append(String.format("The maximum amount of heap memory available to the JVM is %d MB. ", maxMemory)); builder.append("Please increase the maximum heap size using the VOLTDB_HEAPMAX environment variable and then restart VoltDB."); consoleLog.warn(builder.toString()); } else if (maxMemory < warnThresh) { StringBuilder builder = new StringBuilder(); builder.append(String.format("The configuration of %d tables, %d sites-per-host, and k-factor of %d requires at least %d MB of Java heap memory. ", tableCount, sitesPerHost, kfactor, crazyThresh)); builder.append(String.format("The maximum amount of heap memory available to the JVM is %d MB. ", maxMemory)); builder.append("The system has enough memory for normal operation but is in danger of running out of Java heap space if the DR feature is used. "); builder.append("Use the VOLTDB_HEAPMAX environment variable to adjust the Java max heap size before starting VoltDB, as necessary."); consoleLog.warn(builder.toString()); } } // Compute the minimum required heap to run this configuration. This comes from the documentation, // http://voltdb.com/docs/PlanningGuide/MemSizeServers.php#MemSizeHeapGuidelines // Any changes there should get reflected here and vice versa. private long computeMinimumHeapRqt(boolean isPro, int tableCount, int sitesPerHost, int kfactor) { long baseRqt = 384; long tableRqt = 10 * tableCount; long rejoinRqt = (isPro && kfactor > 0) ? 128 * sitesPerHost : 0; return baseRqt + tableRqt + rejoinRqt; } @Override public <T> ListenableFuture<T> submitSnapshotIOWork(Callable<T> work) { assert m_snapshotIOAgent != null; return m_snapshotIOAgent.submit(work); } @Override public long getClusterUptime() { return System.currentTimeMillis() - getHostMessenger().getInstanceId().getTimestamp(); } }
src/frontend/org/voltdb/RealVoltDB.java
/* This file is part of VoltDB. * Copyright (C) 2008-2014 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.lang.management.ManagementFactory; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.SortedMap; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.cassandra_voltpatches.GCInspector; import org.apache.log4j.Appender; import org.apache.log4j.DailyRollingFileAppender; import org.apache.log4j.FileAppender; import org.apache.log4j.Logger; import org.apache.zookeeper_voltpatches.CreateMode; import org.apache.zookeeper_voltpatches.KeeperException; import org.apache.zookeeper_voltpatches.WatchedEvent; import org.apache.zookeeper_voltpatches.Watcher; import org.apache.zookeeper_voltpatches.ZooDefs.Ids; import org.apache.zookeeper_voltpatches.ZooKeeper; import org.apache.zookeeper_voltpatches.data.Stat; import org.json_voltpatches.JSONException; import org.json_voltpatches.JSONObject; import org.json_voltpatches.JSONStringer; import org.voltcore.logging.Level; import org.voltcore.logging.VoltLogger; import org.voltcore.messaging.HostMessenger; import org.voltcore.messaging.SiteMailbox; import org.voltcore.utils.CoreUtils; import org.voltcore.utils.OnDemandBinaryLogger; import org.voltcore.utils.Pair; import org.voltcore.utils.ShutdownHooks; import org.voltcore.zk.ZKCountdownLatch; import org.voltcore.zk.ZKUtil; import org.voltdb.TheHashinator.HashinatorType; import org.voltdb.catalog.Catalog; import org.voltdb.catalog.Cluster; import org.voltdb.catalog.Database; import org.voltdb.catalog.SnapshotSchedule; import org.voltdb.compiler.AdHocCompilerCache; import org.voltdb.compiler.AsyncCompilerAgent; import org.voltdb.compiler.ClusterConfig; import org.voltdb.compiler.deploymentfile.DeploymentType; import org.voltdb.compiler.deploymentfile.HeartbeatType; import org.voltdb.compiler.deploymentfile.UsersType; import org.voltdb.dtxn.InitiatorStats; import org.voltdb.dtxn.LatencyHistogramStats; import org.voltdb.dtxn.LatencyStats; import org.voltdb.dtxn.SiteTracker; import org.voltdb.export.ExportManager; import org.voltdb.iv2.Cartographer; import org.voltdb.iv2.Initiator; import org.voltdb.iv2.KSafetyStats; import org.voltdb.iv2.LeaderAppointer; import org.voltdb.iv2.MpInitiator; import org.voltdb.iv2.SpInitiator; import org.voltdb.iv2.TxnEgo; import org.voltdb.join.BalancePartitionsStatistics; import org.voltdb.join.ElasticJoinService; import org.voltdb.licensetool.LicenseApi; import org.voltdb.messaging.VoltDbMessageFactory; import org.voltdb.planner.ActivePlanRepository; import org.voltdb.rejoin.Iv2RejoinCoordinator; import org.voltdb.rejoin.JoinCoordinator; import org.voltdb.utils.CLibrary; import org.voltdb.utils.CatalogUtil; import org.voltdb.utils.CatalogUtil.CatalogAndIds; import org.voltdb.utils.Encoder; import org.voltdb.utils.HTTPAdminListener; import org.voltdb.utils.LogKeys; import org.voltdb.utils.MiscUtils; import org.voltdb.utils.PlatformProperties; import org.voltdb.utils.SystemStatsCollector; import org.voltdb.utils.VoltSampler; import com.google_voltpatches.common.base.Charsets; import com.google_voltpatches.common.base.Throwables; import com.google_voltpatches.common.collect.ImmutableList; import com.google_voltpatches.common.util.concurrent.ListenableFuture; import com.google_voltpatches.common.util.concurrent.ListeningExecutorService; import com.google_voltpatches.common.util.concurrent.SettableFuture; /** * RealVoltDB initializes global server components, like the messaging * layer, ExecutionSite(s), and ClientInterface. It provides accessors * or references to those global objects. It is basically the global * namespace. A lot of the global namespace is described by VoltDBInterface * to allow test mocking. */ public class RealVoltDB implements VoltDBInterface, RestoreAgent.Callback { private static final boolean DISABLE_JMX; static { DISABLE_JMX = Boolean.valueOf(System.getProperty("DISABLE_JMX", "false")); } private static final VoltLogger hostLog = new VoltLogger("HOST"); private static final VoltLogger consoleLog = new VoltLogger("CONSOLE"); /** Default deployment file contents if path to deployment is null */ private static final String[] defaultDeploymentXML = { "<?xml version=\"1.0\"?>", "<!-- IMPORTANT: This file is an auto-generated default deployment configuration.", " Changes to this file will be overwritten. Copy it elsewhere if you", " want to use it as a starting point for a custom configuration. -->", "<deployment>", " <cluster hostcount=\"1\" />", " <httpd enabled=\"true\">", " <jsonapi enabled=\"true\" />", " </httpd>", "</deployment>" }; public VoltDB.Configuration m_config = new VoltDB.Configuration(); int m_configuredNumberOfPartitions; int m_configuredReplicationFactor; // CatalogContext is immutable, just make sure that accessors see a consistent version volatile CatalogContext m_catalogContext; private String m_buildString; static final String m_defaultVersionString = "4.8"; // by default set the version to only be compatible with itself static final String m_defaultHotfixableRegexPattern = "^\\Q4.8\\E\\z"; // these next two are non-static because they can be overrriden on the CLI for test private String m_versionString = m_defaultVersionString; private String m_hotfixableRegexPattern = m_defaultHotfixableRegexPattern; HostMessenger m_messenger = null; private ClientInterface m_clientInterface = null; HTTPAdminListener m_adminListener; private OpsRegistrar m_opsRegistrar = new OpsRegistrar(); private AsyncCompilerAgent m_asyncCompilerAgent = new AsyncCompilerAgent(); public AsyncCompilerAgent getAsyncCompilerAgent() { return m_asyncCompilerAgent; } private PartitionCountStats m_partitionCountStats = null; private IOStats m_ioStats = null; private MemoryStats m_memoryStats = null; private CpuStats m_cpuStats = null; private StatsManager m_statsManager = null; private SnapshotCompletionMonitor m_snapshotCompletionMonitor; // These are unused locally, but they need to be registered with the StatsAgent so they're // globally available @SuppressWarnings("unused") private InitiatorStats m_initiatorStats; private LiveClientsStats m_liveClientsStats = null; int m_myHostId; String m_httpPortExtraLogMessage = null; boolean m_jsonEnabled; DeploymentType m_deployment; // IV2 things List<Initiator> m_iv2Initiators = new ArrayList<Initiator>(); Cartographer m_cartographer = null; LeaderAppointer m_leaderAppointer = null; GlobalServiceElector m_globalServiceElector = null; MpInitiator m_MPI = null; Map<Integer, Long> m_iv2InitiatorStartingTxnIds = new HashMap<Integer, Long>(); // Should the execution sites be started in recovery mode // (used for joining a node to an existing cluster) // If CL is enabled this will be set to true // by the CL when the truncation snapshot completes // and this node is viable for replay volatile boolean m_rejoining = false; // Need to separate the concepts of rejoin data transfer and rejoin // completion. This boolean tracks whether or not the data transfer // process is done. CL truncation snapshots will not flip the all-complete // boolean until no mode data is pending. // Yes, this is fragile having two booleans. We could aggregate them into // some rejoining state enum at some point. volatile boolean m_rejoinDataPending = false; // Since m_rejoinDataPending is set asynchronously, sites could have inconsistent // view of what the value is during the execution of a sysproc. Use this and // m_safeMpTxnId to prevent the race. The m_safeMpTxnId is updated once in the // lifetime of the node to reflect the first MP txn that witnessed the flip of // m_rejoinDataPending. private final Object m_safeMpTxnIdLock = new Object(); private long m_lastSeenMpTxnId = Long.MIN_VALUE; private long m_safeMpTxnId = Long.MAX_VALUE; String m_rejoinTruncationReqId = null; // Are we adding the node to the cluster instead of rejoining? volatile boolean m_joining = false; boolean m_replicationActive = false; private NodeDRGateway m_nodeDRGateway = null; //Only restrict recovery completion during test static Semaphore m_testBlockRecoveryCompletion = new Semaphore(Integer.MAX_VALUE); private long m_executionSiteRecoveryFinish; private long m_executionSiteRecoveryTransferred; // Rejoin coordinator private JoinCoordinator m_joinCoordinator = null; private ElasticJoinService m_elasticJoinService = null; // Snapshot IO agent private SnapshotIOAgent m_snapshotIOAgent = null; // id of the leader, or the host restore planner says has the catalog int m_hostIdWithStartupCatalog; String m_pathToStartupCatalog; // Synchronize initialize and shutdown private final Object m_startAndStopLock = new Object(); // Synchronize updates of catalog contexts across the multiple sites on this host. // Ensure that the first site to reach catalogUpdate() does all the work and that no // others enter until that's finished. CatalogContext is immutable and volatile, accessors // should be able to always get a valid context without needing this lock. private final Object m_catalogUpdateLock = new Object(); // add a random number to the sampler output to make it likely to be unique for this process. private final VoltSampler m_sampler = new VoltSampler(10, "sample" + String.valueOf(new Random().nextInt() % 10000) + ".txt"); private final AtomicBoolean m_hasStartedSampler = new AtomicBoolean(false); List<Integer> m_partitionsToSitesAtStartupForExportInit; RestoreAgent m_restoreAgent = null; private ListeningExecutorService m_es = CoreUtils.getCachedSingleThreadExecutor("StartAction ZK Watcher", 15000); private volatile boolean m_isRunning = false; @Override public boolean rejoining() { return m_rejoining; } @Override public boolean rejoinDataPending() { return m_rejoinDataPending; } @Override public boolean isMpSysprocSafeToExecute(long txnId) { synchronized (m_safeMpTxnIdLock) { if (txnId >= m_safeMpTxnId) { return true; } if (txnId > m_lastSeenMpTxnId) { m_lastSeenMpTxnId = txnId; if (!rejoinDataPending() && m_safeMpTxnId == Long.MAX_VALUE) { m_safeMpTxnId = txnId; } } return txnId >= m_safeMpTxnId; } } private long m_recoveryStartTime; CommandLog m_commandLog; private volatile OperationMode m_mode = OperationMode.INITIALIZING; private OperationMode m_startMode = null; volatile String m_localMetadata = ""; private ListeningExecutorService m_computationService; private Thread m_configLogger; // methods accessed via the singleton @Override public void startSampler() { if (m_hasStartedSampler.compareAndSet(false, true)) { m_sampler.start(); } } private ScheduledThreadPoolExecutor m_periodicWorkThread; private ScheduledThreadPoolExecutor m_periodicPriorityWorkThread; // The configured license api: use to decide enterprise/community edition feature enablement LicenseApi m_licenseApi; @SuppressWarnings("unused") private LatencyStats m_latencyStats; private LatencyHistogramStats m_latencyHistogramStats; @Override public LicenseApi getLicenseApi() { return m_licenseApi; } /** * Initialize all the global components, then initialize all the m_sites. */ @Override public void initialize(VoltDB.Configuration config) { ShutdownHooks.enableServerStopLogging(); synchronized(m_startAndStopLock) { // check that this is a 64 bit VM if (System.getProperty("java.vm.name").contains("64") == false) { hostLog.fatal("You are running on an unsupported (probably 32 bit) JVM. Exiting."); System.exit(-1); } consoleLog.l7dlog( Level.INFO, LogKeys.host_VoltDB_StartupString.name(), null); // If there's no deployment provide a default and put it under voltdbroot. if (config.m_pathToDeployment == null) { try { config.m_pathToDeployment = setupDefaultDeployment(); config.m_deploymentDefault = true; } catch (IOException e) { VoltDB.crashLocalVoltDB("Failed to write default deployment.", false, null); } } // set the mode first thing m_mode = OperationMode.INITIALIZING; m_config = config; m_startMode = null; // set a bunch of things to null/empty/new for tests // which reusue the process m_safeMpTxnId = Long.MAX_VALUE; m_lastSeenMpTxnId = Long.MIN_VALUE; m_clientInterface = null; m_adminListener = null; m_commandLog = new DummyCommandLog(); m_deployment = null; m_messenger = null; m_startMode = null; m_opsRegistrar = new OpsRegistrar(); m_asyncCompilerAgent = new AsyncCompilerAgent(); m_snapshotCompletionMonitor = null; m_catalogContext = null; m_partitionCountStats = null; m_ioStats = null; m_memoryStats = null; m_statsManager = null; m_restoreAgent = null; m_recoveryStartTime = System.currentTimeMillis(); m_hostIdWithStartupCatalog = 0; m_pathToStartupCatalog = m_config.m_pathToCatalog; m_replicationActive = false; m_configLogger = null; ActivePlanRepository.clear(); // set up site structure final int computationThreads = Math.max(2, CoreUtils.availableProcessors() / 4); m_computationService = CoreUtils.getListeningExecutorService( "Computation service thread", computationThreads, m_config.m_computationCoreBindings); // determine if this is a rejoining node // (used for license check and later the actual rejoin) boolean isRejoin = false; if (config.m_startAction.doesRejoin()) { isRejoin = true; } m_rejoining = isRejoin; m_rejoinDataPending = isRejoin || config.m_startAction == StartAction.JOIN; m_joining = config.m_startAction == StartAction.JOIN; // Set std-out/err to use the UTF-8 encoding and fail if UTF-8 isn't supported try { System.setOut(new PrintStream(System.out, true, "UTF-8")); System.setErr(new PrintStream(System.err, true, "UTF-8")); } catch (UnsupportedEncodingException e) { hostLog.fatal("Support for the UTF-8 encoding is required for VoltDB. This means you are likely running an unsupported JVM. Exiting."); System.exit(-1); } m_snapshotCompletionMonitor = new SnapshotCompletionMonitor(); readBuildInfo(config.m_isEnterprise ? "Enterprise Edition" : "Community Edition"); // Replay command line args that we can see StringBuilder sb = new StringBuilder(2048).append("Command line arguments: "); sb.append(System.getProperty("sun.java.command", "[not available]")); hostLog.info(sb.toString()); List<String> iargs = ManagementFactory.getRuntimeMXBean().getInputArguments(); sb.delete(0, sb.length()).append("Command line JVM arguments:"); for (String iarg : iargs) sb.append(" ").append(iarg); if (iargs.size() > 0) hostLog.info(sb.toString()); else hostLog.info("No JVM command line args known."); sb.delete(0, sb.length()).append("Command line JVM classpath: "); sb.append(System.getProperty("java.class.path", "[not available]")); hostLog.info(sb.toString()); // use CLI overrides for testing hotfix version compatibility if (m_config.m_versionStringOverrideForTest != null) { m_versionString = m_config.m_versionStringOverrideForTest; } if (m_config.m_versionCompatibilityRegexOverrideForTest != null) { m_hotfixableRegexPattern = m_config.m_versionCompatibilityRegexOverrideForTest; } buildClusterMesh(isRejoin || m_joining); //Register dummy agents immediately m_opsRegistrar.registerMailboxes(m_messenger); //Start validating the build string in the background final Future<?> buildStringValidation = validateBuildString(getBuildString(), m_messenger.getZK()); // race to create start action nodes and then verify theirs compatibility. m_messenger.getZK().create(VoltZK.start_action, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new ZKUtil.StringCallback(), null); VoltZK.createStartActionNode(m_messenger.getZK(), m_messenger.getHostId(), m_config.m_startAction); validateStartAction(); final int numberOfNodes = readDeploymentAndCreateStarterCatalogContext(); if (!isRejoin && !m_joining) { m_messenger.waitForGroupJoin(numberOfNodes); } // Create the thread pool here. It's needed by buildClusterMesh() m_periodicWorkThread = CoreUtils.getScheduledThreadPoolExecutor("Periodic Work", 1, CoreUtils.SMALL_STACK_SIZE); m_periodicPriorityWorkThread = CoreUtils.getScheduledThreadPoolExecutor("Periodic Priority Work", 1, CoreUtils.SMALL_STACK_SIZE); Class<?> snapshotIOAgentClass = MiscUtils.loadProClass("org.voltdb.SnapshotIOAgentImpl", "Snapshot", true); if (snapshotIOAgentClass != null) { try { m_snapshotIOAgent = (SnapshotIOAgent) snapshotIOAgentClass.getConstructor(HostMessenger.class, long.class) .newInstance(m_messenger, m_messenger.getHSIdForLocalSite(HostMessenger.SNAPSHOT_IO_AGENT_ID)); m_messenger.createMailbox(m_snapshotIOAgent.getHSId(), m_snapshotIOAgent); } catch (Exception e) { VoltDB.crashLocalVoltDB("Failed to instantiate snapshot IO agent", true, e); } } if (m_config.m_pathToLicense == null) { m_licenseApi = MiscUtils.licenseApiFactory(); if (m_licenseApi == null) { hostLog.fatal("Unable to open license file in default directories"); } } else { m_licenseApi = MiscUtils.licenseApiFactory(m_config.m_pathToLicense); if (m_licenseApi == null) { hostLog.fatal("Unable to open license file in provided path: " + m_config.m_pathToLicense); } } if (m_licenseApi == null) { hostLog.fatal("Please contact [email protected] to request a license."); VoltDB.crashLocalVoltDB("Failed to initialize license verifier. " + "See previous log message for details.", false, null); } // Create the GlobalServiceElector. Do this here so we can register the MPI with it // when we construct it below m_globalServiceElector = new GlobalServiceElector(m_messenger.getZK(), m_messenger.getHostId()); // Start the GlobalServiceElector. Not sure where this will actually belong. try { m_globalServiceElector.start(); } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to start GlobalServiceElector", true, e); } // Always create a mailbox for elastic join data transfer if (m_config.m_isEnterprise) { long elasticHSId = m_messenger.getHSIdForLocalSite(HostMessenger.REBALANCE_SITE_ID); m_messenger.createMailbox(elasticHSId, new SiteMailbox(m_messenger, elasticHSId)); } if (m_joining) { Class<?> elasticJoinCoordClass = MiscUtils.loadProClass("org.voltdb.join.ElasticJoinNodeCoordinator", "Elastic", false); try { Constructor<?> constructor = elasticJoinCoordClass.getConstructor(HostMessenger.class, String.class); m_joinCoordinator = (JoinCoordinator) constructor.newInstance(m_messenger, m_catalogContext.cluster.getVoltroot()); m_messenger.registerMailbox(m_joinCoordinator); m_joinCoordinator.initialize(m_deployment.getCluster().getKfactor()); } catch (Exception e) { VoltDB.crashLocalVoltDB("Failed to instantiate join coordinator", true, e); } } /* * Construct all the mailboxes for things that need to be globally addressable so they can be published * in one atomic shot. * * The starting state for partition assignments are statically derived from the host id generated * by host messenger and the k-factor/host count/sites per host. This starting state * is published to ZK as the topology metadata node. * * On join and rejoin the node has to inspect the topology meta node to find out what is missing * and then update the topology listing itself as the replica for those partitions. * Then it does a compare and set of the topology. * * Ning: topology may not reflect the true partitions in the cluster during join. So if another node * is trying to rejoin, it should rely on the cartographer's view to pick the partitions to replace. */ JSONObject topo = getTopology(config.m_startAction, m_joinCoordinator); m_partitionsToSitesAtStartupForExportInit = new ArrayList<Integer>(); try { // IV2 mailbox stuff ClusterConfig clusterConfig = new ClusterConfig(topo); m_configuredReplicationFactor = clusterConfig.getReplicationFactor(); m_cartographer = new Cartographer(m_messenger, m_configuredReplicationFactor, m_catalogContext.cluster.getNetworkpartition()); List<Integer> partitions = null; if (isRejoin) { m_configuredNumberOfPartitions = m_cartographer.getPartitionCount(); partitions = m_cartographer.getIv2PartitionsToReplace(m_configuredReplicationFactor, clusterConfig.getSitesPerHost()); if (partitions.size() == 0) { VoltDB.crashLocalVoltDB("The VoltDB cluster already has enough nodes to satisfy " + "the requested k-safety factor of " + m_configuredReplicationFactor + ".\n" + "No more nodes can join.", false, null); } } else { m_configuredNumberOfPartitions = clusterConfig.getPartitionCount(); partitions = ClusterConfig.partitionsForHost(topo, m_messenger.getHostId()); } for (int ii = 0; ii < partitions.size(); ii++) { Integer partition = partitions.get(ii); m_iv2InitiatorStartingTxnIds.put( partition, TxnEgo.makeZero(partition).getTxnId()); } m_iv2Initiators = createIv2Initiators( partitions, m_config.m_startAction, m_partitionsToSitesAtStartupForExportInit); m_iv2InitiatorStartingTxnIds.put( MpInitiator.MP_INIT_PID, TxnEgo.makeZero(MpInitiator.MP_INIT_PID).getTxnId()); // Pass the local HSIds to the MPI so it can farm out buddy sites // to the RO MP site pool List<Long> localHSIds = new ArrayList<Long>(); for (Initiator ii : m_iv2Initiators) { localHSIds.add(ii.getInitiatorHSId()); } m_MPI = new MpInitiator(m_messenger, localHSIds, getStatsAgent()); m_iv2Initiators.add(m_MPI); // Make a list of HDIds to join Map<Integer, Long> partsToHSIdsToRejoin = new HashMap<Integer, Long>(); for (Initiator init : m_iv2Initiators) { if (init.isRejoinable()) { partsToHSIdsToRejoin.put(init.getPartitionId(), init.getInitiatorHSId()); } } OnDemandBinaryLogger.path = m_catalogContext.cluster.getVoltroot(); if (isRejoin) { SnapshotSaveAPI.recoveringSiteCount.set(partsToHSIdsToRejoin.size()); hostLog.info("Set recovering site count to " + partsToHSIdsToRejoin.size()); m_joinCoordinator = new Iv2RejoinCoordinator(m_messenger, partsToHSIdsToRejoin.values(), m_catalogContext.cluster.getVoltroot(), m_config.m_startAction == StartAction.LIVE_REJOIN); m_messenger.registerMailbox(m_joinCoordinator); if (m_config.m_startAction == StartAction.LIVE_REJOIN) { hostLog.info("Using live rejoin."); } else { hostLog.info("Using blocking rejoin."); } } else if (m_joining) { m_joinCoordinator.setPartitionsToHSIds(partsToHSIdsToRejoin); } } catch (Exception e) { VoltDB.crashLocalVoltDB(e.getMessage(), true, e); } // do the many init tasks in the Inits class Inits inits = new Inits(this, 1); inits.doInitializationWork(); // Need the catalog so that we know how many tables so we can guess at the necessary heap size // This is done under Inits.doInitializationWork(), so need to wait until we get here. // Current calculation needs pro/community knowledge, number of tables, and the sites/host, // which is the number of initiators (minus the possibly idle MPI initiator) checkHeapSanity(MiscUtils.isPro(), m_catalogContext.tables.size(), (m_iv2Initiators.size() - 1), m_configuredReplicationFactor); if (m_joining && m_config.m_replicationRole == ReplicationRole.REPLICA) { VoltDB.crashLocalVoltDB("Elastic join is prohibited on a replica cluster.", false, null); } collectLocalNetworkMetadata(); /* * Construct an adhoc planner for the initial catalog */ final CatalogSpecificPlanner csp = new CatalogSpecificPlanner(m_asyncCompilerAgent, m_catalogContext); // DR overflow directory File drOverflowDir = new File(m_catalogContext.cluster.getVoltroot(), "dr_overflow"); if (m_config.m_isEnterprise) { try { Class<?> ndrgwClass = null; if (Boolean.getBoolean("USE_DR_V2")) { ndrgwClass = Class.forName("org.voltdb.dr2.InvocationBufferServer"); } else { ndrgwClass = Class.forName("org.voltdb.dr.InvocationBufferServer"); } Constructor<?> ndrgwConstructor = ndrgwClass.getConstructor(File.class, boolean.class); m_nodeDRGateway = (NodeDRGateway) ndrgwConstructor.newInstance(drOverflowDir, m_replicationActive); } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to load DR system", true, e); } } // Initialize stats m_ioStats = new IOStats(); getStatsAgent().registerStatsSource(StatsSelector.IOSTATS, 0, m_ioStats); m_memoryStats = new MemoryStats(); getStatsAgent().registerStatsSource(StatsSelector.MEMORY, 0, m_memoryStats); getStatsAgent().registerStatsSource(StatsSelector.TOPO, 0, m_cartographer); m_partitionCountStats = new PartitionCountStats(m_cartographer); getStatsAgent().registerStatsSource(StatsSelector.PARTITIONCOUNT, 0, m_partitionCountStats); m_initiatorStats = new InitiatorStats(m_myHostId); m_liveClientsStats = new LiveClientsStats(); getStatsAgent().registerStatsSource(StatsSelector.LIVECLIENTS, 0, m_liveClientsStats); m_latencyStats = new LatencyStats(m_myHostId); getStatsAgent().registerStatsSource(StatsSelector.LATENCY, 0, m_latencyStats); m_latencyHistogramStats = new LatencyHistogramStats(m_myHostId); getStatsAgent().registerStatsSource(StatsSelector.LATENCY_HISTOGRAM, 0, m_latencyHistogramStats); BalancePartitionsStatistics rebalanceStats = new BalancePartitionsStatistics(); getStatsAgent().registerStatsSource(StatsSelector.REBALANCE, 0, rebalanceStats); KSafetyStats kSafetyStats = new KSafetyStats(); getStatsAgent().registerStatsSource(StatsSelector.KSAFETY, 0, kSafetyStats); m_cpuStats = new CpuStats(); getStatsAgent().registerStatsSource(StatsSelector.CPU, 0, m_cpuStats); /* * Initialize the command log on rejoin and join before configuring the IV2 * initiators. This will prevent them from receiving transactions * which need logging before the internal file writers are * initialized. Root cause of ENG-4136. * * If sync command log is on, not initializing the command log before the initiators * are up would cause deadlock. */ if ((m_commandLog != null) && (m_commandLog.needsInitialization())) { consoleLog.l7dlog(Level.INFO, LogKeys.host_VoltDB_StayTunedForLogging.name(), null); } else { consoleLog.l7dlog(Level.INFO, LogKeys.host_VoltDB_StayTunedForNoLogging.name(), null); } if (m_commandLog != null && (isRejoin || m_joining)) { //On rejoin the starting IDs are all 0 so technically it will load any snapshot //but the newest snapshot will always be the truncation snapshot taken after rejoin //completes at which point the node will mark itself as actually recovered. // // Use the partition count from the cluster config instead of the cartographer // here. Since the initiators are not started yet, the cartographer still doesn't // know about the new partitions at this point. m_commandLog.initForRejoin( m_catalogContext, Long.MIN_VALUE, m_configuredNumberOfPartitions, true, m_config.m_commandLogBinding, m_iv2InitiatorStartingTxnIds); } /* * Configure and start all the IV2 sites */ boolean usingCommandLog = false; try { usingCommandLog = m_config.m_isEnterprise && m_catalogContext.cluster.getLogconfig().get("log").getEnabled(); for (Initiator iv2init : m_iv2Initiators) { iv2init.configure( getBackendTargetType(), m_catalogContext, m_deployment.getCluster().getKfactor(), csp, m_configuredNumberOfPartitions, m_config.m_startAction, getStatsAgent(), m_memoryStats, m_commandLog, m_nodeDRGateway, m_config.m_executionCoreBindings.poll()); } // LeaderAppointer startup blocks if the initiators are not initialized. // So create the LeaderAppointer after the initiators. m_leaderAppointer = new LeaderAppointer( m_messenger, m_configuredNumberOfPartitions, m_deployment.getCluster().getKfactor(), m_catalogContext.cluster.getNetworkpartition(), m_catalogContext.cluster.getFaultsnapshots().get("CLUSTER_PARTITION"), usingCommandLog, topo, m_MPI, kSafetyStats); m_globalServiceElector.registerService(m_leaderAppointer); } catch (Exception e) { Throwable toLog = e; if (e instanceof ExecutionException) { toLog = ((ExecutionException)e).getCause(); } VoltDB.crashLocalVoltDB("Error configuring IV2 initiator.", true, toLog); } // Need to register the OpsAgents right before we turn on the client interface m_opsRegistrar.setDummyMode(false); // Create the client interface try { InetAddress clientIntf = null; InetAddress adminIntf = null; if (!m_config.m_externalInterface.trim().equals("")) { clientIntf = InetAddress.getByName(m_config.m_externalInterface); //client and admin interfaces are same by default. adminIntf = clientIntf; } //If user has specified on command line host:port override client and admin interfaces. if (m_config.m_clientInterface != null && m_config.m_clientInterface.trim().length() > 0) { clientIntf = InetAddress.getByName(m_config.m_clientInterface); } if (m_config.m_adminInterface != null && m_config.m_adminInterface.trim().length() > 0) { adminIntf = InetAddress.getByName(m_config.m_adminInterface); } m_clientInterface = ClientInterface.create(m_messenger, m_catalogContext, m_config.m_replicationRole, m_cartographer, m_configuredNumberOfPartitions, clientIntf, config.m_port, adminIntf, config.m_adminPort, m_config.m_timestampTestingSalt); } catch (Exception e) { VoltDB.crashLocalVoltDB(e.getMessage(), true, e); } // Create the statistics manager and register it to JMX registry m_statsManager = null; try { final Class<?> statsManagerClass = MiscUtils.loadProClass("org.voltdb.management.JMXStatsManager", "JMX", true); if (statsManagerClass != null && !DISABLE_JMX) { m_statsManager = (StatsManager)statsManagerClass.newInstance(); m_statsManager.initialize(); } } catch (Exception e) { //JMXStatsManager will log and we continue. } try { m_snapshotCompletionMonitor.init(m_messenger.getZK()); } catch (Exception e) { hostLog.fatal("Error initializing snapshot completion monitor", e); VoltDB.crashLocalVoltDB("Error initializing snapshot completion monitor", true, e); } /* * Make sure the build string successfully validated * before continuing to do operations * that might return wrongs answers or lose data. */ try { buildStringValidation.get(); } catch (Exception e) { VoltDB.crashLocalVoltDB("Failed to validate cluster build string", false, e); } if (!isRejoin && !m_joining) { try { m_messenger.waitForAllHostsToBeReady(m_deployment.getCluster().getHostcount()); } catch (Exception e) { hostLog.fatal("Failed to announce ready state."); VoltDB.crashLocalVoltDB("Failed to announce ready state.", false, null); } } if (!m_joining && (m_cartographer.getPartitionCount()) != m_configuredNumberOfPartitions) { for (Map.Entry<Integer, ImmutableList<Long>> entry : getSiteTrackerForSnapshot().m_partitionsToSitesImmutable.entrySet()) { hostLog.info(entry.getKey() + " -- " + CoreUtils.hsIdCollectionToString(entry.getValue())); } VoltDB.crashGlobalVoltDB("Mismatch between configured number of partitions (" + m_configuredNumberOfPartitions + ") and actual (" + m_cartographer.getPartitionCount() + ")", true, null); } schedulePeriodicWorks(); m_clientInterface.schedulePeriodicWorks(); // print out a bunch of useful system info logDebuggingInfo(m_config.m_adminPort, m_config.m_httpPort, m_httpPortExtraLogMessage, m_jsonEnabled); // warn the user on the console if k=0 or if no command logging if (m_configuredReplicationFactor == 0) { consoleLog.warn("This is not a highly available cluster. K-Safety is set to 0."); } if (!usingCommandLog) { // figure out if using a snapshot schedule boolean usingPeridoicSnapshots = false; for (SnapshotSchedule ss : m_catalogContext.database.getSnapshotschedule()) { if (ss.getEnabled()) { usingPeridoicSnapshots = true; } } // print the right warning depending on durability settings if (usingPeridoicSnapshots) { consoleLog.warn("Durability is limited to periodic snapshots. Command logging is off."); } else { consoleLog.warn("Durability is turned off. Command logging is off."); } } // warn if cluster is partitionable, but partition detection is off if ((m_catalogContext.cluster.getNetworkpartition() == false) && (m_configuredReplicationFactor > 0)) { hostLog.warn("Running a redundant (k-safe) cluster with network " + "partition detection disabled is not recommended for production use."); // we decided not to include the stronger language below for the 3.0 version (ENG-4215) //hostLog.warn("With partition detection disabled, data may be lost or " + // "corrupted by certain classes of network failures."); } assert (m_clientInterface != null); m_clientInterface.initializeSnapshotDaemon(m_messenger, m_globalServiceElector); // Start elastic join service try { String clSnapshotPath = null; if (m_catalogContext.cluster.getLogconfig().get("log").getEnabled()) { clSnapshotPath = m_catalogContext.cluster.getLogconfig().get("log").getInternalsnapshotpath(); } if (m_config.m_isEnterprise && TheHashinator.getCurrentConfig().type == HashinatorType.ELASTIC) { Class<?> elasticServiceClass = MiscUtils.loadProClass("org.voltdb.join.ElasticJoinCoordinator", "Elastic join", false); if (elasticServiceClass == null) { VoltDB.crashLocalVoltDB("Missing the ElasticJoinCoordinator class file in the enterprise " + "edition", false, null); } Constructor<?> constructor = elasticServiceClass.getConstructor(HostMessenger.class, ClientInterface.class, Cartographer.class, BalancePartitionsStatistics.class, String.class, int.class); m_elasticJoinService = (ElasticJoinService) constructor.newInstance(m_messenger, m_clientInterface, m_cartographer, rebalanceStats, clSnapshotPath, m_deployment.getCluster().getKfactor()); m_elasticJoinService.updateConfig(m_catalogContext); } } catch (Exception e) { VoltDB.crashLocalVoltDB("Failed to instantiate elastic join service", false, e); } // set additional restore agent stuff if (m_restoreAgent != null) { m_restoreAgent.setCatalogContext(m_catalogContext); m_restoreAgent.setInitiator(new Iv2TransactionCreator(m_clientInterface)); } m_configLogger = new Thread(new ConfigLogging()); m_configLogger.start(); DailyRollingFileAppender dailyAppender = null; Enumeration<?> appenders = Logger.getRootLogger().getAllAppenders(); while (appenders.hasMoreElements()) { Appender appender = (Appender) appenders.nextElement(); if (appender instanceof DailyRollingFileAppender){ dailyAppender = (DailyRollingFileAppender) appender; } } final DailyRollingFileAppender dailyRollingFileAppender = dailyAppender; Field field = null; if (dailyRollingFileAppender != null) { try { field = dailyRollingFileAppender.getClass().getDeclaredField("nextCheck"); field.setAccessible(true); } catch (NoSuchFieldException e) { hostLog.error("Failed to set daily system info logging: " + e.getMessage()); } } final Field nextCheckField = field; class DailyLogTask implements Runnable { @Override public void run() { try { m_myHostId = m_messenger.getHostId(); hostLog.info(String.format("Host id of this node is: %d", m_myHostId)); hostLog.info("URL of deployment info: " + m_config.m_pathToDeployment); hostLog.info("Cluster uptime: " + MiscUtils.formatUptime(getClusterUptime())); logDebuggingInfo(m_config.m_adminPort, m_config.m_httpPort, m_httpPortExtraLogMessage, m_jsonEnabled); long nextCheck = nextCheckField.getLong(dailyRollingFileAppender); scheduleWork(new DailyLogTask(), nextCheck - System.currentTimeMillis() + 30 * 1000, 0, TimeUnit.MILLISECONDS); } catch (IllegalAccessException e) { hostLog.error("Failed to set daily system info logging: " + e.getMessage()); } } } if (dailyRollingFileAppender != null && nextCheckField != null) { try { long nextCheck = nextCheckField.getLong(dailyRollingFileAppender); scheduleWork(new DailyLogTask(), nextCheck - System.currentTimeMillis() + 30 * 1000, 0, TimeUnit.MILLISECONDS); } catch (IllegalAccessException e) { hostLog.error("Failed to set daily system info logging: " + e.getMessage()); } } } } class StartActionWatcher implements Watcher { @Override public void process(WatchedEvent event) { m_es.submit(new Runnable() { @Override public void run() { validateStartAction(); } }); } } private void validateStartAction() { try { ZooKeeper zk = m_messenger.getZK(); boolean initCompleted = zk.exists(VoltZK.init_completed, false) != null; List<String> children = zk.getChildren(VoltZK.start_action, new StartActionWatcher(), null); if (!children.isEmpty()) { for (String child : children) { byte[] data = zk.getData(VoltZK.start_action + "/" + child, false, null); if (data == null) { VoltDB.crashLocalVoltDB("Couldn't find " + VoltZK.start_action + "/" + child); } String startAction = new String(data); if ((startAction.equals(StartAction.JOIN.toString()) || startAction.equals(StartAction.REJOIN.toString()) || startAction.equals(StartAction.LIVE_REJOIN.toString())) && !initCompleted) { int nodeId = VoltZK.getHostIDFromChildName(child); if (nodeId == m_messenger.getHostId()) { VoltDB.crashLocalVoltDB("This node was started with start action " + startAction + " during cluster creation. " + "All nodes should be started with matching create or recover actions when bring up a cluster. " + "Join and rejoin are for adding nodes to an already running cluster."); } else { hostLog.warn("Node " + nodeId + " tried to " + startAction + " cluster but it is not allowed during cluster creation. " + "All nodes should be started with matching create or recover actions when bring up a cluster. " + "Join and rejoin are for adding nodes to an already running cluster."); } } } } } catch (KeeperException e) { hostLog.error("Failed to validate the start actions", e); } catch (InterruptedException e) { VoltDB.crashLocalVoltDB("Interrupted during start action validation:" + e.getMessage(), true, e); } } private class ConfigLogging implements Runnable { private void logConfigInfo() { hostLog.info("Logging config info"); File voltDbRoot = CatalogUtil.getVoltDbRoot(m_deployment.getPaths()); String pathToConfigInfoDir = voltDbRoot.getPath() + File.separator + "config_log"; File configInfoDir = new File(pathToConfigInfoDir); configInfoDir.mkdirs(); String pathToConfigInfo = pathToConfigInfoDir + File.separator + "config.json"; File configInfo = new File(pathToConfigInfo); byte jsonBytes[] = null; try { JSONStringer stringer = new JSONStringer(); stringer.object(); stringer.key("workingDir").value(System.getProperty("user.dir")); stringer.key("pid").value(CLibrary.getpid()); stringer.key("log4jDst").array(); Enumeration<?> appenders = Logger.getRootLogger().getAllAppenders(); while (appenders.hasMoreElements()) { Appender appender = (Appender) appenders.nextElement(); if (appender instanceof FileAppender){ stringer.object(); stringer.key("path").value(new File(((FileAppender) appender).getFile()).getCanonicalPath()); if (appender instanceof DailyRollingFileAppender) { stringer.key("format").value(((DailyRollingFileAppender)appender).getDatePattern()); } stringer.endObject(); } } Enumeration<?> loggers = Logger.getRootLogger().getLoggerRepository().getCurrentLoggers(); while (loggers.hasMoreElements()) { Logger logger = (Logger) loggers.nextElement(); appenders = logger.getAllAppenders(); while (appenders.hasMoreElements()) { Appender appender = (Appender) appenders.nextElement(); if (appender instanceof FileAppender){ stringer.object(); stringer.key("path").value(new File(((FileAppender) appender).getFile()).getCanonicalPath()); if (appender instanceof DailyRollingFileAppender) { stringer.key("format").value(((DailyRollingFileAppender)appender).getDatePattern()); } stringer.endObject(); } } } stringer.endArray(); stringer.endObject(); JSONObject jsObj = new JSONObject(stringer.toString()); jsonBytes = jsObj.toString(4).getBytes(Charsets.UTF_8); } catch (JSONException e) { Throwables.propagate(e); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos = new FileOutputStream(configInfo); fos.write(jsonBytes); fos.getFD().sync(); fos.close(); } catch (IOException e) { hostLog.error("Failed to log config info: " + e.getMessage()); e.printStackTrace(); } } private void logCatalogAndDeployment() { File voltDbRoot = CatalogUtil.getVoltDbRoot(m_deployment.getPaths()); String pathToConfigInfoDir = voltDbRoot.getPath() + File.separator + "config_log"; try { m_catalogContext.writeCatalogJarToFile(pathToConfigInfoDir, "catalog.jar"); } catch (IOException e) { hostLog.error("Failed to log catalog: " + e.getMessage()); e.printStackTrace(); } try { File deploymentFile = new File(pathToConfigInfoDir, "deployment.xml"); if (deploymentFile.exists()) { deploymentFile.delete(); } FileOutputStream fileOutputStream = new FileOutputStream(deploymentFile); CatalogAndIds catalogStuff = CatalogUtil.getCatalogFromZK(getHostMessenger().getZK()); fileOutputStream.write(catalogStuff.deploymentBytes); fileOutputStream.close(); } catch (Exception e) { hostLog.error("Failed to log deployment file: " + e.getMessage()); e.printStackTrace(); } } @Override public void run() { logConfigInfo(); logCatalogAndDeployment(); } } // Get topology information. If rejoining, get it directly from // ZK. Otherwise, try to do the write/read race to ZK on startup. private JSONObject getTopology(StartAction startAction, JoinCoordinator joinCoordinator) { JSONObject topo = null; if (startAction == StartAction.JOIN) { assert(joinCoordinator != null); topo = joinCoordinator.getTopology(); } else if (!startAction.doesRejoin()) { int sitesperhost = m_deployment.getCluster().getSitesperhost(); int hostcount = m_deployment.getCluster().getHostcount(); int kfactor = m_deployment.getCluster().getKfactor(); ClusterConfig clusterConfig = new ClusterConfig(hostcount, sitesperhost, kfactor); if (!clusterConfig.validate()) { VoltDB.crashLocalVoltDB(clusterConfig.getErrorMsg(), false, null); } topo = registerClusterConfig(clusterConfig); } else { Stat stat = new Stat(); try { topo = new JSONObject(new String(m_messenger.getZK().getData(VoltZK.topology, false, stat), "UTF-8")); } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to get topology from ZK", true, e); } } return topo; } private List<Initiator> createIv2Initiators(Collection<Integer> partitions, StartAction startAction, List<Integer> m_partitionsToSitesAtStartupForExportInit) { List<Initiator> initiators = new ArrayList<Initiator>(); for (Integer partition : partitions) { Initiator initiator = new SpInitiator(m_messenger, partition, getStatsAgent(), m_snapshotCompletionMonitor, startAction); initiators.add(initiator); m_partitionsToSitesAtStartupForExportInit.add(partition); } return initiators; } private JSONObject registerClusterConfig(ClusterConfig config) { // First, race to write the topology to ZK using Highlander rules // (In the end, there can be only one) JSONObject topo = null; try { topo = config.getTopology(m_messenger.getLiveHostIds()); byte[] payload = topo.toString(4).getBytes("UTF-8"); m_messenger.getZK().create(VoltZK.topology, payload, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (KeeperException.NodeExistsException nee) { // It's fine if we didn't win, we'll pick up the topology below } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to write topology to ZK, dying", true, e); } // Then, have everyone read the topology data back from ZK try { byte[] data = m_messenger.getZK().getData(VoltZK.topology, false, null); topo = new JSONObject(new String(data, "UTF-8")); } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to read topology from ZK, dying", true, e); } return topo; } private final List<ScheduledFuture<?>> m_periodicWorks = new ArrayList<ScheduledFuture<?>>(); /** * Schedule all the periodic works */ private void schedulePeriodicWorks() { // JMX stats broadcast m_periodicWorks.add(scheduleWork(new Runnable() { @Override public void run() { // A null here was causing a steady stream of annoying but apparently inconsequential // NPEs during a debug session of an unrelated unit test. if (m_statsManager != null) { m_statsManager.sendNotification(); } } }, 0, StatsManager.POLL_INTERVAL, TimeUnit.MILLISECONDS)); // small stats samples m_periodicWorks.add(scheduleWork(new Runnable() { @Override public void run() { SystemStatsCollector.asyncSampleSystemNow(false, false); } }, 0, 5, TimeUnit.SECONDS)); // medium stats samples m_periodicWorks.add(scheduleWork(new Runnable() { @Override public void run() { SystemStatsCollector.asyncSampleSystemNow(true, false); } }, 0, 1, TimeUnit.MINUTES)); // large stats samples m_periodicWorks.add(scheduleWork(new Runnable() { @Override public void run() { SystemStatsCollector.asyncSampleSystemNow(true, true); } }, 0, 6, TimeUnit.MINUTES)); GCInspector.instance.start(m_periodicPriorityWorkThread); } int readDeploymentAndCreateStarterCatalogContext() { /* * Debate with the cluster what the deployment file should be */ try { ZooKeeper zk = m_messenger.getZK(); byte deploymentBytes[] = null; try { deploymentBytes = org.voltcore.utils.CoreUtils.urlToBytes(m_config.m_pathToDeployment); } catch (Exception ex) { //Let us get bytes from ZK } try { if (deploymentBytes != null) { CatalogUtil.writeCatalogToZK(zk, // Fill in innocuous values for non-deployment stuff 0, 0L, 0L, new byte[] {}, // spin loop in Inits.LoadCatalog.run() needs // this to be of zero length until we have a real catalog. deploymentBytes); hostLog.info("URL of deployment: " + m_config.m_pathToDeployment); } else { CatalogAndIds catalogStuff = CatalogUtil.getCatalogFromZK(zk); deploymentBytes = catalogStuff.deploymentBytes; } } catch (KeeperException.NodeExistsException e) { CatalogAndIds catalogStuff = CatalogUtil.getCatalogFromZK(zk); byte[] deploymentBytesTemp = catalogStuff.deploymentBytes; if (deploymentBytesTemp != null) { //Check hash if its a supplied deployment on command line. //We will ignore the supplied or default deployment anyways. if (deploymentBytes != null && !m_config.m_deploymentDefault) { byte[] deploymentHashHere = CatalogUtil.makeCatalogOrDeploymentHash(deploymentBytes); if (!(Arrays.equals(deploymentHashHere, catalogStuff.getDeploymentHash()))) { hostLog.warn("The locally provided deployment configuration did not " + " match the configuration information found in the cluster."); } else { hostLog.info("Deployment configuration pulled from other cluster node."); } } //Use remote deployment obtained. deploymentBytes = deploymentBytesTemp; } else { hostLog.error("Deployment file could not be loaded locally or remotely, " + "local supplied path: " + m_config.m_pathToDeployment); deploymentBytes = null; } } if (deploymentBytes == null) { hostLog.error("Deployment could not be obtained from cluster node or locally"); VoltDB.crashLocalVoltDB("No such deployment file: " + m_config.m_pathToDeployment, false, null); } m_deployment = CatalogUtil.getDeployment(new ByteArrayInputStream(deploymentBytes)); // wasn't a valid xml deployment file if (m_deployment == null) { hostLog.error("Not a valid XML deployment file at URL: " + m_config.m_pathToDeployment); VoltDB.crashLocalVoltDB("Not a valid XML deployment file at URL: " + m_config.m_pathToDeployment, false, null); } /* * Check for invalid deployment file settings (enterprise-only) in the community edition. * Trick here is to print out all applicable problems and then stop, rather than stopping * after the first one is found. */ if (!m_config.m_isEnterprise) { boolean shutdownDeployment = false; boolean shutdownAction = false; // check license features for community version if ((m_deployment.getCluster() != null) && (m_deployment.getCluster().getKfactor() > 0)) { consoleLog.error("K-Safety is not supported " + "in the community edition of VoltDB."); shutdownDeployment = true; } if ((m_deployment.getSnapshot() != null) && (m_deployment.getSnapshot().isEnabled())) { consoleLog.error("Snapshots are not supported " + "in the community edition of VoltDB."); shutdownDeployment = true; } if ((m_deployment.getCommandlog() != null) && (m_deployment.getCommandlog().isEnabled())) { consoleLog.error("Command logging is not supported " + "in the community edition of VoltDB."); shutdownDeployment = true; } if ((m_deployment.getExport() != null) && (m_deployment.getExport().isEnabled())) { consoleLog.error("Export is not supported " + "in the community edition of VoltDB."); shutdownDeployment = true; } // check the start action for the community edition if (m_config.m_startAction != StartAction.CREATE) { consoleLog.error("Start action \"" + m_config.m_startAction.getClass().getSimpleName() + "\" is not supported in the community edition of VoltDB."); shutdownAction = true; } // if the process needs to stop, try to be helpful if (shutdownAction || shutdownDeployment) { String msg = "This process will exit. Please run VoltDB with "; if (shutdownDeployment) { msg += "a deployment file compatible with the community edition"; } if (shutdownDeployment && shutdownAction) { msg += " and "; } if (shutdownAction && !shutdownDeployment) { msg += "the CREATE start action"; } msg += "."; VoltDB.crashLocalVoltDB(msg, false, null); } } // note the heart beats are specified in seconds in xml, but ms internally HeartbeatType hbt = m_deployment.getHeartbeat(); if (hbt != null) { m_config.m_deadHostTimeoutMS = hbt.getTimeout() * 1000; m_messenger.setDeadHostTimeout(m_config.m_deadHostTimeoutMS); } else { hostLog.info("Dead host timeout set to " + m_config.m_deadHostTimeoutMS + " milliseconds"); } final String elasticSetting = m_deployment.getCluster().getElastic().trim().toUpperCase(); if (elasticSetting.equals("ENABLED")) { TheHashinator.setConfiguredHashinatorType(HashinatorType.ELASTIC); } else if (!elasticSetting.equals("DISABLED")) { VoltDB.crashLocalVoltDB("Error in deployment file, elastic attribute of " + "cluster element must be " + "'enabled' or 'disabled' but was '" + elasticSetting + "'", false, null); } else { TheHashinator.setConfiguredHashinatorType(HashinatorType.LEGACY); } // create a dummy catalog to load deployment info into Catalog catalog = new Catalog(); Cluster cluster = catalog.getClusters().add("cluster"); Database db = cluster.getDatabases().add("database"); // create groups as needed for users if (m_deployment.getUsers() != null) { for (UsersType.User user : m_deployment.getUsers().getUser()) { Set<String> roles = CatalogUtil.mergeUserRoles(user); if (roles.isEmpty()) { continue; } for (String role : roles) { if (db.getGroups().get(role) == null) { db.getGroups().add(role); } } } } long result = CatalogUtil.compileDeployment(catalog, m_deployment, true, true); if (result < 0) { hostLog.fatal("Error validating deployment file"); VoltDB.crashLocalVoltDB("Error validating deployment file"); } byte[] deploymentHash = CatalogUtil.makeCatalogOrDeploymentHash(deploymentBytes); m_catalogContext = new CatalogContext( TxnEgo.makeZero(MpInitiator.MP_INIT_PID).getTxnId(), //txnid 0, //timestamp catalog, null, deploymentHash, 0, -1); int numberOfNodes = m_deployment.getCluster().getHostcount(); if (numberOfNodes <= 0) { hostLog.l7dlog( Level.FATAL, LogKeys.host_VoltDB_InvalidHostCount.name(), new Object[] { numberOfNodes }, null); VoltDB.crashLocalVoltDB("Invalid cluster size: " + numberOfNodes, false, null); } return numberOfNodes; } catch (Exception e) { throw new RuntimeException(e); } } void collectLocalNetworkMetadata() { boolean threw = false; JSONStringer stringer = new JSONStringer(); try { stringer.object(); stringer.key("interfaces").array(); /* * If no interface was specified, do a ton of work * to identify all ipv4 or ipv6 interfaces and * marshal them into JSON. Always put the ipv4 address first * so that the export client will use it */ if (m_config.m_externalInterface.equals("")) { LinkedList<NetworkInterface> interfaces = new LinkedList<NetworkInterface>(); try { Enumeration<NetworkInterface> intfEnum = NetworkInterface.getNetworkInterfaces(); while (intfEnum.hasMoreElements()) { NetworkInterface intf = intfEnum.nextElement(); if (intf.isLoopback() || !intf.isUp()) { continue; } interfaces.offer(intf); } } catch (SocketException e) { throw new RuntimeException(e); } if (interfaces.isEmpty()) { stringer.value("localhost"); } else { boolean addedIp = false; while (!interfaces.isEmpty()) { NetworkInterface intf = interfaces.poll(); Enumeration<InetAddress> inetAddrs = intf.getInetAddresses(); Inet6Address inet6addr = null; Inet4Address inet4addr = null; while (inetAddrs.hasMoreElements()) { InetAddress addr = inetAddrs.nextElement(); if (addr instanceof Inet6Address) { inet6addr = (Inet6Address)addr; if (inet6addr.isLinkLocalAddress()) { inet6addr = null; } } else if (addr instanceof Inet4Address) { inet4addr = (Inet4Address)addr; } } if (inet4addr != null) { stringer.value(inet4addr.getHostAddress()); addedIp = true; } if (inet6addr != null) { stringer.value(inet6addr.getHostAddress()); addedIp = true; } } if (!addedIp) { stringer.value("localhost"); } } } else { stringer.value(m_config.m_externalInterface); } } catch (Exception e) { threw = true; hostLog.warn("Error while collecting data about local network interfaces", e); } try { if (threw) { stringer = new JSONStringer(); stringer.object(); stringer.key("interfaces").array(); stringer.value("localhost"); stringer.endArray(); } else { stringer.endArray(); } stringer.key("clientPort").value(m_config.m_port); stringer.key("clientInterface").value(m_config.m_clientInterface); stringer.key("adminPort").value(m_config.m_adminPort); stringer.key("adminInterface").value(m_config.m_adminInterface); stringer.key("httpPort").value(m_config.m_httpPort); stringer.key("httpInterface").value(m_config.m_httpPortInterface); stringer.key("drPort").value(m_config.m_drAgentPortStart); stringer.key("drInterface").value(m_config.m_drInterface); stringer.endObject(); JSONObject obj = new JSONObject(stringer.toString()); // possibly atomic swap from null to realz m_localMetadata = obj.toString(4); hostLog.debug("System Metadata is: " + m_localMetadata); } catch (Exception e) { hostLog.warn("Failed to collect data about lcoal network interfaces", e); } } /** * Start the voltcore HostMessenger. This joins the node * to the existing cluster. In the non rejoin case, this * function will return when the mesh is complete. If * rejoining, it will return when the node and agreement * site are synched to the existing cluster. */ void buildClusterMesh(boolean isRejoin) { final String leaderAddress = m_config.m_leader; String hostname = MiscUtils.getHostnameFromHostnameColonPort(leaderAddress); int port = MiscUtils.getPortFromHostnameColonPort(leaderAddress, m_config.m_internalPort); org.voltcore.messaging.HostMessenger.Config hmconfig; hmconfig = new org.voltcore.messaging.HostMessenger.Config(hostname, port); hmconfig.internalPort = m_config.m_internalPort; if (m_config.m_internalPortInterface != null && m_config.m_internalPortInterface.trim().length() > 0) { hmconfig.internalInterface = m_config.m_internalPortInterface.trim(); } else { hmconfig.internalInterface = m_config.m_internalInterface; } hmconfig.zkInterface = m_config.m_zkInterface; hmconfig.deadHostTimeout = m_config.m_deadHostTimeoutMS; hmconfig.factory = new VoltDbMessageFactory(); hmconfig.coreBindIds = m_config.m_networkCoreBindings; m_messenger = new org.voltcore.messaging.HostMessenger(hmconfig); hostLog.info(String.format("Beginning inter-node communication on port %d.", m_config.m_internalPort)); try { m_messenger.start(); } catch (Exception e) { VoltDB.crashLocalVoltDB(e.getMessage(), true, e); } VoltZK.createPersistentZKNodes(m_messenger.getZK()); // Use the host messenger's hostId. m_myHostId = m_messenger.getHostId(); hostLog.info(String.format("Host id of this node is: %d", m_myHostId)); consoleLog.info(String.format("Host id of this node is: %d", m_myHostId)); // Semi-hacky check to see if we're attempting to rejoin to ourselves. // The leader node gets assigned host ID 0, always, so if we're the // leader and we're rejoining, this is clearly bad. if (m_myHostId == 0 && isRejoin) { VoltDB.crashLocalVoltDB("Unable to rejoin a node to itself. " + "Please check your command line and start action and try again.", false, null); } } void logDebuggingInfo(int adminPort, int httpPort, String httpPortExtraLogMessage, boolean jsonEnabled) { String startAction = m_config.m_startAction.toString(); String startActionLog = "Database start action is " + (startAction.substring(0, 1).toUpperCase() + startAction.substring(1).toLowerCase()) + "."; if (!m_rejoining) { hostLog.info(startActionLog); } hostLog.info("PID of this Volt process is " + CLibrary.getpid()); // print out awesome network stuff hostLog.info(String.format("Listening for native wire protocol clients on port %d.", m_config.m_port)); hostLog.info(String.format("Listening for admin wire protocol clients on port %d.", adminPort)); if (m_startMode == OperationMode.PAUSED) { hostLog.info(String.format("Started in admin mode. Clients on port %d will be rejected in admin mode.", m_config.m_port)); } if (m_config.m_replicationRole == ReplicationRole.REPLICA) { consoleLog.info("Started as " + m_config.m_replicationRole.toString().toLowerCase() + " cluster. " + "Clients can only call read-only procedures."); } if (httpPortExtraLogMessage != null) { hostLog.info(httpPortExtraLogMessage); } if (httpPort != -1) { hostLog.info(String.format("Local machine HTTP monitoring is listening on port %d.", httpPort)); } else { hostLog.info(String.format("Local machine HTTP monitoring is disabled.")); } if (jsonEnabled) { hostLog.info(String.format("Json API over HTTP enabled at path /api/1.0/, listening on port %d.", httpPort)); } else { hostLog.info("Json API disabled."); } // java heap size long javamaxheapmem = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax(); javamaxheapmem /= (1024 * 1024); hostLog.info(String.format("Maximum usable Java heap set to %d mb.", javamaxheapmem)); // Computed minimum heap requirement long minRqt = computeMinimumHeapRqt(MiscUtils.isPro(), m_catalogContext.tables.size(), (m_iv2Initiators.size() - 1), m_configuredReplicationFactor); hostLog.info("Minimum required Java heap for catalog and server config is " + minRqt + " MB."); SortedMap<String, String> dbgMap = m_catalogContext.getDebuggingInfoFromCatalog(); for (String line : dbgMap.values()) { hostLog.info(line); } if (m_catalogContext.cluster.getUseadhocschema()) { consoleLog.warn("Cluster is configured to use live DDL for application changes. " + "This feature is currently a preview of work-in-progress and not recommended for " + "production environments. Remove the schema attribute in the <cluster> " + "element of your deployment file if you did not intend to use the preview."); } // print out a bunch of useful system info PlatformProperties pp = PlatformProperties.getPlatformProperties(); String[] lines = pp.toLogLines().split("\n"); for (String line : lines) { hostLog.info(line.trim()); } final ZooKeeper zk = m_messenger.getZK(); ZKUtil.ByteArrayCallback operationModeFuture = new ZKUtil.ByteArrayCallback(); /* * Publish our cluster metadata, and then retrieve the metadata * for the rest of the cluster */ try { zk.create( VoltZK.cluster_metadata + "/" + m_messenger.getHostId(), getLocalMetadata().getBytes("UTF-8"), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, new ZKUtil.StringCallback(), null); zk.getData(VoltZK.operationMode, false, operationModeFuture, null); } catch (Exception e) { VoltDB.crashLocalVoltDB("Error creating \"/cluster_metadata\" node in ZK", true, e); } Map<Integer, String> clusterMetadata = new HashMap<Integer, String>(0); /* * Spin and attempt to retrieve cluster metadata for all nodes in the cluster. */ Set<Integer> metadataToRetrieve = new HashSet<Integer>(m_messenger.getLiveHostIds()); metadataToRetrieve.remove(m_messenger.getHostId()); while (!metadataToRetrieve.isEmpty()) { Map<Integer, ZKUtil.ByteArrayCallback> callbacks = new HashMap<Integer, ZKUtil.ByteArrayCallback>(); for (Integer hostId : metadataToRetrieve) { ZKUtil.ByteArrayCallback cb = new ZKUtil.ByteArrayCallback(); zk.getData(VoltZK.cluster_metadata + "/" + hostId, false, cb, null); callbacks.put(hostId, cb); } for (Map.Entry<Integer, ZKUtil.ByteArrayCallback> entry : callbacks.entrySet()) { try { ZKUtil.ByteArrayCallback cb = entry.getValue(); Integer hostId = entry.getKey(); clusterMetadata.put(hostId, new String(cb.getData(), "UTF-8")); metadataToRetrieve.remove(hostId); } catch (KeeperException.NoNodeException e) {} catch (Exception e) { VoltDB.crashLocalVoltDB("Error retrieving cluster metadata", true, e); } } } // print out cluster membership hostLog.info("About to list cluster interfaces for all nodes with format [ip1 ip2 ... ipN] client-port:admin-port:http-port"); for (int hostId : m_messenger.getLiveHostIds()) { if (hostId == m_messenger.getHostId()) { hostLog.info( String.format( " Host id: %d with interfaces: %s [SELF]", hostId, MiscUtils.formatHostMetadataFromJSON(getLocalMetadata()))); } else { String hostMeta = clusterMetadata.get(hostId); hostLog.info( String.format( " Host id: %d with interfaces: %s [PEER]", hostId, MiscUtils.formatHostMetadataFromJSON(hostMeta))); } } try { if (operationModeFuture.getData() != null) { String operationModeStr = new String(operationModeFuture.getData(), "UTF-8"); m_startMode = OperationMode.valueOf(operationModeStr); } } catch (KeeperException.NoNodeException e) {} catch (Exception e) { throw new RuntimeException(e); } } public static String[] extractBuildInfo() { StringBuilder sb = new StringBuilder(64); String buildString = "VoltDB"; String versionString = m_defaultVersionString; byte b = -1; try { InputStream buildstringStream = ClassLoader.getSystemResourceAsStream("buildstring.txt"); if (buildstringStream == null) { throw new RuntimeException("Unreadable or missing buildstring.txt file."); } while ((b = (byte) buildstringStream.read()) != -1) { sb.append((char)b); } sb.append("\n"); String parts[] = sb.toString().split(" ", 2); if (parts.length != 2) { throw new RuntimeException("Invalid buildstring.txt file."); } versionString = parts[0].trim(); buildString = parts[1].trim(); } catch (Exception ignored) { try { InputStream buildstringStream = new FileInputStream("version.txt"); try { while ((b = (byte) buildstringStream.read()) != -1) { sb.append((char)b); } versionString = sb.toString().trim(); } finally { buildstringStream.close(); } } catch (Exception ignored2) { hostLog.l7dlog( Level.ERROR, LogKeys.org_voltdb_VoltDB_FailedToRetrieveBuildString.name(), null); } } return new String[] { versionString, buildString }; } @Override public void readBuildInfo(String editionTag) { String buildInfo[] = extractBuildInfo(); m_versionString = buildInfo[0]; m_buildString = buildInfo[1]; consoleLog.info(String.format("Build: %s %s %s", m_versionString, m_buildString, editionTag)); } /** * Start all the site's event loops. That's it. */ @Override public void run() { if (m_restoreAgent != null) { // start restore process m_restoreAgent.restore(); } else { onRestoreCompletion(Long.MIN_VALUE, m_iv2InitiatorStartingTxnIds); } // Start the rejoin coordinator if (m_joinCoordinator != null) { try { if (!m_joinCoordinator.startJoin(m_catalogContext.database)) { VoltDB.crashLocalVoltDB("Failed to join the cluster", true, null); } } catch (Exception e) { VoltDB.crashLocalVoltDB("Failed to join the cluster", true, e); } } m_isRunning = true; } /** * Try to shut everything down so they system is ready to call * initialize again. * @param mainSiteThread The thread that m_inititalized the VoltDB or * null if called from that thread. */ @Override public boolean shutdown(Thread mainSiteThread) throws InterruptedException { synchronized(m_startAndStopLock) { boolean did_it = false; if (m_mode != OperationMode.SHUTTINGDOWN) { did_it = true; m_mode = OperationMode.SHUTTINGDOWN; /* * Various scheduled tasks get crashy in unit tests if they happen to run * while other stuff is being shut down */ for (ScheduledFuture<?> sc : m_periodicWorks) { sc.cancel(false); try { sc.get(); } catch (Throwable t) {} } m_periodicWorks.clear(); m_snapshotCompletionMonitor.shutdown(); m_periodicWorkThread.shutdown(); m_periodicWorkThread.awaitTermination(356, TimeUnit.DAYS); m_periodicPriorityWorkThread.shutdown(); m_periodicPriorityWorkThread.awaitTermination(356, TimeUnit.DAYS); if (m_elasticJoinService != null) { m_elasticJoinService.shutdown(); } if (m_leaderAppointer != null) { m_leaderAppointer.shutdown(); } m_globalServiceElector.shutdown(); if (m_hasStartedSampler.get()) { m_sampler.setShouldStop(); m_sampler.join(); } // shutdown the web monitoring / json if (m_adminListener != null) m_adminListener.stop(); // shut down the client interface if (m_clientInterface != null) { m_clientInterface.shutdown(); m_clientInterface = null; } // tell the iv2 sites to stop their runloop if (m_iv2Initiators != null) { for (Initiator init : m_iv2Initiators) init.shutdown(); } if (m_cartographer != null) { m_cartographer.shutdown(); } if (m_configLogger != null) { m_configLogger.join(); } // shut down Export and its connectors. ExportManager.instance().shutdown(); // After sites are terminated, shutdown the InvocationBufferServer. // The IBS is shared by all sites; don't kill it while any site is active. if (m_nodeDRGateway != null) { try { m_nodeDRGateway.shutdown(); } catch (InterruptedException e) { hostLog.warn("Interrupted shutting down invocation buffer server", e); } } if (m_snapshotIOAgent != null) { m_snapshotIOAgent.shutdown(); } // shut down the network/messaging stuff // Close the host messenger first, which should close down all of // the ForeignHost sockets cleanly if (m_messenger != null) { m_messenger.shutdown(); } m_messenger = null; //Also for test code that expects a fresh stats agent if (m_opsRegistrar != null) { try { m_opsRegistrar.shutdown(); } finally { m_opsRegistrar = null; } } if (m_asyncCompilerAgent != null) { m_asyncCompilerAgent.shutdown(); m_asyncCompilerAgent = null; } ExportManager.instance().shutdown(); m_computationService.shutdown(); m_computationService.awaitTermination(1, TimeUnit.DAYS); m_computationService = null; m_catalogContext = null; m_initiatorStats = null; m_latencyStats = null; m_latencyHistogramStats = null; AdHocCompilerCache.clearVersionCache(); org.voltdb.iv2.InitiatorMailbox.m_allInitiatorMailboxes.clear(); // probably unnecessary System.gc(); m_isRunning = false; } return did_it; } } /** Last transaction ID at which the logging config updated. * Also, use the intrinsic lock to safeguard access from multiple * execution site threads */ private static Long lastLogUpdate_txnId = 0L; @Override synchronized public void logUpdate(String xmlConfig, long currentTxnId) { // another site already did this work. if (currentTxnId == lastLogUpdate_txnId) { return; } else if (currentTxnId < lastLogUpdate_txnId) { throw new RuntimeException( "Trying to update logging config at transaction " + lastLogUpdate_txnId + " with an older transaction: " + currentTxnId); } hostLog.info("Updating RealVoltDB logging config from txnid: " + lastLogUpdate_txnId + " to " + currentTxnId); lastLogUpdate_txnId = currentTxnId; VoltLogger.configure(xmlConfig); } /** Struct to associate a context with a counter of served sites */ private static class ContextTracker { ContextTracker(CatalogContext context, CatalogSpecificPlanner csp) { m_dispensedSites = 1; m_context = context; m_csp = csp; } long m_dispensedSites; final CatalogContext m_context; final CatalogSpecificPlanner m_csp; } /** Associate transaction ids to contexts */ private final HashMap<Long, ContextTracker>m_txnIdToContextTracker = new HashMap<Long, ContextTracker>(); @Override public Pair<CatalogContext, CatalogSpecificPlanner> catalogUpdate( String diffCommands, byte[] newCatalogBytes, byte[] catalogBytesHash, int expectedCatalogVersion, long currentTxnId, long currentTxnUniqueId, byte[] deploymentHash) { synchronized(m_catalogUpdateLock) { // A site is catching up with catalog updates if (currentTxnId <= m_catalogContext.m_transactionId && !m_txnIdToContextTracker.isEmpty()) { ContextTracker contextTracker = m_txnIdToContextTracker.get(currentTxnId); // This 'dispensed' concept is a little crazy fragile. Maybe it would be better // to keep a rolling N catalogs? Or perhaps to keep catalogs for N minutes? Open // to opinions here. contextTracker.m_dispensedSites++; int ttlsites = VoltDB.instance().getSiteTrackerForSnapshot().getSitesForHost(m_messenger.getHostId()).size(); if (contextTracker.m_dispensedSites == ttlsites) { m_txnIdToContextTracker.remove(currentTxnId); } return Pair.of( contextTracker.m_context, contextTracker.m_csp); } else if (m_catalogContext.catalogVersion != expectedCatalogVersion) { hostLog.fatal("Failed catalog update." + " expectedCatalogVersion: " + expectedCatalogVersion + " currentTxnId: " + currentTxnId + " currentTxnUniqueId: " + currentTxnUniqueId + " m_catalogContext.catalogVersion " + m_catalogContext.catalogVersion); throw new RuntimeException("Trying to update main catalog context with diff " + "commands generated for an out-of date catalog. Expected catalog version: " + expectedCatalogVersion + " does not match actual version: " + m_catalogContext.catalogVersion); } hostLog.info(String.format("Globally updating the current application catalog (new hash %s).", Encoder.hexEncode(catalogBytesHash).substring(0, 10))); // get old debugging info SortedMap<String, String> oldDbgMap = m_catalogContext.getDebuggingInfoFromCatalog(); // 0. A new catalog! Update the global context and the context tracker m_catalogContext = m_catalogContext.update( currentTxnId, currentTxnUniqueId, newCatalogBytes, diffCommands, true, deploymentHash); final CatalogSpecificPlanner csp = new CatalogSpecificPlanner( m_asyncCompilerAgent, m_catalogContext); m_txnIdToContextTracker.put(currentTxnId, new ContextTracker( m_catalogContext, csp)); // log the stuff that's changed in this new catalog update SortedMap<String, String> newDbgMap = m_catalogContext.getDebuggingInfoFromCatalog(); for (Entry<String, String> e : newDbgMap.entrySet()) { // skip log lines that are unchanged if (oldDbgMap.containsKey(e.getKey()) && oldDbgMap.get(e.getKey()).equals(e.getValue())) { continue; } hostLog.info(e.getValue()); } //Construct the list of partitions and sites because it simply doesn't exist anymore SiteTracker siteTracker = VoltDB.instance().getSiteTrackerForSnapshot(); List<Long> sites = siteTracker.getSitesForHost(m_messenger.getHostId()); List<Integer> partitions = new ArrayList<Integer>(); for (Long site : sites) { Integer partition = siteTracker.getPartitionForSite(site); partitions.add(partition); } // 1. update the export manager. ExportManager.instance().updateCatalog(m_catalogContext, partitions); // 1.1 Update the elastic join throughput settings if (m_elasticJoinService != null) m_elasticJoinService.updateConfig(m_catalogContext); // 1.5 update the dead host timeout if (m_catalogContext.cluster.getHeartbeattimeout() * 1000 != m_config.m_deadHostTimeoutMS) { m_config.m_deadHostTimeoutMS = m_catalogContext.cluster.getHeartbeattimeout() * 1000; m_messenger.setDeadHostTimeout(m_config.m_deadHostTimeoutMS); } // 2. update client interface (asynchronously) // CI in turn updates the planner thread. if (m_clientInterface != null) { m_clientInterface.notifyOfCatalogUpdate(); } // 3. update HTTPClientInterface (asynchronously) // This purges cached connection state so that access with // stale auth info is prevented. if (m_adminListener != null) { m_adminListener.notifyOfCatalogUpdate(); } // 4. Flush StatisticsAgent old catalog statistics. // Otherwise, the stats agent will hold all old catalogs // in memory. getStatsAgent().notifyOfCatalogUpdate(); // 5. MPIs don't run fragments. Update them here. Do // this after flushing the stats -- this will re-register // the MPI statistics. if (m_MPI != null) { m_MPI.updateCatalog(diffCommands, m_catalogContext, csp); } new ConfigLogging().logCatalogAndDeployment(); return Pair.of(m_catalogContext, csp); } } @Override public VoltDB.Configuration getConfig() { return m_config; } @Override public String getBuildString() { return m_buildString == null ? "VoltDB" : m_buildString; } @Override public String getVersionString() { return m_versionString; } /** * Used for testing when you don't have an instance. Should do roughly what * {@link #isCompatibleVersionString(String)} does. */ static boolean staticIsCompatibleVersionString(String versionString) { return versionString.matches(m_defaultHotfixableRegexPattern); } @Override public boolean isCompatibleVersionString(String versionString) { return versionString.matches(m_hotfixableRegexPattern); } @Override public String getEELibraryVersionString() { return m_defaultVersionString; } @Override public HostMessenger getHostMessenger() { return m_messenger; } @Override public ClientInterface getClientInterface() { return m_clientInterface; } @Override public OpsAgent getOpsAgent(OpsSelector selector) { return m_opsRegistrar.getAgent(selector); } @Override public StatsAgent getStatsAgent() { OpsAgent statsAgent = m_opsRegistrar.getAgent(OpsSelector.STATISTICS); assert(statsAgent instanceof StatsAgent); return (StatsAgent)statsAgent; } @Override public MemoryStats getMemoryStatsSource() { return m_memoryStats; } @Override public CatalogContext getCatalogContext() { return m_catalogContext; } /** * Tells if the VoltDB is running. m_isRunning needs to be set to true * when the run() method is called, and set to false when shutting down. * * @return true if the VoltDB is running. */ @Override public boolean isRunning() { return m_isRunning; } @Override public void halt() { Thread shutdownThread = new Thread() { @Override public void run() { hostLog.warn("VoltDB node shutting down as requested by @StopNode command."); System.exit(0); } }; shutdownThread.start(); } /** * Debugging function - creates a record of the current state of the system. * @param out PrintStream to write report to. */ public void createRuntimeReport(PrintStream out) { // This function may be running in its own thread. out.print("MIME-Version: 1.0\n"); out.print("Content-type: multipart/mixed; boundary=\"reportsection\""); out.print("\n\n--reportsection\nContent-Type: text/plain\n\nClientInterface Report\n"); if (m_clientInterface != null) { out.print(m_clientInterface.toString() + "\n"); } } @Override public BackendTarget getBackendTargetType() { return m_config.m_backend; } @Override public synchronized void onExecutionSiteRejoinCompletion(long transferred) { m_executionSiteRecoveryFinish = System.currentTimeMillis(); m_executionSiteRecoveryTransferred = transferred; onRejoinCompletion(); } private void onRejoinCompletion() { // null out the rejoin coordinator if (m_joinCoordinator != null) { m_joinCoordinator.close(); } m_joinCoordinator = null; // Mark the data transfer as done so CL can make the right decision when a truncation snapshot completes m_rejoinDataPending = false; try { m_testBlockRecoveryCompletion.acquire(); } catch (InterruptedException e) {} final long delta = ((m_executionSiteRecoveryFinish - m_recoveryStartTime) / 1000); final long megabytes = m_executionSiteRecoveryTransferred / (1024 * 1024); final double megabytesPerSecond = megabytes / ((m_executionSiteRecoveryFinish - m_recoveryStartTime) / 1000.0); if (m_clientInterface != null) { m_clientInterface.mayActivateSnapshotDaemon(); try { m_clientInterface.startAcceptingConnections(); } catch (IOException e) { hostLog.l7dlog(Level.FATAL, LogKeys.host_VoltDB_ErrorStartAcceptingConnections.name(), e); VoltDB.crashLocalVoltDB("Error starting client interface.", true, e); } } if (m_config.m_startAction == StartAction.REJOIN) { consoleLog.info( "Node data recovery completed after " + delta + " seconds with " + megabytes + " megabytes transferred at a rate of " + megabytesPerSecond + " megabytes/sec"); } try { final ZooKeeper zk = m_messenger.getZK(); boolean logRecoveryCompleted = false; if (getCommandLog().getClass().getName().equals("org.voltdb.CommandLogImpl")) { String requestNode = zk.create(VoltZK.request_truncation_snapshot_node, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); if (m_rejoinTruncationReqId == null) { m_rejoinTruncationReqId = requestNode; } } else { logRecoveryCompleted = true; } // Join creates a truncation snapshot as part of the join process, // so there is no need to wait for the truncation snapshot requested // above to finish. if (logRecoveryCompleted || m_joining) { String actionName = m_joining ? "join" : "rejoin"; m_rejoining = false; m_joining = false; consoleLog.info(String.format("Node %s completed", actionName)); } } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to log host rejoin completion to ZK", true, e); } hostLog.info("Logging host rejoin completion to ZK"); } @Override public CommandLog getCommandLog() { return m_commandLog; } @Override public OperationMode getMode() { return m_mode; } @Override public void setMode(OperationMode mode) { if (m_mode != mode) { if (mode == OperationMode.PAUSED) { hostLog.info("Server is entering admin mode and pausing."); } else if (m_mode == OperationMode.PAUSED) { hostLog.info("Server is exiting admin mode and resuming operation."); } } m_mode = mode; } @Override public void setStartMode(OperationMode mode) { m_startMode = mode; } @Override public OperationMode getStartMode() { return m_startMode; } @Override public void setReplicationRole(ReplicationRole role) { if (role == ReplicationRole.NONE && m_config.m_replicationRole == ReplicationRole.REPLICA) { consoleLog.info("Promoting replication role from replica to master."); } m_config.m_replicationRole = role; if (m_clientInterface != null) { m_clientInterface.setReplicationRole(m_config.m_replicationRole); } } @Override public ReplicationRole getReplicationRole() { return m_config.m_replicationRole; } /** * Metadata is a JSON object */ @Override public String getLocalMetadata() { return m_localMetadata; } @Override public void onRestoreCompletion(long txnId, Map<Integer, Long> perPartitionTxnIds) { /* * Command log is already initialized if this is a rejoin or a join */ if ((m_commandLog != null) && (m_commandLog.needsInitialization())) { // Initialize command logger m_commandLog.init(m_catalogContext, txnId, m_cartographer.getPartitionCount(), m_config.m_commandLogBinding, perPartitionTxnIds); try { ZKCountdownLatch latch = new ZKCountdownLatch(m_messenger.getZK(), VoltZK.commandlog_init_barrier, m_messenger.getLiveHostIds().size()); latch.countDown(true); latch.await(); } catch (Exception e) { VoltDB.crashLocalVoltDB("Failed to init and wait on command log init barrier", true, e); } } /* * IV2: After the command log is initialized, force the writing of the initial * viable replay set. Turns into a no-op with no command log, on the non-leader sites, and on the MPI. */ for (Initiator initiator : m_iv2Initiators) { initiator.enableWritingIv2FaultLog(); } /* * IV2: From this point on, not all node failures should crash global VoltDB. */ if (m_leaderAppointer != null) { m_leaderAppointer.onReplayCompletion(); } if (!m_rejoining && !m_joining) { if (m_clientInterface != null) { try { m_clientInterface.startAcceptingConnections(); } catch (IOException e) { hostLog.l7dlog(Level.FATAL, LogKeys.host_VoltDB_ErrorStartAcceptingConnections.name(), e); VoltDB.crashLocalVoltDB("Error starting client interface.", true, e); } } } // Start listening on the DR ports prepareReplication(); if (m_startMode != null) { m_mode = m_startMode; } else { // Shouldn't be here, but to be safe m_mode = OperationMode.RUNNING; } consoleLog.l7dlog( Level.INFO, LogKeys.host_VoltDB_ServerCompletedInitialization.name(), null); // Create a zk node to indicate initialization is completed m_messenger.getZK().create(VoltZK.init_completed, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new ZKUtil.StringCallback(), null); } @Override public SnapshotCompletionMonitor getSnapshotCompletionMonitor() { return m_snapshotCompletionMonitor; } @Override public synchronized void recoveryComplete(String requestId) { assert(m_rejoinDataPending == false); if (m_rejoining) { if (m_rejoinTruncationReqId.compareTo(requestId) <= 0) { String actionName = m_joining ? "join" : "rejoin"; consoleLog.info(String.format("Node %s completed", actionName)); m_rejoinTruncationReqId = null; m_rejoining = false; } else { // If we saw some other truncation request ID, then try the same one again. As long as we // don't flip the m_rejoining state, all truncation snapshot completions will call back to here. try { final ZooKeeper zk = m_messenger.getZK(); String requestNode = zk.create(VoltZK.request_truncation_snapshot_node, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); if (m_rejoinTruncationReqId == null) { m_rejoinTruncationReqId = requestNode; } } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to retry post-rejoin truncation snapshot request.", true, e); } } } } @Override public ScheduledExecutorService getSES(boolean priority) { return priority ? m_periodicPriorityWorkThread : m_periodicWorkThread; } /** * See comment on {@link VoltDBInterface#scheduleWork(Runnable, long, long, TimeUnit)} vs * {@link VoltDBInterface#schedulePriorityWork(Runnable, long, long, TimeUnit)} */ @Override public ScheduledFuture<?> scheduleWork(Runnable work, long initialDelay, long delay, TimeUnit unit) { if (delay > 0) { return m_periodicWorkThread.scheduleWithFixedDelay(work, initialDelay, delay, unit); } else { return m_periodicWorkThread.schedule(work, initialDelay, unit); } } @Override public ListeningExecutorService getComputationService() { return m_computationService; } private void prepareReplication() { try { if (m_nodeDRGateway != null) { m_nodeDRGateway.start(); m_nodeDRGateway.bindPorts(); } } catch (Exception ex) { MiscUtils.printPortsInUse(hostLog); VoltDB.crashLocalVoltDB("Failed to initialize DR", false, ex); } } @Override public void setReplicationActive(boolean active) { if (m_replicationActive != active) { m_replicationActive = active; try { JSONStringer js = new JSONStringer(); js.object(); // Replication role should the be same across the cluster js.key("role").value(getReplicationRole().ordinal()); js.key("active").value(m_replicationActive); js.endObject(); getHostMessenger().getZK().setData(VoltZK.replicationconfig, js.toString().getBytes("UTF-8"), -1); } catch (Exception e) { e.printStackTrace(); hostLog.error("Failed to write replication active state to ZK: " + e.getMessage()); } if (m_nodeDRGateway != null) { m_nodeDRGateway.setActive(active); } } } @Override public boolean getReplicationActive() { return m_replicationActive; } @Override public SiteTracker getSiteTrackerForSnapshot() { return new SiteTracker(m_messenger.getHostId(), m_cartographer.getSiteTrackerMailboxMap(), 0); } /** * Create default deployment.xml file in voltdbroot if the deployment path is null. * * @return path to default deployment file * @throws IOException */ static String setupDefaultDeployment() throws IOException { // Since there's apparently no deployment to override the path to voltdbroot it should be // safe to assume it's under the working directory. // CatalogUtil.getVoltDbRoot() creates the voltdbroot directory as needed. File voltDbRoot = CatalogUtil.getVoltDbRoot(null); String pathToDeployment = voltDbRoot.getPath() + File.separator + "deployment.xml"; File deploymentXMLFile = new File(pathToDeployment); hostLog.info("Generating default deployment file \"" + deploymentXMLFile.getAbsolutePath() + "\""); BufferedWriter bw = new BufferedWriter(new FileWriter(deploymentXMLFile)); for (String line : defaultDeploymentXML) { bw.write(line); bw.newLine(); } bw.flush(); bw.close(); return deploymentXMLFile.getAbsolutePath(); } /* * Validate the build string with the rest of the cluster * by racing to publish it to ZK and then comparing the one this process * has to the one in ZK. They should all match. The method returns a future * so that init can continue while the ZK call is pending since it ZK is pretty * slow. */ private Future<?> validateBuildString(final String buildString, ZooKeeper zk) { final SettableFuture<Object> retval = SettableFuture.create(); byte buildStringBytes[] = null; try { buildStringBytes = buildString.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } final byte buildStringBytesFinal[] = buildStringBytes; //Can use a void callback because ZK will execute the create and then the get in order //It's a race so it doesn't have to succeed zk.create( VoltZK.buildstring, buildStringBytes, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new ZKUtil.StringCallback(), null); zk.getData(VoltZK.buildstring, false, new org.apache.zookeeper_voltpatches.AsyncCallback.DataCallback() { @Override public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { KeeperException.Code code = KeeperException.Code.get(rc); if (code == KeeperException.Code.OK) { if (Arrays.equals(buildStringBytesFinal, data)) { retval.set(null); } else { try { VoltDB.crashGlobalVoltDB("Local build string \"" + buildString + "\" does not match cluster build string \"" + new String(data, "UTF-8") + "\"", false, null); } catch (UnsupportedEncodingException e) { retval.setException(new AssertionError(e)); } } } else { retval.setException(KeeperException.create(code)); } } }, null); return retval; } /** * See comment on {@link VoltDBInterface#schedulePriorityWork(Runnable, long, long, TimeUnit)} vs * {@link VoltDBInterface#scheduleWork(Runnable, long, long, TimeUnit)} */ @Override public ScheduledFuture<?> schedulePriorityWork(Runnable work, long initialDelay, long delay, TimeUnit unit) { if (delay > 0) { return m_periodicPriorityWorkThread.scheduleWithFixedDelay(work, initialDelay, delay, unit); } else { return m_periodicPriorityWorkThread.schedule(work, initialDelay, unit); } } private void checkHeapSanity(boolean isPro, int tableCount, int sitesPerHost, int kfactor) { long megabytes = 1024 * 1024; long maxMemory = Runtime.getRuntime().maxMemory() / megabytes; long drRqt = isPro ? 128 * sitesPerHost : 0; long crazyThresh = computeMinimumHeapRqt(isPro, tableCount, sitesPerHost, kfactor); long warnThresh = crazyThresh + drRqt; if (maxMemory < crazyThresh) { StringBuilder builder = new StringBuilder(); builder.append(String.format("The configuration of %d tables, %d sites-per-host, and k-factor of %d requires at least %d MB of Java heap memory. ", tableCount, sitesPerHost, kfactor, crazyThresh)); builder.append(String.format("The maximum amount of heap memory available to the JVM is %d MB. ", maxMemory)); builder.append("Please increase the maximum heap size using the VOLTDB_HEAPMAX environment variable and then restart VoltDB."); consoleLog.warn(builder.toString()); } else if (maxMemory < warnThresh) { StringBuilder builder = new StringBuilder(); builder.append(String.format("The configuration of %d tables, %d sites-per-host, and k-factor of %d requires at least %d MB of Java heap memory. ", tableCount, sitesPerHost, kfactor, crazyThresh)); builder.append(String.format("The maximum amount of heap memory available to the JVM is %d MB. ", maxMemory)); builder.append("The system has enough memory for normal operation but is in danger of running out of Java heap space if the DR feature is used. "); builder.append("Use the VOLTDB_HEAPMAX environment variable to adjust the Java max heap size before starting VoltDB, as necessary."); consoleLog.warn(builder.toString()); } } // Compute the minimum required heap to run this configuration. This comes from the documentation, // http://voltdb.com/docs/PlanningGuide/MemSizeServers.php#MemSizeHeapGuidelines // Any changes there should get reflected here and vice versa. private long computeMinimumHeapRqt(boolean isPro, int tableCount, int sitesPerHost, int kfactor) { long baseRqt = 384; long tableRqt = 10 * tableCount; long rejoinRqt = (isPro && kfactor > 0) ? 128 * sitesPerHost : 0; return baseRqt + tableRqt + rejoinRqt; } @Override public <T> ListenableFuture<T> submitSnapshotIOWork(Callable<T> work) { assert m_snapshotIOAgent != null; return m_snapshotIOAgent.submit(work); } @Override public long getClusterUptime() { return System.currentTimeMillis() - getHostMessenger().getInstanceId().getTimestamp(); } }
For ENG-6859, reduce noise from shutdown in tests
src/frontend/org/voltdb/RealVoltDB.java
For ENG-6859, reduce noise from shutdown in tests
<ide><path>rc/frontend/org/voltdb/RealVoltDB.java <ide> class StartActionWatcher implements Watcher { <ide> @Override <ide> public void process(WatchedEvent event) { <add> if (m_mode == OperationMode.SHUTTINGDOWN) return; <ide> m_es.submit(new Runnable() { <ide> @Override <ide> public void run() {
Java
mit
2474400842ee520901850fa797d9a9ff7be655e4
0
Orchestrate-Cloud-Storage/StorageClient
package com.llnw.storage.client; import com.google.common.collect.Lists; import com.google.common.io.Files; import com.llnw.storage.client.io.ActivityCallback; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.util.List; public class MockEndpointFactory extends EndpointFactory { private final File destination; public MockEndpointFactory() { this(null); } public MockEndpointFactory(File destination) { super(null, null, null); this.destination = destination; } @Override public Endpoint create(boolean useFTP) { return new Endpoint() { @Override public void deleteDirectory(String path) throws IOException { } @Override public void deleteFile(String path) throws IOException { } @Override public void close() { } @Override public void makeDirectory(String path) throws IOException { } @Override public List<String> listFiles(String path) throws IOException { return Lists.newArrayList(); } @Override public void upload(File file, String path, String name, @Nullable ActivityCallback callback) throws IOException { if (destination != null) { Files.copy(file, destination); } } @Override public void noop() throws IOException { } @Override public boolean exists(String path) throws IOException { return false; } }; } }
src/test/java/com/llnw/storage/client/MockEndpointFactory.java
package com.llnw.storage.client; import com.google.common.collect.Lists; import com.llnw.storage.client.io.ActivityCallback; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.util.List; public class MockEndpointFactory extends EndpointFactory { public MockEndpointFactory() { super(null, null, null); } @Override public Endpoint create(boolean useFTP) { return new Endpoint() { @Override public void deleteDirectory(String path) throws IOException { } @Override public void deleteFile(String path) throws IOException { } @Override public void close() { } @Override public void makeDirectory(String path) throws IOException { } @Override public List<String> listFiles(String path) throws IOException { return Lists.newArrayList(); } @Override public void upload(File file, String path, String name, @Nullable ActivityCallback callback) throws IOException { } @Override public void noop() throws IOException { } @Override public boolean exists(String path) throws IOException { return false; } }; } }
Allow for destination file in mock endpoint
src/test/java/com/llnw/storage/client/MockEndpointFactory.java
Allow for destination file in mock endpoint
<ide><path>rc/test/java/com/llnw/storage/client/MockEndpointFactory.java <ide> package com.llnw.storage.client; <ide> <ide> import com.google.common.collect.Lists; <add>import com.google.common.io.Files; <ide> import com.llnw.storage.client.io.ActivityCallback; <ide> <ide> import javax.annotation.Nullable; <ide> import java.util.List; <ide> <ide> public class MockEndpointFactory extends EndpointFactory { <add> <add> private final File destination; <add> <ide> public MockEndpointFactory() { <add> this(null); <add> } <add> <add> public MockEndpointFactory(File destination) { <ide> super(null, null, null); <add> this.destination = destination; <ide> } <add> <ide> <ide> @Override <ide> public Endpoint create(boolean useFTP) { <ide> @Override <ide> public void upload(File file, String path, String name, @Nullable ActivityCallback callback) <ide> throws IOException { <add> if (destination != null) { <add> Files.copy(file, destination); <add> } <ide> } <ide> <ide> @Override
Java
apache-2.0
2eaff688eab0a21c8a7a2e6e676a419990616786
0
SpineEventEngine/core-java,SpineEventEngine/core-java,SpineEventEngine/core-java
/* * Copyright 2019, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server; import com.google.common.base.MoreObjects; import com.google.protobuf.Message; import io.spine.option.EntityOption.Visibility; import io.spine.server.entity.EntityVisibility; import io.spine.server.entity.Repository; import io.spine.server.entity.model.EntityClass; import io.spine.type.TypeName; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static io.spine.util.Exceptions.newIllegalStateException; /** * A registry of repositories that controls access to them depending on the visibility of * corresponding entity states. */ final class VisibilityGuard { private final Map<Class<? extends Message>, RepositoryAccess> repositories = new HashMap<>(); /** Prevent instantiation from outside. */ private VisibilityGuard() { } /** * Creates a new instance of the guard. */ static VisibilityGuard newInstance() { return new VisibilityGuard(); } /** * Registers the passed repository with the guard. */ void register(Repository<?, ?> repository) { checkNotNull(repository); EntityClass<?> entityClass = repository.entityModelClass(); Class<? extends Message> stateClass = entityClass.stateClass(); checkNotAlreadyRegistered(stateClass); repositories.put(stateClass, new RepositoryAccess(repository)); } private void checkNotAlreadyRegistered(Class<? extends Message> stateClass) { RepositoryAccess alreadyRegistered = repositories.get(stateClass); if (alreadyRegistered != null) { throw newIllegalStateException( "A repository for the state class %s already registered: `%s`.", stateClass.getName(), alreadyRegistered ); } } /** * Verifies if there is a registered repository for the passed entity state class. */ boolean hasRepository(Class<? extends Message> stateClass) { checkNotNull(stateClass); boolean result = repositories.containsKey(stateClass); return result; } /** * Obtains the repository for the passed entity state class. * * @param stateClass * the class of the state of entities managed by the repository * @return the repository wrapped into {@code Optional} or {@code Optional#empty()} if the * entity state is {@linkplain Visibility#NONE not visible} * @throws IllegalArgumentException * if the repository for the passed state class was not * {@linkplain #register(Repository) registered} with the guard * prior to this call, or if all repositories were * {@linkplain #shutDownRepositories() shut down} */ Optional<Repository> repositoryFor(Class<? extends Message> stateClass) { checkNotNull(stateClass); RepositoryAccess repositoryAccess = findOrThrow(stateClass); return repositoryAccess.get(); } private RepositoryAccess findOrThrow(Class<? extends Message> stateClass) { RepositoryAccess repository = repositories.get(stateClass); if (repository == null) { throw newIllegalStateException( "A repository for the state class `%s` is not registered.", stateClass.getName() ); } return repository; } /** * Obtains a set of entity type names by their visibility. */ public Set<TypeName> entityStateTypes(Visibility visibility) { checkNotNull(visibility); Set<TypeName> result = repositories.values() .stream() .filter(access -> access.visibility.is(visibility)) .map(access -> access.repository .entityStateType() .toTypeName()) .collect(toImmutableSet()); return result; } Set<TypeName> allEntityTypes() { Set<TypeName> result = repositories.values() .stream() .map(access -> access.repository .entityStateType() .toTypeName()) .collect(toImmutableSet()); return result; } /** * Closes all registered repositories and clears the registration list. */ void shutDownRepositories() { for (RepositoryAccess repositoryAccess : repositories.values()) { repositoryAccess.repository.close(); } repositories.clear(); } boolean isClosed() { return repositories.isEmpty(); } /** * Allows to get a reference to repository if states of its entities are visible. */ private static class RepositoryAccess { private final Repository repository; private final EntityVisibility visibility; private RepositoryAccess(Repository repository) { this.repository = repository; EntityClass entityClass = repository.entityModelClass(); this.visibility = entityClass.visibility(); } private Optional<Repository> get() { return visibility.isNotNone() ? Optional.of(repository) : Optional.empty(); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("repository", repository) .add("visibility", visibility) .toString(); } } }
server/src/main/java/io/spine/server/VisibilityGuard.java
/* * Copyright 2019, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server; import com.google.common.base.MoreObjects; import com.google.protobuf.Message; import io.spine.option.EntityOption.Visibility; import io.spine.server.entity.EntityVisibility; import io.spine.server.entity.Repository; import io.spine.server.entity.model.EntityClass; import io.spine.type.TypeName; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static io.spine.util.Exceptions.newIllegalStateException; /** * A registry of repositories that controls access to them depending on the visibility of * corresponding entity states. */ final class VisibilityGuard { private final Map<Class<? extends Message>, RepositoryAccess> repositories = new HashMap<>(); /** Prevent instantiation from outside. */ private VisibilityGuard() { } /** * Creates a new instance of the guard. */ static VisibilityGuard newInstance() { return new VisibilityGuard(); } /** * Registers the passed repository with the guard. */ void register(Repository<?, ?> repository) { checkNotNull(repository); EntityClass<?> entityClass = repository.entityModelClass(); Class<? extends Message> stateClass = entityClass.stateClass(); checkNotAlreadyRegistered(stateClass); repositories.put(stateClass, new RepositoryAccess(repository)); } private void checkNotAlreadyRegistered(Class<? extends Message> stateClass) { RepositoryAccess alreadyRegistered = repositories.get(stateClass); if (alreadyRegistered != null) { throw newIllegalStateException( "A repository for the state class %s already registered: `%s`", stateClass.getName(), alreadyRegistered); } } /** * Verifies if there is a registered repository for the passed entity state class. */ boolean hasRepository(Class<? extends Message> stateClass) { checkNotNull(stateClass); boolean result = repositories.containsKey(stateClass); return result; } /** * Obtains the repository for the passed entity state class. * * @param stateClass * the class of the state of entities managed by the repository * @return the repository wrapped into {@code Optional} or {@code Optional#empty()} if the * entity state is {@linkplain Visibility#NONE not visible} * @throws IllegalArgumentException * if the repository for the passed state class was not * {@linkplain #register(Repository) registered} with the guard * prior to this call, or if all repositories were * {@linkplain #shutDownRepositories() shut down} */ Optional<Repository> repositoryFor(Class<? extends Message> stateClass) { checkNotNull(stateClass); RepositoryAccess repositoryAccess = findOrThrow(stateClass); return repositoryAccess.get(); } private RepositoryAccess findOrThrow(Class<? extends Message> stateClass) { RepositoryAccess repository = repositories.get(stateClass); if (repository == null) { throw newIllegalStateException( "A repository for the state class `%s` is not registered.", stateClass.getName() ); } return repository; } /** * Obtains a set of entity type names by their visibility. */ public Set<TypeName> entityStateTypes(Visibility visibility) { checkNotNull(visibility); Set<TypeName> result = repositories.values() .stream() .filter(access -> access.visibility.is(visibility)) .map(access -> access.repository .entityStateType() .toTypeName()) .collect(toImmutableSet()); return result; } Set<TypeName> allEntityTypes() { Set<TypeName> result = repositories.values() .stream() .map(access -> access.repository .entityStateType() .toTypeName()) .collect(toImmutableSet()); return result; } /** * Closes all registered repositories and clears the registration list. */ void shutDownRepositories() { for (RepositoryAccess repositoryAccess : repositories.values()) { repositoryAccess.repository.close(); } repositories.clear(); } boolean isClosed() { return repositories.isEmpty(); } /** * Allows to get a reference to repository if states of its entities are visible. */ private static class RepositoryAccess { private final Repository repository; private final EntityVisibility visibility; private RepositoryAccess(Repository repository) { this.repository = repository; EntityClass entityClass = repository.entityModelClass(); this.visibility = entityClass.visibility(); } private Optional<Repository> get() { return visibility.isNotNone() ? Optional.of(repository) : Optional.empty(); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("repository", repository) .add("visibility", visibility) .toString(); } } }
Add a dot at the end of an error message
server/src/main/java/io/spine/server/VisibilityGuard.java
Add a dot at the end of an error message
<ide><path>erver/src/main/java/io/spine/server/VisibilityGuard.java <ide> RepositoryAccess alreadyRegistered = repositories.get(stateClass); <ide> if (alreadyRegistered != null) { <ide> throw newIllegalStateException( <del> "A repository for the state class %s already registered: `%s`", <del> stateClass.getName(), alreadyRegistered); <add> "A repository for the state class %s already registered: `%s`.", <add> stateClass.getName(), <add> alreadyRegistered <add> ); <ide> } <ide> } <ide>
Java
apache-2.0
033e3e36849078af2a3806c961d1260cc8c1b19c
0
StephanEwen/incubator-flink,twalthr/flink,tillrohrmann/flink,twalthr/flink,tillrohrmann/flink,gyfora/flink,xccui/flink,clarkyzl/flink,rmetzger/flink,apache/flink,StephanEwen/incubator-flink,tony810430/flink,wwjiang007/flink,tillrohrmann/flink,tillrohrmann/flink,gyfora/flink,gyfora/flink,StephanEwen/incubator-flink,zjureel/flink,tony810430/flink,godfreyhe/flink,apache/flink,wwjiang007/flink,twalthr/flink,godfreyhe/flink,gyfora/flink,zjureel/flink,StephanEwen/incubator-flink,kl0u/flink,apache/flink,zentol/flink,StephanEwen/incubator-flink,StephanEwen/incubator-flink,rmetzger/flink,rmetzger/flink,zjureel/flink,lincoln-lil/flink,wwjiang007/flink,wwjiang007/flink,kl0u/flink,gyfora/flink,zentol/flink,kl0u/flink,kl0u/flink,lincoln-lil/flink,rmetzger/flink,rmetzger/flink,apache/flink,tony810430/flink,xccui/flink,godfreyhe/flink,apache/flink,lincoln-lil/flink,twalthr/flink,xccui/flink,zentol/flink,clarkyzl/flink,xccui/flink,tony810430/flink,twalthr/flink,tony810430/flink,godfreyhe/flink,lincoln-lil/flink,xccui/flink,godfreyhe/flink,clarkyzl/flink,rmetzger/flink,rmetzger/flink,kl0u/flink,clarkyzl/flink,zjureel/flink,zjureel/flink,clarkyzl/flink,tillrohrmann/flink,zentol/flink,gyfora/flink,lincoln-lil/flink,zjureel/flink,twalthr/flink,tillrohrmann/flink,tony810430/flink,zentol/flink,zentol/flink,wwjiang007/flink,tillrohrmann/flink,xccui/flink,kl0u/flink,xccui/flink,lincoln-lil/flink,zentol/flink,twalthr/flink,wwjiang007/flink,gyfora/flink,apache/flink,godfreyhe/flink,wwjiang007/flink,apache/flink,godfreyhe/flink,lincoln-lil/flink,zjureel/flink,tony810430/flink
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.contrib.streaming.state.snapshot; import org.apache.flink.api.common.typeutils.TypeSerializer; import org.apache.flink.api.common.typeutils.base.array.BytePrimitiveArraySerializer; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.contrib.streaming.state.RocksDBKeyedStateBackend.RocksDbKvStateInfo; import org.apache.flink.contrib.streaming.state.RocksIteratorWrapper; import org.apache.flink.contrib.streaming.state.iterator.RocksStatesPerKeyGroupMergeIterator; import org.apache.flink.contrib.streaming.state.iterator.RocksTransformingIteratorWrapper; import org.apache.flink.core.fs.CloseableRegistry; import org.apache.flink.core.memory.DataOutputView; import org.apache.flink.core.memory.DataOutputViewStreamWrapper; import org.apache.flink.runtime.checkpoint.CheckpointOptions; import org.apache.flink.runtime.state.CheckpointStreamFactory; import org.apache.flink.runtime.state.CheckpointStreamWithResultProvider; import org.apache.flink.runtime.state.CheckpointedStateScope; import org.apache.flink.runtime.state.KeyGroupRange; import org.apache.flink.runtime.state.KeyGroupRangeOffsets; import org.apache.flink.runtime.state.KeyedBackendSerializationProxy; import org.apache.flink.runtime.state.KeyedStateHandle; import org.apache.flink.runtime.state.LocalRecoveryConfig; import org.apache.flink.runtime.state.RegisteredKeyValueStateBackendMetaInfo; import org.apache.flink.runtime.state.SnapshotResources; import org.apache.flink.runtime.state.SnapshotResult; import org.apache.flink.runtime.state.StateSnapshotTransformer; import org.apache.flink.runtime.state.StreamCompressionDecorator; import org.apache.flink.runtime.state.UncompressedStreamCompressionDecorator; import org.apache.flink.runtime.state.metainfo.StateMetaInfoSnapshot; import org.apache.flink.util.IOUtils; import org.apache.flink.util.ResourceGuard; import org.apache.flink.util.function.SupplierWithException; import org.rocksdb.ColumnFamilyHandle; import org.rocksdb.ReadOptions; import org.rocksdb.RocksDB; import org.rocksdb.RocksIterator; import org.rocksdb.Snapshot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Objects; import static org.apache.flink.contrib.streaming.state.snapshot.RocksSnapshotUtil.END_OF_KEY_GROUP_MARK; import static org.apache.flink.contrib.streaming.state.snapshot.RocksSnapshotUtil.hasMetaDataFollowsFlag; import static org.apache.flink.contrib.streaming.state.snapshot.RocksSnapshotUtil.setMetaDataFollowsFlagInKey; /** * Snapshot strategy to create full snapshots of {@link * org.apache.flink.contrib.streaming.state.RocksDBKeyedStateBackend}. Iterates and writes all * states from a RocksDB snapshot of the column families. * * @param <K> type of the backend keys. */ public class RocksFullSnapshotStrategy<K> extends RocksDBSnapshotStrategyBase< K, RocksFullSnapshotStrategy.FullRocksDBSnapshotResources> { private static final Logger LOG = LoggerFactory.getLogger(RocksFullSnapshotStrategy.class); private static final String DESCRIPTION = "Asynchronous full RocksDB snapshot"; /** This decorator is used to apply compression per key-group for the written snapshot data. */ @Nonnull private final StreamCompressionDecorator keyGroupCompressionDecorator; public RocksFullSnapshotStrategy( @Nonnull RocksDB db, @Nonnull ResourceGuard rocksDBResourceGuard, @Nonnull TypeSerializer<K> keySerializer, @Nonnull LinkedHashMap<String, RocksDbKvStateInfo> kvStateInformation, @Nonnull KeyGroupRange keyGroupRange, @Nonnegative int keyGroupPrefixBytes, @Nonnull LocalRecoveryConfig localRecoveryConfig, @Nonnull StreamCompressionDecorator keyGroupCompressionDecorator) { super( DESCRIPTION, db, rocksDBResourceGuard, keySerializer, kvStateInformation, keyGroupRange, keyGroupPrefixBytes, localRecoveryConfig); this.keyGroupCompressionDecorator = keyGroupCompressionDecorator; } @Override public FullRocksDBSnapshotResources syncPrepareResources(long checkpointId) throws Exception { final List<StateMetaInfoSnapshot> stateMetaInfoSnapshots = new ArrayList<>(kvStateInformation.size()); final List<RocksDbKvStateInfo> metaDataCopy = new ArrayList<>(kvStateInformation.size()); for (RocksDbKvStateInfo stateInfo : kvStateInformation.values()) { // snapshot meta info stateMetaInfoSnapshots.add(stateInfo.metaInfo.snapshot()); metaDataCopy.add(stateInfo); } final ResourceGuard.Lease lease = rocksDBResourceGuard.acquireResource(); final Snapshot snapshot = db.getSnapshot(); return new FullRocksDBSnapshotResources( lease, snapshot, metaDataCopy, stateMetaInfoSnapshots, db); } @Override public SnapshotResultSupplier<KeyedStateHandle> asyncSnapshot( FullRocksDBSnapshotResources fullRocksDBSnapshotResources, long checkpointId, long timestamp, @Nonnull CheckpointStreamFactory checkpointStreamFactory, @Nonnull CheckpointOptions checkpointOptions) { if (fullRocksDBSnapshotResources.stateMetaInfoSnapshots.isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug( "Asynchronous RocksDB snapshot performed on empty keyed state at {}. Returning null.", timestamp); } return registry -> SnapshotResult.empty(); } final SupplierWithException<CheckpointStreamWithResultProvider, Exception> checkpointStreamSupplier = createCheckpointStreamSupplier( checkpointId, checkpointStreamFactory, checkpointOptions); return new SnapshotAsynchronousPartCallable( checkpointStreamSupplier, fullRocksDBSnapshotResources.snapshot, fullRocksDBSnapshotResources.stateMetaInfoSnapshots, fullRocksDBSnapshotResources.metaDataCopy); } @Override public void notifyCheckpointComplete(long checkpointId) { // nothing to do. } @Override public void notifyCheckpointAborted(long checkpointId) { // nothing to do. } private SupplierWithException<CheckpointStreamWithResultProvider, Exception> createCheckpointStreamSupplier( long checkpointId, CheckpointStreamFactory primaryStreamFactory, CheckpointOptions checkpointOptions) { return localRecoveryConfig.isLocalRecoveryEnabled() && !checkpointOptions.getCheckpointType().isSavepoint() ? () -> CheckpointStreamWithResultProvider.createDuplicatingStream( checkpointId, CheckpointedStateScope.EXCLUSIVE, primaryStreamFactory, localRecoveryConfig.getLocalStateDirectoryProvider()) : () -> CheckpointStreamWithResultProvider.createSimpleStream( CheckpointedStateScope.EXCLUSIVE, primaryStreamFactory); } /** Encapsulates the process to perform a full snapshot of a RocksDBKeyedStateBackend. */ private class SnapshotAsynchronousPartCallable implements SnapshotResultSupplier<KeyedStateHandle> { /** Supplier for the stream into which we write the snapshot. */ @Nonnull private final SupplierWithException<CheckpointStreamWithResultProvider, Exception> checkpointStreamSupplier; /** RocksDB snapshot. */ @Nonnull private final Snapshot snapshot; @Nonnull private final List<StateMetaInfoSnapshot> stateMetaInfoSnapshots; @Nonnull private final List<MetaData> metaData; SnapshotAsynchronousPartCallable( @Nonnull SupplierWithException<CheckpointStreamWithResultProvider, Exception> checkpointStreamSupplier, @Nonnull Snapshot snapshot, @Nonnull List<StateMetaInfoSnapshot> stateMetaInfoSnapshots, @Nonnull List<RocksDbKvStateInfo> metaDataCopy) { this.checkpointStreamSupplier = checkpointStreamSupplier; this.snapshot = snapshot; this.stateMetaInfoSnapshots = stateMetaInfoSnapshots; this.metaData = fillMetaData(metaDataCopy); } @Override public SnapshotResult<KeyedStateHandle> get(CloseableRegistry snapshotCloseableRegistry) throws Exception { final KeyGroupRangeOffsets keyGroupRangeOffsets = new KeyGroupRangeOffsets(keyGroupRange); final CheckpointStreamWithResultProvider checkpointStreamWithResultProvider = checkpointStreamSupplier.get(); snapshotCloseableRegistry.registerCloseable(checkpointStreamWithResultProvider); writeSnapshotToOutputStream(checkpointStreamWithResultProvider, keyGroupRangeOffsets); if (snapshotCloseableRegistry.unregisterCloseable(checkpointStreamWithResultProvider)) { return CheckpointStreamWithResultProvider.toKeyedStateHandleSnapshotResult( checkpointStreamWithResultProvider.closeAndFinalizeCheckpointStreamResult(), keyGroupRangeOffsets); } else { throw new IOException("Stream is already unregistered/closed."); } } private void writeSnapshotToOutputStream( @Nonnull CheckpointStreamWithResultProvider checkpointStreamWithResultProvider, @Nonnull KeyGroupRangeOffsets keyGroupRangeOffsets) throws IOException, InterruptedException { final DataOutputView outputView = new DataOutputViewStreamWrapper( checkpointStreamWithResultProvider.getCheckpointOutputStream()); writeKVStateMetaData(outputView); List<Tuple2<RocksIteratorWrapper, Integer>> kvStateIterators = null; final ReadOptions readOptions = new ReadOptions(); try { readOptions.setSnapshot(snapshot); kvStateIterators = createKVStateIterators(readOptions); writeKVStateData( kvStateIterators, checkpointStreamWithResultProvider, keyGroupRangeOffsets); } finally { if (kvStateIterators != null) { for (Tuple2<RocksIteratorWrapper, Integer> kvStateIterator : kvStateIterators) { IOUtils.closeQuietly(kvStateIterator.f0); } } IOUtils.closeQuietly(readOptions); } } private List<Tuple2<RocksIteratorWrapper, Integer>> createKVStateIterators( ReadOptions readOptions) { final List<Tuple2<RocksIteratorWrapper, Integer>> kvStateIterators = new ArrayList<>(metaData.size()); int kvStateId = 0; for (MetaData metaDataEntry : metaData) { RocksIteratorWrapper rocksIteratorWrapper = getRocksIterator( db, metaDataEntry.rocksDbKvStateInfo.columnFamilyHandle, metaDataEntry.stateSnapshotTransformer, readOptions); kvStateIterators.add(Tuple2.of(rocksIteratorWrapper, kvStateId)); ++kvStateId; } return kvStateIterators; } private void writeKVStateMetaData(final DataOutputView outputView) throws IOException { KeyedBackendSerializationProxy<K> serializationProxy = new KeyedBackendSerializationProxy<>( // TODO: this code assumes that writing a serializer is threadsafe, we // should support to // get a serialized form already at state registration time in the // future keySerializer, stateMetaInfoSnapshots, !Objects.equals( UncompressedStreamCompressionDecorator.INSTANCE, keyGroupCompressionDecorator)); serializationProxy.write(outputView); } private void writeKVStateData( final List<Tuple2<RocksIteratorWrapper, Integer>> kvStateIterators, final CheckpointStreamWithResultProvider checkpointStreamWithResultProvider, final KeyGroupRangeOffsets keyGroupRangeOffsets) throws IOException, InterruptedException { byte[] previousKey = null; byte[] previousValue = null; DataOutputView kgOutView = null; OutputStream kgOutStream = null; CheckpointStreamFactory.CheckpointStateOutputStream checkpointOutputStream = checkpointStreamWithResultProvider.getCheckpointOutputStream(); try { // Here we transfer ownership of RocksIterators to the // RocksStatesPerKeyGroupMergeIterator try (RocksStatesPerKeyGroupMergeIterator mergeIterator = new RocksStatesPerKeyGroupMergeIterator( kvStateIterators, keyGroupPrefixBytes)) { // preamble: setup with first key-group as our lookahead if (mergeIterator.isValid()) { // begin first key-group by recording the offset keyGroupRangeOffsets.setKeyGroupOffset( mergeIterator.keyGroup(), checkpointOutputStream.getPos()); // write the k/v-state id as metadata kgOutStream = keyGroupCompressionDecorator.decorateWithCompression( checkpointOutputStream); kgOutView = new DataOutputViewStreamWrapper(kgOutStream); // TODO this could be aware of keyGroupPrefixBytes and write only one byte // if possible kgOutView.writeShort(mergeIterator.kvStateId()); previousKey = mergeIterator.key(); previousValue = mergeIterator.value(); mergeIterator.next(); } // main loop: write k/v pairs ordered by (key-group, kv-state), thereby tracking // key-group offsets. while (mergeIterator.isValid()) { assert (!hasMetaDataFollowsFlag(previousKey)); // set signal in first key byte that meta data will follow in the stream // after this k/v pair if (mergeIterator.isNewKeyGroup() || mergeIterator.isNewKeyValueState()) { // be cooperative and check for interruption from time to time in the // hot loop checkInterrupted(); setMetaDataFollowsFlagInKey(previousKey); } writeKeyValuePair(previousKey, previousValue, kgOutView); // write meta data if we have to if (mergeIterator.isNewKeyGroup()) { // TODO this could be aware of keyGroupPrefixBytes and write only one // byte if possible kgOutView.writeShort(END_OF_KEY_GROUP_MARK); // this will just close the outer stream kgOutStream.close(); // begin new key-group keyGroupRangeOffsets.setKeyGroupOffset( mergeIterator.keyGroup(), checkpointOutputStream.getPos()); // write the kev-state // TODO this could be aware of keyGroupPrefixBytes and write only one // byte if possible kgOutStream = keyGroupCompressionDecorator.decorateWithCompression( checkpointOutputStream); kgOutView = new DataOutputViewStreamWrapper(kgOutStream); kgOutView.writeShort(mergeIterator.kvStateId()); } else if (mergeIterator.isNewKeyValueState()) { // write the k/v-state // TODO this could be aware of keyGroupPrefixBytes and write only one // byte if possible kgOutView.writeShort(mergeIterator.kvStateId()); } // request next k/v pair previousKey = mergeIterator.key(); previousValue = mergeIterator.value(); mergeIterator.next(); } } // epilogue: write last key-group if (previousKey != null) { assert (!hasMetaDataFollowsFlag(previousKey)); setMetaDataFollowsFlagInKey(previousKey); writeKeyValuePair(previousKey, previousValue, kgOutView); // TODO this could be aware of keyGroupPrefixBytes and write only one byte if // possible kgOutView.writeShort(END_OF_KEY_GROUP_MARK); // this will just close the outer stream kgOutStream.close(); kgOutStream = null; } } finally { // this will just close the outer stream IOUtils.closeQuietly(kgOutStream); } } private void writeKeyValuePair(byte[] key, byte[] value, DataOutputView out) throws IOException { BytePrimitiveArraySerializer.INSTANCE.serialize(key, out); BytePrimitiveArraySerializer.INSTANCE.serialize(value, out); } private void checkInterrupted() throws InterruptedException { if (Thread.currentThread().isInterrupted()) { throw new InterruptedException("RocksDB snapshot interrupted."); } } } private static List<MetaData> fillMetaData(List<RocksDbKvStateInfo> metaDataCopy) { List<MetaData> metaData = new ArrayList<>(metaDataCopy.size()); for (RocksDbKvStateInfo rocksDbKvStateInfo : metaDataCopy) { StateSnapshotTransformer<byte[]> stateSnapshotTransformer = null; if (rocksDbKvStateInfo.metaInfo instanceof RegisteredKeyValueStateBackendMetaInfo) { stateSnapshotTransformer = ((RegisteredKeyValueStateBackendMetaInfo<?, ?>) rocksDbKvStateInfo.metaInfo) .getStateSnapshotTransformFactory() .createForSerializedState() .orElse(null); } metaData.add(new MetaData(rocksDbKvStateInfo, stateSnapshotTransformer)); } return metaData; } private static RocksIteratorWrapper getRocksIterator( RocksDB db, ColumnFamilyHandle columnFamilyHandle, StateSnapshotTransformer<byte[]> stateSnapshotTransformer, ReadOptions readOptions) { RocksIterator rocksIterator = db.newIterator(columnFamilyHandle, readOptions); return stateSnapshotTransformer == null ? new RocksIteratorWrapper(rocksIterator) : new RocksTransformingIteratorWrapper(rocksIterator, stateSnapshotTransformer); } private static class MetaData { final RocksDbKvStateInfo rocksDbKvStateInfo; final StateSnapshotTransformer<byte[]> stateSnapshotTransformer; private MetaData( RocksDbKvStateInfo rocksDbKvStateInfo, StateSnapshotTransformer<byte[]> stateSnapshotTransformer) { this.rocksDbKvStateInfo = rocksDbKvStateInfo; this.stateSnapshotTransformer = stateSnapshotTransformer; } } static class FullRocksDBSnapshotResources implements SnapshotResources { private final List<StateMetaInfoSnapshot> stateMetaInfoSnapshots; private final List<RocksDbKvStateInfo> metaDataCopy; private final ResourceGuard.Lease lease; private final Snapshot snapshot; private final RocksDB db; public FullRocksDBSnapshotResources( ResourceGuard.Lease lease, Snapshot snapshot, List<RocksDbKvStateInfo> metaDataCopy, List<StateMetaInfoSnapshot> stateMetaInfoSnapshots, RocksDB db) { this.lease = lease; this.snapshot = snapshot; this.metaDataCopy = metaDataCopy; this.stateMetaInfoSnapshots = stateMetaInfoSnapshots; this.db = db; } @Override public void release() { db.releaseSnapshot(snapshot); IOUtils.closeQuietly(snapshot); IOUtils.closeQuietly(lease); } } }
flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/snapshot/RocksFullSnapshotStrategy.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.contrib.streaming.state.snapshot; import org.apache.flink.api.common.typeutils.TypeSerializer; import org.apache.flink.api.common.typeutils.base.array.BytePrimitiveArraySerializer; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.contrib.streaming.state.RocksDBKeyedStateBackend.RocksDbKvStateInfo; import org.apache.flink.contrib.streaming.state.RocksIteratorWrapper; import org.apache.flink.contrib.streaming.state.iterator.RocksStatesPerKeyGroupMergeIterator; import org.apache.flink.contrib.streaming.state.iterator.RocksTransformingIteratorWrapper; import org.apache.flink.core.fs.CloseableRegistry; import org.apache.flink.core.memory.DataOutputView; import org.apache.flink.core.memory.DataOutputViewStreamWrapper; import org.apache.flink.runtime.checkpoint.CheckpointOptions; import org.apache.flink.runtime.state.CheckpointStreamFactory; import org.apache.flink.runtime.state.CheckpointStreamWithResultProvider; import org.apache.flink.runtime.state.CheckpointedStateScope; import org.apache.flink.runtime.state.KeyGroupRange; import org.apache.flink.runtime.state.KeyGroupRangeOffsets; import org.apache.flink.runtime.state.KeyedBackendSerializationProxy; import org.apache.flink.runtime.state.KeyedStateHandle; import org.apache.flink.runtime.state.LocalRecoveryConfig; import org.apache.flink.runtime.state.RegisteredKeyValueStateBackendMetaInfo; import org.apache.flink.runtime.state.SnapshotResources; import org.apache.flink.runtime.state.SnapshotResult; import org.apache.flink.runtime.state.StateSnapshotTransformer; import org.apache.flink.runtime.state.StreamCompressionDecorator; import org.apache.flink.runtime.state.UncompressedStreamCompressionDecorator; import org.apache.flink.runtime.state.metainfo.StateMetaInfoSnapshot; import org.apache.flink.util.IOUtils; import org.apache.flink.util.ResourceGuard; import org.apache.flink.util.function.SupplierWithException; import org.rocksdb.ColumnFamilyHandle; import org.rocksdb.ReadOptions; import org.rocksdb.RocksDB; import org.rocksdb.RocksIterator; import org.rocksdb.Snapshot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Objects; import static org.apache.flink.contrib.streaming.state.snapshot.RocksSnapshotUtil.END_OF_KEY_GROUP_MARK; import static org.apache.flink.contrib.streaming.state.snapshot.RocksSnapshotUtil.hasMetaDataFollowsFlag; import static org.apache.flink.contrib.streaming.state.snapshot.RocksSnapshotUtil.setMetaDataFollowsFlagInKey; /** * Snapshot strategy to create full snapshots of {@link * org.apache.flink.contrib.streaming.state.RocksDBKeyedStateBackend}. Iterates and writes all * states from a RocksDB snapshot of the column families. * * @param <K> type of the backend keys. */ public class RocksFullSnapshotStrategy<K> extends RocksDBSnapshotStrategyBase< K, RocksFullSnapshotStrategy.FullRocksDBSnapshotResources> { private static final Logger LOG = LoggerFactory.getLogger(RocksFullSnapshotStrategy.class); private static final String DESCRIPTION = "Asynchronous full RocksDB snapshot"; /** This decorator is used to apply compression per key-group for the written snapshot data. */ @Nonnull private final StreamCompressionDecorator keyGroupCompressionDecorator; public RocksFullSnapshotStrategy( @Nonnull RocksDB db, @Nonnull ResourceGuard rocksDBResourceGuard, @Nonnull TypeSerializer<K> keySerializer, @Nonnull LinkedHashMap<String, RocksDbKvStateInfo> kvStateInformation, @Nonnull KeyGroupRange keyGroupRange, @Nonnegative int keyGroupPrefixBytes, @Nonnull LocalRecoveryConfig localRecoveryConfig, @Nonnull StreamCompressionDecorator keyGroupCompressionDecorator) { super( DESCRIPTION, db, rocksDBResourceGuard, keySerializer, kvStateInformation, keyGroupRange, keyGroupPrefixBytes, localRecoveryConfig); this.keyGroupCompressionDecorator = keyGroupCompressionDecorator; } @Override public FullRocksDBSnapshotResources syncPrepareResources(long checkpointId) throws Exception { final List<StateMetaInfoSnapshot> stateMetaInfoSnapshots = new ArrayList<>(kvStateInformation.size()); final List<RocksDbKvStateInfo> metaDataCopy = new ArrayList<>(kvStateInformation.size()); for (RocksDbKvStateInfo stateInfo : kvStateInformation.values()) { // snapshot meta info stateMetaInfoSnapshots.add(stateInfo.metaInfo.snapshot()); metaDataCopy.add(stateInfo); } final ResourceGuard.Lease lease = rocksDBResourceGuard.acquireResource(); final Snapshot snapshot = db.getSnapshot(); return new FullRocksDBSnapshotResources( lease, snapshot, metaDataCopy, stateMetaInfoSnapshots, db); } @Override public SnapshotResultSupplier<KeyedStateHandle> asyncSnapshot( FullRocksDBSnapshotResources fullRocksDBSnapshotResources, long checkpointId, long timestamp, @Nonnull CheckpointStreamFactory checkpointStreamFactory, @Nonnull CheckpointOptions checkpointOptions) { if (fullRocksDBSnapshotResources.stateMetaInfoSnapshots.isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug( "Asynchronous RocksDB snapshot performed on empty keyed state at {}. Returning null.", timestamp); } return registry -> SnapshotResult.empty(); } final SupplierWithException<CheckpointStreamWithResultProvider, Exception> checkpointStreamSupplier = createCheckpointStreamSupplier( checkpointId, checkpointStreamFactory, checkpointOptions); return new SnapshotAsynchronousPartCallable( checkpointStreamSupplier, fullRocksDBSnapshotResources.snapshot, fullRocksDBSnapshotResources.stateMetaInfoSnapshots, fullRocksDBSnapshotResources.metaDataCopy); } @Override public void notifyCheckpointComplete(long checkpointId) { // nothing to do. } @Override public void notifyCheckpointAborted(long checkpointId) { // nothing to do. } private SupplierWithException<CheckpointStreamWithResultProvider, Exception> createCheckpointStreamSupplier( long checkpointId, CheckpointStreamFactory primaryStreamFactory, CheckpointOptions checkpointOptions) { return localRecoveryConfig.isLocalRecoveryEnabled() && !checkpointOptions.getCheckpointType().isSavepoint() ? () -> CheckpointStreamWithResultProvider.createDuplicatingStream( checkpointId, CheckpointedStateScope.EXCLUSIVE, primaryStreamFactory, localRecoveryConfig.getLocalStateDirectoryProvider()) : () -> CheckpointStreamWithResultProvider.createSimpleStream( CheckpointedStateScope.EXCLUSIVE, primaryStreamFactory); } /** Encapsulates the process to perform a full snapshot of a RocksDBKeyedStateBackend. */ private class SnapshotAsynchronousPartCallable implements SnapshotResultSupplier<KeyedStateHandle> { /** Supplier for the stream into which we write the snapshot. */ @Nonnull private final SupplierWithException<CheckpointStreamWithResultProvider, Exception> checkpointStreamSupplier; /** RocksDB snapshot. */ @Nonnull private final Snapshot snapshot; @Nonnull private final List<StateMetaInfoSnapshot> stateMetaInfoSnapshots; @Nonnull private final List<MetaData> metaData; SnapshotAsynchronousPartCallable( @Nonnull SupplierWithException<CheckpointStreamWithResultProvider, Exception> checkpointStreamSupplier, @Nonnull Snapshot snapshot, @Nonnull List<StateMetaInfoSnapshot> stateMetaInfoSnapshots, @Nonnull List<RocksDbKvStateInfo> metaDataCopy) { this.checkpointStreamSupplier = checkpointStreamSupplier; this.snapshot = snapshot; this.stateMetaInfoSnapshots = stateMetaInfoSnapshots; this.metaData = fillMetaData(metaDataCopy); } @Override public SnapshotResult<KeyedStateHandle> get(CloseableRegistry snapshotCloseableRegistry) throws Exception { final KeyGroupRangeOffsets keyGroupRangeOffsets = new KeyGroupRangeOffsets(keyGroupRange); final CheckpointStreamWithResultProvider checkpointStreamWithResultProvider = checkpointStreamSupplier.get(); snapshotCloseableRegistry.registerCloseable(checkpointStreamWithResultProvider); writeSnapshotToOutputStream(checkpointStreamWithResultProvider, keyGroupRangeOffsets); if (snapshotCloseableRegistry.unregisterCloseable(checkpointStreamWithResultProvider)) { return CheckpointStreamWithResultProvider.toKeyedStateHandleSnapshotResult( checkpointStreamWithResultProvider.closeAndFinalizeCheckpointStreamResult(), keyGroupRangeOffsets); } else { throw new IOException("Stream is already unregistered/closed."); } } private void writeSnapshotToOutputStream( @Nonnull CheckpointStreamWithResultProvider checkpointStreamWithResultProvider, @Nonnull KeyGroupRangeOffsets keyGroupRangeOffsets) throws IOException, InterruptedException { final List<Tuple2<RocksIteratorWrapper, Integer>> kvStateIterators = new ArrayList<>(metaData.size()); final DataOutputView outputView = new DataOutputViewStreamWrapper( checkpointStreamWithResultProvider.getCheckpointOutputStream()); final ReadOptions readOptions = new ReadOptions(); try { readOptions.setSnapshot(snapshot); writeKVStateMetaData(kvStateIterators, readOptions, outputView); writeKVStateData( kvStateIterators, checkpointStreamWithResultProvider, keyGroupRangeOffsets); } finally { for (Tuple2<RocksIteratorWrapper, Integer> kvStateIterator : kvStateIterators) { IOUtils.closeQuietly(kvStateIterator.f0); } IOUtils.closeQuietly(readOptions); } } private void writeKVStateMetaData( final List<Tuple2<RocksIteratorWrapper, Integer>> kvStateIterators, final ReadOptions readOptions, final DataOutputView outputView) throws IOException { int kvStateId = 0; for (MetaData metaDataEntry : metaData) { RocksIteratorWrapper rocksIteratorWrapper = getRocksIterator( db, metaDataEntry.rocksDbKvStateInfo.columnFamilyHandle, metaDataEntry.stateSnapshotTransformer, readOptions); kvStateIterators.add(Tuple2.of(rocksIteratorWrapper, kvStateId)); ++kvStateId; } KeyedBackendSerializationProxy<K> serializationProxy = new KeyedBackendSerializationProxy<>( // TODO: this code assumes that writing a serializer is threadsafe, we // should support to // get a serialized form already at state registration time in the // future keySerializer, stateMetaInfoSnapshots, !Objects.equals( UncompressedStreamCompressionDecorator.INSTANCE, keyGroupCompressionDecorator)); serializationProxy.write(outputView); } private void writeKVStateData( final List<Tuple2<RocksIteratorWrapper, Integer>> kvStateIterators, final CheckpointStreamWithResultProvider checkpointStreamWithResultProvider, final KeyGroupRangeOffsets keyGroupRangeOffsets) throws IOException, InterruptedException { byte[] previousKey = null; byte[] previousValue = null; DataOutputView kgOutView = null; OutputStream kgOutStream = null; CheckpointStreamFactory.CheckpointStateOutputStream checkpointOutputStream = checkpointStreamWithResultProvider.getCheckpointOutputStream(); try { // Here we transfer ownership of RocksIterators to the // RocksStatesPerKeyGroupMergeIterator try (RocksStatesPerKeyGroupMergeIterator mergeIterator = new RocksStatesPerKeyGroupMergeIterator( kvStateIterators, keyGroupPrefixBytes)) { // preamble: setup with first key-group as our lookahead if (mergeIterator.isValid()) { // begin first key-group by recording the offset keyGroupRangeOffsets.setKeyGroupOffset( mergeIterator.keyGroup(), checkpointOutputStream.getPos()); // write the k/v-state id as metadata kgOutStream = keyGroupCompressionDecorator.decorateWithCompression( checkpointOutputStream); kgOutView = new DataOutputViewStreamWrapper(kgOutStream); // TODO this could be aware of keyGroupPrefixBytes and write only one byte // if possible kgOutView.writeShort(mergeIterator.kvStateId()); previousKey = mergeIterator.key(); previousValue = mergeIterator.value(); mergeIterator.next(); } // main loop: write k/v pairs ordered by (key-group, kv-state), thereby tracking // key-group offsets. while (mergeIterator.isValid()) { assert (!hasMetaDataFollowsFlag(previousKey)); // set signal in first key byte that meta data will follow in the stream // after this k/v pair if (mergeIterator.isNewKeyGroup() || mergeIterator.isNewKeyValueState()) { // be cooperative and check for interruption from time to time in the // hot loop checkInterrupted(); setMetaDataFollowsFlagInKey(previousKey); } writeKeyValuePair(previousKey, previousValue, kgOutView); // write meta data if we have to if (mergeIterator.isNewKeyGroup()) { // TODO this could be aware of keyGroupPrefixBytes and write only one // byte if possible kgOutView.writeShort(END_OF_KEY_GROUP_MARK); // this will just close the outer stream kgOutStream.close(); // begin new key-group keyGroupRangeOffsets.setKeyGroupOffset( mergeIterator.keyGroup(), checkpointOutputStream.getPos()); // write the kev-state // TODO this could be aware of keyGroupPrefixBytes and write only one // byte if possible kgOutStream = keyGroupCompressionDecorator.decorateWithCompression( checkpointOutputStream); kgOutView = new DataOutputViewStreamWrapper(kgOutStream); kgOutView.writeShort(mergeIterator.kvStateId()); } else if (mergeIterator.isNewKeyValueState()) { // write the k/v-state // TODO this could be aware of keyGroupPrefixBytes and write only one // byte if possible kgOutView.writeShort(mergeIterator.kvStateId()); } // request next k/v pair previousKey = mergeIterator.key(); previousValue = mergeIterator.value(); mergeIterator.next(); } } // epilogue: write last key-group if (previousKey != null) { assert (!hasMetaDataFollowsFlag(previousKey)); setMetaDataFollowsFlagInKey(previousKey); writeKeyValuePair(previousKey, previousValue, kgOutView); // TODO this could be aware of keyGroupPrefixBytes and write only one byte if // possible kgOutView.writeShort(END_OF_KEY_GROUP_MARK); // this will just close the outer stream kgOutStream.close(); kgOutStream = null; } } finally { // this will just close the outer stream IOUtils.closeQuietly(kgOutStream); } } private void writeKeyValuePair(byte[] key, byte[] value, DataOutputView out) throws IOException { BytePrimitiveArraySerializer.INSTANCE.serialize(key, out); BytePrimitiveArraySerializer.INSTANCE.serialize(value, out); } private void checkInterrupted() throws InterruptedException { if (Thread.currentThread().isInterrupted()) { throw new InterruptedException("RocksDB snapshot interrupted."); } } } private static List<MetaData> fillMetaData(List<RocksDbKvStateInfo> metaDataCopy) { List<MetaData> metaData = new ArrayList<>(metaDataCopy.size()); for (RocksDbKvStateInfo rocksDbKvStateInfo : metaDataCopy) { StateSnapshotTransformer<byte[]> stateSnapshotTransformer = null; if (rocksDbKvStateInfo.metaInfo instanceof RegisteredKeyValueStateBackendMetaInfo) { stateSnapshotTransformer = ((RegisteredKeyValueStateBackendMetaInfo<?, ?>) rocksDbKvStateInfo.metaInfo) .getStateSnapshotTransformFactory() .createForSerializedState() .orElse(null); } metaData.add(new MetaData(rocksDbKvStateInfo, stateSnapshotTransformer)); } return metaData; } private static RocksIteratorWrapper getRocksIterator( RocksDB db, ColumnFamilyHandle columnFamilyHandle, StateSnapshotTransformer<byte[]> stateSnapshotTransformer, ReadOptions readOptions) { RocksIterator rocksIterator = db.newIterator(columnFamilyHandle, readOptions); return stateSnapshotTransformer == null ? new RocksIteratorWrapper(rocksIterator) : new RocksTransformingIteratorWrapper(rocksIterator, stateSnapshotTransformer); } private static class MetaData { final RocksDbKvStateInfo rocksDbKvStateInfo; final StateSnapshotTransformer<byte[]> stateSnapshotTransformer; private MetaData( RocksDbKvStateInfo rocksDbKvStateInfo, StateSnapshotTransformer<byte[]> stateSnapshotTransformer) { this.rocksDbKvStateInfo = rocksDbKvStateInfo; this.stateSnapshotTransformer = stateSnapshotTransformer; } } static class FullRocksDBSnapshotResources implements SnapshotResources { private final List<StateMetaInfoSnapshot> stateMetaInfoSnapshots; private final List<RocksDbKvStateInfo> metaDataCopy; private final ResourceGuard.Lease lease; private final Snapshot snapshot; private final RocksDB db; public FullRocksDBSnapshotResources( ResourceGuard.Lease lease, Snapshot snapshot, List<RocksDbKvStateInfo> metaDataCopy, List<StateMetaInfoSnapshot> stateMetaInfoSnapshots, RocksDB db) { this.lease = lease; this.snapshot = snapshot; this.metaDataCopy = metaDataCopy; this.stateMetaInfoSnapshots = stateMetaInfoSnapshots; this.db = db; } @Override public void release() { db.releaseSnapshot(snapshot); IOUtils.closeQuietly(snapshot); IOUtils.closeQuietly(lease); } } }
[FLINK-21151] Separate iterator creation from metadata writing in RocksFullSnapshotStrategy The two things are not connected.
flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/snapshot/RocksFullSnapshotStrategy.java
[FLINK-21151] Separate iterator creation from metadata writing in RocksFullSnapshotStrategy
<ide><path>link-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/snapshot/RocksFullSnapshotStrategy.java <ide> @Nonnull KeyGroupRangeOffsets keyGroupRangeOffsets) <ide> throws IOException, InterruptedException { <ide> <del> final List<Tuple2<RocksIteratorWrapper, Integer>> kvStateIterators = <del> new ArrayList<>(metaData.size()); <ide> final DataOutputView outputView = <ide> new DataOutputViewStreamWrapper( <ide> checkpointStreamWithResultProvider.getCheckpointOutputStream()); <add> <add> writeKVStateMetaData(outputView); <add> <add> List<Tuple2<RocksIteratorWrapper, Integer>> kvStateIterators = null; <ide> final ReadOptions readOptions = new ReadOptions(); <add> <ide> try { <ide> readOptions.setSnapshot(snapshot); <del> writeKVStateMetaData(kvStateIterators, readOptions, outputView); <add> kvStateIterators = createKVStateIterators(readOptions); <add> <ide> writeKVStateData( <ide> kvStateIterators, checkpointStreamWithResultProvider, keyGroupRangeOffsets); <ide> } finally { <ide> <del> for (Tuple2<RocksIteratorWrapper, Integer> kvStateIterator : kvStateIterators) { <del> IOUtils.closeQuietly(kvStateIterator.f0); <add> if (kvStateIterators != null) { <add> for (Tuple2<RocksIteratorWrapper, Integer> kvStateIterator : kvStateIterators) { <add> IOUtils.closeQuietly(kvStateIterator.f0); <add> } <ide> } <ide> <ide> IOUtils.closeQuietly(readOptions); <ide> } <ide> } <ide> <del> private void writeKVStateMetaData( <del> final List<Tuple2<RocksIteratorWrapper, Integer>> kvStateIterators, <del> final ReadOptions readOptions, <del> final DataOutputView outputView) <del> throws IOException { <add> private List<Tuple2<RocksIteratorWrapper, Integer>> createKVStateIterators( <add> ReadOptions readOptions) { <add> final List<Tuple2<RocksIteratorWrapper, Integer>> kvStateIterators = <add> new ArrayList<>(metaData.size()); <ide> <ide> int kvStateId = 0; <ide> <ide> kvStateIterators.add(Tuple2.of(rocksIteratorWrapper, kvStateId)); <ide> ++kvStateId; <ide> } <add> <add> return kvStateIterators; <add> } <add> <add> private void writeKVStateMetaData(final DataOutputView outputView) throws IOException { <ide> <ide> KeyedBackendSerializationProxy<K> serializationProxy = <ide> new KeyedBackendSerializationProxy<>(
Java
agpl-3.0
cc7e819f2fef6d05e7e242d7df9e5f5c4dba85f7
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
71e40a96-2e62-11e5-9284-b827eb9e62be
hello.java
71de9444-2e62-11e5-9284-b827eb9e62be
71e40a96-2e62-11e5-9284-b827eb9e62be
hello.java
71e40a96-2e62-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>71de9444-2e62-11e5-9284-b827eb9e62be <add>71e40a96-2e62-11e5-9284-b827eb9e62be
JavaScript
agpl-3.0
f31c747461454298b4eb5aab87588b071f1420bd
0
ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs
/* * (c) Copyright Ascensio System SIA 2010-2017 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, * EU, LV-1021. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ "use strict"; (/** * @param {Window} window * @param {undefined} undefined */ function (window, undefined) { var fSortAscending = AscCommon.fSortAscending; var cElementType = AscCommonExcel.cElementType; var cErrorType = AscCommonExcel.cErrorType; var cNumber = AscCommonExcel.cNumber; var cString = AscCommonExcel.cString; var cBool = AscCommonExcel.cBool; var cError = AscCommonExcel.cError; var cArea = AscCommonExcel.cArea; var cArea3D = AscCommonExcel.cArea3D; var cRef = AscCommonExcel.cRef; var cRef3D = AscCommonExcel.cRef3D; var cEmpty = AscCommonExcel.cEmpty; var cArray = AscCommonExcel.cArray; var cBaseFunction = AscCommonExcel.cBaseFunction; var checkTypeCell = AscCommonExcel.checkTypeCell; var cFormulaFunctionGroup = AscCommonExcel.cFormulaFunctionGroup; var _func = AscCommonExcel._func; var matching = AscCommonExcel.matching; var maxGammaArgument = 171.624376956302; cFormulaFunctionGroup['Statistical'] = cFormulaFunctionGroup['Statistical'] || []; cFormulaFunctionGroup['Statistical'].push(cAVEDEV, cAVERAGE, cAVERAGEA, cAVERAGEIF, cAVERAGEIFS, cBETADIST, cBETA_DIST, cBETA_INV, cBINOMDIST, cBINOM_DIST, cBINOM_DIST_RANGE, cBINOM_INV, cCHIDIST, cCHIINV, cCHISQ_DIST, cCHISQ_DIST_RT, cCHISQ_INV, cCHISQ_INV_RT, cCHITEST, cCHISQ_TEST, cCONFIDENCE, cCONFIDENCE_NORM, cCONFIDENCE_T, cCORREL, cCOUNT, cCOUNTA, cCOUNTBLANK, cCOUNTIF, cCOUNTIFS, cCOVAR, cCOVARIANCE_P, cCOVARIANCE_S, cCRITBINOM, cDEVSQ, cEXPON_DIST, cEXPONDIST, cF_DIST, cFDIST, cF_DIST_RT, cF_INV, cFINV, cF_INV_RT, cFISHER, cFISHERINV, cFORECAST, cFORECAST_ETS, cFORECAST_LINEAR, cFREQUENCY, cFTEST, cGAMMA, cGAMMA_DIST, cGAMMADIST, cGAMMA_INV, cGAMMAINV, cGAMMALN, cGAMMALN_PRECISE, cGAUSS, cGEOMEAN, cGROWTH, cHARMEAN, cHYPGEOMDIST, cINTERCEPT, cKURT, cLARGE, cLINEST, cLOGEST, cLOGINV, cLOGNORM_DIST, cLOGNORM_INV, cLOGNORMDIST, cMAX, cMAXA, cMAXIFS, cMEDIAN, cMIN, cMINA, cMINIFS, cMODE, cMODE_MULT, cMODE_SNGL, cNEGBINOMDIST, cNEGBINOM_DIST, cNORMDIST, cNORM_DIST, cNORMINV, cNORM_INV, cNORMSDIST, cNORM_S_DIST, cNORMSINV, cNORM_S_INV, cPEARSON, cPERCENTILE, cPERCENTILE_EXC, cPERCENTILE_INC, cPERCENTRANK, cPERCENTRANK_EXC, cPERCENTRANK_INC, cPERMUT, cPERMUTATIONA, cPHI, cPOISSON, cPOISSON_DIST, cPROB, cQUARTILE, cQUARTILE_EXC, cQUARTILE_INC, cRANK, cRANK_AVG, cRANK_EQ, cRSQ, cSKEW, cSKEW_P, cSLOPE, cSMALL, cSTANDARDIZE, cSTDEV, cSTDEV_S, cSTDEVA, cSTDEVP, cSTDEV_P, cSTDEVPA, cSTEYX, cTDIST, cT_DIST, cT_DIST_2T, cT_DIST_RT, cT_INV, cT_INV_2T, cTINV, cTREND, cTRIMMEAN, cTTEST, cT_TEST, cVAR, cVARA, cVARP, cVAR_P, cVAR_S, cVARPA, cWEIBULL, cWEIBULL_DIST, cZTEST, cZ_TEST); cFormulaFunctionGroup['NotRealised'] = cFormulaFunctionGroup['NotRealised'] || []; cFormulaFunctionGroup['NotRealised'].push(cFTEST, cGROWTH, cLINEST, cLOGEST, cTREND); function isInteger(value) { return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; } function integralPhi(x) { // Using gauss(x)+0.5 has severe cancellation errors for x<-4 return 0.5 * AscCommonExcel.rtl_math_erfc(-x * 0.7071067811865475); // * 1/sqrt(2) } function phi(x) { return 0.39894228040143268 * Math.exp(-(x * x) / 2); } function gauss(x) { var t0 = [0.39894228040143268, -0.06649038006690545, 0.00997355701003582, -0.00118732821548045, 0.00011543468761616, -0.00000944465625950, 0.00000066596935163, -0.00000004122667415, 0.00000000227352982, 0.00000000011301172, 0.00000000000511243, -0.00000000000021218], t2 = [0.47724986805182079, 0.05399096651318805, -0.05399096651318805, 0.02699548325659403, -0.00449924720943234, -0.00224962360471617, 0.00134977416282970, -0.00011783742691370, -0.00011515930357476, 0.00003704737285544, 0.00000282690796889, -0.00000354513195524, 0.00000037669563126, 0.00000019202407921, -0.00000005226908590, -0.00000000491799345, 0.00000000366377919, -0.00000000015981997, -0.00000000017381238, 0.00000000002624031, 0.00000000000560919, -0.00000000000172127, -0.00000000000008634, 0.00000000000007894], t4 = [0.49996832875816688, 0.00013383022576489, -0.00026766045152977, 0.00033457556441221, -0.00028996548915725, 0.00018178605666397, -0.00008252863922168, 0.00002551802519049, -0.00000391665839292, -0.00000074018205222, 0.00000064422023359, -0.00000017370155340, 0.00000000909595465, 0.00000000944943118, -0.00000000329957075, 0.00000000029492075, 0.00000000011874477, -0.00000000004420396, 0.00000000000361422, 0.00000000000143638, -0.00000000000045848]; var asympt = [-1, 1, -3, 15, -105], xabs = Math.abs(x), xshort = Math.floor(xabs), nval = 0; if (xshort == 0) { nval = taylor(t0, 11, (xabs * xabs)) * xabs; } else if ((xshort >= 1) && (xshort <= 2)) { nval = taylor(t2, 23, (xabs - 2)); } else if ((xshort >= 3) && (xshort <= 4)) { nval = taylor(t4, 20, (xabs - 4)); } else { nval = 0.5 + phi(xabs) * taylor(asympt, 4, 1 / (xabs * xabs)) / xabs; } if (x < 0) { return -nval; } else { return nval; } } function taylor(pPolynom, nMax, x) { var nVal = pPolynom[nMax]; for (var i = nMax - 1; i >= 0; i--) { nVal = pPolynom[i] + (nVal * x); } return nVal; } function gaussinv(x) { var q, t, z; q = x - 0.5; if (Math.abs(q) <= .425) { t = 0.180625 - q * q; z = q * ( ( ( ( ( ( ( t * 2509.0809287301226727 + 33430.575583588128105 ) * t + 67265.770927008700853 ) * t + 45921.953931549871457 ) * t + 13731.693765509461125 ) * t + 1971.5909503065514427 ) * t + 133.14166789178437745 ) * t + 3.387132872796366608 ) / ( ( ( ( ( ( ( t * 5226.495278852854561 + 28729.085735721942674 ) * t + 39307.89580009271061 ) * t + 21213.794301586595867 ) * t + 5394.1960214247511077 ) * t + 687.1870074920579083 ) * t + 42.313330701600911252 ) * t + 1 ); } else { if (q > 0) { t = 1 - x; } else { t = x; } t = Math.sqrt(-Math.log(t)); if (t <= 5) { t += -1.6; z = ( ( ( ( ( ( ( t * 7.7454501427834140764e-4 + 0.0227238449892691845833 ) * t + 0.24178072517745061177 ) * t + 1.27045825245236838258 ) * t + 3.64784832476320460504 ) * t + 5.7694972214606914055 ) * t + 4.6303378461565452959 ) * t + 1.42343711074968357734 ) / ( ( ( ( ( ( ( t * 1.05075007164441684324e-9 + 5.475938084995344946e-4 ) * t + 0.0151986665636164571966 ) * t + 0.14810397642748007459 ) * t + 0.68976733498510000455 ) * t + 1.6763848301838038494 ) * t + 2.05319162663775882187 ) * t + 1 ); } else { t += -5; z = ( ( ( ( ( ( ( t * 2.01033439929228813265e-7 + 2.71155556874348757815e-5 ) * t + 0.0012426609473880784386 ) * t + 0.026532189526576123093 ) * t + 0.29656057182850489123 ) * t + 1.7848265399172913358 ) * t + 5.4637849111641143699 ) * t + 6.6579046435011037772 ) / ( ( ( ( ( ( ( t * 2.04426310338993978564e-15 + 1.4215117583164458887e-7 ) * t + 1.8463183175100546818e-5 ) * t + 7.868691311456132591e-4 ) * t + 0.0148753612908506148525 ) * t + 0.13692988092273580531 ) * t + 0.59983220655588793769 ) * t + 1 ); } if (q < 0) { z = -z; } } return z; } function getLanczosSum(fZ) { var num = [23531376880.41075968857200767445163675473, 42919803642.64909876895789904700198885093, 35711959237.35566804944018545154716670596, 17921034426.03720969991975575445893111267, 6039542586.35202800506429164430729792107, 1439720407.311721673663223072794912393972, 248874557.8620541565114603864132294232163, 31426415.58540019438061423162831820536287, 2876370.628935372441225409051620849613599, 186056.2653952234950402949897160456992822, 8071.672002365816210638002902272250613822, 210.8242777515793458725097339207133627117, 2.506628274631000270164908177133837338626], denom = [0, 39916800, 120543840, 150917976, 105258076, 45995730, 13339535, 2637558, 357423, 32670, 1925, 66, 1]; // Horner scheme var sumNum, sumDenom, i, zInv; if (fZ <= 1) { sumNum = num[12]; sumDenom = denom[12]; for (i = 11; i >= 0; --i) { sumNum *= fZ; sumNum += num[i]; sumDenom *= fZ; sumDenom += denom[i]; } } else // Cancel down with fZ^12; Horner scheme with reverse coefficients { zInv = 1 / fZ; sumNum = num[0]; sumDenom = denom[0]; for (i = 1; i <= 12; ++i) { sumNum *= zInv; sumNum += num[i]; sumDenom *= zInv; sumDenom += denom[i]; } } return sumNum / sumDenom; } /** You must ensure fZ>0; fZ>171.624376956302 will overflow. */ function getGammaHelper(fZ) { var gamma = getLanczosSum(fZ), fg = 6.024680040776729583740234375, zgHelp = fZ + fg - 0.5; // avoid intermediate overflow var halfpower = Math.pow(zgHelp, fZ / 2 - 0.25); gamma *= halfpower; gamma /= Math.exp(zgHelp); gamma *= halfpower; if (fZ <= 20 && fZ == Math.floor(fZ)) { gamma = Math.round(gamma); } return gamma; } /** You must ensure fZ>0 */ function getLogGammaHelper(fZ) { var _fg = 6.024680040776729583740234375, zgHelp = fZ + _fg - 0.5; return Math.log(getLanczosSum(fZ)) + (fZ - 0.5) * Math.log(zgHelp) - zgHelp; } function getLogGamma(fZ) { if (fZ >= maxGammaArgument) { return getLogGammaHelper(fZ); } if (fZ >= 0) { return Math.log(getGammaHelper(fZ)); } if (fZ >= 0.5) { return Math.log(getGammaHelper(fZ + 1) / fZ); } return getLogGammaHelper(fZ + 2) - Math.log(fZ + 1) - Math.log(fZ); } function getPercentile(values, alpha) { values.sort(fSortAscending); var nSize = values.length; if (nSize === 0) { return new cError(cErrorType.not_available); } else { if (nSize === 1) { return new cNumber(values[0]); } else { var nIndex = Math.floor(alpha * (nSize - 1)); var fDiff = alpha * (nSize - 1) - Math.floor(alpha * (nSize - 1)); if (fDiff === 0.0) { return new cNumber(values[nIndex]); } else { return new cNumber(values[nIndex] + fDiff * (values[nIndex + 1] - values[nIndex])); } } } } function getPercentileExclusive(values, alpha) { values.sort(fSortAscending); var nSize1 = values.length + 1; if ( nSize1 == 1){ return new cError(cErrorType.wrong_value_type); } if ( alpha * nSize1 < 1 || alpha * nSize1 > nSize1 - 1 ){ return new cError(cErrorType.not_numeric); } var nIndex = Math.floor(alpha * nSize1 - 1); var fDiff = alpha * nSize1 - 1 - Math.floor(alpha * nSize1 - 1); if (fDiff === 0.0) { return new cNumber(values[nIndex]); } else { return new cNumber(values[nIndex] + fDiff * (values[nIndex + 1] - values[nIndex])); } } function percentrank(tA, fNum, k, bInclusive) { tA.sort(fSortAscending); var nSize = tA.length; if(k < 1){ return new cError(cErrorType.not_numeric); }else if (tA.length < 1 || nSize === 0) { return new cError(cErrorType.not_available); } else { if (fNum < tA[0] || fNum > tA[nSize - 1]) { return new cError(cErrorType.not_available); } else if (nSize === 1) { return new cNumber(1); } else { if ( fNum === tA[0] ){ if ( bInclusive ){ fRes = 0; }else{ fRes = 1 / ( nSize + 1 ); } }else{ var fRes, nOldCount = 0, fOldVal = tA[0], i; for (i = 1; i < nSize && tA[i] < fNum; i++) { if (tA[i] !== fOldVal) { nOldCount = i; fOldVal = tA[i]; } } if (tA[i] !== fOldVal) { nOldCount = i; } if (fNum === tA[i]) { if ( bInclusive ){ fRes = nOldCount / (nSize - 1); }else{ fRes =(i + 1) / (nSize + 1); } } else { if (nOldCount === 0) { fRes = 0; } else { var fFract = ( fNum - tA[nOldCount - 1] ) / ( tA[nOldCount] - tA[nOldCount - 1] ); if ( bInclusive ){ fRes = fRes = ( nOldCount - 1 + fFract ) / (nSize - 1); } else{ fRes = (nOldCount + fFract ) / ( nSize + 1 ); } } } } return new cNumber(fRes.toString().substr(0, fRes.toString().indexOf(".") + 1 + k) - 0); } } } function getMedian(rArray){ rArray.sort(fSortAscending); var nSize = rArray.length; if (nSize == 0){ return new cError(cErrorType.wrong_value_type); } if (nSize % 2 === 0) { return new cNumber((rArray[nSize / 2 - 1] + rArray[nSize / 2]) / 2); } else { return new cNumber(rArray[(nSize - 1) / 2]); } } function getGamma(fZ) { var fLogPi = Math.log(Math.PI); var fLogDblMax = Math.log(2.22507e+308); if (fZ > maxGammaArgument){ //SetError(FormulaError::IllegalFPOperation); //return HUGE_VAL; return; } if (fZ >= 1.0){ return getGammaHelper(fZ); } if (fZ >= 0.5){ return getGammaHelper(fZ + 1) / fZ; } if (fZ >= -0.5){ var fLogTest = getLogGammaHelper(fZ+2) - Math.log1p(fZ) - Math.log( Math.abs(fZ)); if (fLogTest >= fLogDblMax){ //SetError(FormulaError::IllegalFPOperation); //return HUGE_VAL; return; } return getGammaHelper(fZ + 2) / (fZ + 1) / fZ; } var fLogDivisor = getLogGammaHelper(1 - fZ) + Math.log( Math.abs( Math.sin( Math.PI * fZ))); if (fLogDivisor - fLogPi >= fLogDblMax){ return 0; } if (fLogDivisor < 0){ if (fLogPi - fLogDivisor > fLogDblMax){ //SetError(FormulaError::IllegalFPOperation); //return HUGE_VAL; return; } } return Math.exp( fLogPi - fLogDivisor) * ((Math.sin( Math.PI * fZ) < 0) ? -1 : 1); } function getGammaDist( fX, fAlpha, fLambda ){ if (fX <= 0){ return 0; } else{ return GetLowRegIGamma( fAlpha, fX / fLambda); } } function GetLowRegIGamma( fA, fX ){ var fLnFactor = fA * Math.log(fX) - fX - getLogGamma(fA); var fFactor = Math.exp(fLnFactor); if (fX > fA + 1){ return 1 - fFactor * getGammaContFraction(fA, fX); } else{ return fFactor * getGammaSeries(fA, fX); } } function getGammaContFraction( fA, fX ) { var fBigInv = 2.22045e-016;//epsilon var fHalfMachEps = fBigInv / 2; var fBig = 1 / fBigInv; var fCount = 0; var fY = 1 - fA; var fDenom = fX + 2 - fA; var fPkm1 = fX + 1; var fPkm2 = 1; var fQkm1 = fDenom * fX; var fQkm2 = fX; var fApprox = fPkm1 / fQkm1; var bFinished = false; do { fCount = fCount + 1; fY = fY + 1; var fNum = fY * fCount; fDenom = fDenom + 2; var fPk = fPkm1 * fDenom - fPkm2 * fNum; var fQk = fQkm1 * fDenom - fQkm2 * fNum; if (fQk !== 0) { var fR = fPk / fQk; bFinished = (Math.abs( (fApprox - fR) / fR ) <= fHalfMachEps); fApprox = fR; } fPkm2 = fPkm1; fPkm1 = fPk; fQkm2 = fQkm1; fQkm1 = fQk; if (Math.abs(fPk) > fBig) { // reduce a fraction does not change the value fPkm2 = fPkm2 * fBigInv; fPkm1 = fPkm1 * fBigInv; fQkm2 = fQkm2 * fBigInv; fQkm1 = fQkm1 * fBigInv; } } while (!bFinished && fCount < 10000); if (!bFinished) { //SetError(FormulaError::NoConvergence); return; } return fApprox; } function getGammaSeries( fA, fX ){ var fHalfMachEps = 2.22045e-016 / 2; var fDenomfactor = fA; var fSummand = 1 / fA; var fSum = fSummand; var nCount = 1; do { fDenomfactor = fDenomfactor + 1; fSummand = fSummand * fX / fDenomfactor; fSum = fSum + fSummand; nCount = nCount + 1; } while ( fSummand/fSum > fHalfMachEps && nCount <= 10000); if (nCount > 10000) { //SetError(FormulaError::NoConvergence); return; } return fSum; } function getGammaDistPDF( fX, fAlpha, fLambda ) { if (fX < 0){ return 0; }else if (fX === 0){ if (fAlpha < 1.0){ //SetError(FormulaError::DivisionByZero); // should be #DIV/0 //return HUGE_VAL; return; }else if (fAlpha === 1){ return (1 / fLambda); }else{ return 0; } }else{ var fXr = fX / fLambda; if (fXr > 1){ var fLogDblMax = Math.log( 2.22507e+308 ); if (Math.log(fXr) * (fAlpha - 1) < fLogDblMax && fAlpha < maxGammaArgument){ return Math.pow( fXr, fAlpha - 1) * Math.exp(-fXr) / fLambda / getGamma(fAlpha); }else{ return Math.exp( (fAlpha - 1) * Math.log(fXr) - fXr - Math.log(fLambda) - getLogGamma(fAlpha)); } }else { if (fAlpha < maxGammaArgument){ return Math.pow( fXr, fAlpha - 1) * Math.exp(-fXr) / fLambda / getGamma(fAlpha); }else{ return Math.pow( fXr, fAlpha - 1) * Math.exp(-fXr) / fLambda / Math.exp( getLogGamma(fAlpha)); } } } } function getChiDist( fX, fDF){ if (fX <= 0.0){ return 1.0; }else{ return getUpRegIGamma( fDF/2.0, fX/2.0); } } function getUpRegIGamma( fA, fX ){ var fLnFactor= fA * Math.log(fX) - fX - getLogGamma(fA); var fFactor = Math.exp(fLnFactor); if (fX > fA + 1){ return fFactor * getGammaContFraction(fA, fX); }else{ return 1 - fFactor * getGammaSeries(fA, fX); } } function getChiSqDistCDF( fX, fDF){ if (fX <= 0){ return 0; }else{ return GetLowRegIGamma( fDF/2, fX/2); } } function getChiSqDistPDF( fX, fDF){ var fValue; if (fX <= 0){ return 0; } if (fDF*fX > 1391000) { fValue = Math.exp((0.5*fDF - 1) * Math.log(fX*0.5) - 0.5 * fX - Math.log(2) - getLogGamma(0.5*fDF)); } else { var fCount; if (Math.fmod(fDF, 2) < 0.5){ fValue = 0.5; fCount = 2; }else{ fValue = 1 / Math.sqrt(fX * 2 * Math.PI); fCount = 1; } while ( fCount < fDF){ fValue *= (fX / fCount); fCount += 2; } if (fX >= 1425){ fValue = Math.exp(Math.log(fValue) - fX / 2); }else{ fValue *= Math.exp(- fX/2); } } return fValue; } function chiTest(pMat1, pMat2){ if (!pMat1 || !pMat2){ return new cError(cErrorType.not_available); } var nC1 = pMat1.length; var nC2 = pMat2.length; var nR1 = pMat1[0].length; var nR2 = pMat2[0].length; if (nR1 !== nR2 || nC1 !== nC2){ return new cError(cErrorType.not_available); } var fChi = 0.0; var bEmpty = true; for (var i = 0; i < nC1; i++){ for (var j = 0; j < nR1; j++){ if (pMat1[i][j] && pMat2[i][j]){ bEmpty = false; //MS выдает ошибку только если первый элемент строка. LO - если любой. if (i === 0 && j === 0 && cElementType.string === pMat1[i][j].type){ return new cError(cErrorType.division_by_zero); } if(cElementType.number !== pMat1[i][j].type || cElementType.number !== pMat2[i][j].type){ continue; } var fValX = pMat1[i][j].getValue(); var fValE = pMat2[i][j].getValue(); if ( fValE === 0.0 ){ return new cError(cErrorType.division_by_zero); } var fTemp1 = (fValX - fValE) * (fValX - fValE); var fTemp2 = fTemp1; fChi += fTemp2 / fValE; } } } if ( bEmpty ){ return new cError(cErrorType.wrong_value_type); } var fDF; if (nC1 === 1 || nR1 === 1){ fDF = nC1*nR1 - 1; if (fDF === 0){ return new cError(cErrorType.not_available); } }else{ fDF = (nC1 - 1)*(nR1 - 1); } if ( fDF < 1 || fChi < 0 || fDF > Math.pow(10, 10)){ return new cError(cErrorType.not_numeric); } var res = getChiDist(fChi, fDF); return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); } function tTest(pMat1, pMat2, fTails, fTyp){ var fT, fF; var nC1 = pMat1.length; var nC2 = pMat2.length; var nR1 = pMat1[0].length; var nR2 = pMat2[0].length; var calcTest = null; if (fTyp === 1.0){ if (nC1 !== nC2 || nR1 !== nR2){ return new cError(cErrorType.not_available); } var fCount = 0.0; var fSum1 = 0.0; var fSum2 = 0.0; var fSumSqrD = 0.0; var fVal1, fVal2; for (var i = 0; i < nC1; i++){ for (var j = 0; j < nR1; j++){ if(cElementType.number !== pMat1[i][j].type || cElementType.number !== pMat2[i][j].type){ continue; } fVal1 = pMat1[i][j].getValue(); fVal2 = pMat2[i][j].getValue(); fSum1 += fVal1; fSum2 += fVal2; fSumSqrD += (fVal1 - fVal2)*(fVal1 - fVal2); fCount++; } } if (fCount < 1.0){ return new cError(cErrorType.wrong_value_type); } var fSumD = fSum1 - fSum2; var fDivider = (fCount*fSumSqrD - fSumD*fSumD); if ( fDivider === 0.0 ){ return new cError(cErrorType.division_by_zero); } fT = Math.abs(fSumD) * Math.sqrt((fCount-1.0) / fDivider); fF = fCount - 1.0; } else if (fTyp === 2.0){ calcTest = CalculateTest(false, nC1, nC2, nR1, nR2, pMat1, pMat2, fT, fF); } else if (fTyp === 3.0){ calcTest = CalculateTest(true, nC1, nC2, nR1, nR2, pMat1, pMat2, fT, fF); }else{ return new cError(cErrorType.not_numeric); } if(null !== calcTest){ if(false === calcTest){ return new cError(cErrorType.wrong_value_type); }else{ fT = calcTest.fT; fF = calcTest.fF; } } var res = getTDist(fT, fF, fTails); return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); } function CalculateTest( bTemplin, nC1, nC2, nR1, nR2, pMat1, pMat2 , fT, fF) { var fCount1 = 0.0; var fCount2 = 0.0; var fSum1 = 0.0; var fSumSqr1 = 0.0; var fSum2 = 0.0; var fSumSqr2 = 0.0; var fVal; for (var i = 0; i < nC1; i++){ for (var j = 0; j < nR1; j++) { if (cElementType.string !== pMat1[i][j].type) { fVal = pMat1[i][j].getValue(); fSum1 += fVal; fSumSqr1 += fVal * fVal; fCount1++; } } } for (var i = 0; i < nC2; i++){ for (var j = 0; j < nR2; j++) { if (cElementType.string !== pMat2[i][j].type) { fVal = pMat2[i][j].getValue(); fSum2 += fVal; fSumSqr2 += fVal * fVal; fCount2++; } } } if (fCount1 < 2.0 || fCount2 < 2.0){ return false; } if ( bTemplin ){ var fS1 = (fSumSqr1 - fSum1 * fSum1 / fCount1) / (fCount1 - 1.0) / fCount1; var fS2 = (fSumSqr2 - fSum2 * fSum2 / fCount2) / (fCount2 - 1.0) / fCount2; if (fS1 + fS2 === 0.0){ return false; } var c = fS1 / (fS1 + fS2); fT = Math.abs(fSum1 / fCount1 - fSum2 / fCount2) / Math.sqrt(fS1 + fS2); fF = 1.0 / (c * c / (fCount1 - 1.0) + (1.0 - c) * (1.0 - c) / (fCount2 - 1.0)); }else{ var fS1 = (fSumSqr1 - fSum1 * fSum1 / fCount1) / (fCount1 - 1.0); var fS2 = (fSumSqr2 - fSum2 * fSum2 / fCount2) / (fCount2 - 1.0); fT = Math.abs( fSum1 / fCount1 - fSum2 / fCount2 ) / Math.sqrt( (fCount1-1.0)*fS1 + (fCount2-1.0)*fS2 ) * Math.sqrt( fCount1*fCount2*(fCount1+fCount2-2)/(fCount1+fCount2) ); fF = fCount1 + fCount2 - 2; } return {fT: fT, fF: fF}; } //BETA DISTRIBUTION function getBetaDist(fXin, fAlpha, fBeta) { if (fXin <= 0) { return 0; } if (fXin >= 1){ return 1; } if (fBeta === 1) { return Math.pow(fXin, fAlpha); } if (fAlpha === 1){ return - Math.expm1(fBeta * Math.log1p(-fXin)); } var fResult; var fY = (0.5 - fXin) + 0.5; var flnY = Math.log1p(-fXin); var fX = fXin; var flnX = Math.log(fXin); var fA = fAlpha; var fB = fBeta; var bReflect = fXin > fAlpha / (fAlpha + fBeta); if (bReflect){ fA = fBeta; fB = fAlpha; fX = fY; fY = fXin; flnX = flnY; flnY = Math.log(fXin); } fResult = getBetaHelperContFrac(fX, fA, fB); fResult = fResult / fA; var fP = fA / (fA + fB); var fQ = fB / (fA + fB); var fTemp; if (fA > 1 && fB > 1 && fP < 0.97 && fQ < 0.97){ fTemp = getBetaDistPDF(fX, fA, fB) * fX * fY; } else{ fTemp = Math.exp(fA * flnX + fB * flnY - getLogBeta(fA, fB)); } fResult *= fTemp; if (bReflect){ fResult = 0.5 - fResult + 0.5; } if (fResult > 1){ fResult = 1; } if (fResult < 0){ fResult = 0; } return fResult; } // beta distribution probability density function function getTDist(T, fDF, nType) { var res = null; switch ( nType ){ case 1: { res = 0.5 * getBetaDist(fDF / ( fDF + T * T ), fDF / 2, 0.5); break; } case 2: { res = getBetaDist(fDF / ( fDF + T * T ), fDF / 2, 0.5); break; } case 3: { res = Math.pow( 1 + ( T * T / fDF ), -( fDF + 1 ) / 2 ) / ( Math.sqrt( fDF ) * getBeta( 0.5, fDF / 2.0 ) ); break; } case 4: { var X = fDF / ( T * T + fDF ); var R = 0.5 * getBetaDist( X, 0.5 * fDF, 0.5 ); res = ( T < 0 ? R : 1 - R ); break; } } return res; } function getBetaDistPDF(fX, fA, fB) { // special cases if (fA === 1){ if (fB === 1) return 1; if (fB === 2) return -2 * fX + 2; if (fX === 1 && fB < 1){ //SetError(FormulaError::IllegalArgument); //return HUGE_VAL; return; } if (fX <= 0.01) return fB + fB * Math.expm1((fB - 1) * Math.log1p(-fX)); else return fB * Math.pow(0.5 - fX + 0.5, fB - 1); } if (fB === 1){ if (fA === 2) return fA * fX; if (fX === 0 && fA < 1){ //SetError(FormulaError::IllegalArgument); //return HUGE_VAL; return; } return fA * pow(fX, fA - 1); } if (fX <= 0){ if (fA < 1 && fX === 0){ //SetError(FormulaError::IllegalArgument); //return HUGE_VAL; return; } else return 0; } if (fX >= 1){ if (fB < 1 && fX === 1){ //SetError(FormulaError::IllegalArgument); //return HUGE_VAL; return; } else return 0; } var fLogDblMax = Math.log( 2.22507e+308); var fLogDblMin = Math.log( 2.22507e-308 ); var fLogY = (fX < 0.1) ? Math.log1p(-fX) : Math.log(0.5 - fX + 0.5); var fLogX = Math.log(fX); var fAm1LogX = (fA - 1) * fLogX; var fBm1LogY = (fB - 1) * fLogY; var fLogBeta = getLogBeta(fA,fB); if ( fAm1LogX < fLogDblMax && fAm1LogX > fLogDblMin && fBm1LogY < fLogDblMax && fBm1LogY > fLogDblMin && fLogBeta < fLogDblMax && fLogBeta > fLogDblMin && fAm1LogX + fBm1LogY < fLogDblMax && fAm1LogX + fBm1LogY > fLogDblMin){ return Math.pow(fX, fA - 1) * Math.pow(0.5 - fX + 0.5, fB - 1) / getBeta(fA, fB); }else{ return Math.exp( fAm1LogX + fBm1LogY - fLogBeta); } } function getBeta(fAlpha, fBeta) { var fA; var fB; if (fAlpha > fBeta){ fA = fAlpha; fB = fBeta; }else{ fA = fBeta; fB = fAlpha; } if (fA + fB < maxGammaArgument){ return getGamma(fA) / getGamma(fA + fB) * getGamma(fB); } var fg = 6.024680040776729583740234375; var fgm = fg - 0.5; var fLanczos = getLanczosSum(fA); fLanczos /= getLanczosSum(fA + fB); fLanczos *= getLanczosSum(fB); var fABgm = fA +fB + fgm; fLanczos *= Math.sqrt((fABgm / (fA + fgm)) / (fB + fgm)); var fTempA = fB / (fA + fgm); var fTempB = fA / (fB + fgm); var fResult = Math.exp(-fA * Math.log1p(fTempA) - fB * Math.log1p(fTempB) - fgm); fResult *= fLanczos; return fResult; } function getBetaHelperContFrac(fX, fA, fB) { var a1, b1, a2, b2, fnorm, cfnew, cf; a1 = 1; b1 = 1; b2 = 1 - (fA + fB) / (fA + 1) * fX; if (b2 === 0){ a2 = 0; fnorm = 1; cf = 1; }else{ a2 = 1; fnorm = 1 / b2; cf = a2 * fnorm; } cfnew = 1; var rm = 1; var fMaxIter = 50000; var fMachEps = 2.22045e-016; var bfinished = false; do { var apl2m = fA + 2 * rm; var d2m = rm * (fB - rm) * fX / ((apl2m - 1) * apl2m); var d2m1 = -(fA + rm) * (fA + fB + rm) * fX / (apl2m * (apl2m + 1)); a1 = (a2 + d2m * a1) * fnorm; b1 = (b2 + d2m * b1) * fnorm; a2 = a1 + d2m1 * a2 * fnorm; b2 = b1 + d2m1 * b2 * fnorm; if (b2 !== 0){ fnorm = 1 / b2; cfnew = a2 * fnorm; bfinished = (Math.abs(cf - cfnew) < Math.abs(cf) * fMachEps); } cf = cfnew; rm += 1; } while (rm < fMaxIter && !bfinished); return cf; } function getLogBeta(fAlpha, fBeta) { var fA; var fB; if (fAlpha > fBeta) { fA = fAlpha; fB = fBeta; } else { fA = fBeta; fB = fAlpha; } var fg = 6.024680040776729583740234375; var fgm = fg - 0.5; var fLanczos = getLanczosSum(fA); fLanczos /= getLanczosSum(fA + fB); fLanczos *= getLanczosSum(fB); var fLogLanczos = Math.log(fLanczos); var fABgm = fA + fB + fgm; fLogLanczos += 0.5 * (Math.log(fABgm) - Math.log(fA + fgm) - Math.log(fB + fgm)); var fTempA = fB / (fA + fgm); var fTempB = fA / (fB + fgm); var fResult = - fA * Math.log1p(fTempA) -fB * Math.log1p(fTempB) - fgm; fResult += fLogLanczos; return fResult; } function getFDist( x, fF1, fF2) { var arg = fF2 / (fF2 + fF1 * x); var alpha = fF2 / 2; var beta = fF1 / 2; return getBetaDist(arg, alpha, beta); } function iterateInverse( rFunction, fAx, fBx ) { var rConvError = false; var fYEps = 1.0E-307; var fXEps = 2.22045e-016; var fAy = rFunction.GetValue(fAx); var fBy = rFunction.GetValue(fBx); var fTemp; var nCount; for (nCount = 0; nCount < 1000 && !hasChangeOfSign(fAy, fBy); nCount++) { if (Math.abs(fAy) <= Math.abs(fBy)) { fTemp = fAx; fAx += 2 * (fAx - fBx); if (fAx < 0){ fAx = 0; } fBx = fTemp; fBy = fAy; fAy = rFunction.GetValue(fAx); } else { fTemp = fBx; fBx += 2 * (fBx - fAx); fAx = fTemp; fAy = fBy; fBy = rFunction.GetValue(fBx); } } if (fAy === 0){ return {val: fAx, bError: rConvError}; } if (fBy === 0){ return {val: fBx, bError: rConvError}; } if (!hasChangeOfSign( fAy, fBy)){ rConvError = true; return {val: 0, bError: rConvError}; } // inverse quadric interpolation with additional brackets // set three points var fPx = fAx; var fPy = fAy; var fQx = fBx; var fQy = fBy; var fRx = fAx; var fRy = fAy; var fSx = 0.5 * (fAx + fBx); var bHasToInterpolate = true; nCount = 0; while ( nCount < 500 && Math.abs(fRy) > fYEps && (fBx - fAx) > Math.max( Math.abs(fAx), Math.abs(fBx)) * fXEps ){ if (bHasToInterpolate){ if (fPy !== fQy && fQy !== fRy && fRy !== fPy){ fSx = fPx * fRy * fQy / (fRy-fPy) / (fQy-fPy) + fRx * fQy * fPy / (fQy-fRy) / (fPy-fRy) + fQx * fPy * fRy / (fPy-fQy) / (fRy-fQy); bHasToInterpolate = (fAx < fSx) && (fSx < fBx); // inside the brackets? }else{ bHasToInterpolate = false; } } if(!bHasToInterpolate){ fSx = 0.5 * (fAx + fBx); fQx = fBx; fQy = fBy; bHasToInterpolate = true; } fPx = fQx; fQx = fRx; fRx = fSx; fPy = fQy; fQy = fRy; fRy = rFunction.GetValue(fSx); if (hasChangeOfSign( fAy, fRy)) { fBx = fRx; fBy = fRy; }else{ fAx = fRx; fAy = fRy; } bHasToInterpolate = bHasToInterpolate && (Math.abs(fRy) * 2 <= Math.abs(fQy)); ++nCount; } return {val: fRx, bError: rConvError}; } function hasChangeOfSign( u, w ) { return (u < 0 && w > 0) || (u > 0 && w < 0); } function rank( fVal, aSortArray, bAscending, bAverage ) { //sort array aSortArray.sort (function sortArr(a, b) { return a - b; }); var nSize = aSortArray.length; var res; if ( nSize == 0 /*|| nGlobalError != FormulaError::NONE*/ ){ res = null; } else { if ( fVal < aSortArray[ 0 ] || fVal > aSortArray[ nSize - 1 ] ){ res = null; }else{ var fLastPos = 0; var fFirstPos = -1.0; var bFinished = false; var i; for ( i = 0; i < nSize && !bFinished /*&& nGlobalError == FormulaError::NONE*/; i++ ){ if ( aSortArray[ i ] === fVal ){ if ( fFirstPos < 0 ){ fFirstPos = i + 1.0; } }else{ if ( aSortArray[ i ] > fVal ){ fLastPos = i; bFinished = true; } } } if ( !bFinished ){ fLastPos = i; } if ( !bAverage ){ if ( bAscending ){ res = fFirstPos; }else{ res = nSize + 1.0 - fLastPos; } }else { if ( bAscending ){ res = ( fFirstPos + fLastPos ) / 2.0 ; }else{ res = nSize + 1.0 - ( fFirstPos + fLastPos ) / 2.0; } } } } return res; } function skew(x, bSkewp) { var sumSQRDeltaX = 0, _x = 0, xLength = 0, sumSQRDeltaXDivstandDev = 0, i; for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { _x += x[i].getValue(); xLength++; } } if (xLength <= 2) { return new cError(cErrorType.not_available); } _x /= xLength; for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { sumSQRDeltaX += Math.pow(x[i].getValue() - _x, 2); } } var standDev; if(bSkewp){ standDev = Math.sqrt(sumSQRDeltaX / ( xLength )); }else{ standDev = Math.sqrt(sumSQRDeltaX / ( xLength - 1 )); } for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { sumSQRDeltaXDivstandDev += Math.pow((x[i].getValue() - _x) / standDev, 3); } } var res; if(bSkewp){ res = sumSQRDeltaXDivstandDev / xLength; }else{ res = xLength / (xLength - 1) / (xLength - 2) * sumSQRDeltaXDivstandDev; } return new cNumber(res); } function GAMMADISTFUNCTION(fp, fAlpha, fBeta){ this.fp = fp; this.fAlpha = fAlpha; this.fBeta = fBeta; } GAMMADISTFUNCTION.prototype.GetValue = function(x){ var res; var gammaDistVal = getGammaDist(x, this.fAlpha, this.fBeta); res = this.fp - gammaDistVal; return res; }; function BETADISTFUNCTION(fp, fAlpha, fBeta){ this.fp = fp; this.fAlpha = fAlpha; this.fBeta = fBeta; } BETADISTFUNCTION.prototype.GetValue = function(x){ var res; var betaDistVal = getBetaDist(x, this.fAlpha, this.fBeta); res = this.fp - betaDistVal; return res; }; function CHIDISTFUNCTION(fp, fDF){ this.fp = fp; this.fDF = fDF; } CHIDISTFUNCTION.prototype.GetValue = function(x){ var res; var betaDistVal = getChiDist(x, this.fDF); res = this.fp - betaDistVal; return res; }; function CHISQDISTFUNCTION(fp, fDF){ this.fp = fp; this.fDF = fDF; } CHISQDISTFUNCTION.prototype.GetValue = function(x){ var res; var betaDistVal = getChiSqDistCDF(x, this.fDF); res = this.fp - betaDistVal; return res; }; function FDISTFUNCTION(fp, fF1, fF2){ this.fp = fp; this.fF1 = fF1; this.fF2 = fF2; } FDISTFUNCTION.prototype.GetValue = function(x){ var res; var betaDistVal = getFDist(x, this.fF1, this.fF2); res = this.fp - betaDistVal; return res; }; function TDISTFUNCTION(fp, fDF, nT){ this.fp = fp; this.fDF = fDF; this.nT = nT; } TDISTFUNCTION.prototype.GetValue = function(x){ var res; var betaDistVal = getTDist(x, this.fDF, this.nT); res = this.fp - betaDistVal; return res; }; function ScETSForecastCalculation(nSize) { //SvNumberFormatter* mpFormatter; this.maRange = []; // data (X, Y) this.mpBase = []; // calculated base value array this.mpTrend = []; // calculated trend factor array this.mpPerIdx = []; // calculated periodical deviation array, not used with eds this.mpForecast = []; // forecasted value array this.mnSmplInPrd = 0; // samples per period this.mfStepSize = 0; // increment of X in maRange this.mfAlpha, this.mfBeta, this.mfGamma; // constants to minimise the RMSE in the ES-equations this.mnCount = nSize; // No of data points this.mbInitialised; this.mnMonthDay; // n-month X-interval, value is day of month // accuracy indicators this.mfMAE; // mean absolute error this.mfMASE; // mean absolute scaled error this.mfMSE; // mean squared error (variation) this.mfRMSE; // root mean squared error (standard deviation) this.mfSMAPE; // symmetric mean absolute error //FormulaError mnErrorValue; this.bAdditive; // true: additive method, false: multiplicative method this.bEDS; // true: EDS, false: ETS // constants used in determining best fit for alpha, beta, gamma this.cfMinABCResolution = 0.001; // minimum change of alpha, beta, gamma this.cnScenarios = 1000; // No. of scenarios to calculate for PI calculations /*bool initData(); bool prefillBaseData(); bool prefillTrendData(); bool prefillPerIdx(); bool initCalc(); void refill(); SCSIZE CalcPeriodLen(); void CalcAlphaBetaGamma(); void CalcBetaGamma(); void CalcGamma(); void calcAccuracyIndicators(); bool GetForecast( double fTarget, double& rForecast ); double RandDev(); double convertXtoMonths( double x );*/ } /*ScETSForecastCalculation::ScETSForecastCalculation( nSize, pFormatter ) : mpFormatter(pFormatter) , mpBase(nullptr) , mpTrend(nullptr) , mpPerIdx(nullptr) , mpForecast(nullptr) , mnSmplInPrd(0) , mfStepSize(0.0) , mfAlpha(0.0) , mfBeta(0.0) , mfGamma(0.0) , mnCount(nSize) , mbInitialised(false) , mnMonthDay(0) , mfMAE(0.0) , mfMASE(0.0) , mfMSE(0.0) , mfRMSE(0.0) , mfSMAPE(0.0) , mnErrorValue(FormulaError::NONE) , bAdditive(false) , bEDS(false) { maRange.reserve( mnCount ); }*/ ScETSForecastCalculation.prototype = Object.create(ScETSForecastCalculation.prototype); ScETSForecastCalculation.prototype.constructor = ScETSForecastCalculation; ScETSForecastCalculation.prototype.PreprocessDataRange = function( rMatX, rMatY, rSmplInPrd, bDataCompletion, nAggregation, rTMat, eETSType ) { this.bEDS = ( rSmplInPrd === 0 ); this.bAdditive = /*( eETSType == etsAdd || eETSType == etsPIAdd || eETSType == etsStatAdd )*/true; this.mnCount = rMatX.length; var maRange = this.maRange; for ( var i = 0; i < this.mnCount; i++ ){ maRange.push( {X: rMatX[i][0].value, Y: rMatY[i][0].value } ); } maRange.sort(function(a, b) { return a.X - b.X; }); if (rTMat) { if (/*eETSType != etsPIAdd && eETSType != etsPIMult*/true) { if (rTMat[0][0].getValue() < maRange[0].X) { return new cError(cErrorType.not_numeric); } } else { if (rTMat[0] < maRange[this.mnCount - 1].X) { return new cError(cErrorType.wrong_value_type); } } } var aDate = Date.prototype.getDateFromExcel(maRange[ 0 ].X); this.mnMonthDay = aDate.getDate(); for (var i = 1; i < this.mnCount && this.mnMonthDay; i++) { var aDate1 = Date.prototype.getDateFromExcel(maRange[i].X); if (aDate !== aDate1) { if (aDate1.getDate() !== this.mnMonthDay) { this.mnMonthDay = 0; } } } this.mfStepSize = Number.MAX_VALUE; if (/*mnMonthDay*/true) { for (var i = 0; i < this.mnCount; i++) { var aDate = Date.prototype.getDateFromExcel(maRange[i].X); maRange[i].X = aDate.getUTCFullYear() * 12 + aDate.getMonth(); } } for ( var i = 1; i < this.mnCount; i++ ) { var fStep = maRange[ i ].X - maRange[ i - 1 ].X; if ( fStep === 0.0 ) { if (nAggregation === 0) { return new cError(cErrorType.wrong_value_type); } var fTmp = maRange[i - 1].Y; var nCounter = 1; switch (nAggregation) { case 1 : // AVERAGE (default) while (i < this.mnCount && maRange[i].X === maRange[i - 1].X) { maRange.splice(i, 1); --this.mnCount; } break; case 7 : // SUM while (i < mnCount && maRange[i].X === maRange[i - 1].X) { fTmp += maRange[i].Y; maRange.splice(i, 1); --this.mnCount; } maRange[i - 1].Y = fTmp; break; case 2 : // COUNT case 3 : // COUNTA (same as COUNT as there are no non-numeric Y-values) while (i < this.mnCount && maRange[i].X === maRange[i - 1].X) { nCounter++; maRange.splice(i, 1); --this.mnCount; } maRange[i - 1].Y = nCounter; break; case 4 : // MAX while (i < this.mnCount && maRange[i].X === maRange[i - 1].X) { if (maRange[i].Y > fTmp) { fTmp = maRange[i].Y; } maRange.splice(i, 1); --this.mnCount; } maRange[i - 1].Y = fTmp; break; case 5 : // MEDIAN var aTmp = []; aTmp.push(maRange[i - 1].Y); while (i < mnCount && maRange[i].X === maRange[i - 1].X) { aTmp.push(maRange[i].Y); nCounter++; maRange.splice(i, 1); --this.mnCount; } //sort( aTmp.begin(), aTmp.end() ); if (nCounter % 2) { maRange[i - 1].Y = aTmp[nCounter / 2]; } else { maRange[i - 1].Y = ( aTmp[nCounter / 2] + aTmp[nCounter / 2 - 1] ) / 2.0; } break; case 6 : // MIN while (i < this.mnCount && maRange[i].X === maRange[i - 1].X) { if (maRange[i].Y < fTmp) { fTmp = maRange[i].Y; } maRange.splice(i, 1); --this.mnCount; } maRange[i - 1].Y = fTmp; break; } if ( i < this.mnCount - 1 ){ fStep = maRange[ i ].X - maRange[ i - 1 ].X; }else{ fStep = this.mfStepSize; } } if ( fStep > 0 && fStep < this.mfStepSize ){ this.mfStepSize = fStep; } } // step must be constant (or gap multiple of step) var bHasGap = false; for (var i = 1; i < this.mnCount && !bHasGap; i++) { var fStep = maRange[i].X - maRange[i - 1].X; if (fStep != this.mfStepSize) { if (Math.fmod(fStep, this.mfStepSize) !== 0.0) { return new cError(cErrorType.wrong_value_type); } bHasGap = true; } } if (bHasGap) { var nMissingXCount = 0; var fOriginalCount = this.mnCount; if (/*mnMonthDay*/true) { aDate = Date.prototype.getDateFromExcel(maRange[0].X); } for (var i = 1; i < this.mnCount; i++) { var fDist; if (/*mnMonthDay*/true) { var aDate1 = Date.prototype.getDateFromExcel(maRange[i].X); fDist = 12 * ( aDate1.getUTCFullYear() - aDate.getUTCFullYear() ) + ( aDate1.getMonth() - aDate.getMonth() ); aDate = aDate1; } else { fDist = maRange[i].X - maRange[i - 1].X; } if (fDist > this.mfStepSize) { // gap, insert missing data points var fYGap = ( maRange[i].Y + maRange[i - 1].Y ) / 2.0; for (var fXGap = maRange[i - 1].X + this.mfStepSize; fXGap < maRange[i].X; fXGap += this.mfStepSize) { var newAddElem = {X: fXGap, Y: ( bDataCompletion ? fYGap : 0.0 )}; maRange.splice(i, 1, newAddElem); i++; this.mnCount++; nMissingXCount++; if (nMissingXCount / fOriginalCount > 0.3) { // maximum of 30% missing points exceeded return new cError(cErrorType.wrong_value_type); } } } } } if ( rSmplInPrd !== 1 ){ this.mnSmplInPrd = rSmplInPrd; }else { this.mnSmplInPrd = this.CalcPeriodLen(); if ( this.mnSmplInPrd === 1 ){ this.bEDS = true; // period length 1 means no periodic data: EDS suffices } } if ( !this.initData() ){ return false; // note: mnErrorValue is set in called function(s) } return true; }; ScETSForecastCalculation.prototype.initData = function() { // give various vectors size and initial value this.mpBase = []; this.mpBase.length = this.mnCount; this.mpBase.fill(0); this.mpTrend = []; this.mpTrend.length = this.mnCount; this.mpTrend.fill(0); if ( !this.bEDS ){ this.mpPerIdx = []; this.mpPerIdx.length = this.mnCount; this.mpPerIdx.fill(0); } this.mpForecast = []; this.mpForecast.length = this.mnCount; this.mpForecast.fill(0); this.mpForecast[ 0 ] = this.maRange[ 0 ].Y; if ( this.prefillTrendData() ) { if ( this.prefillPerIdx() ) { if ( this.prefillBaseData() ) return true; } } return false; }; ScETSForecastCalculation.prototype.prefillTrendData = function() { if ( this.bEDS ) this.mpTrend[ 0 ] = ( this.maRange[ this.mnCount - 1 ].Y - this.maRange[ 0 ].Y ) / ( this.mnCount - 1 ); else { // we need at least 2 periods in the data range if ( this.mnCount < 2 * this.mnSmplInPrd ) { return new cError(cErrorType.wrong_value_type); } var fSum = 0.0; for ( var i = 0; i < this.mnSmplInPrd; i++ ) fSum += this.maRange[ i + this.mnSmplInPrd ].Y - this.maRange[ i ].Y; var fTrend = fSum / ( this.mnSmplInPrd * this.mnSmplInPrd ); this.mpTrend[ 0 ] = fTrend; } return true; }; ScETSForecastCalculation.prototype.prefillPerIdx2 = function() { /*if ( !this.bEDS ) { // use as many complete periods as available if ( this.mnSmplInPrd == 0 ) { // should never happen; if mnSmplInPrd equals 0, bEDS is true mnErrorValue = FormulaError::UnknownState; return false; } var nPeriods = this.mnCount / this.mnSmplInPrd; std::vector< double > aPeriodAverage( nPeriods, 0.0 ); for ( SCSIZE i = 0; i < nPeriods ; i++ ) { for ( SCSIZE j = 0; j < mnSmplInPrd; j++ ) aPeriodAverage[ i ] += maRange[ i * mnSmplInPrd + j ].Y; aPeriodAverage[ i ] /= static_cast< double >( mnSmplInPrd ); if ( aPeriodAverage[ i ] == 0.0 ) { SAL_WARN( "sc.core", "prefillPerIdx(), average of 0 will cause divide by zero error, quitting calculation" ); mnErrorValue = FormulaError::DivisionByZero; return false; } } for ( SCSIZE j = 0; j < mnSmplInPrd; j++ ) { double fI = 0.0; for ( SCSIZE i = 0; i < nPeriods ; i++ ) { // adjust average value for position within period if ( bAdditive ) fI += ( maRange[ i * mnSmplInPrd + j ].Y - ( aPeriodAverage[ i ] + ( static_cast< double >( j ) - 0.5 * ( mnSmplInPrd - 1 ) ) * mpTrend[ 0 ] ) ); else fI += ( maRange[ i * mnSmplInPrd + j ].Y / ( aPeriodAverage[ i ] + ( static_cast< double >( j ) - 0.5 * ( mnSmplInPrd - 1 ) ) * mpTrend[ 0 ] ) ); } mpPerIdx[ j ] = fI / nPeriods; } } return true;*/ }; ScETSForecastCalculation.prototype.prefillPerIdx = function() { if ( !this.bEDS ) { // use as many complete periods as available if ( this.mnSmplInPrd == 0 ) { // should never happen; if mnSmplInPrd equals 0, bEDS is true //mnErrorValue = FormulaError::UnknownState; return false; } var nPeriods = parseInt(this.mnCount / this.mnSmplInPrd);//scsize var aPeriodAverage = []; for ( var i = 0; i < nPeriods ; i++ ) { aPeriodAverage[ i ] = 0; for ( var j = 0; j < this.mnSmplInPrd; j++ ) aPeriodAverage[ i ] += this.maRange[ i * this.mnSmplInPrd + j ].Y; aPeriodAverage[ i ] /= this.mnSmplInPrd; if ( aPeriodAverage[ i ] == 0.0 ) { //SAL_WARN( "sc.core", "prefillPerIdx(), average of 0 will cause divide by zero error, quitting calculation" ); //mnErrorValue = FormulaError::DivisionByZero; return false; } } for ( var j = 0; j < this.mnSmplInPrd; j++ ) { var fI = 0.0; for ( var i = 0; i < nPeriods ; i++ ) { // adjust average value for position within period if ( this.bAdditive ) fI += ( this.maRange[ i * this.mnSmplInPrd + j ].Y - ( aPeriodAverage[ i ] + ( j - 0.5 * ( this.mnSmplInPrd - 1 ) ) * this.mpTrend[ 0 ] ) ); else fI += ( this.maRange[ i * this.mnSmplInPrd + j ].Y / ( aPeriodAverage[ i ] + ( j - 0.5 * ( this.mnSmplInPrd - 1 ) ) * this.mpTrend[ 0 ] ) ); } this.mpPerIdx[ j ] = fI / nPeriods; } } return true; }; ScETSForecastCalculation.prototype.prefillBaseData = function() { if ( this.bEDS ) this.mpBase[ 0 ] = this.maRange[ 0 ].Y; else this.mpBase[ 0 ] = this.maRange[ 0 ].Y / this.mpPerIdx[ 0 ]; return true; }; ScETSForecastCalculation.prototype.initCalc = function() { if ( !this.mbInitialised ) { this.CalcAlphaBetaGamma(); this.mbInitialised = true; this.calcAccuracyIndicators(); } return true; }; ScETSForecastCalculation.prototype.calcAccuracyIndicators = function() { var fSumAbsErr = 0.0; var fSumDivisor = 0.0; var fSumErrSq = 0.0; var fSumAbsPercErr = 0.0; for ( var i = 1; i < this.mnCount; i++ ) { var fError = this.mpForecast[ i ] - this.maRange[ i ].Y; fSumAbsErr += Math.abs( fError ); fSumErrSq += fError * fError; fSumAbsPercErr += Math.abs( fError ) / ( Math.abs( this.mpForecast[ i ] ) + Math.abs( this.maRange[ i ].Y ) ); } for ( var i = 2; i < this.mnCount; i++ ){ fSumDivisor += Math.abs( this.maRange[ i ].Y - this.maRange[ i - 1 ].Y ); } var nCalcCount = this.mnCount - 1; this.mfMAE = fSumAbsErr / nCalcCount; this.mfMASE = fSumAbsErr / ( nCalcCount * fSumDivisor / ( nCalcCount - 1 ) ); this.mfMSE = fSumErrSq / nCalcCount; this.mfRMSE = Math.sqrt( this.mfMSE ); this.mfSMAPE = fSumAbsPercErr * 2.0 / nCalcCount; }; ScETSForecastCalculation.prototype.CalcPeriodLen = function() { var nBestVal = this.mnCount; var fBestME = Number.MAX_VALUE; var maRange = this.maRange; for ( var nPeriodLen = parseInt(this.mnCount / 2); nPeriodLen >= 1; nPeriodLen-- ) { var fMeanError = 0.0; var nPeriods = parseInt(this.mnCount / nPeriodLen); var nStart = parseInt(this.mnCount - ( nPeriods * nPeriodLen ) + 1); for ( var i = nStart; i < ( this.mnCount - nPeriodLen ); i++ ) { fMeanError += Math.abs( ( maRange[ i ].Y - maRange[ i - 1 ].Y ) - ( maRange[ nPeriodLen + i ].Y - maRange[ nPeriodLen + i - 1 ].Y ) ); } fMeanError /= ( nPeriods - 1 ) * nPeriodLen - 1 ; if ( fMeanError <= fBestME || fMeanError == 0.0 ) { nBestVal = nPeriodLen; fBestME = fMeanError; } } return nBestVal; }; ScETSForecastCalculation.prototype.CalcAlphaBetaGamma = function() { var f0 = 0.0; this.mfAlpha = f0; if ( this.bEDS ) { this.mfBeta = 0.0; // beta is not used with EDS this.CalcGamma(); } else this.CalcBetaGamma(); this.refill(); var fE0 = this.mfMSE; var f2 = 1.0; this.mfAlpha = f2; if ( this.bEDS ) this.CalcGamma(); else this.CalcBetaGamma(); this.refill(); var fE2 = this.mfMSE; var f1 = 0.5; this.mfAlpha = f1; if ( this.bEDS ) this.CalcGamma(); else this.CalcBetaGamma(); this.refill(); if ( fE0 == this.mfMSE && this.mfMSE == fE2 ) { this.mfAlpha = 0; if ( this.bEDS ) this.CalcGamma(); else this.CalcBetaGamma(); this.refill(); return; } while ( ( f2 - f1 ) > this.cfMinABCResolution ) { if ( fE2 > fE0 ) { f2 = f1; fE2 = this.mfMSE; f1 = ( f0 + f1 ) / 2; } else { f0 = f1; fE0 = this.mfMSE; f1 = ( f1 + f2 ) / 2; } this.mfAlpha = f1; if ( this.bEDS ) this.CalcGamma(); else this.CalcBetaGamma(); this.refill(); } if ( fE2 > fE0 ) { if ( fE0 < this.mfMSE ) { this.mfAlpha = f0; if ( this.bEDS ) this.CalcGamma(); else this.CalcBetaGamma(); this.refill(); } } else { if ( fE2 < this.mfMSE ) { this.mfAlpha = f2; if ( this.bEDS ) this.CalcGamma(); else this.CalcBetaGamma(); this.refill(); } } this.calcAccuracyIndicators(); return; }; ScETSForecastCalculation.prototype.CalcBetaGamma = function() { var f0 = 0.0; this.mfBeta = f0; this.CalcGamma(); this.refill(); var fE0 = this.mfMSE; var f2 = 1.0; this.mfBeta = f2; this.CalcGamma(); this.refill(); var fE2 = this.mfMSE; var f1 = 0.5; this.mfBeta = f1; this.CalcGamma(); this.refill(); if ( fE0 == this.mfMSE && this.mfMSE == fE2 ) { this.mfBeta = 0; this.CalcGamma(); this.refill(); return; } while ( ( f2 - f1 ) > this.cfMinABCResolution ) { if ( fE2 > fE0 ) { f2 = f1; fE2 =this. mfMSE; f1 = ( f0 + f1 ) / 2; } else { f0 = f1; fE0 = this.mfMSE; f1 = ( f1 + f2 ) / 2; } this.mfBeta = f1; this.CalcGamma(); this.refill(); } if ( fE2 > fE0 ) { if ( fE0 < this.mfMSE ) { this.mfBeta = f0; this.CalcGamma(); this.refill(); } } else { if ( fE2 < this.mfMSE ) { this.mfBeta = f2; this.CalcGamma(); this.refill(); } } }; ScETSForecastCalculation.prototype.CalcGamma = function() { var f0 = 0.0; this.mfGamma = f0; this.refill(); var fE0 = this.mfMSE; var f2 = 1.0; this.mfGamma = f2; this.refill(); var fE2 = this.mfMSE; var f1 = 0.5; this.mfGamma = f1; this.refill(); if ( fE0 == this.mfMSE && this.mfMSE == fE2 ) { this.mfGamma = 0; this.refill(); return; } while ( ( f2 - f1 ) > this.cfMinABCResolution ) { if ( fE2 > fE0 ) { f2 = f1; fE2 = this.mfMSE; f1 = ( f0 + f1 ) / 2; } else { f0 = f1; fE0 = this.mfMSE; f1 = ( f1 + f2 ) / 2; } this.mfGamma = f1; this.refill(); } if ( fE2 > fE0 ) { if ( fE0 < this.mfMSE ) { this.mfGamma = f0; this.refill(); } } else { if ( fE2 < this.mfMSE ) { this.mfGamma = f2; this.refill(); } } }; ScETSForecastCalculation.prototype.refill = function() { // refill mpBase, mpTrend, mpPerIdx and mpForecast with values // using the calculated mfAlpha, (mfBeta), mfGamma // forecast 1 step ahead for ( var i = 1; i < this.mnCount; i++ ) { if ( this.bEDS ) { this.mpBase[ i ] = this.mfAlpha * this.maRange[ i ].Y + ( 1 - this.mfAlpha ) * ( this.mpBase[ i - 1 ] + this.mpTrend[ i - 1 ] ); this.mpTrend[ i ] = this.mfGamma * ( this.mpBase[ i ] - this.mpBase[ i - 1 ] ) + ( 1 - this.mfGamma ) * this.mpTrend[ i - 1 ]; this.mpForecast[ i ] = this.mpBase[ i - 1 ] + this.mpTrend[ i - 1 ]; } else { var nIdx; if ( this.bAdditive ) { nIdx = ( i > this.mnSmplInPrd ? i - this.mnSmplInPrd : i ); this.mpBase[ i ] = this.mfAlpha * ( this.maRange[ i ].Y - this.mpPerIdx[ nIdx ] ) + ( 1 - this.mfAlpha ) * ( this.mpBase[ i - 1 ] + this.mpTrend[ i - 1 ] ); this.mpPerIdx[ i ] = this.mfBeta * ( this.maRange[ i ].Y - this.mpBase[ i ] ) + ( 1 - this.mfBeta ) * this.mpPerIdx[ nIdx ]; } else { nIdx = ( i >= this.mnSmplInPrd ? i - this.mnSmplInPrd : i ); this.mpBase[ i ] = this.mfAlpha * ( this.maRange[ i ].Y / this.mpPerIdx[ nIdx ] ) + ( 1 - this.mfAlpha ) * ( this.mpBase[ i - 1 ] + this.mpTrend[ i - 1 ] ); this.mpPerIdx[ i ] = this.mfBeta * ( this.maRange[ i ].Y / this.mpBase[ i ] ) + ( 1 - this.mfBeta ) * this.mpPerIdx[ this.nIdx ]; } this.mpTrend[ i ] = this.mfGamma * ( this.mpBase[ i ] - this.mpBase[ i - 1 ] ) + ( 1 - this.mfGamma ) * this.mpTrend[ i - 1 ]; if ( this.bAdditive ) this.mpForecast[ i ] = this.mpBase[ i - 1 ] + this.mpTrend[ i - 1 ] + this.mpPerIdx[ nIdx ]; else this.mpForecast[ i ] = ( this.mpBase[ i - 1 ] + this.mpTrend[ i - 1 ] ) * this.mpPerIdx[ nIdx ]; } } this.calcAccuracyIndicators(); }; ScETSForecastCalculation.prototype.convertXtoMonths = function( x ) { //Date aNullDate = *( mpFormatter->GetNullDate() ); var aDate = Date.prototype.getDateFromExcel(x); var nYear = aDate.getUTCFullYear(); var nMonth = aDate.getMonth(); var fMonthLength; switch ( nMonth ) { case 1 : case 3 : case 5 : case 7 : case 8 : case 10 : case 12 : fMonthLength = 31.0; break; case 2 : fMonthLength = ( aDate.isLeapYear() ? 29.0 : 28.0 ); break; default : fMonthLength = 30.0; } return ( 12.0 * nYear + nMonth + ( aDate.getDate() - this.mnMonthDay ) / fMonthLength ); }; ScETSForecastCalculation.prototype.GetForecast = function( fTarget, rForecast ) { if ( !this.initCalc() ) return false; if ( fTarget <= this.maRange[ this.mnCount - 1 ].X ) { var n = ( fTarget - this.maRange[ 0 ].X ) / this.mfStepSize; var fInterpolate = Math.fmod( fTarget - this.maRange[ 0 ].X, this.mfStepSize ); rForecast = this.maRange[ n ].Y; if ( fInterpolate >= this.cfMinABCResolution ) { var fInterpolateFactor = fInterpolate / this.mfStepSize; var fFc_1 = this.mpForecast[ n + 1 ]; rForecast = rForecast + fInterpolateFactor * ( fFc_1 - rForecast ); } } else { var n = Math.round(( fTarget - this.maRange[ this.mnCount - 1 ].X ) / this.mfStepSize); var fInterpolate = parseInt(Math.fmod( fTarget - this.maRange[ this.mnCount - 1 ].X, this.mfStepSize )); if ( this.bEDS ) rForecast = this.mpBase[ this.mnCount - 1 ] + n * this.mpTrend[ this.mnCount - 1 ]; else if ( this.bAdditive ) rForecast = this.mpBase[ this.mnCount - 1 ] + n * this.mpTrend[ this.mnCount - 1 ] + this.mpPerIdx[ this.mnCount - 1 - this.mnSmplInPrd + ( n % this.mnSmplInPrd ) ]; else rForecast = ( this.mpBase[ this.mnCount - 1 ] + n * this.mpTrend[ this.mnCount - 1 ] ) * this.mpPerIdx[ this.mnCount - 1 - this.mnSmplInPrd + ( n % this.mnSmplInPrd ) ]; if ( fInterpolate >= this.cfMinABCResolution ) { var fInterpolateFactor = fInterpolate / this.mfStepSize; var fFc_1; if ( this.bEDS ) fFc_1 = this.mpBase[ this.mnCount - 1 ] + ( n + 1 ) * this.mpTrend[ this.mnCount - 1 ]; else if ( this.bAdditive ) fFc_1 = this.mpBase[ this.mnCount - 1 ] + ( n + 1 ) * this.mpTrend[ this.mnCount - 1 ] + this.mpPerIdx[ this.mnCount - 1 - this.mnSmplInPrd + ( ( n + 1 ) % this.mnSmplInPrd ) ]; else fFc_1 = ( this.mpBase[ this.mnCount - 1 ] + ( n + 1 ) * this.mpTrend[ this.mnCount - 1 ] ) * this.mpPerIdx[ this.mnCount - 1 - this.mnSmplInPrd + ( ( n + 1 ) % this.mnSmplInPrd ) ]; rForecast = rForecast + fInterpolateFactor * ( fFc_1 - rForecast ); } } return rForecast; }; ScETSForecastCalculation.prototype.GetForecastRange = function( rTMat ) { var nC = rTMat.length, nR = rTMat[0].length; var rFcMat = []; for ( var i = 0; i < nR; i++ ) { for ( var j = 0; j < nC; j++ ) { var fTarget; if ( this.mnMonthDay ) fTarget = this.convertXtoMonths( rTMat[j][i].getValue() ); else fTarget = rTMat[j][i].getValue(); var fForecast; if ( fForecast = this.GetForecast( fTarget ) ){ if(!rFcMat[j]){ rFcMat[j] = []; } rFcMat[j][i] = fForecast; }else{ return false; } } } return rFcMat; }; ScETSForecastCalculation.prototype.GetStatisticValue = function( rTypeMat, rStatMat ) { if ( !this.initCalc() ) return false; var nC = rTypeMat.length, nR = rTypeMat[0].length; for ( var i = 0; i < nR; i++ ) { for ( var j = 0; j < nC; j++ ) { switch ( rTypeMat[j][i] ) { case 1 : // alpha rStatMat.push( this.mfAlpha, j, i ); break; case 2 : // gamma rStatMat.push( this.mfGamma, j, i ); break; case 3 : // beta rStatMat.push( this.mfBeta, j, i ); break; case 4 : // MASE rStatMat.push( this.mfMASE, j, i ); break; case 5 : // SMAPE rStatMat.push(this. mfSMAPE, j, i ); break; case 6 : // MAE rStatMat.push( this.mfMAE, j, i ); break; case 7 : // RMSE rStatMat.push( this.mfRMSE, j, i ); break; case 8 : // step size rStatMat.push( this.mfStepSize, j, i ); break; case 9 : // samples in period rStatMat.push( this.mnSmplInPrd, j, i ); break; } } } return true; }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cAVEDEV() { this.name = "AVEDEV"; this.value = null; this.argumentsCurrent = 0; } cAVEDEV.prototype = Object.create(cBaseFunction.prototype); cAVEDEV.prototype.constructor = cAVEDEV; cAVEDEV.prototype.argumentsMin = 1; cAVEDEV.prototype.Calculate = function (arg) { var count = 0, sum = new cNumber(0), arrX = [], i; for (i = 0; i < arg.length; i++) { var _arg = arg[i]; if (_arg instanceof cRef || _arg instanceof cRef3D) { var _argV = _arg.getValue(); if (_argV instanceof cNumber) { arrX.push(_argV); count++; } } else if (_arg instanceof cArea || _arg instanceof cArea3D) { var _argAreaValue = _arg.getValue(); for (var j = 0; j < _argAreaValue.length; j++) { var __arg = _argAreaValue[j]; if (__arg instanceof cNumber) { arrX.push(__arg); count++; } } } else if (_arg instanceof cArray) { _arg.foreach(function (elem) { var e = elem.tocNumber(); if (e instanceof cNumber) { arrX.push(e); count++; } }) } else { if (_arg instanceof cError) { continue; } arrX.push(_arg); count++; } } for (i = 0; i < arrX.length; i++) { sum = _func[sum.type][arrX[i].type](sum, arrX[i], "+"); } sum = new cNumber(sum.getValue() / count); var a = 0; for (i = 0; i < arrX.length; i++) { a += Math.abs(_func[sum.type][arrX[i].type](sum, arrX[i], "-").getValue()); } return this.value = new cNumber(a / count); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cAVERAGE() { this.name = "AVERAGE"; this.value = null; this.argumentsCurrent = 0; } cAVERAGE.prototype = Object.create(cBaseFunction.prototype); cAVERAGE.prototype.constructor = cAVERAGE; cAVERAGE.prototype.argumentsMin = 1; cAVERAGE.prototype.Calculate = function (arg) { var count = 0, sum = new cNumber(0); for (var i = 0; i < arg.length; i++) { var _arg = arg[i]; if (cElementType.cell === _arg.type || cElementType.cell3D === _arg.type) { if (!this.checkExclude || !_arg.isHidden(this.excludeHiddenRows)) { var _argV = _arg.getValue(); if (cElementType.string === _argV.type || cElementType.empty === _argV.type || cElementType.bool === _argV.type) { continue; } else if (cElementType.number === _argV.type) { sum = _func[sum.type][_argV.type](sum, _argV, "+"); count++; } else if (cElementType.error === _argV.type) { return this.value = _argV; } } } else if (cElementType.cellsRange === _arg.type || cElementType.cellsRange3D === _arg.type) { var _argAreaValue = _arg.getValue(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); for (var j = 0; j < _argAreaValue.length; j++) { var __arg = _argAreaValue[j]; if (cElementType.string === __arg.type || cElementType.empty === __arg.type || cElementType.bool === __arg.type) { continue; } else if (cElementType.number === __arg.type) { sum = _func[sum.type][__arg.type](sum, __arg, "+"); count++; } else if (cElementType.error === __arg.type) { return this.value = __arg; } } } else if (cElementType.array === _arg.type) { _arg.foreach(function (elem) { if (cElementType.string === elem.type || cElementType.empty === elem.type || cElementType.bool === elem.type) { return false; } var e = elem.tocNumber(); if (cElementType.number === e.type) { sum = _func[sum.type][e.type](sum, e, "+"); count++; } }) } else { _arg = _arg.tocNumber(); if (cElementType.error === _arg.type) { return this.value = _arg; } sum = _func[sum.type][_arg.type](sum, _arg, "+"); count++; } } return this.value = new cNumber(sum.getValue() / count); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cAVERAGEA() { this.name = "AVERAGEA"; this.value = null; this.argumentsCurrent = 0; } cAVERAGEA.prototype = Object.create(cBaseFunction.prototype); cAVERAGEA.prototype.constructor = cAVERAGEA; cAVERAGEA.prototype.argumentsMin = 1; cAVERAGEA.prototype.Calculate = function (arg) { var count = 0, sum = new cNumber(0); for (var i = 0; i < arg.length; i++) { var _arg = arg[i]; if (cElementType.cell === _arg.type || cElementType.cell3D === _arg.type) { var _argV = _arg.getValue(); if (cElementType.number === _argV.type || cElementType.bool === _argV.type) { sum = _func[sum.type][_argV.type](sum, _argV, "+"); count++; } else if (cElementType.string === _argV.type) { count++; } } else if (cElementType.cellsRange === _arg.type || cElementType.cellsRange3D === _arg.type) { var _argAreaValue = _arg.getValue(); for (var j = 0; j < _argAreaValue.length; j++) { var __arg = _argAreaValue[j]; if (cElementType.number === __arg.type || cElementType.bool === __arg.type) { sum = _func[sum.type][__arg.type](sum, __arg, "+"); count++; } else if (cElementType.string === __arg.type) { count++; } } } else if (cElementType.array === _arg.type) { _arg.foreach(function (elem) { if (cElementType.string === elem.type || cElementType.empty === elem.type) { return false; } var e = elem.tocNumber(); if (cElementType.number === e.type) { sum = _func[sum.type][e.type](sum, e, "+"); count++; } }) } else { _arg = _arg.tocNumber(); if (cElementType.error === _arg.type) { return this.value = _arg; } sum = _func[sum.type][_arg.type](sum, _arg, "+"); count++; } } return this.value = new cNumber(sum.getValue() / count); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cAVERAGEIF() { this.name = "AVERAGEIF"; this.value = null; this.argumentsCurrent = 0; } cAVERAGEIF.prototype = Object.create(cBaseFunction.prototype); cAVERAGEIF.prototype.constructor = cAVERAGEIF; cAVERAGEIF.prototype.argumentsMin = 2; cAVERAGEIF.prototype.argumentsMax = 3; cAVERAGEIF.prototype.Calculate = function (arg) { var arg0 = arg[0], arg1 = arg[1], arg2 = arg[2] ? arg[2] : arg[0], _sum = 0, _count = 0, matchingInfo, ws; if ((cElementType.cell !== arg0.type && cElementType.cell3D !== arg0.type && cElementType.cellsRange !== arg0.type) || (cElementType.cell !== arg2.type && cElementType.cell3D !== arg2.type && cElementType.cellsRange !== arg2.type)) { return this.value = new cError(cErrorType.wrong_value_type); } if (cElementType.cellsRange === arg1.type || cElementType.cellsRange3D === arg1.type) { arg1 = arg1.cross(arguments[1]); } else if (cElementType.array === arg1.type) { arg1 = arg1.getElementRowCol(0, 0); } arg1 = arg1.tocString(); if (cElementType.string !== arg1.type) { return this.value = new cError(cErrorType.wrong_value_type); } arg1 = arg1.toString(); var r = arg0.getRange(); var r2 = arg2.getRange(); ws = arg0.getWS(); matchingInfo = AscCommonExcel.matchingValue(arg1.toString()); if (cElementType.cellsRange === arg0.type) { arg0.foreach2(function (v, cell) { if (matching(v, matchingInfo)) { var offset = cell.getOffset3(r.bbox.c1 + 1, r.bbox.r1 + 1); r2.setOffset(offset); var val; ws._getCellNoEmpty(r2.bbox.r1, r2.bbox.c1, function(cell) { val = checkTypeCell(cell); }); offset.offsetCol *= -1; offset.offsetRow *= -1; r2.setOffset(offset); if (cElementType.number === val.type) { _sum += val.getValue(); _count++; } } }) } else { if (matching(arg0.getValue(), matchingInfo)) { var val; ws._getCellNoEmpty(r.bbox.r1, r2.bbox.c1, function(cell) { val = checkTypeCell(cell); }); if (cElementType.number === val.type) { _sum += val.getValue(); _count++; } } } if (0 === _count) { return new cError(cErrorType.division_by_zero); } else { return this.value = new cNumber(_sum / _count); } }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cAVERAGEIFS() { this.name = "AVERAGEIFS"; this.value = null; this.argumentsCurrent = 0; } cAVERAGEIFS.prototype = Object.create(cBaseFunction.prototype); cAVERAGEIFS.prototype.constructor = cAVERAGEIFS; cAVERAGEIFS.prototype.argumentsMin = 3; cAVERAGEIFS.prototype.Calculate = function (arg) { var arg0 = arg[0]; if (cElementType.cell !== arg0.type && cElementType.cell3D !== arg0.type && cElementType.cellsRange !== arg0.type) { return this.value = new cError(cErrorType.wrong_value_type); } var arg0Matrix = arg0.getMatrix(); var i, j, arg1, arg2, matchingInfo; for (var k = 1; k < arg.length; k += 2) { arg1 = arg[k]; arg2 = arg[k + 1]; if ((cElementType.cell !== arg1.type && cElementType.cell3D !== arg1.type && cElementType.cellsRange !== arg1.type)) { return this.value = new cError(cErrorType.wrong_value_type); } if (cElementType.cellsRange === arg2.type || cElementType.cellsRange3D === arg2.type) { arg2 = arg2.cross(arguments[1]); } else if (cElementType.array === arg2.type) { arg2 = arg2.getElementRowCol(0, 0); } arg2 = arg2.tocString(); if (cElementType.string !== arg2.type) { return this.value = new cError(cErrorType.wrong_value_type); } matchingInfo = AscCommonExcel.matchingValue(arg2.toString()); var arg1Matrix = arg1.getMatrix(); if (arg0Matrix.length !== arg1Matrix.length) { return this.value = new cError(cErrorType.wrong_value_type); } for (i = 0; i < arg1Matrix.length; ++i) { if (arg0Matrix[i].length !== arg1Matrix[i].length) { return this.value = new cError(cErrorType.wrong_value_type); } for (j = 0; j < arg1Matrix[i].length; ++j) { if (arg0Matrix[i][j] && !AscCommonExcel.matching(arg1Matrix[i][j], matchingInfo)) { arg0Matrix[i][j] = null; } } } } var _sum = 0, _count = 0; var valMatrix0; for (i = 0; i < arg0Matrix.length; ++i) { for (j = 0; j < arg0Matrix[i].length; ++j) { if ((valMatrix0 = arg0Matrix[i][j]) && cElementType.number === valMatrix0.type) { _sum += valMatrix0.getValue(); ++_count; } } } if (0 === _count) { return new cError(cErrorType.division_by_zero); } else { return this.value = new cNumber(_sum / _count); } }; cAVERAGEIFS.prototype.checkArguments = function () { return 1 === this.argumentsCurrent % 2 && cBaseFunction.prototype.checkArguments.apply(this, arguments); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cBETADIST() { this.name = "BETADIST"; this.value = null; this.argumentsCurrent = 0; } cBETADIST.prototype = Object.create(cBaseFunction.prototype); cBETADIST.prototype.constructor = cBETADIST; cBETADIST.prototype.argumentsMin = 3; cBETADIST.prototype.argumentsMax = 5; cBETADIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3] ? argClone[3].tocNumber() : new cNumber(0); argClone[4] = argClone[4] ? argClone[4].tocNumber() : new cNumber(1); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcBeta = function(argArray){ var x = argArray[0]; var alpha = argArray[1]; var beta = argArray[2]; var fLowerBound = argArray[3]; var fUpperBound = argArray[4]; var fScale = fUpperBound - fLowerBound; if (fScale <= 0 || alpha <= 0 || beta <= 0){ return new cError(cErrorType.not_numeric); } var res = null; if (x < fLowerBound){ res = 0; }else if(x > fUpperBound){ res = 1; }else { x = (x - fLowerBound) / fScale; res = getBetaDist(x, alpha, beta); } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcBeta); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cBETA_DIST() { this.name = "BETA.DIST"; this.value = null; this.argumentsCurrent = 0; } cBETA_DIST.prototype = Object.create(cBaseFunction.prototype); cBETA_DIST.prototype.constructor = cBETA_DIST; cBETA_DIST.prototype.argumentsMin = 4; cBETA_DIST.prototype.argumentsMax = 6; cBETA_DIST.prototype.isXLFN = true; cBETA_DIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3].tocNumber(); argClone[4] = argClone[4] ? argClone[4].tocNumber() : new cNumber(0); argClone[5] = argClone[5] ? argClone[5].tocNumber() : new cNumber(1); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcBeta = function(argArray){ var x = argArray[0]; var alpha = argArray[1]; var beta = argArray[2]; var bIsCumulative = argArray[3]; var fLowerBound = argArray[4]; var fUpperBound = argArray[5]; var res = null; if (alpha <= 0 || beta <= 0 || x < fLowerBound || x > fUpperBound) { return new cError(cErrorType.not_numeric); } var fScale = fUpperBound - fLowerBound; x = (x - fLowerBound) / fScale; if (bIsCumulative) { res = getBetaDist(x, alpha, beta); } else { res = getBetaDistPDF(x, alpha, beta) / fScale; } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcBeta); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cBETA_INV() { this.name = "BETA.INV"; this.value = null; this.argumentsCurrent = 0; } cBETA_INV.prototype = Object.create(cBaseFunction.prototype); cBETA_INV.prototype.constructor = cBETA_INV; cBETA_INV.prototype.argumentsMin = 3; cBETA_INV.prototype.argumentsMax = 5; cBETA_INV.prototype.isXLFN = true; cBETA_INV.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3] ? argClone[3].tocNumber() : new cNumber(0); argClone[4] = argClone[4] ? argClone[4].tocNumber() : new cNumber(1); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcGamma = function(argArray){ var fP = argArray[0]; var fAlpha = argArray[1]; var fBeta = argArray[2]; var fA = argArray[3]; var fB = argArray[4]; if (fP < 0 || fP > 1 || fA >= fB || fAlpha <= 0 || fBeta <= 0){ return new cError(cErrorType.not_numeric); } var aFunc = new BETADISTFUNCTION(fP, fAlpha, fBeta); var oVal = iterateInverse( aFunc, 0, 1 ); var bConvError = oVal.bError; if (bConvError){ return new cError(cErrorType.not_numeric); //SetError(FormulaError::NoConvergence); } var res = fA + oVal.val * (fB - fA) ; return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcGamma); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cBINOMDIST() { this.name = "BINOMDIST"; this.value = null; this.argumentsCurrent = 0; } cBINOMDIST.prototype = Object.create(cBaseFunction.prototype); cBINOMDIST.prototype.constructor = cBINOMDIST; cBINOMDIST.prototype.argumentsMin = 4; cBINOMDIST.prototype.argumentsMax = 4; cBINOMDIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3].tocNumber();//bool var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function binomdist(x, n, p) { x = parseInt(x); n = parseInt(n); return Math.binomCoeff(n, x) * Math.pow(p, x) * Math.pow(1 - p, n - x); } var calcBinom = function(argArray){ var arg0 = argArray[0]; var arg1 = argArray[1]; var arg2 = argArray[2]; var arg3 = argArray[3]; if (arg0 < 0 || arg0 > arg1 || arg2 < 0 || arg2 > 1) { return new cError(cErrorType.not_numeric); } if (arg3) { var x = parseInt(arg0), n = parseInt(arg1), p = arg2, bm = 0; for (var y = 0; y <= x; y++) { bm += binomdist(y, n, p); } return new cNumber(bm); } else { return new cNumber(binomdist(arg0, arg1, arg2)); } }; return this.value = this._findArrayInNumberArguments(oArguments, calcBinom); }; /** * @constructor * @extends {cBINOMDIST} */ function cBINOM_DIST() { cBINOMDIST.call(this); this.name = "BINOM.DIST"; } cBINOM_DIST.prototype = Object.create(cBINOMDIST.prototype); cBINOM_DIST.prototype.constructor = cBINOM_DIST; cBINOM_DIST.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cBINOM_DIST_RANGE() { this.name = "BINOM.DIST.RANGE"; this.value = null; this.argumentsCurrent = 0; } cBINOM_DIST_RANGE.prototype = Object.create(cBaseFunction.prototype); cBINOM_DIST_RANGE.prototype.constructor = cBINOM_DIST_RANGE; cBINOM_DIST_RANGE.prototype.argumentsMin = 3; cBINOM_DIST_RANGE.prototype.argumentsMax = 4; cBINOM_DIST_RANGE.prototype.isXLFN = true; cBINOM_DIST_RANGE.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3] ? argClone[3].tocNumber() : argClone[2]; var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function binomdist(x, n, p) { x = parseInt(x); n = parseInt(n); return Math.binomCoeff(n, x) * Math.pow(p, x) * Math.pow(1 - p, n - x); } var calcBinom = function(argArray){ var arg0 = argArray[0]; var arg1 = argArray[1]; var arg2 = argArray[2]; var arg3 = argArray[3]; if (arg0 < 0 || arg1 < 0 || arg1 > 1 || arg2 < 0 || arg2 > arg0 || arg3 < arg2 || arg3 > arg0) { return new cError(cErrorType.not_numeric); } var summ = 0; for(var i = arg2; i <= arg3; i++){ summ += binomdist(i, arg0, arg1); } return new cNumber(summ); }; return this.value = this._findArrayInNumberArguments(oArguments, calcBinom); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCHIDIST() { cBaseFunction.call(this, "CHIDIST"); } cCHIDIST.prototype = Object.create(cBaseFunction.prototype); cCHIDIST.prototype.constructor = cCHIDIST; cCHIDIST.prototype.argumentsMin = 2; cCHIDIST.prototype.argumentsMax = 2; cCHIDIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var fChi = argArray[0]; var fDF = parseInt(argArray[1]); if ( fDF < 1 || fChi < 0 || fDF > Math.pow(10, 10)){ return new cError(cErrorType.not_numeric); } var res = getChiDist( fChi, fDF); return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCHIINV() { cBaseFunction.call(this, "CHIINV"); } cCHIINV.prototype = Object.create(cBaseFunction.prototype); cCHIINV.prototype.constructor = cCHIINV; cCHIINV.prototype.argumentsMin = 2; cCHIINV.prototype.argumentsMax = 2; cCHIINV.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var fP = argArray[0]; var fDF = parseInt(argArray[1]); if ( fDF < 1 || fP <= 0 || fP > 1){ return new cError(cErrorType.not_numeric); } var aFunc = new CHIDISTFUNCTION(fP, fDF); var oVal = iterateInverse(aFunc, fDF * 0.5, fDF); var bConvError = oVal.bError; if (bConvError){ return new cError(cErrorType.not_numeric); } var res = oVal.val; return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCHISQ_DIST() { cBaseFunction.call(this, "CHISQ.DIST"); } cCHISQ_DIST.prototype = Object.create(cBaseFunction.prototype); cCHISQ_DIST.prototype.constructor = cCHISQ_DIST; cCHISQ_DIST.prototype.argumentsMin = 3; cCHISQ_DIST.prototype.argumentsMax = 3; cCHISQ_DIST.prototype.isXLFN = true; cCHISQ_DIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var fX = argArray[0]; var fDF = parseInt(argArray[1]); var bCumulative = argArray[2]; var res = null; if ( fDF < 1 || fDF > 1E10 || fX < 0){ return new cError(cErrorType.not_numeric); }else{ if ( bCumulative ){ res = getChiSqDistCDF( fX, fDF ); }else{ res = getChiSqDistPDF( fX, fDF ); } } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; if (argClone[1].getValue() < 1 ){ return this.value = new cError(cErrorType.not_numeric); } return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {cCHIDIST} */ function cCHISQ_DIST_RT() { cCHIDIST.call(this); this.name = "CHISQ.DIST.RT"; } cCHISQ_DIST_RT.prototype = Object.create(cCHIDIST.prototype); cCHISQ_DIST_RT.prototype.constructor = cCHISQ_DIST_RT; cCHISQ_DIST_RT.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCHISQ_INV() { cBaseFunction.call(this, "CHISQ.INV"); } cCHISQ_INV.prototype = Object.create(cBaseFunction.prototype); cCHISQ_INV.prototype.constructor = cCHISQ_INV; cCHISQ_INV.prototype.argumentsMin = 2; cCHISQ_INV.prototype.argumentsMax = 2; cCHISQ_INV.prototype.isXLFN = true; cCHISQ_INV.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var fP = argArray[0]; var fDF = parseInt(argArray[1]); if ( fDF < 1 || fP < 0 || fP >= 1 || fDF > 1.0E10){ return new cError(cErrorType.not_numeric); } var aFunc = new CHISQDISTFUNCTION(fP, fDF); var oVal = iterateInverse(aFunc, fDF * 0.5, fDF); var bConvError = oVal.bError; if (bConvError){ return new cError(cErrorType.not_numeric); } var res = oVal.val; return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCHISQ_INV_RT() { cBaseFunction.call(this, "CHISQ.INV.RT"); } //TODO check max 64 iterations(from documentaion) cCHISQ_INV_RT.prototype = Object.create(cBaseFunction.prototype); cCHISQ_INV_RT.prototype.constructor = cCHISQ_INV_RT; cCHISQ_INV_RT.prototype.argumentsMin = 2; cCHISQ_INV_RT.prototype.argumentsMax = 2; cCHISQ_INV_RT.prototype.isXLFN = true; cCHISQ_INV_RT.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var fP = argArray[0]; var fDF = parseInt(argArray[1]); if ( fDF < 1 || fP <= 0 || fP > 1){ return new cError(cErrorType.not_numeric); } var aFunc = new CHIDISTFUNCTION(fP, fDF); var oVal = iterateInverse(aFunc, fDF * 0.5, fDF); var bConvError = oVal.bError; if (bConvError){ return new cError(cErrorType.not_numeric); } var res = oVal.val; return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCHITEST() { this.name = "CHITEST"; this.value = null; this.argumentsCurrent = 0; } cCHITEST.prototype = Object.create(cBaseFunction.prototype); cCHITEST.prototype.constructor = cCHITEST; cCHITEST.prototype.argumentsMin = 2; cCHITEST.prototype.argumentsMax = 2; cCHITEST.prototype.Calculate = function (arg) { var arg2 = [arg[0], arg[1]]; //если первое или второе значение строка if(cElementType.string === arg[0].type || cElementType.bool === arg[0].type){ return this.value = new cError(cErrorType.wrong_value_type); } if(cElementType.string === arg[1].type || cElementType.bool === arg[1].type){ return this.value = new cError(cErrorType.wrong_value_type); } //если первое или второе значение число if(cElementType.number === arg[0].type){ arg2[0] = new cArray(); arg2[0].addElement(arg[0]); } if(cElementType.number === arg[1].type){ arg2[1] = new cArray(); arg2[1].addElement(arg[1]); } var oArguments = this._prepareArguments(arg2, arguments[1], true, [cElementType.array, cElementType.array]); var argClone = oArguments.args; var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function calcChitest(argArray) { var arg1 = argArray[0]; var arg2 = argArray[1]; return chiTest(arg1, arg2); } return this.value = this._findArrayInNumberArguments(oArguments, calcChitest); }; /** * @constructor * @extends {cCHITEST} */ function cCHISQ_TEST() { cCHITEST.call(this); this.name = "CHISQ.TEST"; } cCHISQ_TEST.prototype = Object.create(cCHITEST.prototype); cCHISQ_TEST.prototype.constructor = cCHISQ_TEST; cCHISQ_TEST.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCONFIDENCE() { this.name = "CONFIDENCE"; this.value = null; this.argumentsCurrent = 0; } cCONFIDENCE.prototype = Object.create(cBaseFunction.prototype); cCONFIDENCE.prototype.constructor = cCONFIDENCE; cCONFIDENCE.prototype.argumentsMin = 3; cCONFIDENCE.prototype.argumentsMax = 3; cCONFIDENCE.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcConfidence = function(argArray){ var alpha = argArray[0]; var stdev_sigma = argArray[1]; var size = parseInt(argArray[2]); if (alpha <= 0 || alpha >= 1 || stdev_sigma <= 0 || size < 1) { return new cError(cErrorType.not_numeric); } return new cNumber(gaussinv(1 - alpha / 2) * stdev_sigma / Math.sqrt(size)); }; return this.value = this._findArrayInNumberArguments(oArguments, calcConfidence); }; /** * @constructor * @extends {cCONFIDENCE} */ function cCONFIDENCE_NORM() { cCONFIDENCE.call(this); this.name = "CONFIDENCE.NORM"; } cCONFIDENCE_NORM.prototype = Object.create(cCONFIDENCE.prototype); cCONFIDENCE_NORM.prototype.constructor = cCONFIDENCE_NORM; cCONFIDENCE_NORM.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCONFIDENCE_T() { this.name = "CONFIDENCE.T"; this.value = null; this.argumentsCurrent = 0; } cCONFIDENCE_T.prototype = Object.create(cBaseFunction.prototype); cCONFIDENCE_T.prototype.constructor = cCONFIDENCE_T; cCONFIDENCE_T.prototype.argumentsMin = 3; cCONFIDENCE_T.prototype.argumentsMax = 3; cCONFIDENCE_T.prototype.isXLFN = true; cCONFIDENCE_T.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcConfidence = function(argArray){ var alpha = argArray[0]; var stdev_sigma = argArray[1]; var size = parseInt(argArray[2]); if (alpha <= 0 || alpha >= 1 || stdev_sigma <= 0 || size < 1) { return new cError(cErrorType.not_numeric); } var aFunc = new TDISTFUNCTION(alpha, size - 1, 2); var oVal = iterateInverse(aFunc, size * 0.5, size); var bConvError = oVal.bError; if (bConvError){ return new cError(cErrorType.not_numeric); } var res = (stdev_sigma * oVal.val) / Math.sqrt( size ); return new cNumber(res); }; return this.value = this._findArrayInNumberArguments(oArguments, calcConfidence); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCORREL() { this.name = "CORREL"; this.value = null; this.argumentsCurrent = 0; } cCORREL.prototype = Object.create(cBaseFunction.prototype); cCORREL.prototype.constructor = cCORREL; cCORREL.prototype.argumentsMin = 2; cCORREL.prototype.argumentsMax = 2; cCORREL.prototype.Calculate = function (arg) { function correl(x, y) { var s1 = 0, s2 = 0, s3 = 0, _x = 0, _y = 0, xLength = 0, i; if (x.length != y.length) { return new cError(cErrorType.not_available); } for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } _x += x[i].getValue(); _y += y[i].getValue(); xLength++; } _x /= xLength; _y /= xLength; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } s1 += (x[i].getValue() - _x) * (y[i].getValue() - _y); s2 += (x[i].getValue() - _x) * (x[i].getValue() - _x); s3 += (y[i].getValue() - _y) * (y[i].getValue() - _y); } if (s2 == 0 || s3 == 0) { return new cError(cErrorType.division_by_zero); } else { return new cNumber(s1 / Math.sqrt(s2 * s3)); } } var arg0 = arg[0], arg1 = arg[1], arr0 = [], arr1 = []; if (arg0 instanceof cArea) { arr0 = arg0.getValue(); } else if (arg0 instanceof cArray) { arg0.foreach(function (elem) { arr0.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } if (arg1 instanceof cArea) { arr1 = arg1.getValue(); } else if (arg1 instanceof cArray) { arg1.foreach(function (elem) { arr1.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } return this.value = correl(arr0, arr1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCOUNT() { this.name = "COUNT"; this.value = null; this.argumentsCurrent = 0; } cCOUNT.prototype = Object.create(cBaseFunction.prototype); cCOUNT.prototype.constructor = cCOUNT; cCOUNT.prototype.argumentsMin = 1; cCOUNT.prototype.numFormat = AscCommonExcel.cNumFormatNone; cCOUNT.prototype.Calculate = function (arg) { var count = 0; for (var i = 0; i < arg.length; i++) { var _arg = arg[i]; if (cElementType.cell === _arg.type || cElementType.cell3D === _arg.type) { if (!this.checkExclude || !_arg.isHidden(this.excludeHiddenRows)) { var _argV = _arg.getValue(); if (cElementType.number === _argV.type) { count++; } } } else if (cElementType.cellsRange === _arg.type || cElementType.cellsRange3D === _arg.type) { var _argAreaValue = _arg.getValue(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); for (var j = 0; j < _argAreaValue.length; j++) { if (cElementType.number === _argAreaValue[j].type) { count++; } } } else if (cElementType.number === _arg.type || cElementType.bool === _arg.type || cElementType.empty === _arg.type) { count++; } else if (cElementType.string === _arg.type) { if (cElementType.number === _arg.tocNumber().type) { count++; } } else if (cElementType.array === _arg.type) { _arg.foreach(function (elem) { if (cElementType.number === elem.tocNumber().type) { count++; } }) } } return this.value = new cNumber(count); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCOUNTA() { this.name = "COUNTA"; this.value = null; this.argumentsCurrent = 0; } cCOUNTA.prototype = Object.create(cBaseFunction.prototype); cCOUNTA.prototype.constructor = cCOUNTA; cCOUNTA.prototype.argumentsMin = 1; cCOUNTA.prototype.numFormat = AscCommonExcel.cNumFormatNone; cCOUNTA.prototype.Calculate = function (arg) { var element, count = 0; for (var i = 0; i < arg.length; i++) { element = arg[i]; if (cElementType.cell === element.type || cElementType.cell3D === element.type) { if (!this.checkExclude || !element.isHidden(this.excludeHiddenRows)) { var _argV = element.getValue(); if (cElementType.empty !== _argV.type) { count++; } } } else if (cElementType.cellsRange === element.type || cElementType.cellsRange3D === element.type) { var _argAreaValue = element.getValue(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); for (var j = 0; j < _argAreaValue.length; j++) { if (cElementType.empty !== _argAreaValue[j].type) { count++; } } } else if (cElementType.array === element.type) { element.foreach(function (elem) { if (cElementType.empty !== elem.type) { count++; } }) } else if (cElementType.empty !== element.type) { count++; } } return this.value = new cNumber(count); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCOUNTBLANK() { this.name = "COUNTBLANK"; this.value = null; this.argumentsCurrent = 0; } cCOUNTBLANK.prototype = Object.create(cBaseFunction.prototype); cCOUNTBLANK.prototype.constructor = cCOUNTBLANK; cCOUNTBLANK.prototype.argumentsMin = 1; cCOUNTBLANK.prototype.argumentsMax = 1; cCOUNTBLANK.prototype.numFormat = AscCommonExcel.cNumFormatNone; cCOUNTBLANK.prototype.Calculate = function (arg) { var arg0 = arg[0]; if (arg0 instanceof cArea || arg0 instanceof cArea3D) { return this.value = arg0.countCells(); } else if (arg0 instanceof cRef || arg0 instanceof cRef3D) { return this.value = new cNumber(1); } else { return this.value = new cError(cErrorType.bad_reference); } }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCOUNTIF() { this.name = "COUNTIF"; this.value = null; this.argumentsCurrent = 0; } cCOUNTIF.prototype = Object.create(cBaseFunction.prototype); cCOUNTIF.prototype.constructor = cCOUNTIF; cCOUNTIF.prototype.argumentsMin = 2; cCOUNTIF.prototype.argumentsMax = 2; cCOUNTIF.prototype.numFormat = AscCommonExcel.cNumFormatNone; cCOUNTIF.prototype.Calculate = function (arg) { var arg0 = arg[0], arg1 = arg[1], _count = 0, matchingInfo; if (cElementType.cell !== arg0.type && cElementType.cell3D !== arg0.type && cElementType.cellsRange !== arg0.type && cElementType.cellsRange3D !== arg0.type) { return this.value = new cError(cErrorType.wrong_value_type); } if (cElementType.cellsRange === arg1.type || cElementType.cellsRange3D === arg1.type) { arg1 = arg1.cross(arguments[1]); } else if (cElementType.array === arg1.type) { arg1 = arg1.getElementRowCol(0, 0); }else if(cElementType.cell === arg1.type || cElementType.cell3D === arg1.type){ arg1 = arg1.getValue(); } /*arg1 = arg1.tocString(); if (cElementType.string !== arg1.type) { return this.value = new cError(cErrorType.wrong_value_type); }*/ var compareValues = function(val, matchingInfo){ var res; if(val.type === arg1.type && val.value === arg1.value){ return true; } res = matching(val, matchingInfo); return res; }; var val; matchingInfo = AscCommonExcel.matchingValue(arg1.toString()); if (cElementType.cellsRange === arg0.type) { arg0.foreach2(function (_val) { _count += compareValues(_val, matchingInfo); }) } else if (cElementType.cellsRange3D === arg0.type) { val = arg0.getValue(); for (var i = 0; i < val.length; i++) { _count += compareValues(val[i], matchingInfo); } } else { val = arg0.getValue(); _count += compareValues(val, matchingInfo); } return this.value = new cNumber(_count); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCOUNTIFS() { this.name = "COUNTIFS"; this.value = null; this.argumentsCurrent = 0; } cCOUNTIFS.prototype = Object.create(cBaseFunction.prototype); cCOUNTIFS.prototype.constructor = cCOUNTIFS; cCOUNTIFS.prototype.argumentsMin = 2; cCOUNTIFS.prototype.argumentsMax = 254; cCOUNTIFS.prototype.numFormat = AscCommonExcel.cNumFormatNone; cCOUNTIFS.prototype.Calculate = function (arg) { var i, j, arg0, arg1, matchingInfo, arg0Matrix, arg1Matrix, _count = 0; for (var k = 0; k < arg.length; k += 2) { arg0 = arg[k]; arg1 = arg[k + 1]; if (cElementType.cell !== arg0.type && cElementType.cell3D !== arg0.type && cElementType.cellsRange !== arg0.type && !(cElementType.cellsRange3D === arg0.type && arg0.isSingleSheet())) { return this.value = new cError(cErrorType.wrong_value_type); } if (cElementType.cellsRange === arg1.type || cElementType.cellsRange3D === arg1.type) { arg1 = arg1.cross(arguments[1]); } else if (cElementType.array === arg1.type) { arg1 = arg1.getElementRowCol(0, 0); } arg1 = arg1.tocString(); if (cElementType.string !== arg1.type) { return this.value = new cError(cErrorType.wrong_value_type); } matchingInfo = AscCommonExcel.matchingValue(arg1.toString()); arg1Matrix = arg0.getMatrix(); if (cElementType.cellsRange3D === arg0.type) { arg1Matrix = arg1Matrix[0]; } if (!arg0Matrix) { arg0Matrix = arg1Matrix; } if (arg0Matrix.length !== arg1Matrix.length) { return this.value = new cError(cErrorType.wrong_value_type); } for (i = 0; i < arg1Matrix.length; ++i) { if (arg0Matrix[i].length !== arg1Matrix[i].length) { return this.value = new cError(cErrorType.wrong_value_type); } for (j = 0; j < arg1Matrix[i].length; ++j) { if (arg0Matrix[i][j] && !matching(arg1Matrix[i][j], matchingInfo)) { arg0Matrix[i][j] = null; } } } } for (i = 0; i < arg0Matrix.length; ++i) { for (j = 0; j < arg0Matrix[i].length; ++j) { if (arg0Matrix[i][j]) { ++_count; } } } return this.value = new cNumber(_count); }; cCOUNTIFS.prototype.checkArguments = function () { return 0 === this.argumentsCurrent % 2 && cBaseFunction.prototype.checkArguments.apply(this, arguments); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCOVAR() { this.name = "COVAR"; this.value = null; this.argumentsCurrent = 0; } cCOVAR.prototype = Object.create(cBaseFunction.prototype); cCOVAR.prototype.constructor = cCOVAR; cCOVAR.prototype.argumentsMin = 2; cCOVAR.prototype.argumentsMax = 2; cCOVAR.prototype.Calculate = function (arg) { function covar(x, y) { var s1 = 0, _x = 0, _y = 0, xLength = 0, i; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } _x += x[i].getValue(); _y += y[i].getValue(); xLength++; } if (xLength == 0) { return new cError(cErrorType.division_by_zero); } _x /= xLength; _y /= xLength; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } s1 += (x[i].getValue() - _x) * (y[i].getValue() - _y); } return new cNumber(s1 / xLength); } var arg0 = arg[0], arg1 = arg[1], arr0 = [], arr1 = []; if (arg0 instanceof cArea) { arr0 = arg0.getValue(); } else if (arg0 instanceof cArray) { arg0.foreach(function (elem) { arr0.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } if (arg1 instanceof cArea) { arr1 = arg1.getValue(); } else if (arg1 instanceof cArray) { arg1.foreach(function (elem) { arr1.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } return this.value = covar(arr0, arr1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCOVARIANCE_P() { this.name = "COVARIANCE.P"; this.value = null; this.argumentsCurrent = 0; } cCOVARIANCE_P.prototype = Object.create(cBaseFunction.prototype); cCOVARIANCE_P.prototype.constructor = cCOVARIANCE_P; cCOVARIANCE_P.prototype.argumentsMin = 2; cCOVARIANCE_P.prototype.argumentsMax = 2; cCOVARIANCE_P.prototype.isXLFN = true; cCOVARIANCE_P.prototype.Calculate = function (arg) { var arg2 = [arg[0], arg[1]]; //если первое или второе значение строка if(cElementType.string === arg[0].type || cElementType.bool === arg[0].type){ return this.value = new cError(cErrorType.wrong_value_type); } if(cElementType.string === arg[1].type || cElementType.bool === arg[1].type){ return this.value = new cError(cErrorType.wrong_value_type); } //если первое или второе значение число if(cElementType.number === arg[0].type){ arg2[0] = new cArray(); arg2[0].addElement(arg[0]); } if(cElementType.number === arg[1].type){ arg2[1] = new cArray(); arg2[1].addElement(arg[1]); } var oArguments = this._prepareArguments(arg2, arguments[1], true, [cElementType.array, cElementType.array]); var argClone = oArguments.args; var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function pearson(argArray) { var arg1 = argArray[0]; var arg2 = argArray[1]; var x = []; var y = []; for (var i = 0; i < arg1.length; i++) { for (var j = 0; j < arg1[i].length; j++) { x.push(arg1[i][j]); } } for (var i = 0; i < arg2.length; i++) { for (var j = 0; j < arg2[i].length; j++) { y.push(arg2[i][j]); } } var sumXDeltaYDelta = 0, sqrXDelta = 0, sqrYDelta = 0, _x = 0, _y = 0, xLength = 0, i; if (x.length !== y.length) { return new cError(cErrorType.not_available); } for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } _x += x[i].getValue(); _y += y[i].getValue(); xLength++; } _x /= xLength; _y /= xLength; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } sumXDeltaYDelta += (x[i].getValue() - _x) * (y[i].getValue() - _y); } return new cNumber(sumXDeltaYDelta / xLength); } return this.value = this._findArrayInNumberArguments(oArguments, pearson); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCOVARIANCE_S() { this.name = "COVARIANCE.S"; this.value = null; this.argumentsCurrent = 0; } cCOVARIANCE_S.prototype = Object.create(cBaseFunction.prototype); cCOVARIANCE_S.prototype.constructor = cCOVARIANCE_S; cCOVARIANCE_S.prototype.argumentsMin = 2; cCOVARIANCE_S.prototype.argumentsMax = 2; cCOVARIANCE_S.prototype.isXLFN = true; cCOVARIANCE_S.prototype.Calculate = function (arg) { var arg2 = [arg[0], arg[1]]; //если первое или второе значение строка if(cElementType.string === arg[0].type || cElementType.bool === arg[0].type){ return this.value = new cError(cErrorType.wrong_value_type); } if(cElementType.string === arg[1].type || cElementType.bool === arg[1].type){ return this.value = new cError(cErrorType.wrong_value_type); } //если первое или второе значение число if(cElementType.number === arg[0].type){ arg2[0] = new cArray(); arg2[0].addElement(arg[0]); } if(cElementType.number === arg[1].type){ arg2[1] = new cArray(); arg2[1].addElement(arg[1]); } var oArguments = this._prepareArguments(arg2, arguments[1], true, [cElementType.array, cElementType.array]); var argClone = oArguments.args; var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function pearson(argArray) { var arg1 = argArray[0]; var arg2 = argArray[1]; var x = []; var y = []; for (var i = 0; i < arg1.length; i++) { for (var j = 0; j < arg1[i].length; j++) { x.push(arg1[i][j]); } } for (var i = 0; i < arg2.length; i++) { for (var j = 0; j < arg2[i].length; j++) { y.push(arg2[i][j]); } } var sumXDeltaYDelta = 0, sqrXDelta = 0, sqrYDelta = 0, _x = 0, _y = 0, xLength = 0, i; if (x.length !== y.length) { return new cError(cErrorType.not_available); } for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } _x += x[i].getValue(); _y += y[i].getValue(); xLength++; } if (xLength < 2.0){ return new cError(cErrorType.division_by_zero); } _x /= xLength; _y /= xLength; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } sumXDeltaYDelta += (x[i].getValue() - _x) * (y[i].getValue() - _y); } return new cNumber(sumXDeltaYDelta / (xLength - 1)); } return this.value = this._findArrayInNumberArguments(oArguments, pearson); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCRITBINOM() { this.name = "CRITBINOM"; this.value = null; this.argumentsCurrent = 0; } cCRITBINOM.prototype = Object.create(cBaseFunction.prototype); cCRITBINOM.prototype.constructor = cCRITBINOM; cCRITBINOM.prototype.argumentsMin = 3; cCRITBINOM.prototype.argumentsMax = 3; cCRITBINOM.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function critbinom(argArray) { var n = argArray[0]; var p = argArray[1]; var alpha = argArray[2]; if (n < 0 || alpha <= 0 || alpha >= 1 || p < 0 || p > 1) { return new cError(cErrorType.not_numeric); } else { var q = 1 - p, factor = Math.pow(q, n), i, sum, max; if (factor == 0) { factor = Math.pow(p, n); if (factor == 0.0) { return new cError(cErrorType.wrong_value_type); } else { sum = 1 - factor; max = n; for (i = 0; i < max && sum >= alpha; i++) { factor *= (n - i) / (i + 1) * q / p; sum -= factor; } return new cNumber(n - i); } } else { sum = factor; max = n; for (i = 0; i < max && sum < alpha; i++) { factor *= (n - i) / (i + 1) * p / q; sum += factor; } return new cNumber(i); } } } return this.value = this._findArrayInNumberArguments(oArguments, critbinom); }; /** * @constructor * @extends {cCRITBINOM} */ function cBINOM_INV() { cCRITBINOM.call(this); this.name = "BINOM.INV"; } cBINOM_INV.prototype = Object.create(cCRITBINOM.prototype); cBINOM_INV.prototype.constructor = cBINOM_INV; cBINOM_INV.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cDEVSQ() { this.name = "DEVSQ"; this.value = null; this.argumentsCurrent = 0; } cDEVSQ.prototype = Object.create(cBaseFunction.prototype); cDEVSQ.prototype.constructor = cDEVSQ; cDEVSQ.prototype.argumentsMin = 1; cDEVSQ.prototype.Calculate = function (arg) { function devsq(x) { var s1 = 0, _x = 0, xLength = 0, i; for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { _x += x[i].getValue(); xLength++; } } _x /= xLength; for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { s1 += Math.pow(x[i].getValue() - _x, 2); } } return new cNumber(s1); } var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber) { arr0.push(a); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString) { continue; } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = devsq(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cEXPON_DIST() { this.name = "EXPON.DIST"; this.value = null; this.argumentsCurrent = 0; } cEXPON_DIST.prototype = Object.create(cBaseFunction.prototype); cEXPON_DIST.prototype.constructor = cEXPON_DIST; cEXPON_DIST.prototype.argumentsMin = 3; cEXPON_DIST.prototype.argumentsMax = 3; cEXPON_DIST.prototype.isXLFN = true; cEXPON_DIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcFDist = function(argArray){ var arg0 = argArray[0]; var arg1 = argArray[1]; var arg2 = argArray[2]; if (arg0 < 0 || arg1 <= 0) { return new cError(cErrorType.not_numeric); } var res = null; if (arg2) { res = 1 - Math.exp(-arg1 * arg0); } else { res = arg1 * Math.exp(-arg1 * arg0); } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcFDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cEXPONDIST() { this.name = "EXPONDIST"; this.value = null; this.argumentsCurrent = 0; } cEXPONDIST.prototype = Object.create(cBaseFunction.prototype); cEXPONDIST.prototype.constructor = cEXPONDIST; cEXPONDIST.prototype.argumentsMin = 3; cEXPONDIST.prototype.argumentsMax = 3; cEXPONDIST.prototype.Calculate = function (arg) { var arg0 = arg[0], arg1 = arg[1], arg2 = arg[2], arg3 = arg[3]; if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } else if (arg0 instanceof cArray) { arg0 = arg0.getElement(0); } if (arg1 instanceof cArea || arg1 instanceof cArea3D) { arg1 = arg1.cross(arguments[1]); } else if (arg1 instanceof cArray) { arg1 = arg1.getElement(0); } if (arg2 instanceof cArea || arg2 instanceof cArea3D) { arg2 = arg2.cross(arguments[1]); } else if (arg2 instanceof cArray) { arg2 = arg2.getElement(0); } arg0 = arg0.tocNumber(); arg1 = arg1.tocNumber(); arg2 = arg2.tocBool(); if (arg0 instanceof cError) { return this.value = arg0; } if (arg1 instanceof cError) { return this.value = arg1; } if (arg2 instanceof cError) { return this.value = arg2; } if (arg0.getValue() < 0 || arg2.getValue() <= 0) { return this.value = new cError(cErrorType.not_numeric); } if (arg2.toBool()) { return this.value = new cNumber(1 - Math.exp(-arg1.getValue() * arg0.getValue())); } else { return this.value = new cNumber(arg1.getValue() * Math.exp(-arg1.getValue() * arg0.getValue())); } }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cF_DIST() { cBaseFunction.call(this, "F.DIST"); } cF_DIST.prototype = Object.create(cBaseFunction.prototype); cF_DIST.prototype.constructor = cF_DIST; cF_DIST.prototype.argumentsMin = 3; cF_DIST.prototype.argumentsMax = 4; cF_DIST.prototype.isXLFN = true; cF_DIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3] ? argClone[3].tocNumber() : new cBool(true); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcFDist = function(argArray){ var fF = argArray[0]; var fF1 = argArray[1]; var fF2 = argArray[2]; var bCum = argArray[3]; if ( fF < 0 || fF1 < 1 || fF2 < 1 || fF1 >= 1.0E10 || fF2 >= 1.0E10 ){ return new cError(cErrorType.not_numeric); } var res; if ( bCum ) { res = 1 - getFDist( fF, fF1, fF2 ); }else{ res = Math.pow( fF1 / fF2, fF1 / 2 ) * Math.pow( fF, ( fF1 / 2 ) - 1 ) / ( Math.pow( ( 1 + ( fF * fF1 / fF2 ) ), ( fF1 + fF2 ) / 2 ) * getBeta( fF1 / 2, fF2 / 2 ) ); } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcFDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cF_DIST_RT() { cBaseFunction.call(this, "F.DIST.RT"); } cF_DIST_RT.prototype = Object.create(cBaseFunction.prototype); cF_DIST_RT.prototype.constructor = cF_DIST_RT; cF_DIST_RT.prototype.argumentsMin = 3; cF_DIST_RT.prototype.argumentsMax = 3; cF_DIST_RT.prototype.isXLFN = true; cF_DIST_RT.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcFDist = function(argArray){ var fF = argArray[0]; var fF1 = argArray[1]; var fF2 = argArray[2]; if (fF < 0 || fF1 < 1 || fF2 < 1 || fF1 >= 1.0E10 || fF2 >= 1.0E10){ return new cError(cErrorType.not_numeric); } var res = getFDist(fF, fF1, fF2); return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; if (argClone[1].getValue() < 1 ){ return this.value = new cError(cErrorType.not_numeric); } return this.value = this._findArrayInNumberArguments(oArguments, calcFDist); }; /** * @constructor * @extends {cF_DIST_RT} */ function cFDIST() { cF_DIST_RT.call(this); this.name = "FDIST"; } cFDIST.prototype = Object.create(cF_DIST_RT.prototype); cFDIST.prototype.constructor = cFDIST; cFDIST.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cF_INV() { cBaseFunction.call(this, "F.INV"); } cF_INV.prototype = Object.create(cBaseFunction.prototype); cF_INV.prototype.constructor = cF_INV; cF_INV.prototype.argumentsMin = 3; cF_INV.prototype.argumentsMax = 3; cF_INV.prototype.isXLFN = true; cF_INV.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcFDist = function(argArray){ var fP = argArray[0]; var fF1 = parseInt(argArray[1]); var fF2 = parseInt(argArray[2]); if (fP <= 0 || fF1 < 1 || fF2 < 1 || fF1 >= 1.0E10 || fF2 >= 1.0E10 || fP > 1){ return new cError(cErrorType.not_numeric); } var aFunc = new FDISTFUNCTION(1 - fP, fF1, fF2); var oVal = iterateInverse( aFunc, fF1*0.5, fF1 ); var bConvError = oVal.bError; if (bConvError){ return new cError(cErrorType.not_numeric); } var res = oVal.val; return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; if (argClone[1].getValue() < 1 ){ return this.value = new cError(cErrorType.not_numeric); } return this.value = this._findArrayInNumberArguments(oArguments, calcFDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cFINV() { cBaseFunction.call(this, "FINV"); } cFINV.prototype = Object.create(cBaseFunction.prototype); cFINV.prototype.constructor = cFINV; cFINV.prototype.argumentsMin = 3; cFINV.prototype.argumentsMax = 3; cFINV.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcFDist = function(argArray){ var fP = argArray[0]; var fF1 = parseInt(argArray[1]); var fF2 = parseInt(argArray[2]); if (fP <= 0 || fF1 < 1 || fF2 < 1 || fF1 >= 1.0E10 || fF2 >= 1.0E10 || fP > 1){ return new cError(cErrorType.not_numeric); } var aFunc = new FDISTFUNCTION(fP, fF1, fF2); var oVal = iterateInverse( aFunc, fF1*0.5, fF1 ); var bConvError = oVal.bError; if (bConvError){ return new cError(cErrorType.not_numeric); } var res = oVal.val; return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; if (argClone[1].getValue() < 1 ){ return this.value = new cError(cErrorType.not_numeric); } return this.value = this._findArrayInNumberArguments(oArguments, calcFDist); }; /** * @constructor * @extends {cFINV} */ function cF_INV_RT() { cFINV.call(this); this.name = "F.INV.RT"; } cF_INV_RT.prototype = Object.create(cFINV.prototype); cF_INV_RT.prototype.constructor = cF_INV_RT; cF_INV_RT.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cFISHER() { this.name = "FISHER"; this.value = null; this.argumentsCurrent = 0; } cFISHER.prototype = Object.create(cBaseFunction.prototype); cFISHER.prototype.constructor = cFISHER; cFISHER.prototype.argumentsMin = 1; cFISHER.prototype.argumentsMax = 1; cFISHER.prototype.Calculate = function (arg) { var arg0 = arg[0]; function fisher(x) { return 0.5 * Math.ln((1 + x) / (1 - x)); } if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } arg0 = arg0.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } else if (arg0 instanceof cArray) { arg0.foreach(function (elem, r, c) { if (elem instanceof cNumber) { var a = fisher(elem.getValue()); this.array[r][c] = isNaN(a) ? new cError(cErrorType.not_numeric) : new cNumber(a); } else { this.array[r][c] = new cError(cErrorType.wrong_value_type); } }) } else { var a = fisher(arg0.getValue()); return this.value = isNaN(a) ? new cError(cErrorType.not_numeric) : new cNumber(a); } return this.value = arg0; }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cFISHERINV() { this.name = "FISHERINV"; this.value = null; this.argumentsCurrent = 0; } cFISHERINV.prototype = Object.create(cBaseFunction.prototype); cFISHERINV.prototype.constructor = cFISHERINV; cFISHERINV.prototype.argumentsMin = 1; cFISHERINV.prototype.argumentsMax = 1; cFISHERINV.prototype.Calculate = function (arg) { var arg0 = arg[0]; function fisherInv(x) { return ( Math.exp(2 * x) - 1 ) / ( Math.exp(2 * x) + 1 ); } if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } arg0 = arg0.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } else if (arg0 instanceof cArray) { arg0.foreach(function (elem, r, c) { if (elem instanceof cNumber) { var a = fisherInv(elem.getValue()); this.array[r][c] = isNaN(a) ? new cError(cErrorType.not_numeric) : new cNumber(a); } else { this.array[r][c] = new cError(cErrorType.wrong_value_type); } }) } else { var a = fisherInv(arg0.getValue()); return this.value = isNaN(a) ? new cError(cErrorType.not_numeric) : new cNumber(a); } return this.value = arg0; }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cFORECAST() { this.name = "FORECAST"; this.value = null; this.argumentsCurrent = 0; } cFORECAST.prototype = Object.create(cBaseFunction.prototype); cFORECAST.prototype.constructor = cFORECAST; cFORECAST.prototype.argumentsMin = 3; cFORECAST.prototype.argumentsMax = 3; cFORECAST.prototype.Calculate = function (arg) { function forecast(fx, y, x) { var fSumDeltaXDeltaY = 0, fSumSqrDeltaX = 0, _x = 0, _y = 0, xLength = 0, i; if(x.length !== y.length){ return new cError(cErrorType.not_available); } for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } _x += x[i].getValue(); _y += y[i].getValue(); xLength++; } _x /= xLength; _y /= xLength; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } var fValX = x[i].getValue(); var fValY = y[i].getValue(); fSumDeltaXDeltaY += ( fValX - _x ) * ( fValY - _y ); fSumSqrDeltaX += ( fValX - _x ) * ( fValX - _x ); } if (fSumDeltaXDeltaY == 0) { return new cError(cErrorType.division_by_zero); } else { return new cNumber(_y + fSumDeltaXDeltaY / fSumSqrDeltaX * ( fx.getValue() - _x )); } } var arg0 = arg[0], arg1 = arg[1], arg2 = arg[2], arr0 = [], arr1 = []; if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } else if (arg0 instanceof cArray) { arg0 = arg0.getElement(0); } arg0 = arg0.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } if (arg1 instanceof cArea) { arr0 = arg1.getValue(); } else if (arg1 instanceof cArray) { arg1.foreach(function (elem) { arr0.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } if (arg2 instanceof cArea) { arr1 = arg2.getValue(); } else if (arg2 instanceof cArray) { arg2.foreach(function (elem) { arr1.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } return this.value = forecast(arg0, arr0, arr1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cFORECAST_ETS() { this.name = "FORECAST.ETS"; this.value = null; this.argumentsCurrent = 0; } cFORECAST_ETS.prototype = Object.create(cBaseFunction.prototype); cFORECAST_ETS.prototype.constructor = cFORECAST_ETS; cFORECAST_ETS.prototype.argumentsMin = 3; cFORECAST_ETS.prototype.argumentsMax = 6; cFORECAST_ETS.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true, [null, cElementType.array, cElementType.array]); var argClone = oArguments.args; argClone[3] = argClone[3] ? argClone[3].tocNumber() : new cNumber(1); argClone[4] = argClone[4] ? argClone[4].tocNumber() : new cNumber(1); argClone[5] = argClone[5] ? argClone[5].tocNumber() : new cNumber(1); argClone[0] = argClone[0].getMatrix(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var pTMat = argClone[0]; var pMatY = argClone[1]; var pMatX = argClone[2]; var nSmplInPrd = argClone[3].getValue(); var bDataCompletion = argClone[4].getValue(); var nAggregation = argClone[5].getValue(); var aETSCalc = new ScETSForecastCalculation( pMatX.length ); var isError = aETSCalc.PreprocessDataRange( pMatX, pMatY, nSmplInPrd, bDataCompletion, nAggregation, pTMat); if ( !isError) { ///*,( eETSType != etsStatAdd && eETSType != etsStatMult ? pTMat : nullptr ),eETSType ) return new cError(cErrorType.wrong_value_type); }else if(isError && cElementType.error === isError.type){ return isError; } var pFcMat = aETSCalc.GetForecastRange( pTMat); return new cNumber(pFcMat[0][0]); }; /** * @constructor * @extends {cFORECAST} */ function cFORECAST_LINEAR() { cFORECAST.call(this); this.name = "FORECAST.LINEAR"; } cFORECAST_LINEAR.prototype = Object.create(cFORECAST.prototype); cFORECAST_LINEAR.prototype.constructor = cFORECAST_LINEAR; cFORECAST_LINEAR.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cFREQUENCY() { this.name = "FREQUENCY"; this.value = null; this.argumentsCurrent = 0; } cFREQUENCY.prototype = Object.create(cBaseFunction.prototype); cFREQUENCY.prototype.constructor = cFREQUENCY; cFREQUENCY.prototype.argumentsMin = 2; cFREQUENCY.prototype.argumentsMax = 2; cFREQUENCY.prototype.numFormat = AscCommonExcel.cNumFormatNone; cFREQUENCY.prototype.Calculate = function (arg) { function frequency(A, B) { var tA = [], tB = [Number.NEGATIVE_INFINITY], i, j; for (i = 0; i < A.length; i++) { for (j = 0; j < A[i].length; j++) { if (A[i][j] instanceof cError) { return A[i][j]; } else if (A[i][j] instanceof cNumber) { tA.push(A[i][j].getValue()); } else if (A[i][j] instanceof cBool) { tA.push(A[i][j].tocNumber().getValue()); } } } for (i = 0; i < B.length; i++) { for (j = 0; j < B[i].length; j++) { if (B[i][j] instanceof cError) { return B[i][j]; } else if (B[i][j] instanceof cNumber) { tB.push(B[i][j].getValue()); } else if (B[i][j] instanceof cBool) { tB.push(B[i][j].tocNumber().getValue()); } } } tA.sort(fSortAscending); tB.push(Number.POSITIVE_INFINITY); tB.sort(fSortAscending); var C = [[]], k = 0; for (i = 1; i < tB.length; i++, k++) { C[0][k] = new cNumber(0); for (j = 0; j < tA.length; j++) { if (tA[j] > tB[i - 1] && tA[j] <= tB[i]) { var a = C[0][k].getValue(); C[0][k] = new cNumber(++a); } } } var res = new cArray(); res.fillFromArray(C); return res; } var arg0 = arg[0], arg1 = arg[1]; if (arg0 instanceof cArea || arg0 instanceof cArray) { arg0 = arg0.getMatrix(); } else if (arg0 instanceof cArea3D) { arg0 = arg0.getMatrix()[0]; } else { return this.value = new cError(cErrorType.not_available); } if (arg1 instanceof cArea || arg1 instanceof cArray) { arg1 = arg1.getMatrix(); } else if (arg1 instanceof cArea3D) { arg1 = arg1.getMatrix()[0]; } else { return this.value = new cError(cErrorType.not_available); } return this.value = frequency(arg0, arg1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cFTEST() { cBaseFunction.call(this, "FTEST"); } cFTEST.prototype = Object.create(cBaseFunction.prototype); cFTEST.prototype.constructor = cFTEST; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cGAMMA() { this.name = "GAMMA"; this.value = null; this.argumentsCurrent = 0; } cGAMMA.prototype = Object.create(cBaseFunction.prototype); cGAMMA.prototype.constructor = cGAMMA; cGAMMA.prototype.argumentsMin = 1; cGAMMA.prototype.argumentsMax = 1; cGAMMA.prototype.isXLFN = true; cGAMMA.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcGamma = function(argArray){ if(argArray[0] <= 0 && isInteger(argArray[0])){ return new cError(cErrorType.not_numeric); } var res = getGamma(argArray[0]); return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcGamma); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cGAMMA_DIST() { this.name = "GAMMA.DIST"; this.value = null; this.argumentsCurrent = 0; } cGAMMA_DIST.prototype = Object.create(cBaseFunction.prototype); cGAMMA_DIST.prototype.constructor = cGAMMA_DIST; cGAMMA_DIST.prototype.argumentsMin = 4; cGAMMA_DIST.prototype.argumentsMax = 4; cGAMMA_DIST.prototype.isXLFN = true; cGAMMA_DIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcGamma = function(argArray){ var fX = argArray[0]; var fAlpha = argArray[1]; var fBeta = argArray[2]; var bCumulative = argArray[3]; var res = null; if ((fX < 0) || fAlpha <= 0 || fBeta <= 0){ return new cError(cErrorType.not_numeric); } else { if (bCumulative) { res = getGammaDist( fX, fAlpha, fBeta ); }else { res = getGammaDistPDF( fX, fAlpha, fBeta ); } } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcGamma); }; /** * @constructor * @extends {cGAMMA_DIST} */ function cGAMMADIST() { cGAMMA_DIST.call(this); this.name = "GAMMADIST"; } cGAMMADIST.prototype = Object.create(cGAMMA_DIST.prototype); cGAMMADIST.prototype.constructor = cGAMMADIST; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cGAMMA_INV() { this.name = "GAMMA.INV"; this.value = null; this.argumentsCurrent = 0; } cGAMMA_INV.prototype = Object.create(cBaseFunction.prototype); cGAMMA_INV.prototype.constructor = cGAMMA_INV; cGAMMA_INV.prototype.argumentsMin = 3; cGAMMA_INV.prototype.argumentsMax = 3; cGAMMA_INV.prototype.isXLFN = true; cGAMMA_INV.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcGamma = function(argArray){ var fP = argArray[0]; var fAlpha = argArray[1]; var fBeta = argArray[2]; if (fAlpha <= 0 || fBeta <= 0 || fP < 0 || fP >= 1 ){ return new cError(cErrorType.not_numeric); } var res = null; if (fP === 0){ res = 0; }else { var aFunc = new GAMMADISTFUNCTION(fP, fAlpha, fBeta); var fStart = fAlpha * fBeta; var oVal = iterateInverse(aFunc, fStart * 0.5, fStart); var bConvError = oVal.bError; if (bConvError){ return new cError(cErrorType.not_numeric); //SetError(FormulaError::NoConvergence); } res = oVal.val; } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcGamma); }; /** * @constructor * @extends {cGAMMA_INV} */ function cGAMMAINV() { cGAMMA_INV.call(this); this.name = "GAMMAINV"; } cGAMMAINV.prototype = Object.create(cGAMMA_INV.prototype); cGAMMAINV.prototype.constructor = cGAMMAINV; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cGAMMALN() { this.name = "GAMMALN"; this.value = null; this.argumentsCurrent = 0; } cGAMMALN.prototype = Object.create(cBaseFunction.prototype); cGAMMALN.prototype.constructor = cGAMMALN; cGAMMALN.prototype.argumentsMin = 1; cGAMMALN.prototype.argumentsMax = 1; cGAMMALN.prototype.Calculate = function (arg) { /* from OpenOffice Source. end */ var arg0 = arg[0]; if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } arg0 = arg0.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } else if (arg0 instanceof cArray) { arg0.foreach(function (elem, r, c) { if (elem instanceof cNumber) { var a = getLogGamma(elem.getValue()); this.array[r][c] = isNaN(a) ? new cError(cErrorType.not_numeric) : new cNumber(a); } else { this.array[r][c] = new cError(cErrorType.wrong_value_type); } }) } else { var a = getLogGamma(arg0.getValue()); return this.value = isNaN(a) ? new cError(cErrorType.not_numeric) : new cNumber(a); } return this.value = arg0; }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cGAMMALN_PRECISE() { this.name = "GAMMALN.PRECISE"; this.value = null; this.argumentsCurrent = 0; } cGAMMALN_PRECISE.prototype = Object.create(cBaseFunction.prototype); cGAMMALN_PRECISE.prototype.constructor = cGAMMALN_PRECISE; cGAMMALN_PRECISE.prototype.argumentsMin = 1; cGAMMALN_PRECISE.prototype.argumentsMax = 1; cGAMMALN_PRECISE.prototype.isXLFN = true; cGAMMALN_PRECISE.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcGamma = function(argArray) { var a = getLogGamma(argArray[0]); return isNaN(a) ? new cError(cErrorType.not_numeric) : new cNumber(a); }; return this.value = this._findArrayInNumberArguments(oArguments, calcGamma); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cGAUSS() { this.name = "GAUSS"; this.value = null; this.argumentsCurrent = 0; } cGAUSS.prototype = Object.create(cBaseFunction.prototype); cGAUSS.prototype.constructor = cGAUSS; cGAUSS.prototype.argumentsMin = 1; cGAUSS.prototype.argumentsMax = 1; cGAUSS.prototype.isXLFN = true; cGAUSS.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcGauss = function(argArray) { var res = gauss(argArray[0]); return isNaN(res) ? new cError(cErrorType.not_numeric) : new cNumber(res); }; return this.value = this._findArrayInNumberArguments(oArguments, calcGauss); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cGEOMEAN() { this.name = "GEOMEAN"; this.value = null; this.argumentsCurrent = 0; } cGEOMEAN.prototype = Object.create(cBaseFunction.prototype); cGEOMEAN.prototype.constructor = cGEOMEAN; cGEOMEAN.prototype.argumentsMin = 1; cGEOMEAN.prototype.Calculate = function (arg) { function geommean(x) { var _x = 1, xLength = 0, _tx; for (var i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { _x *= x[i].getValue(); xLength++; } else if (( x[i] instanceof cString || x[i] instanceof cBool ) && ( _tx = x[i].tocNumber()) instanceof cNumber) { _x *= _tx.getValue(); xLength++; } } if (_x <= 0) { return new cError(cErrorType.not_numeric); } else { return new cNumber(Math.pow(_x, 1 / xLength)); } } var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber) { arr0.push(a); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString && arg[j].tocNumber() instanceof cNumber) { arr0.push(arg[j].tocNumber()); } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = geommean(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cGROWTH() { cBaseFunction.call(this, "GROWTH"); } cGROWTH.prototype = Object.create(cBaseFunction.prototype); cGROWTH.prototype.constructor = cGROWTH; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cHARMEAN() { this.name = "HARMEAN"; this.value = null; this.argumentsCurrent = 0; } cHARMEAN.prototype = Object.create(cBaseFunction.prototype); cHARMEAN.prototype.constructor = cHARMEAN; cHARMEAN.prototype.argumentsMin = 1; cHARMEAN.prototype.Calculate = function (arg) { function harmmean(x) { var _x = 0, xLength = 0, _tx; for (var i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { if (x[i].getValue() == 0) { return new cError(cErrorType.not_numeric); } _x += 1 / x[i].getValue(); xLength++; } else if (( x[i] instanceof cString || x[i] instanceof cBool ) && ( _tx = x[i].tocNumber()) instanceof cNumber) { if (_tx.getValue() == 0) { return new cError(cErrorType.not_numeric); } _x += 1 / _tx.getValue(); xLength++; } } if (_x <= 0) { return new cError(cErrorType.not_numeric); } else { return new cNumber(xLength / _x); } } var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber) { arr0.push(a); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString && arg[j].tocNumber() instanceof cNumber) { arr0.push(arg[j].tocNumber()); } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = harmmean(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cHYPGEOMDIST() { this.name = "HYPGEOMDIST"; this.value = null; this.argumentsCurrent = 0; } cHYPGEOMDIST.prototype = Object.create(cBaseFunction.prototype); cHYPGEOMDIST.prototype.constructor = cHYPGEOMDIST; cHYPGEOMDIST.prototype.argumentsMin = 4; cHYPGEOMDIST.prototype.argumentsMax = 4; cHYPGEOMDIST.prototype.Calculate = function (arg) { var arg0 = arg[0], arg1 = arg[1], arg2 = arg[2], arg3 = arg[3]; if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } else if (arg0 instanceof cArray) { arg0 = arg0.getElement(0); } if (arg1 instanceof cArea || arg1 instanceof cArea3D) { arg1 = arg1.cross(arguments[1]); } else if (arg1 instanceof cArray) { arg1 = arg1.getElement(0); } if (arg2 instanceof cArea || arg2 instanceof cArea3D) { arg2 = arg2.cross(arguments[1]); } else if (arg2 instanceof cArray) { arg2 = arg2.getElement(0); } if (arg3 instanceof cArea || arg3 instanceof cArea3D) { arg3 = arg3.cross(arguments[1]); } else if (arg3 instanceof cArray) { arg3 = arg3.getElement(0); } arg0 = arg0.tocNumber(); arg1 = arg1.tocNumber(); arg2 = arg2.tocNumber(); arg3 = arg3.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } if (arg1 instanceof cError) { return this.value = arg1; } if (arg2 instanceof cError) { return this.value = arg2; } if (arg3 instanceof cError) { return this.value = arg3; } if (arg0.getValue() < 0 || arg0.getValue() > Math.min(arg1.getValue(), arg2.getValue()) || arg0.getValue() < Math.max(0, arg1.getValue() - arg3.getValue() + arg2.getValue()) || arg1.getValue() <= 0 || arg1.getValue() > arg3.getValue() || arg2.getValue() <= 0 || arg2.getValue() > arg3.getValue() || arg3.getValue() <= 0) { return this.value = new cError(cErrorType.not_numeric); } return this.value = new cNumber(Math.binomCoeff(arg2.getValue(), arg0.getValue()) * Math.binomCoeff(arg3.getValue() - arg2.getValue(), arg1.getValue() - arg0.getValue()) / Math.binomCoeff(arg3.getValue(), arg1.getValue())); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cHYPGEOM_DIST() { cBaseFunction.call(this, "HYPGEOM.DIST"); } cHYPGEOM_DIST.prototype = Object.create(cBaseFunction.prototype); cHYPGEOM_DIST.prototype.constructor = cHYPGEOM_DIST; cHYPGEOM_DIST.prototype.argumentsMin = 5; cHYPGEOM_DIST.prototype.argumentsMax = 5; cHYPGEOM_DIST.prototype.isXLFN = true; cHYPGEOM_DIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3].tocNumber(); argClone[4] = argClone[4].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function hypgeomdist(argArray) { var arg0 = Math.floor(argArray[0]); var arg1 = Math.floor(argArray[1]); var arg2 = Math.floor(argArray[2]); var arg3 = Math.floor(argArray[3]); var bCumulative = argArray[4]; if (arg0 < 0 || arg0 > Math.min(arg1, arg2) || arg0 < Math.max(0, arg1 - arg3 + arg2) || arg1 <= 0 || arg1 > arg3 || arg2 <= 0 || arg2 > arg3 || arg3 <= 0) { return new cError(cErrorType.not_numeric); } var res; if(bCumulative){ var fVal = 0.0; //TODO значения неверные для этой ветки! пересчитать for ( var i = 0; i <= arg0; i++ ){ var temp = Math.binomCoeff(arg2, i) * Math.binomCoeff(arg3 - arg2, arg1 - i) / Math.binomCoeff(arg3, arg1); if(!isNaN(temp)){ fVal += temp; } } res = fVal; }else{ res = Math.binomCoeff(arg2, arg0) * Math.binomCoeff(arg3 - arg2, arg1 - arg0) / Math.binomCoeff(arg3, arg1); } return isNaN(res) ? new cError(cErrorType.not_numeric) : new cNumber(res); } return this.value = this._findArrayInNumberArguments(oArguments, hypgeomdist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cINTERCEPT() { this.name = "INTERCEPT"; this.value = null; this.argumentsCurrent = 0; } cINTERCEPT.prototype = Object.create(cBaseFunction.prototype); cINTERCEPT.prototype.constructor = cINTERCEPT; cINTERCEPT.prototype.argumentsMin = 2; cINTERCEPT.prototype.argumentsMax = 2; cINTERCEPT.prototype.Calculate = function (arg) { function intercept(y, x) { var fSumDeltaXDeltaY = 0, fSumSqrDeltaX = 0, _x = 0, _y = 0, xLength = 0, i; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } _x += x[i].getValue(); _y += y[i].getValue(); xLength++; } _x /= xLength; _y /= xLength; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } var fValX = x[i].getValue(); var fValY = y[i].getValue(); fSumDeltaXDeltaY += ( fValX - _x ) * ( fValY - _y ); fSumSqrDeltaX += ( fValX - _x ) * ( fValX - _x ); } if (fSumDeltaXDeltaY == 0) { return new cError(cErrorType.division_by_zero); } else { return new cNumber(_y - fSumDeltaXDeltaY / fSumSqrDeltaX * _x); } } var arg0 = arg[0], arg1 = arg[1], arr0 = [], arr1 = []; if (arg0 instanceof cArea) { arr0 = arg0.getValue(); } else if (arg0 instanceof cArray) { arg0.foreach(function (elem) { arr0.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } if (arg1 instanceof cArea) { arr1 = arg1.getValue(); } else if (arg1 instanceof cArray) { arg1.foreach(function (elem) { arr1.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } return this.value = intercept(arr0, arr1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cKURT() { this.name = "KURT"; this.value = null; this.argumentsCurrent = 0; } cKURT.prototype = Object.create(cBaseFunction.prototype); cKURT.prototype.constructor = cKURT; cKURT.prototype.argumentsMin = 1; cKURT.prototype.Calculate = function (arg) { function kurt(x) { var sumSQRDeltaX = 0, _x = 0, xLength = 0, sumSQRDeltaXDivstandDev = 0, i; for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { _x += x[i].getValue(); xLength++; } } _x /= xLength; for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { sumSQRDeltaX += Math.pow(x[i].getValue() - _x, 2); } } var standDev = Math.sqrt(sumSQRDeltaX / ( xLength - 1 )); for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { sumSQRDeltaXDivstandDev += Math.pow((x[i].getValue() - _x) / standDev, 4); } } return new cNumber(xLength * (xLength + 1) / (xLength - 1) / (xLength - 2) / (xLength - 3) * sumSQRDeltaXDivstandDev - 3 * (xLength - 1) * (xLength - 1) / (xLength - 2) / (xLength - 3)) } var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber) { arr0.push(a); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString) { continue; } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = kurt(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cLARGE() { this.name = "LARGE"; this.value = null; this.argumentsCurrent = 0; } cLARGE.prototype = Object.create(cBaseFunction.prototype); cLARGE.prototype.constructor = cLARGE; cLARGE.prototype.argumentsMin = 2; cLARGE.prototype.argumentsMax = 2; cLARGE.prototype.numFormat = AscCommonExcel.cNumFormatNone; cLARGE.prototype._getValue = function (arg0, arg1) { if (cElementType.error === arg1.type) { return arg1; } arg1 = arg1.getValue(); if (arg1 <= 0) { return new cError(cErrorType.not_available); } var v, tA = []; for (var i = 0; i < arg0.length; i++) { for (var j = 0; j < arg0[i].length; j++) { v = arg0[i][j]; if (cElementType.error === v.type) { return v; } else if (cElementType.number === v.type) { tA.push(v.getValue()); } else if (cElementType.bool === v.type) { tA.push(v.tocNumber().getValue()); } } } tA.sort(AscCommon.fSortDescending); if (arg1 > tA.length) { return new cError(cErrorType.not_available); } else { return new cNumber(tA[arg1 - 1]); } }; cLARGE.prototype.Calculate = function (arg) { var arg0 = arg[0], arg1 = arg[1]; if (cElementType.cellsRange === arg0.type) { arg0 = arg0.getValuesNoEmpty(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); } else if (cElementType.array === arg0.type) { arg0 = arg0.getMatrix(); } else if (cElementType.cellsRange3D === arg0.type) { arg0 = arg0.getMatrix()[0]; } else { return this.value = new cError(cErrorType.not_numeric); } if (cElementType.cellsRange === arg1.type || cElementType.cellsRange3D === arg1.type) { arg1 = arg1.cross(arguments[1]); } else if (cElementType.array === arg1.type) { arg1 = arg1.getElement(0); } arg1 = arg1.tocNumber(); return this.value = this._getValue(arg0, arg1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cLINEST() { cBaseFunction.call(this, "LINEST"); } cLINEST.prototype = Object.create(cBaseFunction.prototype); cLINEST.prototype.constructor = cLINEST; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cLOGEST() { cBaseFunction.call(this, "LOGEST"); } cLOGEST.prototype = Object.create(cBaseFunction.prototype); cLOGEST.prototype.constructor = cLOGEST; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cLOGINV() { this.name = "LOGINV"; this.value = null; this.argumentsCurrent = 0; } cLOGINV.prototype = Object.create(cBaseFunction.prototype); cLOGINV.prototype.constructor = cLOGINV; cLOGINV.prototype.argumentsMin = 3; cLOGINV.prototype.argumentsMax = 3; cLOGINV.prototype.Calculate = function (arg) { var arg0 = arg[0], arg1 = arg[1], arg2 = arg[2]; function loginv(x, mue, sigma) { if (sigma <= 0 || x <= 0 || x >= 1) { return new cError(cErrorType.not_numeric); } else { return new cNumber(Math.exp(mue + sigma * ( gaussinv(x) ))); } } if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } else if (arg0 instanceof cArray) { arg0 = arg0.getElement(0); } if (arg1 instanceof cArea || arg1 instanceof cArea3D) { arg1 = arg1.cross(arguments[1]); } else if (arg1 instanceof cArray) { arg1 = arg1.getElement(0); } if (arg2 instanceof cArea || arg2 instanceof cArea3D) { arg2 = arg2.cross(arguments[1]); } else if (arg2 instanceof cArray) { arg2 = arg2.getElement(0); } arg0 = arg0.tocNumber(); arg1 = arg1.tocNumber(); arg2 = arg2.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } if (arg1 instanceof cError) { return this.value = arg1; } if (arg2 instanceof cError) { return this.value = arg2; } return this.value = loginv(arg0.getValue(), arg1.getValue(), arg2.getValue()); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cLOGNORM_DIST() { this.name = "LOGNORM.DIST"; this.value = null; this.argumentsCurrent = 0; } cLOGNORM_DIST.prototype = Object.create(cBaseFunction.prototype); cLOGNORM_DIST.prototype.constructor = cLOGNORM_DIST; cLOGNORM_DIST.prototype.argumentsMin = 4; cLOGNORM_DIST.prototype.argumentsMax = 4; cLOGNORM_DIST.prototype.isXLFN = true; cLOGNORM_DIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var normdist = function(argArray){ var x = argArray[0]; var mue = argArray[1]; var sigma = argArray[2]; var bCumulative = argArray[3]; var res = null; if (sigma <= 0.0) { return new cError(cErrorType.not_numeric); } if (bCumulative) { if (x <= 0){ res = 0; }else{ res = 0.5 + gauss((Math.ln(x) - mue) / sigma); } } else{ if (x <= 0){ return new cError(cErrorType.not_numeric); }else{ res = phi((Math.log(x) - mue) / sigma) / sigma / x; } } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, normdist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cLOGNORM_INV() { this.name = "LOGNORM.INV"; this.value = null; this.argumentsCurrent = 0; } cLOGNORM_INV.prototype = Object.create(cBaseFunction.prototype); cLOGNORM_INV.prototype.constructor = cLOGNORM_INV; cLOGNORM_INV.prototype.argumentsMin = 3; cLOGNORM_INV.prototype.argumentsMax = 3; cLOGNORM_INV.prototype.isXLFN = true; cLOGNORM_INV.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var normdist = function(argArray){ var fP = argArray[0]; var fMue = argArray[1]; var fSigma = argArray[2]; var res = null; if ( fSigma <= 0.0 || fP <= 0.0 || fP >= 1.0 ){ return new cError(cErrorType.not_numeric); }else{ res = Math.exp( fMue + fSigma * gaussinv( fP )); } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, normdist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cLOGNORMDIST() { this.name = "LOGNORMDIST"; this.value = null; this.argumentsCurrent = 0; } cLOGNORMDIST.prototype = Object.create(cBaseFunction.prototype); cLOGNORMDIST.prototype.constructor = cLOGNORMDIST; cLOGNORMDIST.prototype.argumentsMin = 3; cLOGNORMDIST.prototype.argumentsMax = 3; cLOGNORMDIST.prototype.Calculate = function (arg) { var arg0 = arg[0], arg1 = arg[1], arg2 = arg[2]; function normdist(x, mue, sigma) { if (sigma <= 0 || x <= 0) { return new cError(cErrorType.not_numeric); } else { return new cNumber(0.5 + gauss((Math.ln(x) - mue) / sigma)); } } if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } else if (arg0 instanceof cArray) { arg0 = arg0.getElement(0); } if (arg1 instanceof cArea || arg1 instanceof cArea3D) { arg1 = arg1.cross(arguments[1]); } else if (arg1 instanceof cArray) { arg1 = arg1.getElement(0); } if (arg2 instanceof cArea || arg2 instanceof cArea3D) { arg2 = arg2.cross(arguments[1]); } else if (arg2 instanceof cArray) { arg2 = arg2.getElement(0); } arg0 = arg0.tocNumber(); arg1 = arg1.tocNumber(); arg2 = arg2.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } if (arg1 instanceof cError) { return this.value = arg1; } if (arg2 instanceof cError) { return this.value = arg2; } return this.value = normdist(arg0.getValue(), arg1.getValue(), arg2.getValue()); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cMAX() { this.name = "MAX"; this.value = null; this.argumentsCurrent = 0; } cMAX.prototype = Object.create(cBaseFunction.prototype); cMAX.prototype.constructor = cMAX; cMAX.prototype.argumentsMin = 1; cMAX.prototype.Calculate = function (arg) { var v, element, argIVal, max = Number.NEGATIVE_INFINITY; for (var i = 0; i < this.argumentsCurrent; i++) { element = arg[i]; argIVal = element.getValue(); if (cElementType.cell === element.type || cElementType.cell3D === element.type) { if (!this.checkExclude || !element.isHidden(this.excludeHiddenRows)) { if (cElementType.error === argIVal.type) { return this.value = argIVal; } if (cElementType.number === argIVal.type) { v = argIVal.tocNumber(); if (v.getValue() > max) { max = v.getValue(); } } } } else if (cElementType.cellsRange === element.type || cElementType.cellsRange3D === element.type) { var argArr = element.getValue(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); for (var j = 0; j < argArr.length; j++) { if (cElementType.number === argArr[j].type) { v = argArr[j].tocNumber(); if (v.getValue() > max) { max = v.getValue(); } } else if (cElementType.error === argArr[j].type) { return this.value = argArr[j]; } } } else if (cElementType.error === element.type) { return this.value = element; } else if (cElementType.string === element.type) { v = element.tocNumber(); if (cElementType.number === v.type) { if (v.getValue() > max) { max = v.getValue(); } } } else if (cElementType.bool === element.type || cElementType.empty === element.type) { v = element.tocNumber(); if (v.getValue() > max) { max = v.getValue(); } } else if (cElementType.array === element.type) { element.foreach(function (elem) { if (cElementType.number === elem.type) { if (elem.getValue() > max) { max = elem.getValue(); } } else if (cElementType.error === elem.type) { max = elem; return true; } }); if (cElementType.error === max.type) { return this.value = max; } } else { if (element.getValue() > max) { max = element.getValue(); } } } return this.value = (max === Number.NEGATIVE_INFINITY ? new cNumber(0) : new cNumber(max)); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cMAXA() { this.name = "MAXA"; this.value = null; this.argumentsCurrent = 0; } cMAXA.prototype = Object.create(cBaseFunction.prototype); cMAXA.prototype.constructor = cMAXA; cMAXA.prototype.argumentsMin = 1; cMAXA.prototype.Calculate = function (arg) { var argI, argIVal, max = Number.NEGATIVE_INFINITY, v; for (var i = 0; i < this.argumentsCurrent; i++) { argI = arg[i]; argIVal = argI.getValue(); if (argI instanceof cRef || argI instanceof cRef3D) { if (argIVal instanceof cError) { return this.value = argIVal; } v = argIVal.tocNumber(); if (v instanceof cNumber && v.getValue() > max) { max = v.getValue(); } } else if (argI instanceof cArea || argI instanceof cArea3D) { var argArr = argI.getValue(); for (var j = 0; j < argArr.length; j++) { if (argArr[j] instanceof cError) { return this.value = argArr[j]; } v = argArr[j].tocNumber(); if (v instanceof cNumber && v.getValue() > max) { max = v.getValue(); } } } else if (argI instanceof cError) { return this.value = argI; } else if (argI instanceof cString) { v = argI.tocNumber(); if (v instanceof cNumber) { if (v.getValue() > max) { max = v.getValue(); } } } else if (argI instanceof cBool || argI instanceof cEmpty) { v = argI.tocNumber(); if (v.getValue() > max) { max = v.getValue(); } } else if (argI instanceof cArray) { argI.foreach(function (elem) { if (elem instanceof cError) { max = elem; return true; } elem = elem.tocNumber(); if (elem instanceof cNumber && elem.getValue() > max) { max = elem.getValue(); } }); if (max instanceof cError) { return this.value = max; } } else { if (argI.getValue() > max) { max = argI.getValue(); } } } return this.value = ( max === Number.NEGATIVE_INFINITY ? new cNumber(0) : new cNumber(max) ) }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cMAXIFS() { this.name = "MAXIFS"; this.value = null; this.argumentsCurrent = 0; } cMAXIFS.prototype = Object.create(cBaseFunction.prototype); cMAXIFS.prototype.constructor = cMAXIFS; cMAXIFS.prototype.argumentsMin = 3; cMAXIFS.prototype.isXLFN = true; cMAXIFS.prototype.Calculate = function (arg) { var arg0 = arg[0]; if (cElementType.cell !== arg0.type && cElementType.cell3D !== arg0.type && cElementType.cellsRange !== arg0.type) { if (cElementType.cellsRange3D === arg0.type) { arg0 = arg0.tocArea(); if (!arg0) { return this.value = new cError(cErrorType.wrong_value_type); } } else { return this.value = new cError(cErrorType.wrong_value_type); } } var arg0Matrix = arg0.getMatrix(); var i, j, arg1, arg2, matchingInfo; for (var k = 1; k < arg.length; k += 2) { arg1 = arg[k]; arg2 = arg[k + 1]; if (cElementType.cell !== arg1.type && cElementType.cell3D !== arg1.type && cElementType.cellsRange !== arg1.type) { if (cElementType.cellsRange3D === arg1.type) { arg1 = arg1.tocArea(); if (!arg1) { return this.value = new cError(cErrorType.wrong_value_type); } } else { return this.value = new cError(cErrorType.wrong_value_type); } } if (cElementType.cellsRange === arg2.type || cElementType.cellsRange3D === arg2.type) { arg2 = arg2.cross(arguments[1]); } else if (cElementType.array === arg2.type) { arg2 = arg2.getElementRowCol(0, 0); } arg2 = arg2.tocString(); if (cElementType.string !== arg2.type) { return this.value = new cError(cErrorType.wrong_value_type); } matchingInfo = AscCommonExcel.matchingValue(arg2.toString()); var arg1Matrix = arg1.getMatrix(); if (arg0Matrix.length !== arg1Matrix.length) { return this.value = new cError(cErrorType.wrong_value_type); } //compare for (i = 0; i < arg1Matrix.length; ++i) { if (arg0Matrix[i].length !== arg1Matrix[i].length) { return this.value = new cError(cErrorType.wrong_value_type); } for (j = 0; j < arg1Matrix[i].length; ++j) { if (arg0Matrix[i][j] && !AscCommonExcel.matching(arg1Matrix[i][j], matchingInfo)) { //MS считает в данном случае, что значение 0 (из диапазона условий) соответсвует условию = "" if(!(null === matchingInfo.op && "" === matchingInfo.val.value && 0 === arg1Matrix[i][j].value)){ arg0Matrix[i][j] = null; } } } } } var resArr = []; var valMatrix0; for (i = 0; i < arg0Matrix.length; ++i) { for (j = 0; j < arg0Matrix[i].length; ++j) { if ((valMatrix0 = arg0Matrix[i][j]) && cElementType.number === valMatrix0.type) { resArr.push(valMatrix0.getValue()); } } } if(0 === resArr.length){ return this.value = new cNumber(0); } resArr.sort(function(a, b) { return b - a; }); return this.value = new cNumber(resArr[0]); }; cMAXIFS.prototype.checkArguments = function () { return 1 === this.argumentsCurrent % 2 && cBaseFunction.prototype.checkArguments.apply(this, arguments); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cMINIFS() { this.name = "MINIFS"; this.value = null; this.argumentsCurrent = 0; } cMINIFS.prototype = Object.create(cBaseFunction.prototype); cMINIFS.prototype.constructor = cMINIFS; cMINIFS.prototype.argumentsMin = 3; cMINIFS.prototype.isXLFN = true; cMINIFS.prototype.Calculate = function (arg) { var arg0 = arg[0]; if (cElementType.cell !== arg0.type && cElementType.cell3D !== arg0.type && cElementType.cellsRange !== arg0.type) { if (cElementType.cellsRange3D === arg0.type) { arg0 = arg0.tocArea(); if (!arg0) { return this.value = new cError(cErrorType.wrong_value_type); } } else { return this.value = new cError(cErrorType.wrong_value_type); } } var arg0Matrix = arg0.getMatrix(); var i, j, arg1, arg2, matchingInfo; for (var k = 1; k < arg.length; k += 2) { arg1 = arg[k]; arg2 = arg[k + 1]; if (cElementType.cell !== arg1.type && cElementType.cell3D !== arg1.type && cElementType.cellsRange !== arg1.type) { if (cElementType.cellsRange3D === arg1.type) { arg1 = arg1.tocArea(); if (!arg1) { return this.value = new cError(cErrorType.wrong_value_type); } } else { return this.value = new cError(cErrorType.wrong_value_type); } } if (cElementType.cellsRange === arg2.type || cElementType.cellsRange3D === arg2.type) { arg2 = arg2.cross(arguments[1]); } else if (cElementType.array === arg2.type) { arg2 = arg2.getElementRowCol(0, 0); } arg2 = arg2.tocString(); if (cElementType.string !== arg2.type) { return this.value = new cError(cErrorType.wrong_value_type); } matchingInfo = AscCommonExcel.matchingValue(arg2.toString()); var arg1Matrix = arg1.getMatrix(); if (arg0Matrix.length !== arg1Matrix.length) { return this.value = new cError(cErrorType.wrong_value_type); } //compare for (i = 0; i < arg1Matrix.length; ++i) { if (arg0Matrix[i].length !== arg1Matrix[i].length) { return this.value = new cError(cErrorType.wrong_value_type); } for (j = 0; j < arg1Matrix[i].length; ++j) { if (arg0Matrix[i][j] && !AscCommonExcel.matching(arg1Matrix[i][j], matchingInfo)) { //MS считает в данном случае, что значение 0 (из диапазона условий) соответсвует условию = "" if(!(null === matchingInfo.op && "" === matchingInfo.val.value && 0 === arg1Matrix[i][j].value)){ arg0Matrix[i][j] = null; } } } } } var resArr = []; var valMatrix0; for (i = 0; i < arg0Matrix.length; ++i) { for (j = 0; j < arg0Matrix[i].length; ++j) { if ((valMatrix0 = arg0Matrix[i][j]) && cElementType.number === valMatrix0.type) { resArr.push(valMatrix0.getValue()); } } } if(0 === resArr.length){ return this.value = new cNumber(0); } resArr.sort(function(a, b) { return a - b; }); return this.value = new cNumber(resArr[0]); }; cMINIFS.prototype.checkArguments = function () { return 1 === this.argumentsCurrent % 2 && cBaseFunction.prototype.checkArguments.apply(this, arguments); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cMEDIAN() { this.name = "MEDIAN"; this.value = null; this.argumentsCurrent = 0; } cMEDIAN.prototype = Object.create(cBaseFunction.prototype); cMEDIAN.prototype.constructor = cMEDIAN; cMEDIAN.prototype.argumentsMin = 1; cMEDIAN.prototype.Calculate = function (arg) { function median(x) { var medArr = [], t; for (var i = 0; i < x.length; i++) { t = x[i].tocNumber(); if (t instanceof cNumber) { medArr.push(t.getValue()) } } medArr.sort(fSortAscending); if (medArr.length < 1) { return new cError(cErrorType.wrong_value_type); } else { if (medArr.length % 2) { return new cNumber(medArr[(medArr.length - 1) / 2]); } else { return new cNumber((medArr[medArr.length / 2 - 1] + medArr[medArr.length / 2]) / 2); } } } var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber) { arr0.push(a); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString) { continue; } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = median(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cMIN() { this.name = "MIN"; this.value = null; this.argumentsCurrent = 0; } cMIN.prototype = Object.create(cBaseFunction.prototype); cMIN.prototype.constructor = cMIN; cMIN.prototype.argumentsMin = 1; cMIN.prototype.Calculate = function (arg) { var v, element, argIVal, min = Number.POSITIVE_INFINITY; for (var i = 0; i < this.argumentsCurrent; i++) { element = arg[i]; argIVal = element.getValue(); if (cElementType.cell === element.type || cElementType.cell3D === element.type) { if (!this.checkExclude || !element.isHidden(this.excludeHiddenRows)) { if (cElementType.error === argIVal.type) { return this.value = argIVal; } if (cElementType.number === argIVal.type) { v = argIVal.tocNumber(); if (v.getValue() < min) { min = v.getValue(); } } } } else if (cElementType.cellsRange === element.type || cElementType.cellsRange3D === element.type) { var argArr = element.getValue(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); for (var j = 0; j < argArr.length; j++) { if (cElementType.number === argArr[j].type) { v = argArr[j].tocNumber(); if (v.getValue() < min) { min = v.getValue(); } continue; } else if (cElementType.error === argArr[j].type) { return this.value = argArr[j]; } } } else if (cElementType.error === element.type) { return this.value = element; } else if (cElementType.string === element.type) { v = element.tocNumber(); if (cElementType.number === v.type) { if (v.getValue() < min) { min = v.getValue(); } } } else if (cElementType.bool === element.type || cElementType.empty === element.type) { v = element.tocNumber(); if (v.getValue() < min) { min = v.getValue(); } } else if (cElementType.array === element.type) { element.foreach(function (elem) { if (cElementType.number === elem.type) { if (elem.getValue() < min) { min = elem.getValue(); } } else if (cElementType.error === elem.type) { min = elem; return true; } }); if (cElementType.error === min.type) { return this.value = min; } } else { if (element.getValue() < min) { min = element.getValue(); } } } return this.value = ( min === Number.POSITIVE_INFINITY ? new cNumber(0) : new cNumber(min) ); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cMINA() { this.name = "MINA"; this.value = null; this.argumentsCurrent = 0; } cMINA.prototype = Object.create(cBaseFunction.prototype); cMINA.prototype.constructor = cMINA; cMINA.prototype.argumentsMin = 1; cMINA.prototype.Calculate = function (arg) { var argI, argIVal, min = Number.POSITIVE_INFINITY, v; for (var i = 0; i < this.argumentsCurrent; i++) { argI = arg[i]; argIVal = argI.getValue(); if (argI instanceof cRef || argI instanceof cRef3D) { if (argIVal instanceof cError) { return this.value = argIVal; } v = argIVal.tocNumber(); if (v instanceof cNumber && v.getValue() < min) { min = v.getValue(); } } else if (argI instanceof cArea || argI instanceof cArea3D) { var argArr = argI.getValue(); for (var j = 0; j < argArr.length; j++) { if (argArr[j] instanceof cError) { return this.value = argArr[j]; } v = argArr[j].tocNumber(); if (v instanceof cNumber && v.getValue() < min) { min = v.getValue(); } } } else if (argI instanceof cError) { return this.value = argI; } else if (argI instanceof cString) { v = argI.tocNumber(); if (v instanceof cNumber) { if (v.getValue() < min) { min = v.getValue(); } } } else if (argI instanceof cBool || argI instanceof cEmpty) { v = argI.tocNumber(); if (v.getValue() < min) { min = v.getValue(); } } else if (argI instanceof cArray) { argI.foreach(function (elem) { if (elem instanceof cError) { min = elem; return true; } elem = elem.tocNumber(); if (elem instanceof cNumber && elem.getValue() < min) { min = elem.getValue(); } }); if (min instanceof cError) { return this.value = min; } } else { if (argI.getValue() < min) { min = argI.getValue(); } } } return this.value = ( min === Number.POSITIVE_INFINITY ? new cNumber(0) : new cNumber(min) ); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cMODE() { this.name = "MODE"; this.value = null; this.argumentsCurrent = 0; } cMODE.prototype = Object.create(cBaseFunction.prototype); cMODE.prototype.constructor = cMODE; cMODE.prototype.argumentsMin = 1; cMODE.prototype.Calculate = function (arg) { function mode(x) { var medArr = [], t, i; for (i = 0; i < x.length; i++) { t = x[i].tocNumber(); if (t instanceof cNumber) { medArr.push(t.getValue()) } } medArr.sort(fSortAscending); if (medArr.length < 1) { return new cError(cErrorType.wrong_value_type); } else { var nMaxIndex = 0, nMax = 1, nCount = 1, nOldVal = medArr[0]; for (i = 1; i < medArr.length; i++) { if (medArr[i] == nOldVal) { nCount++; } else { nOldVal = medArr[i]; if (nCount > nMax) { nMax = nCount; nMaxIndex = i - 1; } nCount = 1; } } if (nCount > nMax) { nMax = nCount; nMaxIndex = i - 1; } if (nMax == 1 && nCount == 1) { return new cError(cErrorType.wrong_value_type); } else if (nMax == 1) { return new cNumber(nOldVal); } else { return new cNumber(medArr[nMaxIndex]); } } } var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber) { arr0.push(a); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString) { continue; } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = mode(arr0); }; /** * @constructor * @extends {cPERCENTILE} */ //TODO разницы в работе функций cMODE_MULT и cMODE не нашёл, но в LO обработки немного разные. проверить! function cMODE_MULT() { cMODE.call(this); this.name = "MODE.MULT"; } cMODE_MULT.prototype = Object.create(cMODE.prototype); cMODE_MULT.prototype.constructor = cMODE_MULT; cMODE_MULT.prototype.isXLFN = true; /** * @constructor * @extends {cPERCENTILE} */ function cMODE_SNGL() { cMODE.call(this); this.name = "MODE.SNGL"; } cMODE_SNGL.prototype = Object.create(cMODE.prototype); cMODE_SNGL.prototype.constructor = cMODE_SNGL; cMODE_SNGL.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cNEGBINOMDIST() { cBaseFunction.call(this, "NEGBINOMDIST"); } cNEGBINOMDIST.prototype = Object.create(cBaseFunction.prototype); cNEGBINOMDIST.prototype.constructor = cNEGBINOMDIST; cNEGBINOMDIST.prototype.argumentsMin = 3; cNEGBINOMDIST.prototype.argumentsMax = 3; cNEGBINOMDIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function negbinomdist(argArray) { var x = argArray[0]; var r = argArray[1]; var p = argArray[2]; if (x < 0 || r < 1 || p < 0 || p > 1) { return new cError(cErrorType.not_numeric); } else { return new cNumber(Math.binomCoeff(x + r - 1, r - 1) * Math.pow(p, r) * Math.pow(1 - p, x)); } } return this.value = this._findArrayInNumberArguments(oArguments, negbinomdist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cNEGBINOM_DIST() { cBaseFunction.call(this, "NEGBINOM.DIST"); } cNEGBINOM_DIST.prototype = Object.create(cBaseFunction.prototype); cNEGBINOM_DIST.prototype.constructor = cNEGBINOM_DIST; cNEGBINOM_DIST.prototype.argumentsMin = 4; cNEGBINOM_DIST.prototype.argumentsMax = 4; cNEGBINOM_DIST.prototype.isXLFN = true; cNEGBINOM_DIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function negbinomdist(argArray) { var x = parseInt(argArray[0]); var r = parseInt(argArray[1]); var p = argArray[2]; var bCumulative = argArray[3]; if (x < 0 || r < 1 || p < 0 || p > 1) { return new cError(cErrorType.not_numeric); } var res; if ( bCumulative ){ res = 1 - getBetaDist( 1 - p, x + 1, r ); }else{ res = Math.binomCoeff(x + r - 1, r - 1) * Math.pow(p, r) * Math.pow(1 - p, x); } return isNaN(res) ? new cError(cErrorType.not_numeric) : new cNumber(res); } return this.value = this._findArrayInNumberArguments(oArguments, negbinomdist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cNORMDIST() { this.name = "NORMDIST"; this.value = null; this.argumentsCurrent = 0; } cNORMDIST.prototype = Object.create(cBaseFunction.prototype); cNORMDIST.prototype.constructor = cNORMDIST; cNORMDIST.prototype.argumentsMin = 4; cNORMDIST.prototype.argumentsMax = 4; cNORMDIST.prototype.Calculate = function (arg) { var arg0 = arg[0], arg1 = arg[1], arg2 = arg[2], arg3 = arg[3]; function normdist(x, mue, sigma, kum) { if (sigma <= 0) { return new cError(cErrorType.not_numeric); } if (kum) { return new cNumber(integralPhi((x - mue) / sigma)); } else { return new cNumber(phi((x - mue) / sigma) / sigma); } } if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } else if (arg0 instanceof cArray) { arg0 = arg0.getElement(0); } if (arg1 instanceof cArea || arg1 instanceof cArea3D) { arg1 = arg1.cross(arguments[1]); } else if (arg1 instanceof cArray) { arg1 = arg1.getElement(0); } if (arg2 instanceof cArea || arg2 instanceof cArea3D) { arg2 = arg2.cross(arguments[1]); } else if (arg2 instanceof cArray) { arg2 = arg2.getElement(0); } if (arg3 instanceof cArea || arg3 instanceof cArea3D) { arg3 = arg3.cross(arguments[1]); } else if (arg3 instanceof cArray) { arg3 = arg3.getElement(0); } arg0 = arg0.tocNumber(); arg1 = arg1.tocNumber(); arg2 = arg2.tocNumber(); arg3 = arg3.tocBool(); if (arg0 instanceof cError) { return this.value = arg0; } if (arg1 instanceof cError) { return this.value = arg1; } if (arg2 instanceof cError) { return this.value = arg2; } if (arg3 instanceof cError) { return this.value = arg3; } return this.value = normdist(arg0.getValue(), arg1.getValue(), arg2.getValue(), arg3.toBool()); }; /** * @constructor * @extends {cPERCENTILE} */ function cNORM_DIST() { cNORMDIST.call(this); this.name = "NORM.DIST"; } cNORM_DIST.prototype = Object.create(cNORMDIST.prototype); cNORM_DIST.prototype.constructor = cNORM_DIST; cNORM_DIST.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cNORMINV() { this.name = "NORMINV"; this.value = null; this.argumentsCurrent = 0; } cNORMINV.prototype = Object.create(cBaseFunction.prototype); cNORMINV.prototype.constructor = cNORMINV; cNORMINV.prototype.argumentsMin = 3; cNORMINV.prototype.argumentsMax = 3; cNORMINV.prototype.Calculate = function (arg) { var arg0 = arg[0], arg1 = arg[1], arg2 = arg[2]; function norminv(x, mue, sigma) { if (sigma <= 0.0 || x <= 0.0 || x >= 1.0) { return new cError(cErrorType.not_numeric); } else { return new cNumber(gaussinv(x) * sigma + mue); } } if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } else if (arg0 instanceof cArray) { arg0 = arg0.getElement(0); } if (arg1 instanceof cArea || arg1 instanceof cArea3D) { arg1 = arg1.cross(arguments[1]); } else if (arg1 instanceof cArray) { arg1 = arg1.getElement(0); } if (arg2 instanceof cArea || arg2 instanceof cArea3D) { arg2 = arg2.cross(arguments[1]); } else if (arg2 instanceof cArray) { arg2 = arg2.getElement(0); } arg0 = arg0.tocNumber(); arg1 = arg1.tocNumber(); arg2 = arg2.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } if (arg1 instanceof cError) { return this.value = arg1; } if (arg2 instanceof cError) { return this.value = arg2; } return this.value = norminv(arg0.getValue(), arg1.getValue(), arg2.getValue()); }; /** * @constructor * @extends {cNORMINV} */ function cNORM_INV() { cNORMINV.call(this); this.name = "NORM.INV"; } cNORM_INV.prototype = Object.create(cNORMINV.prototype); cNORM_INV.prototype.constructor = cNORM_INV; cNORM_INV.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cNORMSDIST() { this.name = "NORMSDIST"; this.value = null; this.argumentsCurrent = 0; } cNORMSDIST.prototype = Object.create(cBaseFunction.prototype); cNORMSDIST.prototype.constructor = cNORMSDIST; cNORMSDIST.prototype.argumentsMin = 1; cNORMSDIST.prototype.argumentsMax = 1; cNORMSDIST.prototype.Calculate = function (arg) { var arg0 = arg[0]; if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } arg0 = arg0.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } else if (arg0 instanceof cArray) { arg0.foreach(function (elem, r, c) { if (elem instanceof cNumber) { var a = 0.5 + gauss(elem.getValue()); this.array[r][c] = isNaN(a) ? new cError(cErrorType.not_numeric) : new cNumber(a); } else { this.array[r][c] = new cError(cErrorType.wrong_value_type); } }) } else { var a = 0.5 + gauss(arg0.getValue()); return this.value = isNaN(a) ? new cError(cErrorType.not_numeric) : new cNumber(a); } return this.value = arg0; }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cNORM_S_DIST() { this.name = "NORM.S.DIST"; this.value = null; this.argumentsCurrent = 0; } cNORM_S_DIST.prototype = Object.create(cBaseFunction.prototype); cNORM_S_DIST.prototype.constructor = cNORM_S_DIST; cNORM_S_DIST.prototype.argumentsMin = 2; cNORM_S_DIST.prototype.argumentsMax = 2; cNORM_S_DIST.prototype.isXLFN = true; cNORM_S_DIST.prototype.numFormat = AscCommonExcel.cNumFormatNone; cNORM_S_DIST.prototype.Calculate = function (arg) { function normDistCalc(argArray) { var arg0 = argArray[0], arg1 = argArray[1]; var res; if(arg1){ res = 0.5 + gauss(arg0); }else{ res = Math.exp( - Math.pow( arg0, 2 ) / 2 ) / Math.sqrt( 2 * Math.PI ); } return isNaN(res) ? new cError(cErrorType.not_numeric) : new cNumber(res); } var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } return this.value = this._findArrayInNumberArguments(oArguments, normDistCalc); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cNORMSINV() { this.name = "NORMSINV"; this.value = null; this.argumentsCurrent = 0; } cNORMSINV.prototype = Object.create(cBaseFunction.prototype); cNORMSINV.prototype.constructor = cNORMSINV; cNORMSINV.prototype.argumentsMin = 1; cNORMSINV.prototype.argumentsMax = 1; cNORMSINV.prototype.Calculate = function (arg) { function normsinv(x) { if (x <= 0.0 || x >= 1.0) { return new cError(cErrorType.not_numeric); } else { return new cNumber(gaussinv(x)); } } var arg0 = arg[0]; if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } arg0 = arg0.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } else if (arg0 instanceof cArray) { arg0.foreach(function (elem, r, c) { if (elem instanceof cNumber) { var a = normsinv(elem.getValue()); this.array[r][c] = isNaN(a) ? new cError(cErrorType.not_available) : new cNumber(a); } else { this.array[r][c] = new cError(cErrorType.wrong_value_type); } }) } else { var a = normsinv(arg0.getValue()); return this.value = isNaN(a) ? new cError(cErrorType.not_available) : new cNumber(a); } return this.value = arg0; }; /** * @constructor * @extends {cNORMSINV} */ function cNORM_S_INV() { cNORMSINV.call(this); this.name = "NORM.S.INV"; } cNORM_S_INV.prototype = Object.create(cNORMSINV.prototype); cNORM_S_INV.prototype.constructor = cNORM_S_INV; cNORM_S_INV.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cPEARSON() { this.name = "PEARSON"; this.value = null; this.argumentsCurrent = 0; } cPEARSON.prototype = Object.create(cBaseFunction.prototype); cPEARSON.prototype.constructor = cPEARSON; cPEARSON.prototype.argumentsMin = 2; cPEARSON.prototype.argumentsMax = 2; cPEARSON.prototype.Calculate = function (arg) { function pearson(x, y) { var sumXDeltaYDelta = 0, sqrXDelta = 0, sqrYDelta = 0, _x = 0, _y = 0, xLength = 0, i; if (x.length != y.length) { return new cError(cErrorType.not_available); } for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } _x += x[i].getValue(); _y += y[i].getValue(); xLength++; } _x /= xLength; _y /= xLength; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } sumXDeltaYDelta += (x[i].getValue() - _x) * (y[i].getValue() - _y); sqrXDelta += (x[i].getValue() - _x) * (x[i].getValue() - _x); sqrYDelta += (y[i].getValue() - _y) * (y[i].getValue() - _y); } if (sqrXDelta == 0 || sqrYDelta == 0) { return new cError(cErrorType.division_by_zero); } else { return new cNumber(sumXDeltaYDelta / Math.sqrt(sqrXDelta * sqrYDelta)); } } var arg0 = arg[0], arg1 = arg[1], arr0 = [], arr1 = []; if (arg0 instanceof cArea) { arr0 = arg0.getValue(); } else if (arg0 instanceof cArray) { arg0.foreach(function (elem) { arr0.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } if (arg1 instanceof cArea) { arr1 = arg1.getValue(); } else if (arg1 instanceof cArray) { arg1.foreach(function (elem) { arr1.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } return this.value = pearson(arr0, arr1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cPERCENTILE() { this.name = "PERCENTILE"; this.value = null; this.argumentsCurrent = 0; } cPERCENTILE.prototype = Object.create(cBaseFunction.prototype); cPERCENTILE.prototype.constructor = cPERCENTILE; cPERCENTILE.prototype.argumentsMin = 2; cPERCENTILE.prototype.argumentsMax = 2; cPERCENTILE.prototype.numFormat = AscCommonExcel.cNumFormatNone; cPERCENTILE.prototype.Calculate = function (arg) { function percentile(argArray) { var tA = [], A = argArray[0], alpha = argArray[1]; for (var i = 0; i < A.length; i++) { for (var j = 0; j < A[i].length; j++) { if (A[i][j] instanceof cError) { return A[i][j]; } else if (A[i][j] instanceof cNumber) { tA.push(A[i][j].getValue()); } else if (A[i][j] instanceof cBool) { tA.push(A[i][j].tocNumber().getValue()); } } } return getPercentile(tA, alpha); } var oArguments = this._prepareArguments(arg, arguments[1], true, [cElementType.array]); var argClone = oArguments.args; argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } return this.value = this._findArrayInNumberArguments(oArguments, percentile); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cPERCENTILE_EXC() { this.name = "PERCENTILE.EXC"; this.value = null; this.argumentsCurrent = 0; } cPERCENTILE_EXC.prototype = Object.create(cBaseFunction.prototype); cPERCENTILE_EXC.prototype.constructor = cPERCENTILE_EXC; cPERCENTILE_EXC.prototype.argumentsMin = 2; cPERCENTILE_EXC.prototype.argumentsMax = 2; cPERCENTILE_EXC.prototype.isXLFN = true; cPERCENTILE_EXC.prototype.numFormat = AscCommonExcel.cNumFormatNone; cPERCENTILE_EXC.prototype.Calculate = function (arg) { function percentile(argArray) { var tA = [], A = argArray[0], alpha = argArray[1]; for (var i = 0; i < A.length; i++) { for (var j = 0; j < A[i].length; j++) { if (A[i][j] instanceof cError) { return A[i][j]; } else if (A[i][j] instanceof cNumber) { tA.push(A[i][j].getValue()); } else if (A[i][j] instanceof cBool) { tA.push(A[i][j].tocNumber().getValue()); } } } return getPercentileExclusive(tA, alpha); } var oArguments = this._prepareArguments(arg, arguments[1], true, [cElementType.array]); var argClone = oArguments.args; argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } return this.value = this._findArrayInNumberArguments(oArguments, percentile); }; /** * @constructor * @extends {cPERCENTILE} */ function cPERCENTILE_INC() { cPERCENTILE.call(this); this.name = "PERCENTILE.INC"; } cPERCENTILE_INC.prototype = Object.create(cPERCENTILE.prototype); cPERCENTILE_INC.prototype.constructor = cPERCENTILE_INC; cPERCENTILE_INC.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cPERCENTRANK() { this.name = "PERCENTRANK"; this.value = null; this.argumentsCurrent = 0; } cPERCENTRANK.prototype = Object.create(cBaseFunction.prototype); cPERCENTRANK.prototype.constructor = cPERCENTRANK; cPERCENTRANK.prototype.argumentsMin = 2; cPERCENTRANK.prototype.argumentsMax = 3; cPERCENTRANK.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true, [cElementType.array]); var argClone = oArguments.args; argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2] ? argClone[2].tocNumber() : new cNumber(3); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function calcPercenTrank(argArray) { var tA = [], A = argArray[0], fNum = argArray[1], k = argArray[2]; for (var i = 0; i < A.length; i++) { for (var j = 0; j < A[i].length; j++) { if (A[i][j] instanceof cError) { return A[i][j]; } else if (A[i][j] instanceof cNumber) { tA.push(A[i][j].getValue()); } else if (A[i][j] instanceof cBool) { tA.push(A[i][j].tocNumber().getValue()); } } } return percentrank(tA, fNum, k, true); } return this.value = this._findArrayInNumberArguments(oArguments, calcPercenTrank); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cPERCENTRANK_EXC() { this.name = "PERCENTRANK.EXC"; this.value = null; this.argumentsCurrent = 0; } cPERCENTRANK_EXC.prototype = Object.create(cBaseFunction.prototype); cPERCENTRANK_EXC.prototype.constructor = cPERCENTRANK_EXC; cPERCENTRANK_EXC.prototype.argumentsMin = 2; cPERCENTRANK_EXC.prototype.argumentsMax = 3; cPERCENTRANK_EXC.prototype.isXLFN = true; cPERCENTRANK_EXC.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true, [cElementType.array]); var argClone = oArguments.args; argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2] ? argClone[2].tocNumber() : new cNumber(3); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function calcPercenTrank(argArray) { var tA = [], A = argArray[0], fNum = argArray[1], k = argArray[2]; for (var i = 0; i < A.length; i++) { for (var j = 0; j < A[i].length; j++) { if (A[i][j] instanceof cError) { return A[i][j]; } else if (A[i][j] instanceof cNumber) { tA.push(A[i][j].getValue()); } else if (A[i][j] instanceof cBool) { tA.push(A[i][j].tocNumber().getValue()); } } } return percentrank(tA, fNum, k); } return this.value = this._findArrayInNumberArguments(oArguments, calcPercenTrank); }; /** * @constructor * @extends {cPERCENTRANK} */ function cPERCENTRANK_INC() { cPERCENTRANK.call(this); this.name = "PERCENTRANK.INC"; } cPERCENTRANK_INC.prototype = Object.create(cPERCENTRANK.prototype); cPERCENTRANK_INC.prototype.constructor = cPERCENTRANK_INC; cPERCENTRANK_INC.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cPERMUT() { this.name = "PERMUT"; this.value = null; this.argumentsCurrent = 0; } cPERMUT.prototype = Object.create(cBaseFunction.prototype); cPERMUT.prototype.constructor = cPERMUT; cPERMUT.prototype.argumentsMin = 2; cPERMUT.prototype.argumentsMax = 2; cPERMUT.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function permut(argArray) { var n = Math.floor(argArray[0]); var k = Math.floor(argArray[1]); if (n <= 0 || k <= 0 || n < k) { return new cError(cErrorType.not_numeric); } return new cNumber(Math.permut(n, k)); } return this.value = this._findArrayInNumberArguments(oArguments, permut); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cPERMUTATIONA() { this.name = "PERMUTATIONA"; this.value = null; this.argumentsCurrent = 0; } cPERMUTATIONA.prototype = Object.create(cBaseFunction.prototype); cPERMUTATIONA.prototype.constructor = cPERMUTATIONA; cPERMUTATIONA.prototype.argumentsMin = 2; cPERMUTATIONA.prototype.argumentsMax = 2; cPERMUTATIONA.prototype.isXLFN = true; cPERMUTATIONA.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function permutationa(argArray) { var n = Math.floor(argArray[0]); var k = Math.floor(argArray[1]); if (n < 0.0 || k < 0.0){ return new cError(cErrorType.not_numeric); } return new cNumber(Math.pow(n,k)); } return this.value = this._findArrayInNumberArguments(oArguments, permutationa); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cPHI() { this.name = "PHI"; this.value = null; this.argumentsCurrent = 0; } cPHI.prototype = Object.create(cBaseFunction.prototype); cPHI.prototype.constructor = cPHI; cPHI.prototype.argumentsMin = 1; cPHI.prototype.argumentsMax = 1; cPHI.prototype.isXLFN = true; cPHI.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function calcPhi(argArray) { var res = phi(argArray[0]); return isNaN(res) ? new cError(cErrorType.not_available) : new cNumber(res); } return this.value = this._findArrayInNumberArguments(oArguments, calcPhi); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cPOISSON() { this.name = "POISSON"; this.value = null; this.argumentsCurrent = 0; } cPOISSON.prototype = Object.create(cBaseFunction.prototype); cPOISSON.prototype.constructor = cPOISSON; cPOISSON.prototype.argumentsMin = 3; cPOISSON.prototype.argumentsMax = 3; cPOISSON.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function poisson(argArray) { var _x = parseInt(argArray[0]); var _l = argArray[1]; var f = argArray[2]; if (_x < 0 || _l < 0) { return new cError(cErrorType.not_numeric); } if (f) { var sum = 0; for (var k = 0; k <= _x; k++) { sum += Math.pow(_l, k) / Math.fact(k); } sum *= Math.exp(-_l); return new cNumber(sum); } else { return new cNumber(Math.exp(-_l) * Math.pow(_l, _x) / Math.fact(_x)); } } return this.value = this._findArrayInNumberArguments(oArguments, poisson); }; /** * @constructor * @extends {cPERCENTRANK} */ function cPOISSON_DIST() { cPOISSON.call(this); this.name = "POISSON.DIST"; } cPOISSON_DIST.prototype = Object.create(cPOISSON.prototype); cPOISSON_DIST.prototype.constructor = cPOISSON_DIST; cPOISSON_DIST.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cPROB() { this.name = "PROB"; this.value = null; this.argumentsCurrent = 0; } cPROB.prototype = Object.create(cBaseFunction.prototype); cPROB.prototype.constructor = cPROB; cPROB.prototype.argumentsMin = 3; cPROB.prototype.argumentsMax = 4; cPROB.prototype.numFormat = AscCommonExcel.cNumFormatNone; cPROB.prototype.Calculate = function (arg) { function prob(x, p, l, u) { var fUp, fLo; fLo = l.getValue(); if (u instanceof cEmpty) { fUp = fLo; } else { fUp = u.getValue(); } if (fLo > fUp) { var fTemp = fLo; fLo = fUp; fUp = fTemp; } var nC1 = x[0].length, nC2 = p[0].length, nR1 = x.length, nR2 = p.length; if (nC1 != nC2 || nR1 != nR2 || nC1 == 0 || nR1 == 0 || nC2 == 0 || nR2 == 0) { return new cError(cErrorType.not_available); } else { var fSum = 0, fRes = 0, bStop = false, fP, fW; for (var i = 0; i < nR1 && !bStop; i++) { for (var j = 0; j < nC1 && !bStop; j++) { if (x[i][j] instanceof cNumber && p[i][j] instanceof cNumber) { fP = p[i][j].getValue(); fW = x[i][j].getValue(); if (fP < 0.0 || fP > 1.0) { bStop = true; } else { fSum += fP; if (fW >= fLo && fW <= fUp) { fRes += fP; } } } else { return new cError(cErrorType.not_available); } } } if (bStop || Math.abs(fSum - 1.0) > 1.0E-7) { return new cError(cErrorType.not_available); } else { return new cNumber(fRes); } } } var arg0 = arg[0], arg1 = arg[1], arg2 = arg[2], arg3 = arg[3] ? arg[3] : new cEmpty(); if (arg0 instanceof cArea || arg0 instanceof cArray) { arg0 = arg0.getMatrix(); } else if (arg0 instanceof cArea3D) { arg0 = arg0.getMatrix()[0]; } else { return this.value = new cError(cErrorType.not_available); } if (arg1 instanceof cArea || arg1 instanceof cArray) { arg1 = arg1.getMatrix(); } else if (arg1 instanceof cArea3D) { arg1 = arg1.getMatrix()[0]; } else { return this.value = new cError(cErrorType.not_available); } if (arg2 instanceof cArea || arg2 instanceof cArea3D) { arg2 = arg2.cross(arguments[1]); } else if (arg2 instanceof cArray) { arg2 = arg2.getElement(0); } if (arg3 instanceof cArea || arg3 instanceof cArea3D) { arg3 = arg3.cross(arguments[1]); } else if (arg3 instanceof cArray) { arg3 = arg3.getElement(0); } arg2 = arg2.tocNumber(); if (!arg3 instanceof cEmpty) { arg3 = arg3.tocNumber(); } if (arg2 instanceof cError) { return this.value = arg2; } if (arg3 instanceof cError) { return this.value = arg3; } return this.value = prob(arg0, arg1, arg2, arg3); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cQUARTILE() { this.name = "QUARTILE"; this.value = null; this.argumentsCurrent = 0; } cQUARTILE.prototype = Object.create(cBaseFunction.prototype); cQUARTILE.prototype.constructor = cQUARTILE; cQUARTILE.prototype.argumentsMin = 2; cQUARTILE.prototype.argumentsMax = 2; cQUARTILE.prototype.numFormat = AscCommonExcel.cNumFormatNone; cQUARTILE.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true, [cElementType.array]); var argClone = oArguments.args; argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function quartile(argArray) { var A = argArray[0]; var fFlag = Math.floor(argArray[1]); var tA = []; for (var i = 0; i < A.length; i++) { for (var j = 0; j < A[i].length; j++) { if (A[i][j] instanceof cError) { return A[i][j]; } else if (A[i][j] instanceof cNumber || A[i][j] instanceof cEmpty) { tA.push(A[i][j].getValue()); } else if (A[i][j] instanceof cBool) { tA.push(A[i][j].tocNumber().getValue()); } } } var nSize = tA.length; if(tA.length < 1 || nSize === 0){ return new cError(cErrorType.not_available); }else if(fFlag < 0.0 || fFlag > 4.0){ return new cError(cErrorType.not_numeric); }else if(nSize === 1){ return new cNumber(tA[0]); } return fFlag === 2 ? getMedian( tA ) : getPercentile( tA, 0.25 * fFlag ); } return this.value = this._findArrayInNumberArguments(oArguments, quartile); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cQUARTILE_EXC() { this.name = "QUARTILE.EXC"; this.value = null; this.argumentsCurrent = 0; } cQUARTILE_EXC.prototype = Object.create(cBaseFunction.prototype); cQUARTILE_EXC.prototype.constructor = cQUARTILE_EXC; cQUARTILE_EXC.prototype.argumentsMin = 2; cQUARTILE_EXC.prototype.argumentsMax = 2; cQUARTILE_EXC.prototype.numFormat = AscCommonExcel.cNumFormatNone; cQUARTILE_EXC.prototype.isXLFN = true; cQUARTILE_EXC.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true, [cElementType.array]); var argClone = oArguments.args; argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function quartile(argArray) { var A = argArray[0]; var fFlag = Math.floor(argArray[1]); var tA = []; for (var i = 0; i < A.length; i++) { for (var j = 0; j < A[i].length; j++) { if (A[i][j] instanceof cError) { return A[i][j]; } else if (A[i][j] instanceof cNumber) { tA.push(A[i][j].getValue()); } else if (A[i][j] instanceof cBool) { tA.push(A[i][j].tocNumber().getValue()); } } } var nSize = tA.length; if(tA.length < 1 || nSize === 0){ return new cError(cErrorType.not_available); }else if(fFlag <= 0.0 || fFlag >= 4.0){ return new cError(cErrorType.not_numeric); }else if(nSize === 1){ return new cNumber(tA[0]); } return fFlag === 2 ? getMedian( tA ) : getPercentileExclusive( tA, 0.25 * fFlag ); } return this.value = this._findArrayInNumberArguments(oArguments, quartile); }; /** * @constructor * @extends {cQUARTILE} */ function cQUARTILE_INC() { cQUARTILE.call(this); this.name = "QUARTILE.INC"; } cQUARTILE_INC.prototype = Object.create(cQUARTILE.prototype); cQUARTILE_INC.prototype.constructor = cQUARTILE_INC; cQUARTILE_INC.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cRANK() { cBaseFunction.call(this, "RANK"); } cRANK.prototype = Object.create(cBaseFunction.prototype); cRANK.prototype.constructor = cRANK; cRANK.prototype.argumentsMin = 2; cRANK.prototype.argumentsMax = 3; cRANK.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true, [null, cElementType.array]); var argClone = oArguments.args; //1 argument - array argClone[0] = argClone[0].tocNumber(); argClone[2] = undefined !== argClone[2] ? argClone[2].tocNumber() : new cNumber(0); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcRank = function(argArray){ var number = argArray[0]; var ref = argArray[1]; var order = argArray[2]; var changedRef = []; for (var i = 0; i < ref.length; i++) { for (var j = 0; j < ref[i].length; j++) { if (ref[i][j] instanceof cError) { return ref[i][j]; } else if (ref[i][j] instanceof cNumber) { changedRef.push(ref[i][j].getValue()); } else if (ref[i][j] instanceof cBool) { changedRef.push(ref[i][j].tocNumber().getValue()); } } } if(!changedRef.length){ return new cError(cErrorType.wrong_value_type); } var res = rank(number, changedRef, order); return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcRank); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cRANK_AVG() { cBaseFunction.call(this, "RANK.AVG"); } cRANK_AVG.prototype = Object.create(cBaseFunction.prototype); cRANK_AVG.prototype.constructor = cRANK_AVG; cRANK_AVG.prototype.argumentsMin = 2; cRANK_AVG.prototype.argumentsMax = 3; cRANK_AVG.prototype.isXLFN = true; cRANK_AVG.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true, [null, cElementType.array]); var argClone = oArguments.args; //1 argument - array argClone[0] = argClone[0].tocNumber(); argClone[2] = undefined !== argClone[2] ? argClone[2].tocNumber() : new cNumber(0); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcRank = function(argArray){ var number = argArray[0]; var ref = argArray[1]; var order = argArray[2]; var changedRef = []; for (var i = 0; i < ref.length; i++) { for (var j = 0; j < ref[i].length; j++) { if (ref[i][j] instanceof cError) { return ref[i][j]; } else if (ref[i][j] instanceof cNumber) { changedRef.push(ref[i][j].getValue()); } else if (ref[i][j] instanceof cBool) { changedRef.push(ref[i][j].tocNumber().getValue()); } } } if(!changedRef.length){ return new cError(cErrorType.wrong_value_type); } var res = rank(number, changedRef, order, true); return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcRank); }; /** * @constructor * @extends {cRANK} */ function cRANK_EQ() { cRANK.call(this); this.name = "RANK.EQ"; } cRANK_EQ.prototype = Object.create(cRANK.prototype); cRANK_EQ.prototype.constructor = cRANK_EQ; cRANK_EQ.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cRSQ() { this.name = "RSQ"; this.value = null; this.argumentsCurrent = 0; } cRSQ.prototype = Object.create(cBaseFunction.prototype); cRSQ.prototype.constructor = cRSQ; cRSQ.prototype.argumentsMin = 2; cRSQ.prototype.argumentsMax = 2; cRSQ.prototype.Calculate = function (arg) { function rsq(x, y) { var sumXDeltaYDelta = 0, sqrXDelta = 0, sqrYDelta = 0, _x = 0, _y = 0, xLength = 0, i; if (x.length != y.length) { return new cError(cErrorType.not_available); } for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } _x += x[i].getValue(); _y += y[i].getValue(); xLength++; } _x /= xLength; _y /= xLength; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } sumXDeltaYDelta += (x[i].getValue() - _x) * (y[i].getValue() - _y); sqrXDelta += (x[i].getValue() - _x) * (x[i].getValue() - _x); sqrYDelta += (y[i].getValue() - _y) * (y[i].getValue() - _y); } if (sqrXDelta == 0 || sqrYDelta == 0) { return new cError(cErrorType.division_by_zero); } else { return new cNumber(Math.pow(sumXDeltaYDelta / Math.sqrt(sqrXDelta * sqrYDelta), 2)); } } var arg0 = arg[0], arg1 = arg[1], arr0 = [], arr1 = []; if (arg0 instanceof cArea) { arr0 = arg0.getValue(); } else if (arg0 instanceof cArray) { arg0.foreach(function (elem) { arr0.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } if (arg1 instanceof cArea) { arr1 = arg1.getValue(); } else if (arg1 instanceof cArray) { arg1.foreach(function (elem) { arr1.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } return this.value = rsq(arr0, arr1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cSKEW() { this.name = "SKEW"; this.value = null; this.argumentsCurrent = 0; } cSKEW.prototype = Object.create(cBaseFunction.prototype); cSKEW.prototype.constructor = cSKEW; cSKEW.prototype.argumentsMin = 1; cSKEW.prototype.Calculate = function (arg) { var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber) { arr0.push(a); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString) { continue; } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = skew(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cSKEW_P() { this.name = "SKEW.P"; this.value = null; this.argumentsCurrent = 0; } cSKEW_P.prototype = Object.create(cBaseFunction.prototype); cSKEW_P.prototype.constructor = cSKEW_P; cSKEW_P.prototype.argumentsMin = 1; cSKEW_P.prototype.isXLFN = true; cSKEW_P.prototype.Calculate = function (arg) { var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber) { arr0.push(a); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString) { continue; } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = skew(arr0, true); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cSLOPE() { this.name = "SLOPE"; this.value = null; this.argumentsCurrent = 0; } cSLOPE.prototype = Object.create(cBaseFunction.prototype); cSLOPE.prototype.constructor = cSLOPE; cSLOPE.prototype.argumentsMin = 2; cSLOPE.prototype.argumentsMax = 2; cSLOPE.prototype.Calculate = function (arg) { function slope(y, x) { var sumXDeltaYDelta = 0, sqrXDelta = 0, _x = 0, _y = 0, xLength = 0, i; if (x.length != y.length) { return new cError(cErrorType.not_available); } for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } _x += x[i].getValue(); _y += y[i].getValue(); xLength++; } _x /= xLength; _y /= xLength; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } sumXDeltaYDelta += (x[i].getValue() - _x) * (y[i].getValue() - _y); sqrXDelta += (x[i].getValue() - _x) * (x[i].getValue() - _x); } if (sqrXDelta == 0) { return new cError(cErrorType.division_by_zero); } else { return new cNumber(sumXDeltaYDelta / sqrXDelta); } } var arg0 = arg[0], arg1 = arg[1], arr0 = [], arr1 = []; if (arg0 instanceof cArea) { arr0 = arg0.getValue(); } else if (arg0 instanceof cArray) { arg0.foreach(function (elem) { arr0.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } if (arg1 instanceof cArea) { arr1 = arg1.getValue(); } else if (arg1 instanceof cArray) { arg1.foreach(function (elem) { arr1.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } return this.value = slope(arr0, arr1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cSMALL() { this.name = "SMALL"; this.value = null; this.argumentsCurrent = 0; } cSMALL.prototype = Object.create(cBaseFunction.prototype); cSMALL.prototype.constructor = cSMALL; cSMALL.prototype.argumentsMin = 2; cSMALL.prototype.argumentsMax = 2; cSMALL.prototype.numFormat = AscCommonExcel.cNumFormatNone; cSMALL.prototype.Calculate = function (arg) { var retArr = new cArray(); function frequency(A, k) { var tA = []; for (var i = 0; i < A.length; i++) { for (var j = 0; j < A[i].length; j++) { if (A[i][j] instanceof cError) { return A[i][j]; } else if (A[i][j] instanceof cNumber) { tA.push(A[i][j].getValue()); } else if (A[i][j] instanceof cBool) { tA.push(A[i][j].tocNumber().getValue()); } } } tA.sort(fSortAscending); if (k.getValue() > tA.length || k.getValue() <= 0) { return new cError(cErrorType.not_available); } else { return new cNumber(tA[k.getValue() - 1]); } } function actionArray(elem, r, c) { var e = elem.tocNumber(); if (e instanceof cError) { retArr.addElement(e); } retArr.addElement(frequency(arg0, e)); } var arg0 = arg[0], arg1 = arg[1]; if (arg0 instanceof cArea || arg0 instanceof cArray) { arg0 = arg0.getMatrix(this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); } else if (arg0 instanceof cArea3D) { arg0 = arg0.getMatrix(this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg)[0]; } else { return this.value = new cError(cErrorType.not_numeric); } if (arg1 instanceof cArea || arg1 instanceof cArea3D) { arg1 = arg1.cross(arguments[1]); } else if (arg1 instanceof cArray) { // arg1 = arg1.getElement( 0 ); arg1.foreach(actionArray); return this.value = retArr; } return this.value = frequency(arg0, arg1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cSTANDARDIZE() { this.name = "STANDARDIZE"; this.value = null; this.argumentsCurrent = 0; } cSTANDARDIZE.prototype = Object.create(cBaseFunction.prototype); cSTANDARDIZE.prototype.constructor = cSTANDARDIZE; cSTANDARDIZE.prototype.argumentsMin = 3; cSTANDARDIZE.prototype.argumentsMax = 3; cSTANDARDIZE.prototype.Calculate = function (arg) { var arg0 = arg[0], arg1 = arg[1], arg2 = arg[2]; function standardize(x, mue, sigma) { if (sigma <= 0.0) { return new cError(cErrorType.not_numeric); } else { return new cNumber((x - mue) / sigma); } } if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } else if (arg0 instanceof cArray) { arg0 = arg0.getElement(0); } if (arg1 instanceof cArea || arg1 instanceof cArea3D) { arg1 = arg1.cross(arguments[1]); } else if (arg1 instanceof cArray) { arg1 = arg1.getElement(0); } if (arg2 instanceof cArea || arg2 instanceof cArea3D) { arg2 = arg2.cross(arguments[1]); } else if (arg2 instanceof cArray) { arg2 = arg2.getElement(0); } arg0 = arg0.tocNumber(); arg1 = arg1.tocNumber(); arg2 = arg2.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } if (arg1 instanceof cError) { return this.value = arg1; } if (arg2 instanceof cError) { return this.value = arg2; } return this.value = standardize(arg0.getValue(), arg1.getValue(), arg2.getValue()); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cSTDEV() { this.name = "STDEV"; this.value = null; this.argumentsCurrent = 0; } cSTDEV.prototype = Object.create(cBaseFunction.prototype); cSTDEV.prototype.constructor = cSTDEV; cSTDEV.prototype.argumentsMin = 1; cSTDEV.prototype.numFormat = AscCommonExcel.cNumFormatNone; cSTDEV.prototype.Calculate = function (arg) { var i, element, count = 0, sum = new cNumber(0), member = []; for (i = 0; i < arg.length; i++) { element = arg[i]; if (cElementType.cell === element.type || cElementType.cell3D === element.type) { if (!this.checkExclude || !element.isHidden(this.excludeHiddenRows)) { var _argV = element.getValue(); if (cElementType.number === _argV.type) { member.push(_argV); sum = _func[sum.type][_argV.type](sum, _argV, "+"); count++; } } } else if (cElementType.cellsRange === element.type || cElementType.cellsRange3D === element.type) { var _argAreaValue = element.getValue(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); for (var j = 0; j < _argAreaValue.length; j++) { var __arg = _argAreaValue[j]; if (cElementType.number === __arg.type) { member.push(__arg); sum = _func[sum.type][__arg.type](sum, __arg, "+"); count++; } } } else if (cElementType.array === element.type) { element.foreach(function (elem) { var e = elem.tocNumber(); if (cElementType.number === e.type) { member.push(e); sum = _func[sum.type][e.type](sum, e, "+"); count++; } }) } else { element = element.tocNumber(); if (cElementType.number === element.type) { member.push(element); sum = _func[sum.type][element.type](sum, element, "+"); count++; } } } var average = sum.getValue() / count, res = 0, av; for (i = 0; i < member.length; i++) { av = member[i] - average; res += av * av; } if(1 === count){ return new cError(cErrorType.division_by_zero); } return this.value = new cNumber(Math.sqrt(res / (count - 1))); }; /** * @constructor * @extends {cSTDEV} */ function cSTDEV_S() { cSTDEV.call(this); this.name = "STDEV.S"; } cSTDEV_S.prototype = Object.create(cSTDEV.prototype); cSTDEV_S.prototype.constructor = cSTDEV_S; cSTDEV_S.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cSTDEVA() { this.name = "STDEVA"; this.value = null; this.argumentsCurrent = 0; } cSTDEVA.prototype = Object.create(cBaseFunction.prototype); cSTDEVA.prototype.constructor = cSTDEVA; cSTDEVA.prototype.argumentsMin = 1; cSTDEVA.prototype.Calculate = function (arg) { var count = 0, sum = new cNumber(0), member = [], i; for (i = 0; i < arg.length; i++) { var _arg = arg[i]; if (_arg instanceof cRef || _arg instanceof cRef3D) { var _argV = _arg.getValue().tocNumber(); if (_argV instanceof cNumber) { member.push(_argV); sum = _func[sum.type][_argV.type](sum, _argV, "+"); count++; } } else if (_arg instanceof cArea || _arg instanceof cArea3D) { var _argAreaValue = _arg.getValue(); for (var j = 0; j < _argAreaValue.length; j++) { var __arg = _argAreaValue[j].tocNumber(); if (__arg instanceof cNumber) { member.push(__arg); sum = _func[sum.type][__arg.type](sum, __arg, "+"); count++; } } } else if (_arg instanceof cArray) { _arg.foreach(function (elem) { var e = elem.tocNumber(); if (e instanceof cNumber) { member.push(e); sum = _func[sum.type][e.type](sum, e, "+"); count++; } }) } else { _arg = _arg.tocNumber(); if (_arg instanceof cNumber) { member.push(_arg); sum = _func[sum.type][_arg.type](sum, _arg, "+"); count++; } } } var average = sum.getValue() / count, res = 0, av; for (i = 0; i < member.length; i++) { av = member[i] - average; res += av * av; } return this.value = new cNumber(Math.sqrt(res / (count - 1))); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cSTDEVP() { this.name = "STDEVP"; this.value = null; this.argumentsCurrent = 0; } cSTDEVP.prototype = Object.create(cBaseFunction.prototype); cSTDEVP.prototype.constructor = cSTDEVP; cSTDEVP.prototype.argumentsMin = 1; cSTDEVP.prototype.Calculate = function (arg) { function _var(x) { var i, tA = [], sumSQRDeltaX = 0, _x = 0, xLength = 0; for (i = 0; i < x.length; i++) { if (cElementType.number === x[i].type) { _x += x[i].getValue(); tA.push(x[i].getValue()); xLength++; } else if (cElementType.error === x[i].type) { return x[i]; } } _x /= xLength; for (i = 0; i < x.length; i++) { sumSQRDeltaX += (tA[i] - _x) * (tA[i] - _x) } return new cNumber(isNaN(_x) ? new cError(cErrorType.division_by_zero) : Math.sqrt(sumSQRDeltaX / xLength)); } var element, arr0 = []; for (var j = 0; j < arg.length; j++) { element = arg[j]; if (cElementType.cellsRange === element.type || cElementType.cellsRange3D === element.type) { var _arrVal = element.getValue(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); _arrVal.forEach(function (elem) { if (cElementType.number === elem.type || cElementType.error === elem.type) { arr0.push(elem); } }); } else if (cElementType.cell === element.type || cElementType.cell3D === element.type) { if (!this.checkExclude || !element.isHidden(this.excludeHiddenRows)) { var a = element.getValue(); if (cElementType.number === a.type || cElementType.error === a.type) { arr0.push(a); } } } else if (cElementType.array === element.type) { element.foreach(function (elem) { if (cElementType.number === elem.type || cElementType.error === elem.type) { arr0.push(elem); } }); } else if (cElementType.number === element.type || cElementType.bool === element.type) { arr0.push(element.tocNumber()); } else if (cElementType.string === element.type || cElementType.empty === element.type) { arr0.push(new cNumber(0)); } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = _var(arr0); }; /** * @constructor * @extends {cSTDEVP} */ function cSTDEV_P() { cSTDEVP.call(this); this.name = "STDEV.P"; } cSTDEV_P.prototype = Object.create(cSTDEVP.prototype); cSTDEV_P.prototype.constructor = cSTDEV_P; cSTDEV_P.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cSTDEVPA() { this.name = "STDEVPA"; this.value = null; this.argumentsCurrent = 0; } cSTDEVPA.prototype = Object.create(cBaseFunction.prototype); cSTDEVPA.prototype.constructor = cSTDEVPA; cSTDEVPA.prototype.argumentsMin = 1; cSTDEVPA.prototype.Calculate = function (arg) { function _var(x) { var tA = [], sumSQRDeltaX = 0, _x = 0, xLength = 0, i; for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { _x += x[i].getValue(); tA.push(x[i].getValue()); xLength++; } else if (x[i] instanceof cError) { return x[i]; } } _x /= xLength; for (i = 0; i < x.length; i++) { sumSQRDeltaX += (tA[i] - _x) * (tA[i] - _x) } return new cNumber(Math.sqrt(sumSQRDeltaX / xLength)); } var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber || elem instanceof cError) { arr0.push(elem); } else if (elem instanceof cBool) { arr0.push(elem.tocNumber()); } else if (elem instanceof cString) { arr0.push(new cNumber(0)); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber || a instanceof cError) { arr0.push(a); } else if (a instanceof cBool) { arr0.push(a.tocNumber()); } else if (a instanceof cString) { arr0.push(new cNumber(0)); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber || elem instanceof cError) { arr0.push(elem); } else if (elem instanceof cBool) { arr0.push(elem.tocNumber()); } else if (elem instanceof cString) { arr0.push(new cNumber(0)); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString) { arr0.push(new cNumber(0)); } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = _var(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cSTEYX() { this.name = "STEYX"; this.value = null; this.argumentsCurrent = 0; } cSTEYX.prototype = Object.create(cBaseFunction.prototype); cSTEYX.prototype.constructor = cSTEYX; cSTEYX.prototype.argumentsMin = 2; cSTEYX.prototype.argumentsMax = 2; cSTEYX.prototype.Calculate = function (arg) { function steyx(y, x) { var sumXDeltaYDelta = 0, sqrXDelta = 0, sqrYDelta = 0, _x = 0, _y = 0, xLength = 0, i; if (x.length != y.length) { return new cError(cErrorType.not_available); } for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } _x += x[i].getValue(); _y += y[i].getValue(); xLength++; } _x /= xLength; _y /= xLength; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } sumXDeltaYDelta += (x[i].getValue() - _x) * (y[i].getValue() - _y); sqrXDelta += (x[i].getValue() - _x) * (x[i].getValue() - _x); sqrYDelta += (y[i].getValue() - _y) * (y[i].getValue() - _y); } if (sqrXDelta == 0 || sqrYDelta == 0 || xLength < 3) { return new cError(cErrorType.division_by_zero); } else { return new cNumber(Math.sqrt( (1 / (xLength - 2)) * (sqrYDelta - sumXDeltaYDelta * sumXDeltaYDelta / sqrXDelta))); } } var arg0 = arg[0], arg1 = arg[1], arr0 = [], arr1 = []; if (arg0 instanceof cArea) { arr0 = arg0.getValue(); } else if (arg0 instanceof cArray) { arg0.foreach(function (elem) { arr0.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } if (arg1 instanceof cArea) { arr1 = arg1.getValue(); } else if (arg1 instanceof cArray) { arg1.foreach(function (elem) { arr1.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } return this.value = steyx(arr0, arr1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cTDIST() { cBaseFunction.call(this, "TDIST"); } cTDIST.prototype = Object.create(cBaseFunction.prototype); cTDIST.prototype.constructor = cTDIST; cTDIST.prototype.argumentsMin = 3; cTDIST.prototype.argumentsMax = 3; cTDIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var T = argArray[0]; var fDF = argArray[1]; var nType = argArray[2]; var res = getTDist(T, fDF, nType); return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; if (argClone[1].getValue() < 1 || argClone[0].getValue() < 0 || (argClone[2].getValue() !== 1 && argClone[2].getValue() !== 2) ){ return this.value = new cError(cErrorType.not_numeric); } return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cT_DIST() { cBaseFunction.call(this, "T.DIST"); } cT_DIST.prototype = Object.create(cBaseFunction.prototype); cT_DIST.prototype.constructor = cT_DIST; cT_DIST.prototype.argumentsMin = 3; cT_DIST.prototype.argumentsMax = 3; cT_DIST.prototype.isXLFN = true; cT_DIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var T = argArray[0]; var fDF = argArray[1]; var bCumulative = argArray[2]; var res = getTDist(T, fDF, bCumulative ? 4 : 3); return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; if (argClone[1].getValue() < 1 ){ return this.value = new cError(cErrorType.not_numeric); } return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cT_DIST_2T() { cBaseFunction.call(this, "T.DIST.2T"); } cT_DIST_2T.prototype = Object.create(cBaseFunction.prototype); cT_DIST_2T.prototype.constructor = cT_DIST_2T; cT_DIST_2T.prototype.argumentsMin = 2; cT_DIST_2T.prototype.argumentsMax = 2; cT_DIST_2T.prototype.isXLFN = true; cT_DIST_2T.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var T = argArray[0]; var fDF = argArray[1]; if (fDF < 1 || T < 0){ return new cError(cErrorType.not_numeric); } var res = getTDist(T, fDF, 2); return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cT_DIST_RT() { cBaseFunction.call(this, "T.DIST.RT"); } cT_DIST_RT.prototype = Object.create(cBaseFunction.prototype); cT_DIST_RT.prototype.constructor = cT_DIST_RT; cT_DIST_RT.prototype.argumentsMin = 2; cT_DIST_RT.prototype.argumentsMax = 2; cT_DIST_RT.prototype.isXLFN = true; cT_DIST_RT.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var T = argArray[0]; var fDF = argArray[1]; if (fDF < 1){ return new cError(cErrorType.not_numeric); } var res = getTDist(T, fDF, 1); if ( T < 0 ){ res = 1 - res; } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cT_INV() { cBaseFunction.call(this, "T.INV"); } cT_INV.prototype = Object.create(cBaseFunction.prototype); cT_INV.prototype.constructor = cT_INV; cT_INV.prototype.argumentsMin = 2; cT_INV.prototype.argumentsMax = 2; cT_INV.prototype.isXLFN = true; cT_INV.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var fP = argArray[0]; var fDF = parseInt(argArray[1]); if ( fDF < 1.0 || fP <= 0.0 || fP > 1.0 ){ return new cError(cErrorType.not_numeric); } var aFunc, oVal, bConvError, res = null; if ( fP === 1.0 ){ return new cError(cErrorType.not_numeric); }else if(fP < 0.5){ aFunc = new TDISTFUNCTION(1 - fP, fDF, 4); oVal = iterateInverse(aFunc, fDF * 0.5, fDF); bConvError = oVal.bError; res = - oVal.val; }else{ aFunc = new TDISTFUNCTION(fP, fDF, 4); oVal = iterateInverse(aFunc, fDF * 0.5, fDF); bConvError = oVal.bError; res = oVal.val; } if (bConvError){ return new cError(cErrorType.not_numeric); } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cT_INV_2T() { cBaseFunction.call(this, "T.INV.2T"); } cT_INV_2T.prototype = Object.create(cBaseFunction.prototype); cT_INV_2T.prototype.constructor = cT_INV_2T; cT_INV_2T.prototype.argumentsMin = 2; cT_INV_2T.prototype.argumentsMax = 2; cT_INV_2T.prototype.isXLFN = true; cT_INV_2T.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var fP = argArray[0]; var fDF = parseInt(argArray[1]); //ms игнорирует услвие fP > 1. сделал как в документации if ( fDF < 1.0 || fP <= 0 || fP > 1 ){ return new cError(cErrorType.not_numeric); } var aFunc = new TDISTFUNCTION(fP, fDF, 2); var oVal = iterateInverse(aFunc, fDF * 0.5, fDF); var bConvError = oVal.bError; var res = oVal.val; if (bConvError){ return new cError(cErrorType.not_numeric); } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {cT_INV_2T} */ function cTINV() { cT_INV_2T.call(this); this.name = "TINV"; } cTINV.prototype = Object.create(cT_INV_2T.prototype); cTINV.prototype.constructor = cTINV; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cTREND() { cBaseFunction.call(this, "TREND"); } cTREND.prototype = Object.create(cBaseFunction.prototype); cTREND.prototype.constructor = cTREND; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cTRIMMEAN() { this.name = "TRIMMEAN"; this.value = null; this.argumentsCurrent = 0; } cTRIMMEAN.prototype = Object.create(cBaseFunction.prototype); cTRIMMEAN.prototype.constructor = cTRIMMEAN; cTRIMMEAN.prototype.argumentsMin = 2; cTRIMMEAN.prototype.argumentsMax = 2; cTRIMMEAN.prototype.Calculate = function (arg) { var arg2 = [arg[0], arg[1]]; //если первое значение строка if(cElementType.string === arg[0].type || cElementType.bool === arg[0].type){ return this.value = new cError(cErrorType.wrong_value_type); } //если первое значение число if(cElementType.number === arg[0].type){ arg2[0] = new cArray(); arg2[0].addElement(arg[0]); } var oArguments = this._prepareArguments(arg2, arguments[1], true, [cElementType.array]); var argClone = oArguments.args; argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTrimMean = function(argArray){ var arg0 = argArray[0]; var arg1 = argArray[1]; if (arg1 < 0.0 || arg1 >= 1.0){ return new cError(cErrorType.not_numeric); } var arr = []; for (var i = 0; i < arg0.length; i++) { for (var j = 0; j < arg0[i].length; j++) { if (cElementType.number === arg0[i][j].type) { arr.push(arg0[i][j].getValue()); } } } var aSortArray = arr.sort(fSortAscending); var nSize = aSortArray.length; if (nSize == 0){ return new cError(cErrorType.not_numeric); }else{ var nIndex = Math.floor(arg1 * nSize); if (nIndex % 2 !== 0){ nIndex--; } nIndex /= 2; var fSum = 0.0; for (var i = nIndex; i < nSize-nIndex; i++){ fSum += aSortArray[i]; } return new cNumber(fSum / (nSize - 2*nIndex)); } }; return this.value = this._findArrayInNumberArguments(oArguments, calcTrimMean); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cTTEST() { this.name = "TTEST"; this.value = null; this.argumentsCurrent = 0; } cTTEST.prototype = Object.create(cBaseFunction.prototype); cTTEST.prototype.constructor = cTTEST; cTTEST.prototype.argumentsMin = 4; cTTEST.prototype.argumentsMax = 4; cTTEST.prototype.Calculate = function (arg) { var arg2 = [arg[0], arg[1], arg[2], arg[3]]; //если первое или второе значение строка if(cElementType.string === arg[0].type || cElementType.bool === arg[0].type){ return this.value = new cError(cErrorType.wrong_value_type); } if(cElementType.string === arg[1].type || cElementType.bool === arg[1].type){ return this.value = new cError(cErrorType.wrong_value_type); } //если первое или второе значение число if(cElementType.number === arg[0].type){ arg2[0] = new cArray(); arg2[0].addElement(arg[0]); } if(cElementType.number === arg[1].type){ arg2[1] = new cArray(); arg2[1].addElement(arg[1]); } var oArguments = this._prepareArguments(arg2, arguments[1], true, [cElementType.array, cElementType.array]); var argClone = oArguments.args; argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3].tocNumber();//bool var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTTest = function(argArray){ var arg0 = argArray[0]; var arg1 = argArray[1]; var arg2 = parseInt(argArray[2]); var arg3 = parseInt(argArray[3]); if(!(arg2 === 1 || arg2 === 2)){ return new cError(cErrorType.not_numeric); } return tTest(arg0, arg1, arg2, arg3); }; return this.value = this._findArrayInNumberArguments(oArguments, calcTTest); }; /** * @constructor * @extends {cTTEST} */ function cT_TEST() { cTTEST.call(this); this.name = "T.TEST"; } cT_TEST.prototype = Object.create(cTTEST.prototype); cT_TEST.prototype.constructor = cT_TEST; cT_TEST.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cVAR() { this.name = "VAR"; this.value = null; this.argumentsCurrent = 0; } cVAR.prototype = Object.create(cBaseFunction.prototype); cVAR.prototype.constructor = cVAR; cVAR.prototype.argumentsMin = 1; cVAR.prototype.Calculate = function (arg) { function _var(x) { if (x.length < 1) { return new cError(cErrorType.division_by_zero); } var i, tA = [], sumSQRDeltaX = 0, _x = 0, xLength = 0; for (i = 0; i < x.length; i++) { if (cElementType.number === x[i].type) { _x += x[i].getValue(); tA.push(x[i].getValue()); xLength++; } else if (cElementType.error === x[i].type) { return x[i]; } } _x /= xLength; for (i = 0; i < x.length; i++) { sumSQRDeltaX += (tA[i] - _x) * (tA[i] - _x) } return new cNumber(sumSQRDeltaX / (xLength - 1)) } var element, arr0 = []; for (var j = 0; j < arg.length; j++) { element = arg[j]; if (cElementType.cellsRange === element.type || cElementType.cellsRange3D === element.type) { var _arrVal = element.getValue(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); _arrVal.forEach(function (elem) { if (cElementType.number === elem.type || cElementType.error === elem.type) { arr0.push(elem); } }); } else if (cElementType.cell === element.type || cElementType.cell3D === element.type) { if (!this.checkExclude || !element.isHidden(this.excludeHiddenRows)) { var a = element.getValue(); if (cElementType.number === a.type || cElementType.error === a.type) { arr0.push(a); } } } else if (cElementType.array === element.type) { element.foreach(function (elem) { if (cElementType.number === elem.type || cElementType.error === elem.type) { arr0.push(elem); } }); } else if (cElementType.number === element.type || cElementType.bool === element.type) { arr0.push(element.tocNumber()); } else if (cElementType.string === element.type || cElementType.empty === element.type) { continue; } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = _var(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cVARA() { this.name = "VARA"; this.value = null; this.argumentsCurrent = 0; } cVARA.prototype = Object.create(cBaseFunction.prototype); cVARA.prototype.constructor = cVARA; cVARA.prototype.argumentsMin = 1; cVARA.prototype.Calculate = function (arg) { function _var(x) { if (x.length < 1) { return new cError(cErrorType.division_by_zero); } var tA = [], sumSQRDeltaX = 0, _x = 0, xLength = 0, i; for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { _x += x[i].getValue(); tA.push(x[i].getValue()); xLength++; } else if (x[i] instanceof cError) { return x[i]; } } _x /= xLength; for (i = 0; i < x.length; i++) { sumSQRDeltaX += (tA[i] - _x) * (tA[i] - _x) } return new cNumber(sumSQRDeltaX / (xLength - 1)) } var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber || elem instanceof cError) { arr0.push(elem); } else if (elem instanceof cBool) { arr0.push(elem.tocNumber()); } else if (elem instanceof cString) { arr0.push(new cNumber(0)); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber || a instanceof cError) { arr0.push(a); } else if (a instanceof cBool) { arr0.push(a.tocNumber()); } else if (a instanceof cString) { arr0.push(new cNumber(0)); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber || elem instanceof cError) { arr0.push(elem); } else if (elem instanceof cBool) { arr0.push(elem.tocNumber()); } else if (a instanceof cString) { arr0.push(new cNumber(0)); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString) { arr0.push(new cNumber(0)); } else if (arg[j] instanceof cError) { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = _var(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cVARP() { this.name = "VARP"; this.value = null; this.argumentsCurrent = 0; } cVARP.prototype = Object.create(cBaseFunction.prototype); cVARP.prototype.constructor = cVARP; cVARP.prototype.argumentsMin = 1; cVARP.prototype.Calculate = function (arg) { function _var(x) { if (x.length < 1) { return new cError(cErrorType.division_by_zero); } var tA = [], sumSQRDeltaX = 0, _x = 0, xLength = 0, i; for (i = 0; i < x.length; i++) { if (cElementType.number === x[i].type) { _x += x[i].getValue(); tA.push(x[i].getValue()); xLength++; } else if (cElementType.error === x[i].type) { return x[i]; } } _x /= xLength; for (i = 0; i < x.length; i++) { sumSQRDeltaX += (tA[i] - _x) * (tA[i] - _x); } return new cNumber(sumSQRDeltaX / xLength); } var element, arr0 = []; for (var j = 0; j < arg.length; j++) { element = arg[j]; if (cElementType.cellsRange === element.type || cElementType.cellsRange3D === element.type) { var _arrVal = element.getValue(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); _arrVal.forEach(function (elem) { if (cElementType.number === elem.type || cElementType.error === elem.type) { arr0.push(elem); } }); } else if (cElementType.cell === element.type || cElementType.cell3D === element.type) { if (!this.checkExclude || !element.isHidden(this.excludeHiddenRows)) { var a = element.getValue(); if (cElementType.number === a.type || cElementType.error === a.type) { arr0.push(a); } } } else if (cElementType.array === element.type) { element.foreach(function (elem) { if (cElementType.number === elem.type || cElementType.error === elem.type) { arr0.push(elem); } }); } else if (cElementType.number === element.type || cElementType.bool === element.type) { arr0.push(element.tocNumber()); } else if (cElementType.string === element.type || cElementType.empty === element.type) { arr0.push(new cNumber(0)); } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = _var(arr0); }; /** * @constructor * @extends {cVARP} */ function cVAR_P() { cVARP.call(this); this.name = "VAR.P"; } cVAR_P.prototype = Object.create(cVARP.prototype); cVAR_P.prototype.constructor = cVAR_P; cVAR_P.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cVAR_S() { this.name = "VAR.S"; this.value = null; this.argumentsCurrent = 0; } cVAR_S.prototype = Object.create(cBaseFunction.prototype); cVAR_S.prototype.constructor = cVAR_S; cVAR_S.prototype.argumentsMin = 1; cVAR_S.prototype.isXLFN = true; cVAR_S.prototype.Calculate = function (arg) { function _var(x) { if (x.length <= 1) { return new cError(cErrorType.division_by_zero); } var tA = [], sumSQRDeltaX = 0, _x = 0, xLength = 0, i; for (i = 0; i < x.length; i++) { if (cElementType.number === x[i].type) { _x += x[i].getValue(); tA.push(x[i].getValue()); xLength++; } else if (cElementType.error === x[i].type) { return x[i]; } } _x /= xLength; for (i = 0; i < x.length; i++) { sumSQRDeltaX += (tA[i] - _x) * (tA[i] - _x); } return new cNumber(sumSQRDeltaX / (xLength - 1)); } var element, arr0 = []; for (var j = 0; j < arg.length; j++) { element = arg[j]; if (cElementType.cellsRange === element.type || cElementType.cellsRange3D === element.type) { var _arrVal = element.getValue(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); _arrVal.forEach(function (elem) { if (cElementType.number === elem.type || cElementType.error === elem.type) { arr0.push(elem); } }); } else if (cElementType.cell === element.type || cElementType.cell3D === element.type) { if (!this.checkExclude || !element.isHidden(this.excludeHiddenRows)) { var a = element.getValue(); if (cElementType.number === a.type || cElementType.error === a.type) { arr0.push(a); } } } else if (cElementType.array === element.type) { element.foreach(function (elem) { if (cElementType.number === elem.type || cElementType.error === elem.type) { arr0.push(elem); } }); } else if (cElementType.number === element.type || cElementType.bool === element.type) { arr0.push(element.tocNumber()); } else if (cElementType.string === element.type || cElementType.empty === element.type) { arr0.push(new cNumber(0)); } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = _var(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cVARdotP() { this.name = "VAR.P"; this.value = null; this.argumentsCurrent = 0; } cVARdotP.prototype = Object.create(cBaseFunction.prototype); cVARdotP.prototype.constructor = cVARdotP; cVARdotP.prototype.argumentsMin = 1; cVARdotP.prototype.Calculate = cVARP.prototype.Calculate; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cVARPA() { this.name = "VARPA"; this.value = null; this.argumentsCurrent = 0; } cVARPA.prototype = Object.create(cBaseFunction.prototype); cVARPA.prototype.constructor = cVARPA; cVARPA.prototype.argumentsMin = 1; cVARPA.prototype.Calculate = function (arg) { function _var(x) { if (x.length < 1) { return new cError(cErrorType.division_by_zero); } var tA = [], sumSQRDeltaX = 0, _x = 0, xLength = 0, i; for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { _x += x[i].getValue(); tA.push(x[i].getValue()); xLength++; } else if (x[i] instanceof cError) { return x[i]; } } _x /= xLength; for (i = 0; i < x.length; i++) { sumSQRDeltaX += (tA[i] - _x) * (tA[i] - _x) } return new cNumber(sumSQRDeltaX / xLength); } var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber || elem instanceof cError) { arr0.push(elem); } else if (elem instanceof cBool) { arr0.push(elem.tocNumber()); } else if (elem instanceof cString) { arr0.push(new cNumber(0)); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber || a instanceof cError) { arr0.push(a); } else if (a instanceof cBool) { arr0.push(a.tocNumber()); } else if (a instanceof cString) { arr0.push(new cNumber(0)); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber || elem instanceof cError) { arr0.push(elem); } else if (elem instanceof cBool) { arr0.push(elem.tocNumber()); } else if (elem instanceof cString) { arr0.push(new cNumber(0)); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString) { arr0.push(new cNumber(0)); } else if (elem instanceof cError) { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = _var(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cWEIBULL() { this.name = "WEIBULL"; this.value = null; this.argumentsCurrent = 0; } cWEIBULL.prototype = Object.create(cBaseFunction.prototype); cWEIBULL.prototype.constructor = cWEIBULL; cWEIBULL.prototype.argumentsMin = 4; cWEIBULL.prototype.argumentsMax = 4; cWEIBULL.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcWeibull = function(argArray){ var x = argArray[0]; var alpha = argArray[1]; var beta = argArray[2]; var kum = argArray[3]; var res; if (alpha <= 0 || beta <= 0 || x < 0){ return new cError(cErrorType.not_numeric); } else if (kum === 0){ res = alpha / Math.pow(beta,alpha) * Math.pow(x,alpha-1.0) * Math.exp(-Math.pow(x/beta,alpha)); }else{ res = 1.0 - Math.exp(-Math.pow(x / beta, alpha)); } return new cNumber(res); }; return this.value = this._findArrayInNumberArguments(oArguments, calcWeibull); }; /** * @constructor * @extends {cRANK} */ function cWEIBULL_DIST() { cWEIBULL.call(this); this.name = "WEIBULL.DIST"; } cWEIBULL_DIST.prototype = Object.create(cWEIBULL.prototype); cWEIBULL_DIST.prototype.constructor = cWEIBULL_DIST; cWEIBULL_DIST.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cZTEST() { this.name = "ZTEST"; this.value = null; this.argumentsCurrent = 0; } cZTEST.prototype = Object.create(cBaseFunction.prototype); cZTEST.prototype.constructor = cZTEST; cZTEST.prototype.argumentsMin = 2; cZTEST.prototype.argumentsMax = 3; cZTEST.prototype.Calculate = function (arg) { var arg2 = arg[2] ? [arg[0], arg[1], arg[2]] : [arg[0], arg[1]]; //если первое или второе значение строка if(cElementType.string === arg[0].type || cElementType.bool === arg[0].type){ return this.value = new cError(cErrorType.wrong_value_type); } //если первое или второе значение число if(cElementType.number === arg[0].type){ arg2[0] = new cArray(); arg2[0].addElement(arg[0]); } var oArguments = this._prepareArguments(arg2, arguments[1], true, [cElementType.array]); var argClone = oArguments.args; argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2] ? argClone[2].tocNumber() : new AscCommonExcel.cUndefined(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function calcZTest(argArray) { var arg0 = argArray[0]; var x = argArray[1]; var sigma = argArray[2]; if ( sigma !== undefined && sigma <= 0 ){ return new cError(cErrorType.not_numeric); } var nC1 = arg0.length; var nR1 = arg0[0].length; var fSum = 0.0; var fSumSqr = 0.0; var fVal; var rValCount = 0.0; for (var i = 0; i < nC1; i++){ for (var j = 0; j < nR1; j++){ if(cElementType.number !== arg0[i][j].type || cElementType.number !== arg0[i][j].type){ continue; } fVal = arg0[i][j].getValue(); fSum += fVal; fSumSqr += fVal*fVal; rValCount++; } } var res; if (rValCount <= 1.0){ return new cError(cErrorType.division_by_zero); }else{ var mue = fSum / rValCount; if (undefined === sigma){ sigma = (fSumSqr - fSum * fSum / rValCount) / (rValCount - 1.0); res = 0.5 - gauss((mue - x) / Math.sqrt(sigma / rValCount)); }else{ res = 0.5 - gauss((mue - x) * Math.sqrt(rValCount) / sigma); } } return new cNumber(res); } return this.value = this._findArrayInNumberArguments(oArguments, calcZTest); }; /** * @constructor * @extends {cZTEST} */ function cZ_TEST() { cZTEST.call(this); this.name = "Z.TEST"; } cZ_TEST.prototype = Object.create(cZTEST.prototype); cZ_TEST.prototype.constructor = cZ_TEST; cZ_TEST.prototype.isXLFN = true; //----------------------------------------------------------export---------------------------------------------------- window['AscCommonExcel'] = window['AscCommonExcel'] || {}; window['AscCommonExcel'].phi = phi; window['AscCommonExcel'].gauss = gauss; window['AscCommonExcel'].gaussinv = gaussinv; window['AscCommonExcel'].getPercentile = getPercentile; window['AscCommonExcel'].cAVERAGE = cAVERAGE; window['AscCommonExcel'].cCOUNT = cCOUNT; window['AscCommonExcel'].cCOUNTA = cCOUNTA; window['AscCommonExcel'].cMAX = cMAX; window['AscCommonExcel'].cMIN = cMIN; window['AscCommonExcel'].cSTDEV = cSTDEV; window['AscCommonExcel'].cSTDEVP = cSTDEVP; window['AscCommonExcel'].cVAR = cVAR; window['AscCommonExcel'].cVARP = cVARP; window['AscCommonExcel'].cLARGE = cLARGE; window['AscCommonExcel'].cSMALL = cSMALL; window['AscCommonExcel'].cMEDIAN = cMEDIAN; window['AscCommonExcel'].cSTDEV_S = cSTDEV_S; window['AscCommonExcel'].cSTDEV_P = cSTDEV_P; window['AscCommonExcel'].cVAR_S = cVAR_S; window['AscCommonExcel'].cVAR_P = cVAR_P; window['AscCommonExcel'].cMODE_SNGL = cMODE_SNGL; window['AscCommonExcel'].cPERCENTILE_INC = cPERCENTILE_INC; window['AscCommonExcel'].cQUARTILE_INC = cQUARTILE_INC; window['AscCommonExcel'].cPERCENTILE_EXC = cPERCENTILE_EXC; window['AscCommonExcel'].cQUARTILE_EXC = cQUARTILE_EXC; })(window);
cell/model/FormulaObjects/statisticalFunctions.js
/* * (c) Copyright Ascensio System SIA 2010-2017 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, * EU, LV-1021. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ "use strict"; (/** * @param {Window} window * @param {undefined} undefined */ function (window, undefined) { var fSortAscending = AscCommon.fSortAscending; var cElementType = AscCommonExcel.cElementType; var cErrorType = AscCommonExcel.cErrorType; var cNumber = AscCommonExcel.cNumber; var cString = AscCommonExcel.cString; var cBool = AscCommonExcel.cBool; var cError = AscCommonExcel.cError; var cArea = AscCommonExcel.cArea; var cArea3D = AscCommonExcel.cArea3D; var cRef = AscCommonExcel.cRef; var cRef3D = AscCommonExcel.cRef3D; var cEmpty = AscCommonExcel.cEmpty; var cArray = AscCommonExcel.cArray; var cBaseFunction = AscCommonExcel.cBaseFunction; var checkTypeCell = AscCommonExcel.checkTypeCell; var cFormulaFunctionGroup = AscCommonExcel.cFormulaFunctionGroup; var _func = AscCommonExcel._func; var matching = AscCommonExcel.matching; var maxGammaArgument = 171.624376956302; cFormulaFunctionGroup['Statistical'] = cFormulaFunctionGroup['Statistical'] || []; cFormulaFunctionGroup['Statistical'].push(cAVEDEV, cAVERAGE, cAVERAGEA, cAVERAGEIF, cAVERAGEIFS, cBETADIST, cBETA_DIST, cBETA_INV, cBINOMDIST, cBINOM_DIST, cBINOM_DIST_RANGE, cBINOM_INV, cCHIDIST, cCHIINV, cCHISQ_DIST, cCHISQ_DIST_RT, cCHISQ_INV, cCHISQ_INV_RT, cCHITEST, cCHISQ_TEST, cCONFIDENCE, cCONFIDENCE_NORM, cCONFIDENCE_T, cCORREL, cCOUNT, cCOUNTA, cCOUNTBLANK, cCOUNTIF, cCOUNTIFS, cCOVAR, cCOVARIANCE_P, cCOVARIANCE_S, cCRITBINOM, cDEVSQ, cEXPON_DIST, cEXPONDIST, cF_DIST, cFDIST, cF_DIST_RT, cF_INV, cFINV, cF_INV_RT, cFISHER, cFISHERINV, cFORECAST, cFORECAST_ETS, cFORECAST_LINEAR, cFREQUENCY, cFTEST, cGAMMA, cGAMMA_DIST, cGAMMADIST, cGAMMA_INV, cGAMMAINV, cGAMMALN, cGAMMALN_PRECISE, cGAUSS, cGEOMEAN, cGROWTH, cHARMEAN, cHYPGEOMDIST, cINTERCEPT, cKURT, cLARGE, cLINEST, cLOGEST, cLOGINV, cLOGNORM_DIST, cLOGNORM_INV, cLOGNORMDIST, cMAX, cMAXA, cMAXIFS, cMEDIAN, cMIN, cMINA, cMINIFS, cMODE, cMODE_MULT, cMODE_SNGL, cNEGBINOMDIST, cNEGBINOM_DIST, cNORMDIST, cNORM_DIST, cNORMINV, cNORM_INV, cNORMSDIST, cNORM_S_DIST, cNORMSINV, cNORM_S_INV, cPEARSON, cPERCENTILE, cPERCENTILE_EXC, cPERCENTILE_INC, cPERCENTRANK, cPERCENTRANK_EXC, cPERCENTRANK_INC, cPERMUT, cPERMUTATIONA, cPHI, cPOISSON, cPOISSON_DIST, cPROB, cQUARTILE, cQUARTILE_EXC, cQUARTILE_INC, cRANK, cRANK_AVG, cRANK_EQ, cRSQ, cSKEW, cSKEW_P, cSLOPE, cSMALL, cSTANDARDIZE, cSTDEV, cSTDEV_S, cSTDEVA, cSTDEVP, cSTDEV_P, cSTDEVPA, cSTEYX, cTDIST, cT_DIST, cT_DIST_2T, cT_DIST_RT, cT_INV, cT_INV_2T, cTINV, cTREND, cTRIMMEAN, cTTEST, cT_TEST, cVAR, cVARA, cVARP, cVAR_P, cVAR_S, cVARPA, cWEIBULL, cWEIBULL_DIST, cZTEST, cZ_TEST); cFormulaFunctionGroup['NotRealised'] = cFormulaFunctionGroup['NotRealised'] || []; cFormulaFunctionGroup['NotRealised'].push(cFTEST, cGROWTH, cLINEST, cLOGEST, cTREND); function isInteger(value) { return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; } function integralPhi(x) { // Using gauss(x)+0.5 has severe cancellation errors for x<-4 return 0.5 * AscCommonExcel.rtl_math_erfc(-x * 0.7071067811865475); // * 1/sqrt(2) } function phi(x) { return 0.39894228040143268 * Math.exp(-(x * x) / 2); } function gauss(x) { var t0 = [0.39894228040143268, -0.06649038006690545, 0.00997355701003582, -0.00118732821548045, 0.00011543468761616, -0.00000944465625950, 0.00000066596935163, -0.00000004122667415, 0.00000000227352982, 0.00000000011301172, 0.00000000000511243, -0.00000000000021218], t2 = [0.47724986805182079, 0.05399096651318805, -0.05399096651318805, 0.02699548325659403, -0.00449924720943234, -0.00224962360471617, 0.00134977416282970, -0.00011783742691370, -0.00011515930357476, 0.00003704737285544, 0.00000282690796889, -0.00000354513195524, 0.00000037669563126, 0.00000019202407921, -0.00000005226908590, -0.00000000491799345, 0.00000000366377919, -0.00000000015981997, -0.00000000017381238, 0.00000000002624031, 0.00000000000560919, -0.00000000000172127, -0.00000000000008634, 0.00000000000007894], t4 = [0.49996832875816688, 0.00013383022576489, -0.00026766045152977, 0.00033457556441221, -0.00028996548915725, 0.00018178605666397, -0.00008252863922168, 0.00002551802519049, -0.00000391665839292, -0.00000074018205222, 0.00000064422023359, -0.00000017370155340, 0.00000000909595465, 0.00000000944943118, -0.00000000329957075, 0.00000000029492075, 0.00000000011874477, -0.00000000004420396, 0.00000000000361422, 0.00000000000143638, -0.00000000000045848]; var asympt = [-1, 1, -3, 15, -105], xabs = Math.abs(x), xshort = Math.floor(xabs), nval = 0; if (xshort == 0) { nval = taylor(t0, 11, (xabs * xabs)) * xabs; } else if ((xshort >= 1) && (xshort <= 2)) { nval = taylor(t2, 23, (xabs - 2)); } else if ((xshort >= 3) && (xshort <= 4)) { nval = taylor(t4, 20, (xabs - 4)); } else { nval = 0.5 + phi(xabs) * taylor(asympt, 4, 1 / (xabs * xabs)) / xabs; } if (x < 0) { return -nval; } else { return nval; } } function taylor(pPolynom, nMax, x) { var nVal = pPolynom[nMax]; for (var i = nMax - 1; i >= 0; i--) { nVal = pPolynom[i] + (nVal * x); } return nVal; } function gaussinv(x) { var q, t, z; q = x - 0.5; if (Math.abs(q) <= .425) { t = 0.180625 - q * q; z = q * ( ( ( ( ( ( ( t * 2509.0809287301226727 + 33430.575583588128105 ) * t + 67265.770927008700853 ) * t + 45921.953931549871457 ) * t + 13731.693765509461125 ) * t + 1971.5909503065514427 ) * t + 133.14166789178437745 ) * t + 3.387132872796366608 ) / ( ( ( ( ( ( ( t * 5226.495278852854561 + 28729.085735721942674 ) * t + 39307.89580009271061 ) * t + 21213.794301586595867 ) * t + 5394.1960214247511077 ) * t + 687.1870074920579083 ) * t + 42.313330701600911252 ) * t + 1 ); } else { if (q > 0) { t = 1 - x; } else { t = x; } t = Math.sqrt(-Math.log(t)); if (t <= 5) { t += -1.6; z = ( ( ( ( ( ( ( t * 7.7454501427834140764e-4 + 0.0227238449892691845833 ) * t + 0.24178072517745061177 ) * t + 1.27045825245236838258 ) * t + 3.64784832476320460504 ) * t + 5.7694972214606914055 ) * t + 4.6303378461565452959 ) * t + 1.42343711074968357734 ) / ( ( ( ( ( ( ( t * 1.05075007164441684324e-9 + 5.475938084995344946e-4 ) * t + 0.0151986665636164571966 ) * t + 0.14810397642748007459 ) * t + 0.68976733498510000455 ) * t + 1.6763848301838038494 ) * t + 2.05319162663775882187 ) * t + 1 ); } else { t += -5; z = ( ( ( ( ( ( ( t * 2.01033439929228813265e-7 + 2.71155556874348757815e-5 ) * t + 0.0012426609473880784386 ) * t + 0.026532189526576123093 ) * t + 0.29656057182850489123 ) * t + 1.7848265399172913358 ) * t + 5.4637849111641143699 ) * t + 6.6579046435011037772 ) / ( ( ( ( ( ( ( t * 2.04426310338993978564e-15 + 1.4215117583164458887e-7 ) * t + 1.8463183175100546818e-5 ) * t + 7.868691311456132591e-4 ) * t + 0.0148753612908506148525 ) * t + 0.13692988092273580531 ) * t + 0.59983220655588793769 ) * t + 1 ); } if (q < 0) { z = -z; } } return z; } function getLanczosSum(fZ) { var num = [23531376880.41075968857200767445163675473, 42919803642.64909876895789904700198885093, 35711959237.35566804944018545154716670596, 17921034426.03720969991975575445893111267, 6039542586.35202800506429164430729792107, 1439720407.311721673663223072794912393972, 248874557.8620541565114603864132294232163, 31426415.58540019438061423162831820536287, 2876370.628935372441225409051620849613599, 186056.2653952234950402949897160456992822, 8071.672002365816210638002902272250613822, 210.8242777515793458725097339207133627117, 2.506628274631000270164908177133837338626], denom = [0, 39916800, 120543840, 150917976, 105258076, 45995730, 13339535, 2637558, 357423, 32670, 1925, 66, 1]; // Horner scheme var sumNum, sumDenom, i, zInv; if (fZ <= 1) { sumNum = num[12]; sumDenom = denom[12]; for (i = 11; i >= 0; --i) { sumNum *= fZ; sumNum += num[i]; sumDenom *= fZ; sumDenom += denom[i]; } } else // Cancel down with fZ^12; Horner scheme with reverse coefficients { zInv = 1 / fZ; sumNum = num[0]; sumDenom = denom[0]; for (i = 1; i <= 12; ++i) { sumNum *= zInv; sumNum += num[i]; sumDenom *= zInv; sumDenom += denom[i]; } } return sumNum / sumDenom; } /** You must ensure fZ>0; fZ>171.624376956302 will overflow. */ function getGammaHelper(fZ) { var gamma = getLanczosSum(fZ), fg = 6.024680040776729583740234375, zgHelp = fZ + fg - 0.5; // avoid intermediate overflow var halfpower = Math.pow(zgHelp, fZ / 2 - 0.25); gamma *= halfpower; gamma /= Math.exp(zgHelp); gamma *= halfpower; if (fZ <= 20 && fZ == Math.floor(fZ)) { gamma = Math.round(gamma); } return gamma; } /** You must ensure fZ>0 */ function getLogGammaHelper(fZ) { var _fg = 6.024680040776729583740234375, zgHelp = fZ + _fg - 0.5; return Math.log(getLanczosSum(fZ)) + (fZ - 0.5) * Math.log(zgHelp) - zgHelp; } function getLogGamma(fZ) { if (fZ >= maxGammaArgument) { return getLogGammaHelper(fZ); } if (fZ >= 0) { return Math.log(getGammaHelper(fZ)); } if (fZ >= 0.5) { return Math.log(getGammaHelper(fZ + 1) / fZ); } return getLogGammaHelper(fZ + 2) - Math.log(fZ + 1) - Math.log(fZ); } function getPercentile(values, alpha) { values.sort(fSortAscending); var nSize = values.length; if (nSize === 0) { return new cError(cErrorType.not_available); } else { if (nSize === 1) { return new cNumber(values[0]); } else { var nIndex = Math.floor(alpha * (nSize - 1)); var fDiff = alpha * (nSize - 1) - Math.floor(alpha * (nSize - 1)); if (fDiff === 0.0) { return new cNumber(values[nIndex]); } else { return new cNumber(values[nIndex] + fDiff * (values[nIndex + 1] - values[nIndex])); } } } } function getPercentileExclusive(values, alpha) { values.sort(fSortAscending); var nSize1 = values.length + 1; if ( nSize1 == 1){ return new cError(cErrorType.wrong_value_type); } if ( alpha * nSize1 < 1 || alpha * nSize1 > nSize1 - 1 ){ return new cError(cErrorType.not_numeric); } var nIndex = Math.floor(alpha * nSize1 - 1); var fDiff = alpha * nSize1 - 1 - Math.floor(alpha * nSize1 - 1); if (fDiff === 0.0) { return new cNumber(values[nIndex]); } else { return new cNumber(values[nIndex] + fDiff * (values[nIndex + 1] - values[nIndex])); } } function percentrank(tA, fNum, k, bInclusive) { tA.sort(fSortAscending); var nSize = tA.length; if(k < 1){ return new cError(cErrorType.not_numeric); }else if (tA.length < 1 || nSize === 0) { return new cError(cErrorType.not_available); } else { if (fNum < tA[0] || fNum > tA[nSize - 1]) { return new cError(cErrorType.not_available); } else if (nSize === 1) { return new cNumber(1); } else { if ( fNum === tA[0] ){ if ( bInclusive ){ fRes = 0; }else{ fRes = 1 / ( nSize + 1 ); } }else{ var fRes, nOldCount = 0, fOldVal = tA[0], i; for (i = 1; i < nSize && tA[i] < fNum; i++) { if (tA[i] !== fOldVal) { nOldCount = i; fOldVal = tA[i]; } } if (tA[i] !== fOldVal) { nOldCount = i; } if (fNum === tA[i]) { if ( bInclusive ){ fRes = nOldCount / (nSize - 1); }else{ fRes =(i + 1) / (nSize + 1); } } else { if (nOldCount === 0) { fRes = 0; } else { var fFract = ( fNum - tA[nOldCount - 1] ) / ( tA[nOldCount] - tA[nOldCount - 1] ); if ( bInclusive ){ fRes = fRes = ( nOldCount - 1 + fFract ) / (nSize - 1); } else{ fRes = (nOldCount + fFract ) / ( nSize + 1 ); } } } } return new cNumber(fRes.toString().substr(0, fRes.toString().indexOf(".") + 1 + k) - 0); } } } function getMedian(rArray){ rArray.sort(fSortAscending); var nSize = rArray.length; if (nSize == 0){ return new cError(cErrorType.wrong_value_type); } if (nSize % 2 === 0) { return new cNumber((rArray[nSize / 2 - 1] + rArray[nSize / 2]) / 2); } else { return new cNumber(rArray[(nSize - 1) / 2]); } } function getGamma(fZ) { var fLogPi = Math.log(Math.PI); var fLogDblMax = Math.log(2.22507e+308); if (fZ > maxGammaArgument){ //SetError(FormulaError::IllegalFPOperation); //return HUGE_VAL; return; } if (fZ >= 1.0){ return getGammaHelper(fZ); } if (fZ >= 0.5){ return getGammaHelper(fZ + 1) / fZ; } if (fZ >= -0.5){ var fLogTest = getLogGammaHelper(fZ+2) - Math.log1p(fZ) - Math.log( Math.abs(fZ)); if (fLogTest >= fLogDblMax){ //SetError(FormulaError::IllegalFPOperation); //return HUGE_VAL; return; } return getGammaHelper(fZ + 2) / (fZ + 1) / fZ; } var fLogDivisor = getLogGammaHelper(1 - fZ) + Math.log( Math.abs( Math.sin( Math.PI * fZ))); if (fLogDivisor - fLogPi >= fLogDblMax){ return 0; } if (fLogDivisor < 0){ if (fLogPi - fLogDivisor > fLogDblMax){ //SetError(FormulaError::IllegalFPOperation); //return HUGE_VAL; return; } } return Math.exp( fLogPi - fLogDivisor) * ((Math.sin( Math.PI * fZ) < 0) ? -1 : 1); } function getGammaDist( fX, fAlpha, fLambda ){ if (fX <= 0){ return 0; } else{ return GetLowRegIGamma( fAlpha, fX / fLambda); } } function GetLowRegIGamma( fA, fX ){ var fLnFactor = fA * Math.log(fX) - fX - getLogGamma(fA); var fFactor = Math.exp(fLnFactor); if (fX > fA + 1){ return 1 - fFactor * getGammaContFraction(fA, fX); } else{ return fFactor * getGammaSeries(fA, fX); } } function getGammaContFraction( fA, fX ) { var fBigInv = 2.22045e-016;//epsilon var fHalfMachEps = fBigInv / 2; var fBig = 1 / fBigInv; var fCount = 0; var fY = 1 - fA; var fDenom = fX + 2 - fA; var fPkm1 = fX + 1; var fPkm2 = 1; var fQkm1 = fDenom * fX; var fQkm2 = fX; var fApprox = fPkm1 / fQkm1; var bFinished = false; do { fCount = fCount + 1; fY = fY + 1; var fNum = fY * fCount; fDenom = fDenom + 2; var fPk = fPkm1 * fDenom - fPkm2 * fNum; var fQk = fQkm1 * fDenom - fQkm2 * fNum; if (fQk !== 0) { var fR = fPk / fQk; bFinished = (Math.abs( (fApprox - fR) / fR ) <= fHalfMachEps); fApprox = fR; } fPkm2 = fPkm1; fPkm1 = fPk; fQkm2 = fQkm1; fQkm1 = fQk; if (Math.abs(fPk) > fBig) { // reduce a fraction does not change the value fPkm2 = fPkm2 * fBigInv; fPkm1 = fPkm1 * fBigInv; fQkm2 = fQkm2 * fBigInv; fQkm1 = fQkm1 * fBigInv; } } while (!bFinished && fCount < 10000); if (!bFinished) { //SetError(FormulaError::NoConvergence); return; } return fApprox; } function getGammaSeries( fA, fX ){ var fHalfMachEps = 2.22045e-016 / 2; var fDenomfactor = fA; var fSummand = 1 / fA; var fSum = fSummand; var nCount = 1; do { fDenomfactor = fDenomfactor + 1; fSummand = fSummand * fX / fDenomfactor; fSum = fSum + fSummand; nCount = nCount + 1; } while ( fSummand/fSum > fHalfMachEps && nCount <= 10000); if (nCount > 10000) { //SetError(FormulaError::NoConvergence); return; } return fSum; } function getGammaDistPDF( fX, fAlpha, fLambda ) { if (fX < 0){ return 0; }else if (fX === 0){ if (fAlpha < 1.0){ //SetError(FormulaError::DivisionByZero); // should be #DIV/0 //return HUGE_VAL; return; }else if (fAlpha === 1){ return (1 / fLambda); }else{ return 0; } }else{ var fXr = fX / fLambda; if (fXr > 1){ var fLogDblMax = Math.log( 2.22507e+308 ); if (Math.log(fXr) * (fAlpha - 1) < fLogDblMax && fAlpha < maxGammaArgument){ return Math.pow( fXr, fAlpha - 1) * Math.exp(-fXr) / fLambda / getGamma(fAlpha); }else{ return Math.exp( (fAlpha - 1) * Math.log(fXr) - fXr - Math.log(fLambda) - getLogGamma(fAlpha)); } }else { if (fAlpha < maxGammaArgument){ return Math.pow( fXr, fAlpha - 1) * Math.exp(-fXr) / fLambda / getGamma(fAlpha); }else{ return Math.pow( fXr, fAlpha - 1) * Math.exp(-fXr) / fLambda / Math.exp( getLogGamma(fAlpha)); } } } } function getChiDist( fX, fDF){ if (fX <= 0.0){ return 1.0; }else{ return getUpRegIGamma( fDF/2.0, fX/2.0); } } function getUpRegIGamma( fA, fX ){ var fLnFactor= fA * Math.log(fX) - fX - getLogGamma(fA); var fFactor = Math.exp(fLnFactor); if (fX > fA + 1){ return fFactor * getGammaContFraction(fA, fX); }else{ return 1 - fFactor * getGammaSeries(fA, fX); } } function getChiSqDistCDF( fX, fDF){ if (fX <= 0){ return 0; }else{ return GetLowRegIGamma( fDF/2, fX/2); } } function getChiSqDistPDF( fX, fDF){ var fValue; if (fX <= 0){ return 0; } if (fDF*fX > 1391000) { fValue = Math.exp((0.5*fDF - 1) * Math.log(fX*0.5) - 0.5 * fX - Math.log(2) - getLogGamma(0.5*fDF)); } else { var fCount; if (Math.fmod(fDF, 2) < 0.5){ fValue = 0.5; fCount = 2; }else{ fValue = 1 / Math.sqrt(fX * 2 * Math.PI); fCount = 1; } while ( fCount < fDF){ fValue *= (fX / fCount); fCount += 2; } if (fX >= 1425){ fValue = Math.exp(Math.log(fValue) - fX / 2); }else{ fValue *= Math.exp(- fX/2); } } return fValue; } function chiTest(pMat1, pMat2){ if (!pMat1 || !pMat2){ return new cError(cErrorType.not_available); } var nC1 = pMat1.length; var nC2 = pMat2.length; var nR1 = pMat1[0].length; var nR2 = pMat2[0].length; if (nR1 !== nR2 || nC1 !== nC2){ return new cError(cErrorType.not_available); } var fChi = 0.0; var bEmpty = true; for (var i = 0; i < nC1; i++){ for (var j = 0; j < nR1; j++){ if (pMat1[i][j] && pMat2[i][j]){ bEmpty = false; //MS выдает ошибку только если первый элемент строка. LO - если любой. if (i === 0 && j === 0 && cElementType.string === pMat1[i][j].type){ return new cError(cErrorType.division_by_zero); } if(cElementType.number !== pMat1[i][j].type || cElementType.number !== pMat2[i][j].type){ continue; } var fValX = pMat1[i][j].getValue(); var fValE = pMat2[i][j].getValue(); if ( fValE === 0.0 ){ return new cError(cErrorType.division_by_zero); } var fTemp1 = (fValX - fValE) * (fValX - fValE); var fTemp2 = fTemp1; fChi += fTemp2 / fValE; } } } if ( bEmpty ){ return new cError(cErrorType.wrong_value_type); } var fDF; if (nC1 === 1 || nR1 === 1){ fDF = nC1*nR1 - 1; if (fDF === 0){ return new cError(cErrorType.not_available); } }else{ fDF = (nC1 - 1)*(nR1 - 1); } if ( fDF < 1 || fChi < 0 || fDF > Math.pow(10, 10)){ return new cError(cErrorType.not_numeric); } var res = getChiDist(fChi, fDF); return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); } function tTest(pMat1, pMat2, fTails, fTyp){ var fT, fF; var nC1 = pMat1.length; var nC2 = pMat2.length; var nR1 = pMat1[0].length; var nR2 = pMat2[0].length; var calcTest = null; if (fTyp === 1.0){ if (nC1 !== nC2 || nR1 !== nR2){ return new cError(cErrorType.not_available); } var fCount = 0.0; var fSum1 = 0.0; var fSum2 = 0.0; var fSumSqrD = 0.0; var fVal1, fVal2; for (var i = 0; i < nC1; i++){ for (var j = 0; j < nR1; j++){ if(cElementType.number !== pMat1[i][j].type || cElementType.number !== pMat2[i][j].type){ continue; } fVal1 = pMat1[i][j].getValue(); fVal2 = pMat2[i][j].getValue(); fSum1 += fVal1; fSum2 += fVal2; fSumSqrD += (fVal1 - fVal2)*(fVal1 - fVal2); fCount++; } } if (fCount < 1.0){ return new cError(cErrorType.wrong_value_type); } var fSumD = fSum1 - fSum2; var fDivider = (fCount*fSumSqrD - fSumD*fSumD); if ( fDivider === 0.0 ){ return new cError(cErrorType.division_by_zero); } fT = Math.abs(fSumD) * Math.sqrt((fCount-1.0) / fDivider); fF = fCount - 1.0; } else if (fTyp === 2.0){ calcTest = CalculateTest(false, nC1, nC2, nR1, nR2, pMat1, pMat2, fT, fF); } else if (fTyp === 3.0){ calcTest = CalculateTest(true, nC1, nC2, nR1, nR2, pMat1, pMat2, fT, fF); }else{ return new cError(cErrorType.not_numeric); } if(null !== calcTest){ if(false === calcTest){ return new cError(cErrorType.wrong_value_type); }else{ fT = calcTest.fT; fF = calcTest.fF; } } var res = getTDist(fT, fF, fTails); return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); } function CalculateTest( bTemplin, nC1, nC2, nR1, nR2, pMat1, pMat2 , fT, fF) { var fCount1 = 0.0; var fCount2 = 0.0; var fSum1 = 0.0; var fSumSqr1 = 0.0; var fSum2 = 0.0; var fSumSqr2 = 0.0; var fVal; for (var i = 0; i < nC1; i++){ for (var j = 0; j < nR1; j++) { if (cElementType.string !== pMat1[i][j].type) { fVal = pMat1[i][j].getValue(); fSum1 += fVal; fSumSqr1 += fVal * fVal; fCount1++; } } } for (var i = 0; i < nC2; i++){ for (var j = 0; j < nR2; j++) { if (cElementType.string !== pMat2[i][j].type) { fVal = pMat2[i][j].getValue(); fSum2 += fVal; fSumSqr2 += fVal * fVal; fCount2++; } } } if (fCount1 < 2.0 || fCount2 < 2.0){ return false; } if ( bTemplin ){ var fS1 = (fSumSqr1 - fSum1 * fSum1 / fCount1) / (fCount1 - 1.0) / fCount1; var fS2 = (fSumSqr2 - fSum2 * fSum2 / fCount2) / (fCount2 - 1.0) / fCount2; if (fS1 + fS2 === 0.0){ return false; } var c = fS1 / (fS1 + fS2); fT = Math.abs(fSum1 / fCount1 - fSum2 / fCount2) / Math.sqrt(fS1 + fS2); fF = 1.0 / (c * c / (fCount1 - 1.0) + (1.0 - c) * (1.0 - c) / (fCount2 - 1.0)); }else{ var fS1 = (fSumSqr1 - fSum1 * fSum1 / fCount1) / (fCount1 - 1.0); var fS2 = (fSumSqr2 - fSum2 * fSum2 / fCount2) / (fCount2 - 1.0); fT = Math.abs( fSum1 / fCount1 - fSum2 / fCount2 ) / Math.sqrt( (fCount1-1.0)*fS1 + (fCount2-1.0)*fS2 ) * Math.sqrt( fCount1*fCount2*(fCount1+fCount2-2)/(fCount1+fCount2) ); fF = fCount1 + fCount2 - 2; } return {fT: fT, fF: fF}; } //BETA DISTRIBUTION function getBetaDist(fXin, fAlpha, fBeta) { if (fXin <= 0) { return 0; } if (fXin >= 1){ return 1; } if (fBeta === 1) { return Math.pow(fXin, fAlpha); } if (fAlpha === 1){ return - Math.expm1(fBeta * Math.log1p(-fXin)); } var fResult; var fY = (0.5 - fXin) + 0.5; var flnY = Math.log1p(-fXin); var fX = fXin; var flnX = Math.log(fXin); var fA = fAlpha; var fB = fBeta; var bReflect = fXin > fAlpha / (fAlpha + fBeta); if (bReflect){ fA = fBeta; fB = fAlpha; fX = fY; fY = fXin; flnX = flnY; flnY = Math.log(fXin); } fResult = getBetaHelperContFrac(fX, fA, fB); fResult = fResult / fA; var fP = fA / (fA + fB); var fQ = fB / (fA + fB); var fTemp; if (fA > 1 && fB > 1 && fP < 0.97 && fQ < 0.97){ fTemp = getBetaDistPDF(fX, fA, fB) * fX * fY; } else{ fTemp = Math.exp(fA * flnX + fB * flnY - getLogBeta(fA, fB)); } fResult *= fTemp; if (bReflect){ fResult = 0.5 - fResult + 0.5; } if (fResult > 1){ fResult = 1; } if (fResult < 0){ fResult = 0; } return fResult; } // beta distribution probability density function function getTDist(T, fDF, nType) { var res = null; switch ( nType ){ case 1: { res = 0.5 * getBetaDist(fDF / ( fDF + T * T ), fDF / 2, 0.5); break; } case 2: { res = getBetaDist(fDF / ( fDF + T * T ), fDF / 2, 0.5); break; } case 3: { res = Math.pow( 1 + ( T * T / fDF ), -( fDF + 1 ) / 2 ) / ( Math.sqrt( fDF ) * getBeta( 0.5, fDF / 2.0 ) ); break; } case 4: { var X = fDF / ( T * T + fDF ); var R = 0.5 * getBetaDist( X, 0.5 * fDF, 0.5 ); res = ( T < 0 ? R : 1 - R ); break; } } return res; } function getBetaDistPDF(fX, fA, fB) { // special cases if (fA === 1){ if (fB === 1) return 1; if (fB === 2) return -2 * fX + 2; if (fX === 1 && fB < 1){ //SetError(FormulaError::IllegalArgument); //return HUGE_VAL; return; } if (fX <= 0.01) return fB + fB * Math.expm1((fB - 1) * Math.log1p(-fX)); else return fB * Math.pow(0.5 - fX + 0.5, fB - 1); } if (fB === 1){ if (fA === 2) return fA * fX; if (fX === 0 && fA < 1){ //SetError(FormulaError::IllegalArgument); //return HUGE_VAL; return; } return fA * pow(fX, fA - 1); } if (fX <= 0){ if (fA < 1 && fX === 0){ //SetError(FormulaError::IllegalArgument); //return HUGE_VAL; return; } else return 0; } if (fX >= 1){ if (fB < 1 && fX === 1){ //SetError(FormulaError::IllegalArgument); //return HUGE_VAL; return; } else return 0; } var fLogDblMax = Math.log( 2.22507e+308); var fLogDblMin = Math.log( 2.22507e-308 ); var fLogY = (fX < 0.1) ? Math.log1p(-fX) : Math.log(0.5 - fX + 0.5); var fLogX = Math.log(fX); var fAm1LogX = (fA - 1) * fLogX; var fBm1LogY = (fB - 1) * fLogY; var fLogBeta = getLogBeta(fA,fB); if ( fAm1LogX < fLogDblMax && fAm1LogX > fLogDblMin && fBm1LogY < fLogDblMax && fBm1LogY > fLogDblMin && fLogBeta < fLogDblMax && fLogBeta > fLogDblMin && fAm1LogX + fBm1LogY < fLogDblMax && fAm1LogX + fBm1LogY > fLogDblMin){ return Math.pow(fX, fA - 1) * Math.pow(0.5 - fX + 0.5, fB - 1) / getBeta(fA, fB); }else{ return Math.exp( fAm1LogX + fBm1LogY - fLogBeta); } } function getBeta(fAlpha, fBeta) { var fA; var fB; if (fAlpha > fBeta){ fA = fAlpha; fB = fBeta; }else{ fA = fBeta; fB = fAlpha; } if (fA + fB < maxGammaArgument){ return getGamma(fA) / getGamma(fA + fB) * getGamma(fB); } var fg = 6.024680040776729583740234375; var fgm = fg - 0.5; var fLanczos = getLanczosSum(fA); fLanczos /= getLanczosSum(fA + fB); fLanczos *= getLanczosSum(fB); var fABgm = fA +fB + fgm; fLanczos *= Math.sqrt((fABgm / (fA + fgm)) / (fB + fgm)); var fTempA = fB / (fA + fgm); var fTempB = fA / (fB + fgm); var fResult = Math.exp(-fA * Math.log1p(fTempA) - fB * Math.log1p(fTempB) - fgm); fResult *= fLanczos; return fResult; } function getBetaHelperContFrac(fX, fA, fB) { var a1, b1, a2, b2, fnorm, cfnew, cf; a1 = 1; b1 = 1; b2 = 1 - (fA + fB) / (fA + 1) * fX; if (b2 === 0){ a2 = 0; fnorm = 1; cf = 1; }else{ a2 = 1; fnorm = 1 / b2; cf = a2 * fnorm; } cfnew = 1; var rm = 1; var fMaxIter = 50000; var fMachEps = 2.22045e-016; var bfinished = false; do { var apl2m = fA + 2 * rm; var d2m = rm * (fB - rm) * fX / ((apl2m - 1) * apl2m); var d2m1 = -(fA + rm) * (fA + fB + rm) * fX / (apl2m * (apl2m + 1)); a1 = (a2 + d2m * a1) * fnorm; b1 = (b2 + d2m * b1) * fnorm; a2 = a1 + d2m1 * a2 * fnorm; b2 = b1 + d2m1 * b2 * fnorm; if (b2 !== 0){ fnorm = 1 / b2; cfnew = a2 * fnorm; bfinished = (Math.abs(cf - cfnew) < Math.abs(cf) * fMachEps); } cf = cfnew; rm += 1; } while (rm < fMaxIter && !bfinished); return cf; } function getLogBeta(fAlpha, fBeta) { var fA; var fB; if (fAlpha > fBeta) { fA = fAlpha; fB = fBeta; } else { fA = fBeta; fB = fAlpha; } var fg = 6.024680040776729583740234375; var fgm = fg - 0.5; var fLanczos = getLanczosSum(fA); fLanczos /= getLanczosSum(fA + fB); fLanczos *= getLanczosSum(fB); var fLogLanczos = Math.log(fLanczos); var fABgm = fA + fB + fgm; fLogLanczos += 0.5 * (Math.log(fABgm) - Math.log(fA + fgm) - Math.log(fB + fgm)); var fTempA = fB / (fA + fgm); var fTempB = fA / (fB + fgm); var fResult = - fA * Math.log1p(fTempA) -fB * Math.log1p(fTempB) - fgm; fResult += fLogLanczos; return fResult; } function getFDist( x, fF1, fF2) { var arg = fF2 / (fF2 + fF1 * x); var alpha = fF2 / 2; var beta = fF1 / 2; return getBetaDist(arg, alpha, beta); } function iterateInverse( rFunction, fAx, fBx ) { var rConvError = false; var fYEps = 1.0E-307; var fXEps = 2.22045e-016; var fAy = rFunction.GetValue(fAx); var fBy = rFunction.GetValue(fBx); var fTemp; var nCount; for (nCount = 0; nCount < 1000 && !hasChangeOfSign(fAy, fBy); nCount++) { if (Math.abs(fAy) <= Math.abs(fBy)) { fTemp = fAx; fAx += 2 * (fAx - fBx); if (fAx < 0){ fAx = 0; } fBx = fTemp; fBy = fAy; fAy = rFunction.GetValue(fAx); } else { fTemp = fBx; fBx += 2 * (fBx - fAx); fAx = fTemp; fAy = fBy; fBy = rFunction.GetValue(fBx); } } if (fAy === 0){ return {val: fAx, bError: rConvError}; } if (fBy === 0){ return {val: fBx, bError: rConvError}; } if (!hasChangeOfSign( fAy, fBy)){ rConvError = true; return {val: 0, bError: rConvError}; } // inverse quadric interpolation with additional brackets // set three points var fPx = fAx; var fPy = fAy; var fQx = fBx; var fQy = fBy; var fRx = fAx; var fRy = fAy; var fSx = 0.5 * (fAx + fBx); var bHasToInterpolate = true; nCount = 0; while ( nCount < 500 && Math.abs(fRy) > fYEps && (fBx - fAx) > Math.max( Math.abs(fAx), Math.abs(fBx)) * fXEps ){ if (bHasToInterpolate){ if (fPy !== fQy && fQy !== fRy && fRy !== fPy){ fSx = fPx * fRy * fQy / (fRy-fPy) / (fQy-fPy) + fRx * fQy * fPy / (fQy-fRy) / (fPy-fRy) + fQx * fPy * fRy / (fPy-fQy) / (fRy-fQy); bHasToInterpolate = (fAx < fSx) && (fSx < fBx); // inside the brackets? }else{ bHasToInterpolate = false; } } if(!bHasToInterpolate){ fSx = 0.5 * (fAx + fBx); fQx = fBx; fQy = fBy; bHasToInterpolate = true; } fPx = fQx; fQx = fRx; fRx = fSx; fPy = fQy; fQy = fRy; fRy = rFunction.GetValue(fSx); if (hasChangeOfSign( fAy, fRy)) { fBx = fRx; fBy = fRy; }else{ fAx = fRx; fAy = fRy; } bHasToInterpolate = bHasToInterpolate && (Math.abs(fRy) * 2 <= Math.abs(fQy)); ++nCount; } return {val: fRx, bError: rConvError}; } function hasChangeOfSign( u, w ) { return (u < 0 && w > 0) || (u > 0 && w < 0); } function rank( fVal, aSortArray, bAscending, bAverage ) { //sort array aSortArray.sort (function sortArr(a, b) { return a - b; }); var nSize = aSortArray.length; var res; if ( nSize == 0 /*|| nGlobalError != FormulaError::NONE*/ ){ res = null; } else { if ( fVal < aSortArray[ 0 ] || fVal > aSortArray[ nSize - 1 ] ){ res = null; }else{ var fLastPos = 0; var fFirstPos = -1.0; var bFinished = false; var i; for ( i = 0; i < nSize && !bFinished /*&& nGlobalError == FormulaError::NONE*/; i++ ){ if ( aSortArray[ i ] === fVal ){ if ( fFirstPos < 0 ){ fFirstPos = i + 1.0; } }else{ if ( aSortArray[ i ] > fVal ){ fLastPos = i; bFinished = true; } } } if ( !bFinished ){ fLastPos = i; } if ( !bAverage ){ if ( bAscending ){ res = fFirstPos; }else{ res = nSize + 1.0 - fLastPos; } }else { if ( bAscending ){ res = ( fFirstPos + fLastPos ) / 2.0 ; }else{ res = nSize + 1.0 - ( fFirstPos + fLastPos ) / 2.0; } } } } return res; } function skew(x, bSkewp) { var sumSQRDeltaX = 0, _x = 0, xLength = 0, sumSQRDeltaXDivstandDev = 0, i; for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { _x += x[i].getValue(); xLength++; } } if (xLength <= 2) { return new cError(cErrorType.not_available); } _x /= xLength; for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { sumSQRDeltaX += Math.pow(x[i].getValue() - _x, 2); } } var standDev; if(bSkewp){ standDev = Math.sqrt(sumSQRDeltaX / ( xLength )); }else{ standDev = Math.sqrt(sumSQRDeltaX / ( xLength - 1 )); } for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { sumSQRDeltaXDivstandDev += Math.pow((x[i].getValue() - _x) / standDev, 3); } } var res; if(bSkewp){ res = sumSQRDeltaXDivstandDev / xLength; }else{ res = xLength / (xLength - 1) / (xLength - 2) * sumSQRDeltaXDivstandDev; } return new cNumber(res); } function GAMMADISTFUNCTION(fp, fAlpha, fBeta){ this.fp = fp; this.fAlpha = fAlpha; this.fBeta = fBeta; } GAMMADISTFUNCTION.prototype.GetValue = function(x){ var res; var gammaDistVal = getGammaDist(x, this.fAlpha, this.fBeta); res = this.fp - gammaDistVal; return res; }; function BETADISTFUNCTION(fp, fAlpha, fBeta){ this.fp = fp; this.fAlpha = fAlpha; this.fBeta = fBeta; } BETADISTFUNCTION.prototype.GetValue = function(x){ var res; var betaDistVal = getBetaDist(x, this.fAlpha, this.fBeta); res = this.fp - betaDistVal; return res; }; function CHIDISTFUNCTION(fp, fDF){ this.fp = fp; this.fDF = fDF; } CHIDISTFUNCTION.prototype.GetValue = function(x){ var res; var betaDistVal = getChiDist(x, this.fDF); res = this.fp - betaDistVal; return res; }; function CHISQDISTFUNCTION(fp, fDF){ this.fp = fp; this.fDF = fDF; } CHISQDISTFUNCTION.prototype.GetValue = function(x){ var res; var betaDistVal = getChiSqDistCDF(x, this.fDF); res = this.fp - betaDistVal; return res; }; function FDISTFUNCTION(fp, fF1, fF2){ this.fp = fp; this.fF1 = fF1; this.fF2 = fF2; } FDISTFUNCTION.prototype.GetValue = function(x){ var res; var betaDistVal = getFDist(x, this.fF1, this.fF2); res = this.fp - betaDistVal; return res; }; function TDISTFUNCTION(fp, fDF, nT){ this.fp = fp; this.fDF = fDF; this.nT = nT; } TDISTFUNCTION.prototype.GetValue = function(x){ var res; var betaDistVal = getTDist(x, this.fDF, this.nT); res = this.fp - betaDistVal; return res; }; function ScETSForecastCalculation(nSize) { //SvNumberFormatter* mpFormatter; this.maRange = []; // data (X, Y) this.mpBase = []; // calculated base value array this.mpTrend = []; // calculated trend factor array this.mpPerIdx = []; // calculated periodical deviation array, not used with eds this.mpForecast = []; // forecasted value array this.mnSmplInPrd = 0; // samples per period this.mfStepSize = 0; // increment of X in maRange this.mfAlpha, this.mfBeta, this.mfGamma; // constants to minimise the RMSE in the ES-equations this.mnCount = nSize; // No of data points this.mbInitialised; this.mnMonthDay; // n-month X-interval, value is day of month // accuracy indicators this.mfMAE; // mean absolute error this.mfMASE; // mean absolute scaled error this.mfMSE; // mean squared error (variation) this.mfRMSE; // root mean squared error (standard deviation) this.mfSMAPE; // symmetric mean absolute error //FormulaError mnErrorValue; this.bAdditive; // true: additive method, false: multiplicative method this.bEDS; // true: EDS, false: ETS // constants used in determining best fit for alpha, beta, gamma this.cfMinABCResolution = 0.001; // minimum change of alpha, beta, gamma this.cnScenarios = 1000; // No. of scenarios to calculate for PI calculations /*bool initData(); bool prefillBaseData(); bool prefillTrendData(); bool prefillPerIdx(); bool initCalc(); void refill(); SCSIZE CalcPeriodLen(); void CalcAlphaBetaGamma(); void CalcBetaGamma(); void CalcGamma(); void calcAccuracyIndicators(); bool GetForecast( double fTarget, double& rForecast ); double RandDev(); double convertXtoMonths( double x );*/ } /*ScETSForecastCalculation::ScETSForecastCalculation( nSize, pFormatter ) : mpFormatter(pFormatter) , mpBase(nullptr) , mpTrend(nullptr) , mpPerIdx(nullptr) , mpForecast(nullptr) , mnSmplInPrd(0) , mfStepSize(0.0) , mfAlpha(0.0) , mfBeta(0.0) , mfGamma(0.0) , mnCount(nSize) , mbInitialised(false) , mnMonthDay(0) , mfMAE(0.0) , mfMASE(0.0) , mfMSE(0.0) , mfRMSE(0.0) , mfSMAPE(0.0) , mnErrorValue(FormulaError::NONE) , bAdditive(false) , bEDS(false) { maRange.reserve( mnCount ); }*/ ScETSForecastCalculation.prototype = Object.create(ScETSForecastCalculation.prototype); ScETSForecastCalculation.prototype.constructor = ScETSForecastCalculation; ScETSForecastCalculation.prototype.PreprocessDataRange = function( rMatX, rMatY, rSmplInPrd, bDataCompletion, nAggregation, rTMat, eETSType ) { this.bEDS = ( rSmplInPrd == 0 ); this.bAdditive = /*( eETSType == etsAdd || eETSType == etsPIAdd || eETSType == etsStatAdd )*/true; this.mnCount = rMatX.length; var maRange = this.maRange; for ( var i = 0; i < this.mnCount; i++ ){ maRange.push( {X: rMatX[i][0].value, Y: rMatY[i][0].value } ); } maRange.sort(function(a, b) { return a.X - b.X; }); if (rTMat) { if (/*eETSType != etsPIAdd && eETSType != etsPIMult*/true) { if (rTMat[0][0].getValue() < maRange[0].X) { return new cError(cErrorType.not_numeric); } } else { if (rTMat[0] < maRange[this.mnCount - 1].X) { return new cError(cErrorType.wrong_value_type); } } } var aDate = Date.prototype.getDateFromExcel(maRange[ 0 ].X); this.mnMonthDay = aDate.getDate(); for (var i = 1; i < this.mnCount && this.mnMonthDay; i++) { var aDate1 = Date.prototype.getDateFromExcel(maRange[i].X); if (aDate !== aDate1) { if (aDate1.getDate() !== this.mnMonthDay) { this.mnMonthDay = 0; } } } this.mfStepSize = Number.MAX_VALUE; if (/*mnMonthDay*/true) { for (var i = 0; i < this.mnCount; i++) { var aDate = Date.prototype.getDateFromExcel(maRange[i].X); maRange[i].X = aDate.getUTCFullYear() * 12 + aDate.getMonth(); } } for ( var i = 1; i < this.mnCount; i++ ) { var fStep = maRange[ i ].X - maRange[ i - 1 ].X; if ( fStep === 0.0 ) { if (nAggregation === 0) { return new cError(cErrorType.wrong_value_type); } var fTmp = maRange[i - 1].Y; var nCounter = 1; switch (nAggregation) { case 1 : // AVERAGE (default) while (i < this.mnCount && maRange[i].X === maRange[i - 1].X) { maRange.splice(i, 1); --this.mnCount; } break; case 7 : // SUM while (i < mnCount && maRange[i].X === maRange[i - 1].X) { fTmp += maRange[i].Y; maRange.splice(i, 1); --this.mnCount; } maRange[i - 1].Y = fTmp; break; case 2 : // COUNT case 3 : // COUNTA (same as COUNT as there are no non-numeric Y-values) while (i < this.mnCount && maRange[i].X === maRange[i - 1].X) { nCounter++; maRange.splice(i, 1); --this.mnCount; } maRange[i - 1].Y = nCounter; break; case 4 : // MAX while (i < this.mnCount && maRange[i].X === maRange[i - 1].X) { if (maRange[i].Y > fTmp) { fTmp = maRange[i].Y; } maRange.splice(i, 1); --this.mnCount; } maRange[i - 1].Y = fTmp; break; case 5 : // MEDIAN var aTmp = []; aTmp.push(maRange[i - 1].Y); while (i < mnCount && maRange[i].X === maRange[i - 1].X) { aTmp.push(maRange[i].Y); nCounter++; maRange.splice(i, 1); --this.mnCount; } //sort( aTmp.begin(), aTmp.end() ); if (nCounter % 2) { maRange[i - 1].Y = aTmp[nCounter / 2]; } else { maRange[i - 1].Y = ( aTmp[nCounter / 2] + aTmp[nCounter / 2 - 1] ) / 2.0; } break; case 6 : // MIN while (i < this.mnCount && maRange[i].X === maRange[i - 1].X) { if (maRange[i].Y < fTmp) { fTmp = maRange[i].Y; } maRange.splice(i, 1); --this.mnCount; } maRange[i - 1].Y = fTmp; break; } if ( i < this.mnCount - 1 ){ fStep = maRange[ i ].X - maRange[ i - 1 ].X; }else{ fStep = this.mfStepSize; } } if ( fStep > 0 && fStep < this.mfStepSize ){ this.mfStepSize = fStep; } } // step must be constant (or gap multiple of step) var bHasGap = false; for (var i = 1; i < this.mnCount && !bHasGap; i++) { var fStep = maRange[i].X - maRange[i - 1].X; if (fStep != this.mfStepSize) { if (Math.fmod(fStep, this.mfStepSize) !== 0.0) { return new cError(cErrorType.wrong_value_type); } bHasGap = true; } } if (bHasGap) { var nMissingXCount = 0; var fOriginalCount = this.mnCount; if (/*mnMonthDay*/true) { aDate = Date.prototype.getDateFromExcel(maRange[0].X); } for (var i = 1; i < this.mnCount; i++) { var fDist; if (/*mnMonthDay*/true) { var aDate1 = Date.prototype.getDateFromExcel(maRange[i].X); fDist = 12 * ( aDate1.getUTCFullYear() - aDate.getUTCFullYear() ) + ( aDate1.getMonth() - aDate.getMonth() ); aDate = aDate1; } else { fDist = maRange[i].X - maRange[i - 1].X; } if (fDist > this.mfStepSize) { // gap, insert missing data points var fYGap = ( maRange[i].Y + maRange[i - 1].Y ) / 2.0; for (var fXGap = maRange[i - 1].X + this.mfStepSize; fXGap < maRange[i].X; fXGap += this.mfStepSize) { var newAddElem = {X: fXGap, Y: ( bDataCompletion ? fYGap : 0.0 )}; maRange.splice(i, 1, newAddElem); i++; this.mnCount++; nMissingXCount++; if (nMissingXCount / fOriginalCount > 0.3) { // maximum of 30% missing points exceeded return new cError(cErrorType.wrong_value_type); } } } } } if ( rSmplInPrd != 1 ){ this.mnSmplInPrd = rSmplInPrd; }else { this.mnSmplInPrd = this.CalcPeriodLen(); if ( this.mnSmplInPrd == 1 ){ this.bEDS = true; // period length 1 means no periodic data: EDS suffices } } if ( !this.initData() ){ return false; // note: mnErrorValue is set in called function(s) } return true; }; ScETSForecastCalculation.prototype.initData = function() { // give various vectors size and initial value this.mpBase = []; this.mpBase.length = this.mnCount; this.mpBase.fill(0); this.mpTrend = []; this.mpTrend.length = this.mnCount; this.mpTrend.fill(0); if ( !this.bEDS ){ this.mpPerIdx = []; this.mpPerIdx.length = this.mnCount; this.mpPerIdx.fill(0); } this.mpForecast = []; this.mpForecast.length = this.mnCount; this.mpForecast.fill(0); this.mpForecast[ 0 ] = this.maRange[ 0 ].Y; if ( this.prefillTrendData() ) { if ( this.prefillPerIdx() ) { if ( this.prefillBaseData() ) return true; } } return false; }; ScETSForecastCalculation.prototype.prefillTrendData = function() { if ( this.bEDS ) this.mpTrend[ 0 ] = ( this.maRange[ this.mnCount - 1 ].Y - this.maRange[ 0 ].Y ) / ( this.mnCount - 1 ); else { // we need at least 2 periods in the data range if ( this.mnCount < 2 * this.mnSmplInPrd ) { return new cError(cErrorType.wrong_value_type); } var fSum = 0.0; for ( var i = 0; i < this.mnSmplInPrd; i++ ) fSum += this.maRange[ i + this.mnSmplInPrd ].Y - this.maRange[ i ].Y; var fTrend = fSum / ( this.mnSmplInPrd * this.mnSmplInPrd ); this.mpTrend[ 0 ] = fTrend; } return true; }; ScETSForecastCalculation.prototype.prefillPerIdx2 = function() { /*if ( !this.bEDS ) { // use as many complete periods as available if ( this.mnSmplInPrd == 0 ) { // should never happen; if mnSmplInPrd equals 0, bEDS is true mnErrorValue = FormulaError::UnknownState; return false; } var nPeriods = this.mnCount / this.mnSmplInPrd; std::vector< double > aPeriodAverage( nPeriods, 0.0 ); for ( SCSIZE i = 0; i < nPeriods ; i++ ) { for ( SCSIZE j = 0; j < mnSmplInPrd; j++ ) aPeriodAverage[ i ] += maRange[ i * mnSmplInPrd + j ].Y; aPeriodAverage[ i ] /= static_cast< double >( mnSmplInPrd ); if ( aPeriodAverage[ i ] == 0.0 ) { SAL_WARN( "sc.core", "prefillPerIdx(), average of 0 will cause divide by zero error, quitting calculation" ); mnErrorValue = FormulaError::DivisionByZero; return false; } } for ( SCSIZE j = 0; j < mnSmplInPrd; j++ ) { double fI = 0.0; for ( SCSIZE i = 0; i < nPeriods ; i++ ) { // adjust average value for position within period if ( bAdditive ) fI += ( maRange[ i * mnSmplInPrd + j ].Y - ( aPeriodAverage[ i ] + ( static_cast< double >( j ) - 0.5 * ( mnSmplInPrd - 1 ) ) * mpTrend[ 0 ] ) ); else fI += ( maRange[ i * mnSmplInPrd + j ].Y / ( aPeriodAverage[ i ] + ( static_cast< double >( j ) - 0.5 * ( mnSmplInPrd - 1 ) ) * mpTrend[ 0 ] ) ); } mpPerIdx[ j ] = fI / nPeriods; } } return true;*/ }; ScETSForecastCalculation.prototype.prefillPerIdx = function() { if ( !this.bEDS ) { // use as many complete periods as available if ( this.mnSmplInPrd == 0 ) { // should never happen; if mnSmplInPrd equals 0, bEDS is true //mnErrorValue = FormulaError::UnknownState; return false; } var nPeriods = parseInt(this.mnCount / this.mnSmplInPrd);//scsize var aPeriodAverage = []; for ( var i = 0; i < nPeriods ; i++ ) { aPeriodAverage[ i ] = 0; for ( var j = 0; j < this.mnSmplInPrd; j++ ) aPeriodAverage[ i ] += this.maRange[ i * this.mnSmplInPrd + j ].Y; aPeriodAverage[ i ] /= this.mnSmplInPrd; if ( aPeriodAverage[ i ] == 0.0 ) { //SAL_WARN( "sc.core", "prefillPerIdx(), average of 0 will cause divide by zero error, quitting calculation" ); //mnErrorValue = FormulaError::DivisionByZero; return false; } } for ( var j = 0; j < this.mnSmplInPrd; j++ ) { var fI = 0.0; for ( var i = 0; i < nPeriods ; i++ ) { // adjust average value for position within period if ( this.bAdditive ) fI += ( this.maRange[ i * this.mnSmplInPrd + j ].Y - ( aPeriodAverage[ i ] + ( j - 0.5 * ( this.mnSmplInPrd - 1 ) ) * this.mpTrend[ 0 ] ) ); else fI += ( this.maRange[ i * this.mnSmplInPrd + j ].Y / ( aPeriodAverage[ i ] + ( j - 0.5 * ( this.mnSmplInPrd - 1 ) ) * this.mpTrend[ 0 ] ) ); } this.mpPerIdx[ j ] = fI / nPeriods; } } return true; }; ScETSForecastCalculation.prototype.prefillBaseData = function() { if ( this.bEDS ) this.mpBase[ 0 ] = this.maRange[ 0 ].Y; else this.mpBase[ 0 ] = this.maRange[ 0 ].Y / this.mpPerIdx[ 0 ]; return true; }; ScETSForecastCalculation.prototype.initCalc = function() { if ( !this.mbInitialised ) { this.CalcAlphaBetaGamma(); this.mbInitialised = true; this.calcAccuracyIndicators(); } return true; }; ScETSForecastCalculation.prototype.calcAccuracyIndicators = function() { var fSumAbsErr = 0.0; var fSumDivisor = 0.0; var fSumErrSq = 0.0; var fSumAbsPercErr = 0.0; for ( var i = 1; i < this.mnCount; i++ ) { var fError = this.mpForecast[ i ] - this.maRange[ i ].Y; fSumAbsErr += Math.abs( fError ); fSumErrSq += fError * fError; fSumAbsPercErr += Math.abs( fError ) / ( Math.abs( this.mpForecast[ i ] ) + Math.abs( this.maRange[ i ].Y ) ); } for ( var i = 2; i < this.mnCount; i++ ){ fSumDivisor += Math.abs( this.maRange[ i ].Y - this.maRange[ i - 1 ].Y ); } var nCalcCount = this.mnCount - 1; this.mfMAE = fSumAbsErr / nCalcCount; this.mfMASE = fSumAbsErr / ( nCalcCount * fSumDivisor / ( nCalcCount - 1 ) ); this.mfMSE = fSumErrSq / nCalcCount; this.mfRMSE = Math.sqrt( this.mfMSE ); this.mfSMAPE = fSumAbsPercErr * 2.0 / nCalcCount; }; ScETSForecastCalculation.prototype.CalcPeriodLen = function() { var nBestVal = this.mnCount; var fBestME = Number.MAX_VALUE; var maRange = this.maRange; for ( var nPeriodLen = parseInt(this.mnCount / 2); nPeriodLen >= 1; nPeriodLen-- ) { var fMeanError = 0.0; var nPeriods = parseInt(this.mnCount / nPeriodLen); var nStart = parseInt(this.mnCount - ( nPeriods * nPeriodLen ) + 1); for ( var i = nStart; i < ( this.mnCount - nPeriodLen ); i++ ) { fMeanError += Math.abs( ( maRange[ i ].Y - maRange[ i - 1 ].Y ) - ( maRange[ nPeriodLen + i ].Y - maRange[ nPeriodLen + i - 1 ].Y ) ); } fMeanError /= ( nPeriods - 1 ) * nPeriodLen - 1 ; if ( fMeanError <= fBestME || fMeanError == 0.0 ) { nBestVal = nPeriodLen; fBestME = fMeanError; } } return nBestVal; }; ScETSForecastCalculation.prototype.CalcAlphaBetaGamma = function() { var f0 = 0.0; this.mfAlpha = f0; if ( this.bEDS ) { this.mfBeta = 0.0; // beta is not used with EDS this.CalcGamma(); } else this.CalcBetaGamma(); this.refill(); var fE0 = this.mfMSE; var f2 = 1.0; this.mfAlpha = f2; if ( this.bEDS ) this.CalcGamma(); else this.CalcBetaGamma(); this.refill(); var fE2 = this.mfMSE; var f1 = 0.5; this.mfAlpha = f1; if ( this.bEDS ) this.CalcGamma(); else this.CalcBetaGamma(); this.refill(); if ( fE0 == this.mfMSE && this.mfMSE == fE2 ) { this.mfAlpha = 0; if ( this.bEDS ) this.CalcGamma(); else this.CalcBetaGamma(); this.refill(); return; } while ( ( f2 - f1 ) > this.cfMinABCResolution ) { if ( fE2 > fE0 ) { f2 = f1; fE2 = this.mfMSE; f1 = ( f0 + f1 ) / 2; } else { f0 = f1; fE0 = this.mfMSE; f1 = ( f1 + f2 ) / 2; } this.mfAlpha = f1; if ( this.bEDS ) this.CalcGamma(); else this.CalcBetaGamma(); this.refill(); } if ( fE2 > fE0 ) { if ( fE0 < this.mfMSE ) { this.mfAlpha = f0; if ( this.bEDS ) this.CalcGamma(); else this.CalcBetaGamma(); this.refill(); } } else { if ( fE2 < this.mfMSE ) { this.mfAlpha = f2; if ( this.bEDS ) this.CalcGamma(); else this.CalcBetaGamma(); this.refill(); } } this.calcAccuracyIndicators(); return; }; ScETSForecastCalculation.prototype.CalcBetaGamma = function() { var f0 = 0.0; this.mfBeta = f0; this.CalcGamma(); this.refill(); var fE0 = this.mfMSE; var f2 = 1.0; this.mfBeta = f2; this.CalcGamma(); this.refill(); var fE2 = this.mfMSE; var f1 = 0.5; this.mfBeta = f1; this.CalcGamma(); this.refill(); if ( fE0 == this.mfMSE && this.mfMSE == fE2 ) { this.mfBeta = 0; this.CalcGamma(); this.refill(); return; } while ( ( f2 - f1 ) > this.cfMinABCResolution ) { if ( fE2 > fE0 ) { f2 = f1; fE2 =this. mfMSE; f1 = ( f0 + f1 ) / 2; } else { f0 = f1; fE0 = this.mfMSE; f1 = ( f1 + f2 ) / 2; } this.mfBeta = f1; this.CalcGamma(); this.refill(); } if ( fE2 > fE0 ) { if ( fE0 < this.mfMSE ) { this.mfBeta = f0; this.CalcGamma(); this.refill(); } } else { if ( fE2 < this.mfMSE ) { this.mfBeta = f2; this.CalcGamma(); this.refill(); } } }; ScETSForecastCalculation.prototype.CalcGamma = function() { var f0 = 0.0; this.mfGamma = f0; this.refill(); var fE0 = this.mfMSE; var f2 = 1.0; this.mfGamma = f2; this.refill(); var fE2 = this.mfMSE; var f1 = 0.5; this.mfGamma = f1; this.refill(); if ( fE0 == this.mfMSE && this.mfMSE == fE2 ) { this.mfGamma = 0; this.refill(); return; } while ( ( f2 - f1 ) > this.cfMinABCResolution ) { if ( fE2 > fE0 ) { f2 = f1; fE2 = this.mfMSE; f1 = ( f0 + f1 ) / 2; } else { f0 = f1; fE0 = this.mfMSE; f1 = ( f1 + f2 ) / 2; } this.mfGamma = f1; this.refill(); } if ( fE2 > fE0 ) { if ( fE0 < this.mfMSE ) { this.mfGamma = f0; this.refill(); } } else { if ( fE2 < this.mfMSE ) { this.mfGamma = f2; this.refill(); } } }; ScETSForecastCalculation.prototype.refill = function() { // refill mpBase, mpTrend, mpPerIdx and mpForecast with values // using the calculated mfAlpha, (mfBeta), mfGamma // forecast 1 step ahead for ( var i = 1; i < this.mnCount; i++ ) { if ( this.bEDS ) { this.mpBase[ i ] = this.mfAlpha * this.maRange[ i ].Y + ( 1 - this.mfAlpha ) * ( this.mpBase[ i - 1 ] + this.mpTrend[ i - 1 ] ); this.mpTrend[ i ] = this.mfGamma * ( this.mpBase[ i ] - this.mpBase[ i - 1 ] ) + ( 1 - this.mfGamma ) * this.mpTrend[ i - 1 ]; this.mpForecast[ i ] = this.mpBase[ i - 1 ] + this.mpTrend[ i - 1 ]; } else { var nIdx; if ( this.bAdditive ) { nIdx = ( i > this.mnSmplInPrd ? i - this.mnSmplInPrd : i ); this.mpBase[ i ] = this.mfAlpha * ( this.maRange[ i ].Y - this.mpPerIdx[ nIdx ] ) + ( 1 - this.mfAlpha ) * ( this.mpBase[ i - 1 ] + this.mpTrend[ i - 1 ] ); this.mpPerIdx[ i ] = this.mfBeta * ( this.maRange[ i ].Y - this.mpBase[ i ] ) + ( 1 - this.mfBeta ) * this.mpPerIdx[ nIdx ]; } else { nIdx = ( i >= this.mnSmplInPrd ? i - this.mnSmplInPrd : i ); this.mpBase[ i ] = this.mfAlpha * ( this.maRange[ i ].Y / this.mpPerIdx[ nIdx ] ) + ( 1 - this.mfAlpha ) * ( this.mpBase[ i - 1 ] + this.mpTrend[ i - 1 ] ); this.mpPerIdx[ i ] = this.mfBeta * ( this.maRange[ i ].Y / this.mpBase[ i ] ) + ( 1 - this.mfBeta ) * this.mpPerIdx[ this.nIdx ]; } this.mpTrend[ i ] = this.mfGamma * ( this.mpBase[ i ] - this.mpBase[ i - 1 ] ) + ( 1 - this.mfGamma ) * this.mpTrend[ i - 1 ]; if ( this.bAdditive ) this.mpForecast[ i ] = this.mpBase[ i - 1 ] + this.mpTrend[ i - 1 ] + this.mpPerIdx[ nIdx ]; else this.mpForecast[ i ] = ( this.mpBase[ i - 1 ] + this.mpTrend[ i - 1 ] ) * this.mpPerIdx[ nIdx ]; } } this.calcAccuracyIndicators(); }; ScETSForecastCalculation.prototype.convertXtoMonths = function( x ) { //Date aNullDate = *( mpFormatter->GetNullDate() ); var aDate = Date.prototype.getDateFromExcel(x); var nYear = aDate.getUTCFullYear(); var nMonth = aDate.getMonth(); var fMonthLength; switch ( nMonth ) { case 1 : case 3 : case 5 : case 7 : case 8 : case 10 : case 12 : fMonthLength = 31.0; break; case 2 : fMonthLength = ( aDate.isLeapYear() ? 29.0 : 28.0 ); break; default : fMonthLength = 30.0; } return ( 12.0 * nYear + nMonth + ( aDate.getDate() - this.mnMonthDay ) / fMonthLength ); }; ScETSForecastCalculation.prototype.GetForecast = function( fTarget, rForecast ) { if ( !this.initCalc() ) return false; if ( fTarget <= this.maRange[ this.mnCount - 1 ].X ) { var n = ( fTarget - this.maRange[ 0 ].X ) / this.mfStepSize; var fInterpolate = Math.fmod( fTarget - this.maRange[ 0 ].X, this.mfStepSize ); rForecast = this.maRange[ n ].Y; if ( fInterpolate >= this.cfMinABCResolution ) { var fInterpolateFactor = fInterpolate / this.mfStepSize; var fFc_1 = this.mpForecast[ n + 1 ]; rForecast = rForecast + fInterpolateFactor * ( fFc_1 - rForecast ); } } else { var n = Math.round(( fTarget - this.maRange[ this.mnCount - 1 ].X ) / this.mfStepSize); var fInterpolate = parseInt(Math.fmod( fTarget - this.maRange[ this.mnCount - 1 ].X, this.mfStepSize )); if ( this.bEDS ) rForecast = this.mpBase[ this.mnCount - 1 ] + n * this.mpTrend[ this.mnCount - 1 ]; else if ( this.bAdditive ) rForecast = this.mpBase[ this.mnCount - 1 ] + n * this.mpTrend[ this.mnCount - 1 ] + this.mpPerIdx[ this.mnCount - 1 - this.mnSmplInPrd + ( n % this.mnSmplInPrd ) ]; else rForecast = ( this.mpBase[ this.mnCount - 1 ] + n * this.mpTrend[ this.mnCount - 1 ] ) * this.mpPerIdx[ this.mnCount - 1 - this.mnSmplInPrd + ( n % this.mnSmplInPrd ) ]; if ( fInterpolate >= this.cfMinABCResolution ) { var fInterpolateFactor = fInterpolate / this.mfStepSize; var fFc_1; if ( this.bEDS ) fFc_1 = this.mpBase[ this.mnCount - 1 ] + ( n + 1 ) * this.mpTrend[ this.mnCount - 1 ]; else if ( this.bAdditive ) fFc_1 = this.mpBase[ this.mnCount - 1 ] + ( n + 1 ) * this.mpTrend[ this.mnCount - 1 ] + this.mpPerIdx[ this.mnCount - 1 - this.mnSmplInPrd + ( ( n + 1 ) % this.mnSmplInPrd ) ]; else fFc_1 = ( this.mpBase[ this.mnCount - 1 ] + ( n + 1 ) * this.mpTrend[ this.mnCount - 1 ] ) * this.mpPerIdx[ this.mnCount - 1 - this.mnSmplInPrd + ( ( n + 1 ) % this.mnSmplInPrd ) ]; rForecast = rForecast + fInterpolateFactor * ( fFc_1 - rForecast ); } } return rForecast; }; ScETSForecastCalculation.prototype.GetForecastRange = function( rTMat ) { var nC = rTMat.length, nR = rTMat[0].length; var rFcMat = []; for ( var i = 0; i < nR; i++ ) { for ( var j = 0; j < nC; j++ ) { var fTarget; if ( this.mnMonthDay ) fTarget = this.convertXtoMonths( rTMat[j][i].getValue() ); else fTarget = rTMat[j][i].getValue(); var fForecast; if ( fForecast = this.GetForecast( fTarget ) ){ if(!rFcMat[j]){ rFcMat[j] = []; } rFcMat[j][i] = fForecast; }else{ return false; } } } return rFcMat; }; ScETSForecastCalculation.prototype.GetStatisticValue = function( rTypeMat, rStatMat ) { if ( !this.initCalc() ) return false; var nC = rTypeMat.length, nR = rTypeMat[0].length; for ( var i = 0; i < nR; i++ ) { for ( var j = 0; j < nC; j++ ) { switch ( rTypeMat[j][i] ) { case 1 : // alpha rStatMat.push( this.mfAlpha, j, i ); break; case 2 : // gamma rStatMat.push( this.mfGamma, j, i ); break; case 3 : // beta rStatMat.push( this.mfBeta, j, i ); break; case 4 : // MASE rStatMat.push( this.mfMASE, j, i ); break; case 5 : // SMAPE rStatMat.push(this. mfSMAPE, j, i ); break; case 6 : // MAE rStatMat.push( this.mfMAE, j, i ); break; case 7 : // RMSE rStatMat.push( this.mfRMSE, j, i ); break; case 8 : // step size rStatMat.push( this.mfStepSize, j, i ); break; case 9 : // samples in period rStatMat.push( this.mnSmplInPrd, j, i ); break; } } } return true; }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cAVEDEV() { this.name = "AVEDEV"; this.value = null; this.argumentsCurrent = 0; } cAVEDEV.prototype = Object.create(cBaseFunction.prototype); cAVEDEV.prototype.constructor = cAVEDEV; cAVEDEV.prototype.argumentsMin = 1; cAVEDEV.prototype.Calculate = function (arg) { var count = 0, sum = new cNumber(0), arrX = [], i; for (i = 0; i < arg.length; i++) { var _arg = arg[i]; if (_arg instanceof cRef || _arg instanceof cRef3D) { var _argV = _arg.getValue(); if (_argV instanceof cNumber) { arrX.push(_argV); count++; } } else if (_arg instanceof cArea || _arg instanceof cArea3D) { var _argAreaValue = _arg.getValue(); for (var j = 0; j < _argAreaValue.length; j++) { var __arg = _argAreaValue[j]; if (__arg instanceof cNumber) { arrX.push(__arg); count++; } } } else if (_arg instanceof cArray) { _arg.foreach(function (elem) { var e = elem.tocNumber(); if (e instanceof cNumber) { arrX.push(e); count++; } }) } else { if (_arg instanceof cError) { continue; } arrX.push(_arg); count++; } } for (i = 0; i < arrX.length; i++) { sum = _func[sum.type][arrX[i].type](sum, arrX[i], "+"); } sum = new cNumber(sum.getValue() / count); var a = 0; for (i = 0; i < arrX.length; i++) { a += Math.abs(_func[sum.type][arrX[i].type](sum, arrX[i], "-").getValue()); } return this.value = new cNumber(a / count); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cAVERAGE() { this.name = "AVERAGE"; this.value = null; this.argumentsCurrent = 0; } cAVERAGE.prototype = Object.create(cBaseFunction.prototype); cAVERAGE.prototype.constructor = cAVERAGE; cAVERAGE.prototype.argumentsMin = 1; cAVERAGE.prototype.Calculate = function (arg) { var count = 0, sum = new cNumber(0); for (var i = 0; i < arg.length; i++) { var _arg = arg[i]; if (cElementType.cell === _arg.type || cElementType.cell3D === _arg.type) { if (!this.checkExclude || !_arg.isHidden(this.excludeHiddenRows)) { var _argV = _arg.getValue(); if (cElementType.string === _argV.type || cElementType.empty === _argV.type || cElementType.bool === _argV.type) { continue; } else if (cElementType.number === _argV.type) { sum = _func[sum.type][_argV.type](sum, _argV, "+"); count++; } else if (cElementType.error === _argV.type) { return this.value = _argV; } } } else if (cElementType.cellsRange === _arg.type || cElementType.cellsRange3D === _arg.type) { var _argAreaValue = _arg.getValue(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); for (var j = 0; j < _argAreaValue.length; j++) { var __arg = _argAreaValue[j]; if (cElementType.string === __arg.type || cElementType.empty === __arg.type || cElementType.bool === __arg.type) { continue; } else if (cElementType.number === __arg.type) { sum = _func[sum.type][__arg.type](sum, __arg, "+"); count++; } else if (cElementType.error === __arg.type) { return this.value = __arg; } } } else if (cElementType.array === _arg.type) { _arg.foreach(function (elem) { if (cElementType.string === elem.type || cElementType.empty === elem.type || cElementType.bool === elem.type) { return false; } var e = elem.tocNumber(); if (cElementType.number === e.type) { sum = _func[sum.type][e.type](sum, e, "+"); count++; } }) } else { _arg = _arg.tocNumber(); if (cElementType.error === _arg.type) { return this.value = _arg; } sum = _func[sum.type][_arg.type](sum, _arg, "+"); count++; } } return this.value = new cNumber(sum.getValue() / count); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cAVERAGEA() { this.name = "AVERAGEA"; this.value = null; this.argumentsCurrent = 0; } cAVERAGEA.prototype = Object.create(cBaseFunction.prototype); cAVERAGEA.prototype.constructor = cAVERAGEA; cAVERAGEA.prototype.argumentsMin = 1; cAVERAGEA.prototype.Calculate = function (arg) { var count = 0, sum = new cNumber(0); for (var i = 0; i < arg.length; i++) { var _arg = arg[i]; if (cElementType.cell === _arg.type || cElementType.cell3D === _arg.type) { var _argV = _arg.getValue(); if (cElementType.number === _argV.type || cElementType.bool === _argV.type) { sum = _func[sum.type][_argV.type](sum, _argV, "+"); count++; } else if (cElementType.string === _argV.type) { count++; } } else if (cElementType.cellsRange === _arg.type || cElementType.cellsRange3D === _arg.type) { var _argAreaValue = _arg.getValue(); for (var j = 0; j < _argAreaValue.length; j++) { var __arg = _argAreaValue[j]; if (cElementType.number === __arg.type || cElementType.bool === __arg.type) { sum = _func[sum.type][__arg.type](sum, __arg, "+"); count++; } else if (cElementType.string === __arg.type) { count++; } } } else if (cElementType.array === _arg.type) { _arg.foreach(function (elem) { if (cElementType.string === elem.type || cElementType.empty === elem.type) { return false; } var e = elem.tocNumber(); if (cElementType.number === e.type) { sum = _func[sum.type][e.type](sum, e, "+"); count++; } }) } else { _arg = _arg.tocNumber(); if (cElementType.error === _arg.type) { return this.value = _arg; } sum = _func[sum.type][_arg.type](sum, _arg, "+"); count++; } } return this.value = new cNumber(sum.getValue() / count); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cAVERAGEIF() { this.name = "AVERAGEIF"; this.value = null; this.argumentsCurrent = 0; } cAVERAGEIF.prototype = Object.create(cBaseFunction.prototype); cAVERAGEIF.prototype.constructor = cAVERAGEIF; cAVERAGEIF.prototype.argumentsMin = 2; cAVERAGEIF.prototype.argumentsMax = 3; cAVERAGEIF.prototype.Calculate = function (arg) { var arg0 = arg[0], arg1 = arg[1], arg2 = arg[2] ? arg[2] : arg[0], _sum = 0, _count = 0, matchingInfo, ws; if ((cElementType.cell !== arg0.type && cElementType.cell3D !== arg0.type && cElementType.cellsRange !== arg0.type) || (cElementType.cell !== arg2.type && cElementType.cell3D !== arg2.type && cElementType.cellsRange !== arg2.type)) { return this.value = new cError(cErrorType.wrong_value_type); } if (cElementType.cellsRange === arg1.type || cElementType.cellsRange3D === arg1.type) { arg1 = arg1.cross(arguments[1]); } else if (cElementType.array === arg1.type) { arg1 = arg1.getElementRowCol(0, 0); } arg1 = arg1.tocString(); if (cElementType.string !== arg1.type) { return this.value = new cError(cErrorType.wrong_value_type); } arg1 = arg1.toString(); var r = arg0.getRange(); var r2 = arg2.getRange(); ws = arg0.getWS(); matchingInfo = AscCommonExcel.matchingValue(arg1.toString()); if (cElementType.cellsRange === arg0.type) { arg0.foreach2(function (v, cell) { if (matching(v, matchingInfo)) { var offset = cell.getOffset3(r.bbox.c1 + 1, r.bbox.r1 + 1); r2.setOffset(offset); var val; ws._getCellNoEmpty(r2.bbox.r1, r2.bbox.c1, function(cell) { val = checkTypeCell(cell); }); offset.offsetCol *= -1; offset.offsetRow *= -1; r2.setOffset(offset); if (cElementType.number === val.type) { _sum += val.getValue(); _count++; } } }) } else { if (matching(arg0.getValue(), matchingInfo)) { var val; ws._getCellNoEmpty(r.bbox.r1, r2.bbox.c1, function(cell) { val = checkTypeCell(cell); }); if (cElementType.number === val.type) { _sum += val.getValue(); _count++; } } } if (0 === _count) { return new cError(cErrorType.division_by_zero); } else { return this.value = new cNumber(_sum / _count); } }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cAVERAGEIFS() { this.name = "AVERAGEIFS"; this.value = null; this.argumentsCurrent = 0; } cAVERAGEIFS.prototype = Object.create(cBaseFunction.prototype); cAVERAGEIFS.prototype.constructor = cAVERAGEIFS; cAVERAGEIFS.prototype.argumentsMin = 3; cAVERAGEIFS.prototype.Calculate = function (arg) { var arg0 = arg[0]; if (cElementType.cell !== arg0.type && cElementType.cell3D !== arg0.type && cElementType.cellsRange !== arg0.type) { return this.value = new cError(cErrorType.wrong_value_type); } var arg0Matrix = arg0.getMatrix(); var i, j, arg1, arg2, matchingInfo; for (var k = 1; k < arg.length; k += 2) { arg1 = arg[k]; arg2 = arg[k + 1]; if ((cElementType.cell !== arg1.type && cElementType.cell3D !== arg1.type && cElementType.cellsRange !== arg1.type)) { return this.value = new cError(cErrorType.wrong_value_type); } if (cElementType.cellsRange === arg2.type || cElementType.cellsRange3D === arg2.type) { arg2 = arg2.cross(arguments[1]); } else if (cElementType.array === arg2.type) { arg2 = arg2.getElementRowCol(0, 0); } arg2 = arg2.tocString(); if (cElementType.string !== arg2.type) { return this.value = new cError(cErrorType.wrong_value_type); } matchingInfo = AscCommonExcel.matchingValue(arg2.toString()); var arg1Matrix = arg1.getMatrix(); if (arg0Matrix.length !== arg1Matrix.length) { return this.value = new cError(cErrorType.wrong_value_type); } for (i = 0; i < arg1Matrix.length; ++i) { if (arg0Matrix[i].length !== arg1Matrix[i].length) { return this.value = new cError(cErrorType.wrong_value_type); } for (j = 0; j < arg1Matrix[i].length; ++j) { if (arg0Matrix[i][j] && !AscCommonExcel.matching(arg1Matrix[i][j], matchingInfo)) { arg0Matrix[i][j] = null; } } } } var _sum = 0, _count = 0; var valMatrix0; for (i = 0; i < arg0Matrix.length; ++i) { for (j = 0; j < arg0Matrix[i].length; ++j) { if ((valMatrix0 = arg0Matrix[i][j]) && cElementType.number === valMatrix0.type) { _sum += valMatrix0.getValue(); ++_count; } } } if (0 === _count) { return new cError(cErrorType.division_by_zero); } else { return this.value = new cNumber(_sum / _count); } }; cAVERAGEIFS.prototype.checkArguments = function () { return 1 === this.argumentsCurrent % 2 && cBaseFunction.prototype.checkArguments.apply(this, arguments); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cBETADIST() { this.name = "BETADIST"; this.value = null; this.argumentsCurrent = 0; } cBETADIST.prototype = Object.create(cBaseFunction.prototype); cBETADIST.prototype.constructor = cBETADIST; cBETADIST.prototype.argumentsMin = 3; cBETADIST.prototype.argumentsMax = 5; cBETADIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3] ? argClone[3].tocNumber() : new cNumber(0); argClone[4] = argClone[4] ? argClone[4].tocNumber() : new cNumber(1); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcBeta = function(argArray){ var x = argArray[0]; var alpha = argArray[1]; var beta = argArray[2]; var fLowerBound = argArray[3]; var fUpperBound = argArray[4]; var fScale = fUpperBound - fLowerBound; if (fScale <= 0 || alpha <= 0 || beta <= 0){ return new cError(cErrorType.not_numeric); } var res = null; if (x < fLowerBound){ res = 0; }else if(x > fUpperBound){ res = 1; }else { x = (x - fLowerBound) / fScale; res = getBetaDist(x, alpha, beta); } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcBeta); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cBETA_DIST() { this.name = "BETA.DIST"; this.value = null; this.argumentsCurrent = 0; } cBETA_DIST.prototype = Object.create(cBaseFunction.prototype); cBETA_DIST.prototype.constructor = cBETA_DIST; cBETA_DIST.prototype.argumentsMin = 4; cBETA_DIST.prototype.argumentsMax = 6; cBETA_DIST.prototype.isXLFN = true; cBETA_DIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3].tocNumber(); argClone[4] = argClone[4] ? argClone[4].tocNumber() : new cNumber(0); argClone[5] = argClone[5] ? argClone[5].tocNumber() : new cNumber(1); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcBeta = function(argArray){ var x = argArray[0]; var alpha = argArray[1]; var beta = argArray[2]; var bIsCumulative = argArray[3]; var fLowerBound = argArray[4]; var fUpperBound = argArray[5]; var res = null; if (alpha <= 0 || beta <= 0 || x < fLowerBound || x > fUpperBound) { return new cError(cErrorType.not_numeric); } var fScale = fUpperBound - fLowerBound; x = (x - fLowerBound) / fScale; if (bIsCumulative) { res = getBetaDist(x, alpha, beta); } else { res = getBetaDistPDF(x, alpha, beta) / fScale; } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcBeta); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cBETA_INV() { this.name = "BETA.INV"; this.value = null; this.argumentsCurrent = 0; } cBETA_INV.prototype = Object.create(cBaseFunction.prototype); cBETA_INV.prototype.constructor = cBETA_INV; cBETA_INV.prototype.argumentsMin = 3; cBETA_INV.prototype.argumentsMax = 5; cBETA_INV.prototype.isXLFN = true; cBETA_INV.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3] ? argClone[3].tocNumber() : new cNumber(0); argClone[4] = argClone[4] ? argClone[4].tocNumber() : new cNumber(1); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcGamma = function(argArray){ var fP = argArray[0]; var fAlpha = argArray[1]; var fBeta = argArray[2]; var fA = argArray[3]; var fB = argArray[4]; if (fP < 0 || fP > 1 || fA >= fB || fAlpha <= 0 || fBeta <= 0){ return new cError(cErrorType.not_numeric); } var aFunc = new BETADISTFUNCTION(fP, fAlpha, fBeta); var oVal = iterateInverse( aFunc, 0, 1 ); var bConvError = oVal.bError; if (bConvError){ return new cError(cErrorType.not_numeric); //SetError(FormulaError::NoConvergence); } var res = fA + oVal.val * (fB - fA) ; return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcGamma); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cBINOMDIST() { this.name = "BINOMDIST"; this.value = null; this.argumentsCurrent = 0; } cBINOMDIST.prototype = Object.create(cBaseFunction.prototype); cBINOMDIST.prototype.constructor = cBINOMDIST; cBINOMDIST.prototype.argumentsMin = 4; cBINOMDIST.prototype.argumentsMax = 4; cBINOMDIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3].tocNumber();//bool var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function binomdist(x, n, p) { x = parseInt(x); n = parseInt(n); return Math.binomCoeff(n, x) * Math.pow(p, x) * Math.pow(1 - p, n - x); } var calcBinom = function(argArray){ var arg0 = argArray[0]; var arg1 = argArray[1]; var arg2 = argArray[2]; var arg3 = argArray[3]; if (arg0 < 0 || arg0 > arg1 || arg2 < 0 || arg2 > 1) { return new cError(cErrorType.not_numeric); } if (arg3) { var x = parseInt(arg0), n = parseInt(arg1), p = arg2, bm = 0; for (var y = 0; y <= x; y++) { bm += binomdist(y, n, p); } return new cNumber(bm); } else { return new cNumber(binomdist(arg0, arg1, arg2)); } }; return this.value = this._findArrayInNumberArguments(oArguments, calcBinom); }; /** * @constructor * @extends {cBINOMDIST} */ function cBINOM_DIST() { cBINOMDIST.call(this); this.name = "BINOM.DIST"; } cBINOM_DIST.prototype = Object.create(cBINOMDIST.prototype); cBINOM_DIST.prototype.constructor = cBINOM_DIST; cBINOM_DIST.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cBINOM_DIST_RANGE() { this.name = "BINOM.DIST.RANGE"; this.value = null; this.argumentsCurrent = 0; } cBINOM_DIST_RANGE.prototype = Object.create(cBaseFunction.prototype); cBINOM_DIST_RANGE.prototype.constructor = cBINOM_DIST_RANGE; cBINOM_DIST_RANGE.prototype.argumentsMin = 3; cBINOM_DIST_RANGE.prototype.argumentsMax = 4; cBINOM_DIST_RANGE.prototype.isXLFN = true; cBINOM_DIST_RANGE.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3] ? argClone[3].tocNumber() : argClone[2]; var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function binomdist(x, n, p) { x = parseInt(x); n = parseInt(n); return Math.binomCoeff(n, x) * Math.pow(p, x) * Math.pow(1 - p, n - x); } var calcBinom = function(argArray){ var arg0 = argArray[0]; var arg1 = argArray[1]; var arg2 = argArray[2]; var arg3 = argArray[3]; if (arg0 < 0 || arg1 < 0 || arg1 > 1 || arg2 < 0 || arg2 > arg0 || arg3 < arg2 || arg3 > arg0) { return new cError(cErrorType.not_numeric); } var summ = 0; for(var i = arg2; i <= arg3; i++){ summ += binomdist(i, arg0, arg1); } return new cNumber(summ); }; return this.value = this._findArrayInNumberArguments(oArguments, calcBinom); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCHIDIST() { cBaseFunction.call(this, "CHIDIST"); } cCHIDIST.prototype = Object.create(cBaseFunction.prototype); cCHIDIST.prototype.constructor = cCHIDIST; cCHIDIST.prototype.argumentsMin = 2; cCHIDIST.prototype.argumentsMax = 2; cCHIDIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var fChi = argArray[0]; var fDF = parseInt(argArray[1]); if ( fDF < 1 || fChi < 0 || fDF > Math.pow(10, 10)){ return new cError(cErrorType.not_numeric); } var res = getChiDist( fChi, fDF); return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCHIINV() { cBaseFunction.call(this, "CHIINV"); } cCHIINV.prototype = Object.create(cBaseFunction.prototype); cCHIINV.prototype.constructor = cCHIINV; cCHIINV.prototype.argumentsMin = 2; cCHIINV.prototype.argumentsMax = 2; cCHIINV.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var fP = argArray[0]; var fDF = parseInt(argArray[1]); if ( fDF < 1 || fP <= 0 || fP > 1){ return new cError(cErrorType.not_numeric); } var aFunc = new CHIDISTFUNCTION(fP, fDF); var oVal = iterateInverse(aFunc, fDF * 0.5, fDF); var bConvError = oVal.bError; if (bConvError){ return new cError(cErrorType.not_numeric); } var res = oVal.val; return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCHISQ_DIST() { cBaseFunction.call(this, "CHISQ.DIST"); } cCHISQ_DIST.prototype = Object.create(cBaseFunction.prototype); cCHISQ_DIST.prototype.constructor = cCHISQ_DIST; cCHISQ_DIST.prototype.argumentsMin = 3; cCHISQ_DIST.prototype.argumentsMax = 3; cCHISQ_DIST.prototype.isXLFN = true; cCHISQ_DIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var fX = argArray[0]; var fDF = parseInt(argArray[1]); var bCumulative = argArray[2]; var res = null; if ( fDF < 1 || fDF > 1E10 || fX < 0){ return new cError(cErrorType.not_numeric); }else{ if ( bCumulative ){ res = getChiSqDistCDF( fX, fDF ); }else{ res = getChiSqDistPDF( fX, fDF ); } } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; if (argClone[1].getValue() < 1 ){ return this.value = new cError(cErrorType.not_numeric); } return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {cCHIDIST} */ function cCHISQ_DIST_RT() { cCHIDIST.call(this); this.name = "CHISQ.DIST.RT"; } cCHISQ_DIST_RT.prototype = Object.create(cCHIDIST.prototype); cCHISQ_DIST_RT.prototype.constructor = cCHISQ_DIST_RT; cCHISQ_DIST_RT.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCHISQ_INV() { cBaseFunction.call(this, "CHISQ.INV"); } cCHISQ_INV.prototype = Object.create(cBaseFunction.prototype); cCHISQ_INV.prototype.constructor = cCHISQ_INV; cCHISQ_INV.prototype.argumentsMin = 2; cCHISQ_INV.prototype.argumentsMax = 2; cCHISQ_INV.prototype.isXLFN = true; cCHISQ_INV.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var fP = argArray[0]; var fDF = parseInt(argArray[1]); if ( fDF < 1 || fP < 0 || fP >= 1 || fDF > 1.0E10){ return new cError(cErrorType.not_numeric); } var aFunc = new CHISQDISTFUNCTION(fP, fDF); var oVal = iterateInverse(aFunc, fDF * 0.5, fDF); var bConvError = oVal.bError; if (bConvError){ return new cError(cErrorType.not_numeric); } var res = oVal.val; return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCHISQ_INV_RT() { cBaseFunction.call(this, "CHISQ.INV.RT"); } //TODO check max 64 iterations(from documentaion) cCHISQ_INV_RT.prototype = Object.create(cBaseFunction.prototype); cCHISQ_INV_RT.prototype.constructor = cCHISQ_INV_RT; cCHISQ_INV_RT.prototype.argumentsMin = 2; cCHISQ_INV_RT.prototype.argumentsMax = 2; cCHISQ_INV_RT.prototype.isXLFN = true; cCHISQ_INV_RT.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var fP = argArray[0]; var fDF = parseInt(argArray[1]); if ( fDF < 1 || fP <= 0 || fP > 1){ return new cError(cErrorType.not_numeric); } var aFunc = new CHIDISTFUNCTION(fP, fDF); var oVal = iterateInverse(aFunc, fDF * 0.5, fDF); var bConvError = oVal.bError; if (bConvError){ return new cError(cErrorType.not_numeric); } var res = oVal.val; return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCHITEST() { this.name = "CHITEST"; this.value = null; this.argumentsCurrent = 0; } cCHITEST.prototype = Object.create(cBaseFunction.prototype); cCHITEST.prototype.constructor = cCHITEST; cCHITEST.prototype.argumentsMin = 2; cCHITEST.prototype.argumentsMax = 2; cCHITEST.prototype.Calculate = function (arg) { var arg2 = [arg[0], arg[1]]; //если первое или второе значение строка if(cElementType.string === arg[0].type || cElementType.bool === arg[0].type){ return this.value = new cError(cErrorType.wrong_value_type); } if(cElementType.string === arg[1].type || cElementType.bool === arg[1].type){ return this.value = new cError(cErrorType.wrong_value_type); } //если первое или второе значение число if(cElementType.number === arg[0].type){ arg2[0] = new cArray(); arg2[0].addElement(arg[0]); } if(cElementType.number === arg[1].type){ arg2[1] = new cArray(); arg2[1].addElement(arg[1]); } var oArguments = this._prepareArguments(arg2, arguments[1], true, [cElementType.array, cElementType.array]); var argClone = oArguments.args; var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function calcChitest(argArray) { var arg1 = argArray[0]; var arg2 = argArray[1]; return chiTest(arg1, arg2); } return this.value = this._findArrayInNumberArguments(oArguments, calcChitest); }; /** * @constructor * @extends {cCHITEST} */ function cCHISQ_TEST() { cCHITEST.call(this); this.name = "CHISQ.TEST"; } cCHISQ_TEST.prototype = Object.create(cCHITEST.prototype); cCHISQ_TEST.prototype.constructor = cCHISQ_TEST; cCHISQ_TEST.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCONFIDENCE() { this.name = "CONFIDENCE"; this.value = null; this.argumentsCurrent = 0; } cCONFIDENCE.prototype = Object.create(cBaseFunction.prototype); cCONFIDENCE.prototype.constructor = cCONFIDENCE; cCONFIDENCE.prototype.argumentsMin = 3; cCONFIDENCE.prototype.argumentsMax = 3; cCONFIDENCE.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcConfidence = function(argArray){ var alpha = argArray[0]; var stdev_sigma = argArray[1]; var size = parseInt(argArray[2]); if (alpha <= 0 || alpha >= 1 || stdev_sigma <= 0 || size < 1) { return new cError(cErrorType.not_numeric); } return new cNumber(gaussinv(1 - alpha / 2) * stdev_sigma / Math.sqrt(size)); }; return this.value = this._findArrayInNumberArguments(oArguments, calcConfidence); }; /** * @constructor * @extends {cCONFIDENCE} */ function cCONFIDENCE_NORM() { cCONFIDENCE.call(this); this.name = "CONFIDENCE.NORM"; } cCONFIDENCE_NORM.prototype = Object.create(cCONFIDENCE.prototype); cCONFIDENCE_NORM.prototype.constructor = cCONFIDENCE_NORM; cCONFIDENCE_NORM.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCONFIDENCE_T() { this.name = "CONFIDENCE.T"; this.value = null; this.argumentsCurrent = 0; } cCONFIDENCE_T.prototype = Object.create(cBaseFunction.prototype); cCONFIDENCE_T.prototype.constructor = cCONFIDENCE_T; cCONFIDENCE_T.prototype.argumentsMin = 3; cCONFIDENCE_T.prototype.argumentsMax = 3; cCONFIDENCE_T.prototype.isXLFN = true; cCONFIDENCE_T.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcConfidence = function(argArray){ var alpha = argArray[0]; var stdev_sigma = argArray[1]; var size = parseInt(argArray[2]); if (alpha <= 0 || alpha >= 1 || stdev_sigma <= 0 || size < 1) { return new cError(cErrorType.not_numeric); } var aFunc = new TDISTFUNCTION(alpha, size - 1, 2); var oVal = iterateInverse(aFunc, size * 0.5, size); var bConvError = oVal.bError; if (bConvError){ return new cError(cErrorType.not_numeric); } var res = (stdev_sigma * oVal.val) / Math.sqrt( size ); return new cNumber(res); }; return this.value = this._findArrayInNumberArguments(oArguments, calcConfidence); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCORREL() { this.name = "CORREL"; this.value = null; this.argumentsCurrent = 0; } cCORREL.prototype = Object.create(cBaseFunction.prototype); cCORREL.prototype.constructor = cCORREL; cCORREL.prototype.argumentsMin = 2; cCORREL.prototype.argumentsMax = 2; cCORREL.prototype.Calculate = function (arg) { function correl(x, y) { var s1 = 0, s2 = 0, s3 = 0, _x = 0, _y = 0, xLength = 0, i; if (x.length != y.length) { return new cError(cErrorType.not_available); } for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } _x += x[i].getValue(); _y += y[i].getValue(); xLength++; } _x /= xLength; _y /= xLength; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } s1 += (x[i].getValue() - _x) * (y[i].getValue() - _y); s2 += (x[i].getValue() - _x) * (x[i].getValue() - _x); s3 += (y[i].getValue() - _y) * (y[i].getValue() - _y); } if (s2 == 0 || s3 == 0) { return new cError(cErrorType.division_by_zero); } else { return new cNumber(s1 / Math.sqrt(s2 * s3)); } } var arg0 = arg[0], arg1 = arg[1], arr0 = [], arr1 = []; if (arg0 instanceof cArea) { arr0 = arg0.getValue(); } else if (arg0 instanceof cArray) { arg0.foreach(function (elem) { arr0.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } if (arg1 instanceof cArea) { arr1 = arg1.getValue(); } else if (arg1 instanceof cArray) { arg1.foreach(function (elem) { arr1.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } return this.value = correl(arr0, arr1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCOUNT() { this.name = "COUNT"; this.value = null; this.argumentsCurrent = 0; } cCOUNT.prototype = Object.create(cBaseFunction.prototype); cCOUNT.prototype.constructor = cCOUNT; cCOUNT.prototype.argumentsMin = 1; cCOUNT.prototype.numFormat = AscCommonExcel.cNumFormatNone; cCOUNT.prototype.Calculate = function (arg) { var count = 0; for (var i = 0; i < arg.length; i++) { var _arg = arg[i]; if (cElementType.cell === _arg.type || cElementType.cell3D === _arg.type) { if (!this.checkExclude || !_arg.isHidden(this.excludeHiddenRows)) { var _argV = _arg.getValue(); if (cElementType.number === _argV.type) { count++; } } } else if (cElementType.cellsRange === _arg.type || cElementType.cellsRange3D === _arg.type) { var _argAreaValue = _arg.getValue(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); for (var j = 0; j < _argAreaValue.length; j++) { if (cElementType.number === _argAreaValue[j].type) { count++; } } } else if (cElementType.number === _arg.type || cElementType.bool === _arg.type || cElementType.empty === _arg.type) { count++; } else if (cElementType.string === _arg.type) { if (cElementType.number === _arg.tocNumber().type) { count++; } } else if (cElementType.array === _arg.type) { _arg.foreach(function (elem) { if (cElementType.number === elem.tocNumber().type) { count++; } }) } } return this.value = new cNumber(count); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCOUNTA() { this.name = "COUNTA"; this.value = null; this.argumentsCurrent = 0; } cCOUNTA.prototype = Object.create(cBaseFunction.prototype); cCOUNTA.prototype.constructor = cCOUNTA; cCOUNTA.prototype.argumentsMin = 1; cCOUNTA.prototype.numFormat = AscCommonExcel.cNumFormatNone; cCOUNTA.prototype.Calculate = function (arg) { var element, count = 0; for (var i = 0; i < arg.length; i++) { element = arg[i]; if (cElementType.cell === element.type || cElementType.cell3D === element.type) { if (!this.checkExclude || !element.isHidden(this.excludeHiddenRows)) { var _argV = element.getValue(); if (cElementType.empty !== _argV.type) { count++; } } } else if (cElementType.cellsRange === element.type || cElementType.cellsRange3D === element.type) { var _argAreaValue = element.getValue(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); for (var j = 0; j < _argAreaValue.length; j++) { if (cElementType.empty !== _argAreaValue[j].type) { count++; } } } else if (cElementType.array === element.type) { element.foreach(function (elem) { if (cElementType.empty !== elem.type) { count++; } }) } else if (cElementType.empty !== element.type) { count++; } } return this.value = new cNumber(count); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCOUNTBLANK() { this.name = "COUNTBLANK"; this.value = null; this.argumentsCurrent = 0; } cCOUNTBLANK.prototype = Object.create(cBaseFunction.prototype); cCOUNTBLANK.prototype.constructor = cCOUNTBLANK; cCOUNTBLANK.prototype.argumentsMin = 1; cCOUNTBLANK.prototype.argumentsMax = 1; cCOUNTBLANK.prototype.numFormat = AscCommonExcel.cNumFormatNone; cCOUNTBLANK.prototype.Calculate = function (arg) { var arg0 = arg[0]; if (arg0 instanceof cArea || arg0 instanceof cArea3D) { return this.value = arg0.countCells(); } else if (arg0 instanceof cRef || arg0 instanceof cRef3D) { return this.value = new cNumber(1); } else { return this.value = new cError(cErrorType.bad_reference); } }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCOUNTIF() { this.name = "COUNTIF"; this.value = null; this.argumentsCurrent = 0; } cCOUNTIF.prototype = Object.create(cBaseFunction.prototype); cCOUNTIF.prototype.constructor = cCOUNTIF; cCOUNTIF.prototype.argumentsMin = 2; cCOUNTIF.prototype.argumentsMax = 2; cCOUNTIF.prototype.numFormat = AscCommonExcel.cNumFormatNone; cCOUNTIF.prototype.Calculate = function (arg) { var arg0 = arg[0], arg1 = arg[1], _count = 0, matchingInfo; if (cElementType.cell !== arg0.type && cElementType.cell3D !== arg0.type && cElementType.cellsRange !== arg0.type && cElementType.cellsRange3D !== arg0.type) { return this.value = new cError(cErrorType.wrong_value_type); } if (cElementType.cellsRange === arg1.type || cElementType.cellsRange3D === arg1.type) { arg1 = arg1.cross(arguments[1]); } else if (cElementType.array === arg1.type) { arg1 = arg1.getElementRowCol(0, 0); }else if(cElementType.cell === arg1.type || cElementType.cell3D === arg1.type){ arg1 = arg1.getValue(); } /*arg1 = arg1.tocString(); if (cElementType.string !== arg1.type) { return this.value = new cError(cErrorType.wrong_value_type); }*/ var compareValues = function(val, matchingInfo){ var res; if(val.type === arg1.type && val.value === arg1.value){ return true; } res = matching(val, matchingInfo); return res; }; var val; matchingInfo = AscCommonExcel.matchingValue(arg1.toString()); if (cElementType.cellsRange === arg0.type) { arg0.foreach2(function (_val) { _count += compareValues(_val, matchingInfo); }) } else if (cElementType.cellsRange3D === arg0.type) { val = arg0.getValue(); for (var i = 0; i < val.length; i++) { _count += compareValues(val[i], matchingInfo); } } else { val = arg0.getValue(); _count += compareValues(val, matchingInfo); } return this.value = new cNumber(_count); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCOUNTIFS() { this.name = "COUNTIFS"; this.value = null; this.argumentsCurrent = 0; } cCOUNTIFS.prototype = Object.create(cBaseFunction.prototype); cCOUNTIFS.prototype.constructor = cCOUNTIFS; cCOUNTIFS.prototype.argumentsMin = 2; cCOUNTIFS.prototype.argumentsMax = 254; cCOUNTIFS.prototype.numFormat = AscCommonExcel.cNumFormatNone; cCOUNTIFS.prototype.Calculate = function (arg) { var i, j, arg0, arg1, matchingInfo, arg0Matrix, arg1Matrix, _count = 0; for (var k = 0; k < arg.length; k += 2) { arg0 = arg[k]; arg1 = arg[k + 1]; if (cElementType.cell !== arg0.type && cElementType.cell3D !== arg0.type && cElementType.cellsRange !== arg0.type && !(cElementType.cellsRange3D === arg0.type && arg0.isSingleSheet())) { return this.value = new cError(cErrorType.wrong_value_type); } if (cElementType.cellsRange === arg1.type || cElementType.cellsRange3D === arg1.type) { arg1 = arg1.cross(arguments[1]); } else if (cElementType.array === arg1.type) { arg1 = arg1.getElementRowCol(0, 0); } arg1 = arg1.tocString(); if (cElementType.string !== arg1.type) { return this.value = new cError(cErrorType.wrong_value_type); } matchingInfo = AscCommonExcel.matchingValue(arg1.toString()); arg1Matrix = arg0.getMatrix(); if (cElementType.cellsRange3D === arg0.type) { arg1Matrix = arg1Matrix[0]; } if (!arg0Matrix) { arg0Matrix = arg1Matrix; } if (arg0Matrix.length !== arg1Matrix.length) { return this.value = new cError(cErrorType.wrong_value_type); } for (i = 0; i < arg1Matrix.length; ++i) { if (arg0Matrix[i].length !== arg1Matrix[i].length) { return this.value = new cError(cErrorType.wrong_value_type); } for (j = 0; j < arg1Matrix[i].length; ++j) { if (arg0Matrix[i][j] && !matching(arg1Matrix[i][j], matchingInfo)) { arg0Matrix[i][j] = null; } } } } for (i = 0; i < arg0Matrix.length; ++i) { for (j = 0; j < arg0Matrix[i].length; ++j) { if (arg0Matrix[i][j]) { ++_count; } } } return this.value = new cNumber(_count); }; cCOUNTIFS.prototype.checkArguments = function () { return 0 === this.argumentsCurrent % 2 && cBaseFunction.prototype.checkArguments.apply(this, arguments); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCOVAR() { this.name = "COVAR"; this.value = null; this.argumentsCurrent = 0; } cCOVAR.prototype = Object.create(cBaseFunction.prototype); cCOVAR.prototype.constructor = cCOVAR; cCOVAR.prototype.argumentsMin = 2; cCOVAR.prototype.argumentsMax = 2; cCOVAR.prototype.Calculate = function (arg) { function covar(x, y) { var s1 = 0, _x = 0, _y = 0, xLength = 0, i; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } _x += x[i].getValue(); _y += y[i].getValue(); xLength++; } if (xLength == 0) { return new cError(cErrorType.division_by_zero); } _x /= xLength; _y /= xLength; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } s1 += (x[i].getValue() - _x) * (y[i].getValue() - _y); } return new cNumber(s1 / xLength); } var arg0 = arg[0], arg1 = arg[1], arr0 = [], arr1 = []; if (arg0 instanceof cArea) { arr0 = arg0.getValue(); } else if (arg0 instanceof cArray) { arg0.foreach(function (elem) { arr0.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } if (arg1 instanceof cArea) { arr1 = arg1.getValue(); } else if (arg1 instanceof cArray) { arg1.foreach(function (elem) { arr1.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } return this.value = covar(arr0, arr1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCOVARIANCE_P() { this.name = "COVARIANCE.P"; this.value = null; this.argumentsCurrent = 0; } cCOVARIANCE_P.prototype = Object.create(cBaseFunction.prototype); cCOVARIANCE_P.prototype.constructor = cCOVARIANCE_P; cCOVARIANCE_P.prototype.argumentsMin = 2; cCOVARIANCE_P.prototype.argumentsMax = 2; cCOVARIANCE_P.prototype.isXLFN = true; cCOVARIANCE_P.prototype.Calculate = function (arg) { var arg2 = [arg[0], arg[1]]; //если первое или второе значение строка if(cElementType.string === arg[0].type || cElementType.bool === arg[0].type){ return this.value = new cError(cErrorType.wrong_value_type); } if(cElementType.string === arg[1].type || cElementType.bool === arg[1].type){ return this.value = new cError(cErrorType.wrong_value_type); } //если первое или второе значение число if(cElementType.number === arg[0].type){ arg2[0] = new cArray(); arg2[0].addElement(arg[0]); } if(cElementType.number === arg[1].type){ arg2[1] = new cArray(); arg2[1].addElement(arg[1]); } var oArguments = this._prepareArguments(arg2, arguments[1], true, [cElementType.array, cElementType.array]); var argClone = oArguments.args; var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function pearson(argArray) { var arg1 = argArray[0]; var arg2 = argArray[1]; var x = []; var y = []; for (var i = 0; i < arg1.length; i++) { for (var j = 0; j < arg1[i].length; j++) { x.push(arg1[i][j]); } } for (var i = 0; i < arg2.length; i++) { for (var j = 0; j < arg2[i].length; j++) { y.push(arg2[i][j]); } } var sumXDeltaYDelta = 0, sqrXDelta = 0, sqrYDelta = 0, _x = 0, _y = 0, xLength = 0, i; if (x.length !== y.length) { return new cError(cErrorType.not_available); } for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } _x += x[i].getValue(); _y += y[i].getValue(); xLength++; } _x /= xLength; _y /= xLength; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } sumXDeltaYDelta += (x[i].getValue() - _x) * (y[i].getValue() - _y); } return new cNumber(sumXDeltaYDelta / xLength); } return this.value = this._findArrayInNumberArguments(oArguments, pearson); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCOVARIANCE_S() { this.name = "COVARIANCE.S"; this.value = null; this.argumentsCurrent = 0; } cCOVARIANCE_S.prototype = Object.create(cBaseFunction.prototype); cCOVARIANCE_S.prototype.constructor = cCOVARIANCE_S; cCOVARIANCE_S.prototype.argumentsMin = 2; cCOVARIANCE_S.prototype.argumentsMax = 2; cCOVARIANCE_S.prototype.isXLFN = true; cCOVARIANCE_S.prototype.Calculate = function (arg) { var arg2 = [arg[0], arg[1]]; //если первое или второе значение строка if(cElementType.string === arg[0].type || cElementType.bool === arg[0].type){ return this.value = new cError(cErrorType.wrong_value_type); } if(cElementType.string === arg[1].type || cElementType.bool === arg[1].type){ return this.value = new cError(cErrorType.wrong_value_type); } //если первое или второе значение число if(cElementType.number === arg[0].type){ arg2[0] = new cArray(); arg2[0].addElement(arg[0]); } if(cElementType.number === arg[1].type){ arg2[1] = new cArray(); arg2[1].addElement(arg[1]); } var oArguments = this._prepareArguments(arg2, arguments[1], true, [cElementType.array, cElementType.array]); var argClone = oArguments.args; var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function pearson(argArray) { var arg1 = argArray[0]; var arg2 = argArray[1]; var x = []; var y = []; for (var i = 0; i < arg1.length; i++) { for (var j = 0; j < arg1[i].length; j++) { x.push(arg1[i][j]); } } for (var i = 0; i < arg2.length; i++) { for (var j = 0; j < arg2[i].length; j++) { y.push(arg2[i][j]); } } var sumXDeltaYDelta = 0, sqrXDelta = 0, sqrYDelta = 0, _x = 0, _y = 0, xLength = 0, i; if (x.length !== y.length) { return new cError(cErrorType.not_available); } for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } _x += x[i].getValue(); _y += y[i].getValue(); xLength++; } if (xLength < 2.0){ return new cError(cErrorType.division_by_zero); } _x /= xLength; _y /= xLength; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } sumXDeltaYDelta += (x[i].getValue() - _x) * (y[i].getValue() - _y); } return new cNumber(sumXDeltaYDelta / (xLength - 1)); } return this.value = this._findArrayInNumberArguments(oArguments, pearson); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cCRITBINOM() { this.name = "CRITBINOM"; this.value = null; this.argumentsCurrent = 0; } cCRITBINOM.prototype = Object.create(cBaseFunction.prototype); cCRITBINOM.prototype.constructor = cCRITBINOM; cCRITBINOM.prototype.argumentsMin = 3; cCRITBINOM.prototype.argumentsMax = 3; cCRITBINOM.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function critbinom(argArray) { var n = argArray[0]; var p = argArray[1]; var alpha = argArray[2]; if (n < 0 || alpha <= 0 || alpha >= 1 || p < 0 || p > 1) { return new cError(cErrorType.not_numeric); } else { var q = 1 - p, factor = Math.pow(q, n), i, sum, max; if (factor == 0) { factor = Math.pow(p, n); if (factor == 0.0) { return new cError(cErrorType.wrong_value_type); } else { sum = 1 - factor; max = n; for (i = 0; i < max && sum >= alpha; i++) { factor *= (n - i) / (i + 1) * q / p; sum -= factor; } return new cNumber(n - i); } } else { sum = factor; max = n; for (i = 0; i < max && sum < alpha; i++) { factor *= (n - i) / (i + 1) * p / q; sum += factor; } return new cNumber(i); } } } return this.value = this._findArrayInNumberArguments(oArguments, critbinom); }; /** * @constructor * @extends {cCRITBINOM} */ function cBINOM_INV() { cCRITBINOM.call(this); this.name = "BINOM.INV"; } cBINOM_INV.prototype = Object.create(cCRITBINOM.prototype); cBINOM_INV.prototype.constructor = cBINOM_INV; cBINOM_INV.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cDEVSQ() { this.name = "DEVSQ"; this.value = null; this.argumentsCurrent = 0; } cDEVSQ.prototype = Object.create(cBaseFunction.prototype); cDEVSQ.prototype.constructor = cDEVSQ; cDEVSQ.prototype.argumentsMin = 1; cDEVSQ.prototype.Calculate = function (arg) { function devsq(x) { var s1 = 0, _x = 0, xLength = 0, i; for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { _x += x[i].getValue(); xLength++; } } _x /= xLength; for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { s1 += Math.pow(x[i].getValue() - _x, 2); } } return new cNumber(s1); } var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber) { arr0.push(a); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString) { continue; } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = devsq(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cEXPON_DIST() { this.name = "EXPON.DIST"; this.value = null; this.argumentsCurrent = 0; } cEXPON_DIST.prototype = Object.create(cBaseFunction.prototype); cEXPON_DIST.prototype.constructor = cEXPON_DIST; cEXPON_DIST.prototype.argumentsMin = 3; cEXPON_DIST.prototype.argumentsMax = 3; cEXPON_DIST.prototype.isXLFN = true; cEXPON_DIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcFDist = function(argArray){ var arg0 = argArray[0]; var arg1 = argArray[1]; var arg2 = argArray[2]; if (arg0 < 0 || arg1 <= 0) { return new cError(cErrorType.not_numeric); } var res = null; if (arg2) { res = 1 - Math.exp(-arg1 * arg0); } else { res = arg1 * Math.exp(-arg1 * arg0); } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcFDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cEXPONDIST() { this.name = "EXPONDIST"; this.value = null; this.argumentsCurrent = 0; } cEXPONDIST.prototype = Object.create(cBaseFunction.prototype); cEXPONDIST.prototype.constructor = cEXPONDIST; cEXPONDIST.prototype.argumentsMin = 3; cEXPONDIST.prototype.argumentsMax = 3; cEXPONDIST.prototype.Calculate = function (arg) { var arg0 = arg[0], arg1 = arg[1], arg2 = arg[2], arg3 = arg[3]; if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } else if (arg0 instanceof cArray) { arg0 = arg0.getElement(0); } if (arg1 instanceof cArea || arg1 instanceof cArea3D) { arg1 = arg1.cross(arguments[1]); } else if (arg1 instanceof cArray) { arg1 = arg1.getElement(0); } if (arg2 instanceof cArea || arg2 instanceof cArea3D) { arg2 = arg2.cross(arguments[1]); } else if (arg2 instanceof cArray) { arg2 = arg2.getElement(0); } arg0 = arg0.tocNumber(); arg1 = arg1.tocNumber(); arg2 = arg2.tocBool(); if (arg0 instanceof cError) { return this.value = arg0; } if (arg1 instanceof cError) { return this.value = arg1; } if (arg2 instanceof cError) { return this.value = arg2; } if (arg0.getValue() < 0 || arg2.getValue() <= 0) { return this.value = new cError(cErrorType.not_numeric); } if (arg2.toBool()) { return this.value = new cNumber(1 - Math.exp(-arg1.getValue() * arg0.getValue())); } else { return this.value = new cNumber(arg1.getValue() * Math.exp(-arg1.getValue() * arg0.getValue())); } }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cF_DIST() { cBaseFunction.call(this, "F.DIST"); } cF_DIST.prototype = Object.create(cBaseFunction.prototype); cF_DIST.prototype.constructor = cF_DIST; cF_DIST.prototype.argumentsMin = 3; cF_DIST.prototype.argumentsMax = 4; cF_DIST.prototype.isXLFN = true; cF_DIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3] ? argClone[3].tocNumber() : new cBool(true); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcFDist = function(argArray){ var fF = argArray[0]; var fF1 = argArray[1]; var fF2 = argArray[2]; var bCum = argArray[3]; if ( fF < 0 || fF1 < 1 || fF2 < 1 || fF1 >= 1.0E10 || fF2 >= 1.0E10 ){ return new cError(cErrorType.not_numeric); } var res; if ( bCum ) { res = 1 - getFDist( fF, fF1, fF2 ); }else{ res = Math.pow( fF1 / fF2, fF1 / 2 ) * Math.pow( fF, ( fF1 / 2 ) - 1 ) / ( Math.pow( ( 1 + ( fF * fF1 / fF2 ) ), ( fF1 + fF2 ) / 2 ) * getBeta( fF1 / 2, fF2 / 2 ) ); } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcFDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cF_DIST_RT() { cBaseFunction.call(this, "F.DIST.RT"); } cF_DIST_RT.prototype = Object.create(cBaseFunction.prototype); cF_DIST_RT.prototype.constructor = cF_DIST_RT; cF_DIST_RT.prototype.argumentsMin = 3; cF_DIST_RT.prototype.argumentsMax = 3; cF_DIST_RT.prototype.isXLFN = true; cF_DIST_RT.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcFDist = function(argArray){ var fF = argArray[0]; var fF1 = argArray[1]; var fF2 = argArray[2]; if (fF < 0 || fF1 < 1 || fF2 < 1 || fF1 >= 1.0E10 || fF2 >= 1.0E10){ return new cError(cErrorType.not_numeric); } var res = getFDist(fF, fF1, fF2); return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; if (argClone[1].getValue() < 1 ){ return this.value = new cError(cErrorType.not_numeric); } return this.value = this._findArrayInNumberArguments(oArguments, calcFDist); }; /** * @constructor * @extends {cF_DIST_RT} */ function cFDIST() { cF_DIST_RT.call(this); this.name = "FDIST"; } cFDIST.prototype = Object.create(cF_DIST_RT.prototype); cFDIST.prototype.constructor = cFDIST; cFDIST.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cF_INV() { cBaseFunction.call(this, "F.INV"); } cF_INV.prototype = Object.create(cBaseFunction.prototype); cF_INV.prototype.constructor = cF_INV; cF_INV.prototype.argumentsMin = 3; cF_INV.prototype.argumentsMax = 3; cF_INV.prototype.isXLFN = true; cF_INV.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcFDist = function(argArray){ var fP = argArray[0]; var fF1 = parseInt(argArray[1]); var fF2 = parseInt(argArray[2]); if (fP <= 0 || fF1 < 1 || fF2 < 1 || fF1 >= 1.0E10 || fF2 >= 1.0E10 || fP > 1){ return new cError(cErrorType.not_numeric); } var aFunc = new FDISTFUNCTION(1 - fP, fF1, fF2); var oVal = iterateInverse( aFunc, fF1*0.5, fF1 ); var bConvError = oVal.bError; if (bConvError){ return new cError(cErrorType.not_numeric); } var res = oVal.val; return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; if (argClone[1].getValue() < 1 ){ return this.value = new cError(cErrorType.not_numeric); } return this.value = this._findArrayInNumberArguments(oArguments, calcFDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cFINV() { cBaseFunction.call(this, "FINV"); } cFINV.prototype = Object.create(cBaseFunction.prototype); cFINV.prototype.constructor = cFINV; cFINV.prototype.argumentsMin = 3; cFINV.prototype.argumentsMax = 3; cFINV.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcFDist = function(argArray){ var fP = argArray[0]; var fF1 = parseInt(argArray[1]); var fF2 = parseInt(argArray[2]); if (fP <= 0 || fF1 < 1 || fF2 < 1 || fF1 >= 1.0E10 || fF2 >= 1.0E10 || fP > 1){ return new cError(cErrorType.not_numeric); } var aFunc = new FDISTFUNCTION(fP, fF1, fF2); var oVal = iterateInverse( aFunc, fF1*0.5, fF1 ); var bConvError = oVal.bError; if (bConvError){ return new cError(cErrorType.not_numeric); } var res = oVal.val; return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; if (argClone[1].getValue() < 1 ){ return this.value = new cError(cErrorType.not_numeric); } return this.value = this._findArrayInNumberArguments(oArguments, calcFDist); }; /** * @constructor * @extends {cFINV} */ function cF_INV_RT() { cFINV.call(this); this.name = "F.INV.RT"; } cF_INV_RT.prototype = Object.create(cFINV.prototype); cF_INV_RT.prototype.constructor = cF_INV_RT; cF_INV_RT.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cFISHER() { this.name = "FISHER"; this.value = null; this.argumentsCurrent = 0; } cFISHER.prototype = Object.create(cBaseFunction.prototype); cFISHER.prototype.constructor = cFISHER; cFISHER.prototype.argumentsMin = 1; cFISHER.prototype.argumentsMax = 1; cFISHER.prototype.Calculate = function (arg) { var arg0 = arg[0]; function fisher(x) { return 0.5 * Math.ln((1 + x) / (1 - x)); } if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } arg0 = arg0.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } else if (arg0 instanceof cArray) { arg0.foreach(function (elem, r, c) { if (elem instanceof cNumber) { var a = fisher(elem.getValue()); this.array[r][c] = isNaN(a) ? new cError(cErrorType.not_numeric) : new cNumber(a); } else { this.array[r][c] = new cError(cErrorType.wrong_value_type); } }) } else { var a = fisher(arg0.getValue()); return this.value = isNaN(a) ? new cError(cErrorType.not_numeric) : new cNumber(a); } return this.value = arg0; }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cFISHERINV() { this.name = "FISHERINV"; this.value = null; this.argumentsCurrent = 0; } cFISHERINV.prototype = Object.create(cBaseFunction.prototype); cFISHERINV.prototype.constructor = cFISHERINV; cFISHERINV.prototype.argumentsMin = 1; cFISHERINV.prototype.argumentsMax = 1; cFISHERINV.prototype.Calculate = function (arg) { var arg0 = arg[0]; function fisherInv(x) { return ( Math.exp(2 * x) - 1 ) / ( Math.exp(2 * x) + 1 ); } if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } arg0 = arg0.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } else if (arg0 instanceof cArray) { arg0.foreach(function (elem, r, c) { if (elem instanceof cNumber) { var a = fisherInv(elem.getValue()); this.array[r][c] = isNaN(a) ? new cError(cErrorType.not_numeric) : new cNumber(a); } else { this.array[r][c] = new cError(cErrorType.wrong_value_type); } }) } else { var a = fisherInv(arg0.getValue()); return this.value = isNaN(a) ? new cError(cErrorType.not_numeric) : new cNumber(a); } return this.value = arg0; }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cFORECAST() { this.name = "FORECAST"; this.value = null; this.argumentsCurrent = 0; } cFORECAST.prototype = Object.create(cBaseFunction.prototype); cFORECAST.prototype.constructor = cFORECAST; cFORECAST.prototype.argumentsMin = 3; cFORECAST.prototype.argumentsMax = 3; cFORECAST.prototype.Calculate = function (arg) { function forecast(fx, y, x) { var fSumDeltaXDeltaY = 0, fSumSqrDeltaX = 0, _x = 0, _y = 0, xLength = 0, i; if(x.length !== y.length){ return new cError(cErrorType.not_available); } for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } _x += x[i].getValue(); _y += y[i].getValue(); xLength++; } _x /= xLength; _y /= xLength; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } var fValX = x[i].getValue(); var fValY = y[i].getValue(); fSumDeltaXDeltaY += ( fValX - _x ) * ( fValY - _y ); fSumSqrDeltaX += ( fValX - _x ) * ( fValX - _x ); } if (fSumDeltaXDeltaY == 0) { return new cError(cErrorType.division_by_zero); } else { return new cNumber(_y + fSumDeltaXDeltaY / fSumSqrDeltaX * ( fx.getValue() - _x )); } } var arg0 = arg[0], arg1 = arg[1], arg2 = arg[2], arr0 = [], arr1 = []; if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } else if (arg0 instanceof cArray) { arg0 = arg0.getElement(0); } arg0 = arg0.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } if (arg1 instanceof cArea) { arr0 = arg1.getValue(); } else if (arg1 instanceof cArray) { arg1.foreach(function (elem) { arr0.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } if (arg2 instanceof cArea) { arr1 = arg2.getValue(); } else if (arg2 instanceof cArray) { arg2.foreach(function (elem) { arr1.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } return this.value = forecast(arg0, arr0, arr1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cFORECAST_ETS() { this.name = "FORECAST.ETS"; this.value = null; this.argumentsCurrent = 0; } cFORECAST_ETS.prototype = Object.create(cBaseFunction.prototype); cFORECAST_ETS.prototype.constructor = cFORECAST_ETS; cFORECAST_ETS.prototype.argumentsMin = 3; cFORECAST_ETS.prototype.argumentsMax = 6; cFORECAST_ETS.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true, [null, cElementType.array, cElementType.array]); var argClone = oArguments.args; argClone[3] = argClone[3] ? argClone[3].tocNumber() : new cNumber(1); argClone[4] = argClone[4] ? argClone[4].tocNumber() : new cNumber(1); argClone[5] = argClone[5] ? argClone[5].tocNumber() : new cNumber(1); argClone[0] = argClone[0].getMatrix(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var pTMat = argClone[0]; var pMatY = argClone[1]; var pMatX = argClone[2]; var nSmplInPrd = argClone[3]; var bDataCompletion = argClone[4]; var nAggregation = argClone[5]; var aETSCalc = new ScETSForecastCalculation( pMatX.length ); var isError = aETSCalc.PreprocessDataRange( pMatX, pMatY, nSmplInPrd, bDataCompletion, nAggregation, pTMat); if ( !isError) { ///*,( eETSType != etsStatAdd && eETSType != etsStatMult ? pTMat : nullptr ),eETSType ) return new cError(cErrorType.wrong_value_type); }else if(isError && cElementType.error === isError.type){ return isError; } var pFcMat = aETSCalc.GetForecastRange( pTMat); return new cNumber(pFcMat[0][0]); }; /** * @constructor * @extends {cFORECAST} */ function cFORECAST_LINEAR() { cFORECAST.call(this); this.name = "FORECAST.LINEAR"; } cFORECAST_LINEAR.prototype = Object.create(cFORECAST.prototype); cFORECAST_LINEAR.prototype.constructor = cFORECAST_LINEAR; cFORECAST_LINEAR.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cFREQUENCY() { this.name = "FREQUENCY"; this.value = null; this.argumentsCurrent = 0; } cFREQUENCY.prototype = Object.create(cBaseFunction.prototype); cFREQUENCY.prototype.constructor = cFREQUENCY; cFREQUENCY.prototype.argumentsMin = 2; cFREQUENCY.prototype.argumentsMax = 2; cFREQUENCY.prototype.numFormat = AscCommonExcel.cNumFormatNone; cFREQUENCY.prototype.Calculate = function (arg) { function frequency(A, B) { var tA = [], tB = [Number.NEGATIVE_INFINITY], i, j; for (i = 0; i < A.length; i++) { for (j = 0; j < A[i].length; j++) { if (A[i][j] instanceof cError) { return A[i][j]; } else if (A[i][j] instanceof cNumber) { tA.push(A[i][j].getValue()); } else if (A[i][j] instanceof cBool) { tA.push(A[i][j].tocNumber().getValue()); } } } for (i = 0; i < B.length; i++) { for (j = 0; j < B[i].length; j++) { if (B[i][j] instanceof cError) { return B[i][j]; } else if (B[i][j] instanceof cNumber) { tB.push(B[i][j].getValue()); } else if (B[i][j] instanceof cBool) { tB.push(B[i][j].tocNumber().getValue()); } } } tA.sort(fSortAscending); tB.push(Number.POSITIVE_INFINITY); tB.sort(fSortAscending); var C = [[]], k = 0; for (i = 1; i < tB.length; i++, k++) { C[0][k] = new cNumber(0); for (j = 0; j < tA.length; j++) { if (tA[j] > tB[i - 1] && tA[j] <= tB[i]) { var a = C[0][k].getValue(); C[0][k] = new cNumber(++a); } } } var res = new cArray(); res.fillFromArray(C); return res; } var arg0 = arg[0], arg1 = arg[1]; if (arg0 instanceof cArea || arg0 instanceof cArray) { arg0 = arg0.getMatrix(); } else if (arg0 instanceof cArea3D) { arg0 = arg0.getMatrix()[0]; } else { return this.value = new cError(cErrorType.not_available); } if (arg1 instanceof cArea || arg1 instanceof cArray) { arg1 = arg1.getMatrix(); } else if (arg1 instanceof cArea3D) { arg1 = arg1.getMatrix()[0]; } else { return this.value = new cError(cErrorType.not_available); } return this.value = frequency(arg0, arg1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cFTEST() { cBaseFunction.call(this, "FTEST"); } cFTEST.prototype = Object.create(cBaseFunction.prototype); cFTEST.prototype.constructor = cFTEST; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cGAMMA() { this.name = "GAMMA"; this.value = null; this.argumentsCurrent = 0; } cGAMMA.prototype = Object.create(cBaseFunction.prototype); cGAMMA.prototype.constructor = cGAMMA; cGAMMA.prototype.argumentsMin = 1; cGAMMA.prototype.argumentsMax = 1; cGAMMA.prototype.isXLFN = true; cGAMMA.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcGamma = function(argArray){ if(argArray[0] <= 0 && isInteger(argArray[0])){ return new cError(cErrorType.not_numeric); } var res = getGamma(argArray[0]); return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcGamma); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cGAMMA_DIST() { this.name = "GAMMA.DIST"; this.value = null; this.argumentsCurrent = 0; } cGAMMA_DIST.prototype = Object.create(cBaseFunction.prototype); cGAMMA_DIST.prototype.constructor = cGAMMA_DIST; cGAMMA_DIST.prototype.argumentsMin = 4; cGAMMA_DIST.prototype.argumentsMax = 4; cGAMMA_DIST.prototype.isXLFN = true; cGAMMA_DIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcGamma = function(argArray){ var fX = argArray[0]; var fAlpha = argArray[1]; var fBeta = argArray[2]; var bCumulative = argArray[3]; var res = null; if ((fX < 0) || fAlpha <= 0 || fBeta <= 0){ return new cError(cErrorType.not_numeric); } else { if (bCumulative) { res = getGammaDist( fX, fAlpha, fBeta ); }else { res = getGammaDistPDF( fX, fAlpha, fBeta ); } } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcGamma); }; /** * @constructor * @extends {cGAMMA_DIST} */ function cGAMMADIST() { cGAMMA_DIST.call(this); this.name = "GAMMADIST"; } cGAMMADIST.prototype = Object.create(cGAMMA_DIST.prototype); cGAMMADIST.prototype.constructor = cGAMMADIST; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cGAMMA_INV() { this.name = "GAMMA.INV"; this.value = null; this.argumentsCurrent = 0; } cGAMMA_INV.prototype = Object.create(cBaseFunction.prototype); cGAMMA_INV.prototype.constructor = cGAMMA_INV; cGAMMA_INV.prototype.argumentsMin = 3; cGAMMA_INV.prototype.argumentsMax = 3; cGAMMA_INV.prototype.isXLFN = true; cGAMMA_INV.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcGamma = function(argArray){ var fP = argArray[0]; var fAlpha = argArray[1]; var fBeta = argArray[2]; if (fAlpha <= 0 || fBeta <= 0 || fP < 0 || fP >= 1 ){ return new cError(cErrorType.not_numeric); } var res = null; if (fP === 0){ res = 0; }else { var aFunc = new GAMMADISTFUNCTION(fP, fAlpha, fBeta); var fStart = fAlpha * fBeta; var oVal = iterateInverse(aFunc, fStart * 0.5, fStart); var bConvError = oVal.bError; if (bConvError){ return new cError(cErrorType.not_numeric); //SetError(FormulaError::NoConvergence); } res = oVal.val; } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcGamma); }; /** * @constructor * @extends {cGAMMA_INV} */ function cGAMMAINV() { cGAMMA_INV.call(this); this.name = "GAMMAINV"; } cGAMMAINV.prototype = Object.create(cGAMMA_INV.prototype); cGAMMAINV.prototype.constructor = cGAMMAINV; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cGAMMALN() { this.name = "GAMMALN"; this.value = null; this.argumentsCurrent = 0; } cGAMMALN.prototype = Object.create(cBaseFunction.prototype); cGAMMALN.prototype.constructor = cGAMMALN; cGAMMALN.prototype.argumentsMin = 1; cGAMMALN.prototype.argumentsMax = 1; cGAMMALN.prototype.Calculate = function (arg) { /* from OpenOffice Source. end */ var arg0 = arg[0]; if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } arg0 = arg0.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } else if (arg0 instanceof cArray) { arg0.foreach(function (elem, r, c) { if (elem instanceof cNumber) { var a = getLogGamma(elem.getValue()); this.array[r][c] = isNaN(a) ? new cError(cErrorType.not_numeric) : new cNumber(a); } else { this.array[r][c] = new cError(cErrorType.wrong_value_type); } }) } else { var a = getLogGamma(arg0.getValue()); return this.value = isNaN(a) ? new cError(cErrorType.not_numeric) : new cNumber(a); } return this.value = arg0; }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cGAMMALN_PRECISE() { this.name = "GAMMALN.PRECISE"; this.value = null; this.argumentsCurrent = 0; } cGAMMALN_PRECISE.prototype = Object.create(cBaseFunction.prototype); cGAMMALN_PRECISE.prototype.constructor = cGAMMALN_PRECISE; cGAMMALN_PRECISE.prototype.argumentsMin = 1; cGAMMALN_PRECISE.prototype.argumentsMax = 1; cGAMMALN_PRECISE.prototype.isXLFN = true; cGAMMALN_PRECISE.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcGamma = function(argArray) { var a = getLogGamma(argArray[0]); return isNaN(a) ? new cError(cErrorType.not_numeric) : new cNumber(a); }; return this.value = this._findArrayInNumberArguments(oArguments, calcGamma); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cGAUSS() { this.name = "GAUSS"; this.value = null; this.argumentsCurrent = 0; } cGAUSS.prototype = Object.create(cBaseFunction.prototype); cGAUSS.prototype.constructor = cGAUSS; cGAUSS.prototype.argumentsMin = 1; cGAUSS.prototype.argumentsMax = 1; cGAUSS.prototype.isXLFN = true; cGAUSS.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcGauss = function(argArray) { var res = gauss(argArray[0]); return isNaN(res) ? new cError(cErrorType.not_numeric) : new cNumber(res); }; return this.value = this._findArrayInNumberArguments(oArguments, calcGauss); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cGEOMEAN() { this.name = "GEOMEAN"; this.value = null; this.argumentsCurrent = 0; } cGEOMEAN.prototype = Object.create(cBaseFunction.prototype); cGEOMEAN.prototype.constructor = cGEOMEAN; cGEOMEAN.prototype.argumentsMin = 1; cGEOMEAN.prototype.Calculate = function (arg) { function geommean(x) { var _x = 1, xLength = 0, _tx; for (var i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { _x *= x[i].getValue(); xLength++; } else if (( x[i] instanceof cString || x[i] instanceof cBool ) && ( _tx = x[i].tocNumber()) instanceof cNumber) { _x *= _tx.getValue(); xLength++; } } if (_x <= 0) { return new cError(cErrorType.not_numeric); } else { return new cNumber(Math.pow(_x, 1 / xLength)); } } var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber) { arr0.push(a); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString && arg[j].tocNumber() instanceof cNumber) { arr0.push(arg[j].tocNumber()); } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = geommean(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cGROWTH() { cBaseFunction.call(this, "GROWTH"); } cGROWTH.prototype = Object.create(cBaseFunction.prototype); cGROWTH.prototype.constructor = cGROWTH; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cHARMEAN() { this.name = "HARMEAN"; this.value = null; this.argumentsCurrent = 0; } cHARMEAN.prototype = Object.create(cBaseFunction.prototype); cHARMEAN.prototype.constructor = cHARMEAN; cHARMEAN.prototype.argumentsMin = 1; cHARMEAN.prototype.Calculate = function (arg) { function harmmean(x) { var _x = 0, xLength = 0, _tx; for (var i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { if (x[i].getValue() == 0) { return new cError(cErrorType.not_numeric); } _x += 1 / x[i].getValue(); xLength++; } else if (( x[i] instanceof cString || x[i] instanceof cBool ) && ( _tx = x[i].tocNumber()) instanceof cNumber) { if (_tx.getValue() == 0) { return new cError(cErrorType.not_numeric); } _x += 1 / _tx.getValue(); xLength++; } } if (_x <= 0) { return new cError(cErrorType.not_numeric); } else { return new cNumber(xLength / _x); } } var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber) { arr0.push(a); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString && arg[j].tocNumber() instanceof cNumber) { arr0.push(arg[j].tocNumber()); } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = harmmean(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cHYPGEOMDIST() { this.name = "HYPGEOMDIST"; this.value = null; this.argumentsCurrent = 0; } cHYPGEOMDIST.prototype = Object.create(cBaseFunction.prototype); cHYPGEOMDIST.prototype.constructor = cHYPGEOMDIST; cHYPGEOMDIST.prototype.argumentsMin = 4; cHYPGEOMDIST.prototype.argumentsMax = 4; cHYPGEOMDIST.prototype.Calculate = function (arg) { var arg0 = arg[0], arg1 = arg[1], arg2 = arg[2], arg3 = arg[3]; if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } else if (arg0 instanceof cArray) { arg0 = arg0.getElement(0); } if (arg1 instanceof cArea || arg1 instanceof cArea3D) { arg1 = arg1.cross(arguments[1]); } else if (arg1 instanceof cArray) { arg1 = arg1.getElement(0); } if (arg2 instanceof cArea || arg2 instanceof cArea3D) { arg2 = arg2.cross(arguments[1]); } else if (arg2 instanceof cArray) { arg2 = arg2.getElement(0); } if (arg3 instanceof cArea || arg3 instanceof cArea3D) { arg3 = arg3.cross(arguments[1]); } else if (arg3 instanceof cArray) { arg3 = arg3.getElement(0); } arg0 = arg0.tocNumber(); arg1 = arg1.tocNumber(); arg2 = arg2.tocNumber(); arg3 = arg3.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } if (arg1 instanceof cError) { return this.value = arg1; } if (arg2 instanceof cError) { return this.value = arg2; } if (arg3 instanceof cError) { return this.value = arg3; } if (arg0.getValue() < 0 || arg0.getValue() > Math.min(arg1.getValue(), arg2.getValue()) || arg0.getValue() < Math.max(0, arg1.getValue() - arg3.getValue() + arg2.getValue()) || arg1.getValue() <= 0 || arg1.getValue() > arg3.getValue() || arg2.getValue() <= 0 || arg2.getValue() > arg3.getValue() || arg3.getValue() <= 0) { return this.value = new cError(cErrorType.not_numeric); } return this.value = new cNumber(Math.binomCoeff(arg2.getValue(), arg0.getValue()) * Math.binomCoeff(arg3.getValue() - arg2.getValue(), arg1.getValue() - arg0.getValue()) / Math.binomCoeff(arg3.getValue(), arg1.getValue())); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cHYPGEOM_DIST() { cBaseFunction.call(this, "HYPGEOM.DIST"); } cHYPGEOM_DIST.prototype = Object.create(cBaseFunction.prototype); cHYPGEOM_DIST.prototype.constructor = cHYPGEOM_DIST; cHYPGEOM_DIST.prototype.argumentsMin = 5; cHYPGEOM_DIST.prototype.argumentsMax = 5; cHYPGEOM_DIST.prototype.isXLFN = true; cHYPGEOM_DIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3].tocNumber(); argClone[4] = argClone[4].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function hypgeomdist(argArray) { var arg0 = Math.floor(argArray[0]); var arg1 = Math.floor(argArray[1]); var arg2 = Math.floor(argArray[2]); var arg3 = Math.floor(argArray[3]); var bCumulative = argArray[4]; if (arg0 < 0 || arg0 > Math.min(arg1, arg2) || arg0 < Math.max(0, arg1 - arg3 + arg2) || arg1 <= 0 || arg1 > arg3 || arg2 <= 0 || arg2 > arg3 || arg3 <= 0) { return new cError(cErrorType.not_numeric); } var res; if(bCumulative){ var fVal = 0.0; //TODO значения неверные для этой ветки! пересчитать for ( var i = 0; i <= arg0; i++ ){ var temp = Math.binomCoeff(arg2, i) * Math.binomCoeff(arg3 - arg2, arg1 - i) / Math.binomCoeff(arg3, arg1); if(!isNaN(temp)){ fVal += temp; } } res = fVal; }else{ res = Math.binomCoeff(arg2, arg0) * Math.binomCoeff(arg3 - arg2, arg1 - arg0) / Math.binomCoeff(arg3, arg1); } return isNaN(res) ? new cError(cErrorType.not_numeric) : new cNumber(res); } return this.value = this._findArrayInNumberArguments(oArguments, hypgeomdist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cINTERCEPT() { this.name = "INTERCEPT"; this.value = null; this.argumentsCurrent = 0; } cINTERCEPT.prototype = Object.create(cBaseFunction.prototype); cINTERCEPT.prototype.constructor = cINTERCEPT; cINTERCEPT.prototype.argumentsMin = 2; cINTERCEPT.prototype.argumentsMax = 2; cINTERCEPT.prototype.Calculate = function (arg) { function intercept(y, x) { var fSumDeltaXDeltaY = 0, fSumSqrDeltaX = 0, _x = 0, _y = 0, xLength = 0, i; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } _x += x[i].getValue(); _y += y[i].getValue(); xLength++; } _x /= xLength; _y /= xLength; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } var fValX = x[i].getValue(); var fValY = y[i].getValue(); fSumDeltaXDeltaY += ( fValX - _x ) * ( fValY - _y ); fSumSqrDeltaX += ( fValX - _x ) * ( fValX - _x ); } if (fSumDeltaXDeltaY == 0) { return new cError(cErrorType.division_by_zero); } else { return new cNumber(_y - fSumDeltaXDeltaY / fSumSqrDeltaX * _x); } } var arg0 = arg[0], arg1 = arg[1], arr0 = [], arr1 = []; if (arg0 instanceof cArea) { arr0 = arg0.getValue(); } else if (arg0 instanceof cArray) { arg0.foreach(function (elem) { arr0.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } if (arg1 instanceof cArea) { arr1 = arg1.getValue(); } else if (arg1 instanceof cArray) { arg1.foreach(function (elem) { arr1.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } return this.value = intercept(arr0, arr1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cKURT() { this.name = "KURT"; this.value = null; this.argumentsCurrent = 0; } cKURT.prototype = Object.create(cBaseFunction.prototype); cKURT.prototype.constructor = cKURT; cKURT.prototype.argumentsMin = 1; cKURT.prototype.Calculate = function (arg) { function kurt(x) { var sumSQRDeltaX = 0, _x = 0, xLength = 0, sumSQRDeltaXDivstandDev = 0, i; for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { _x += x[i].getValue(); xLength++; } } _x /= xLength; for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { sumSQRDeltaX += Math.pow(x[i].getValue() - _x, 2); } } var standDev = Math.sqrt(sumSQRDeltaX / ( xLength - 1 )); for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { sumSQRDeltaXDivstandDev += Math.pow((x[i].getValue() - _x) / standDev, 4); } } return new cNumber(xLength * (xLength + 1) / (xLength - 1) / (xLength - 2) / (xLength - 3) * sumSQRDeltaXDivstandDev - 3 * (xLength - 1) * (xLength - 1) / (xLength - 2) / (xLength - 3)) } var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber) { arr0.push(a); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString) { continue; } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = kurt(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cLARGE() { this.name = "LARGE"; this.value = null; this.argumentsCurrent = 0; } cLARGE.prototype = Object.create(cBaseFunction.prototype); cLARGE.prototype.constructor = cLARGE; cLARGE.prototype.argumentsMin = 2; cLARGE.prototype.argumentsMax = 2; cLARGE.prototype.numFormat = AscCommonExcel.cNumFormatNone; cLARGE.prototype._getValue = function (arg0, arg1) { if (cElementType.error === arg1.type) { return arg1; } arg1 = arg1.getValue(); if (arg1 <= 0) { return new cError(cErrorType.not_available); } var v, tA = []; for (var i = 0; i < arg0.length; i++) { for (var j = 0; j < arg0[i].length; j++) { v = arg0[i][j]; if (cElementType.error === v.type) { return v; } else if (cElementType.number === v.type) { tA.push(v.getValue()); } else if (cElementType.bool === v.type) { tA.push(v.tocNumber().getValue()); } } } tA.sort(AscCommon.fSortDescending); if (arg1 > tA.length) { return new cError(cErrorType.not_available); } else { return new cNumber(tA[arg1 - 1]); } }; cLARGE.prototype.Calculate = function (arg) { var arg0 = arg[0], arg1 = arg[1]; if (cElementType.cellsRange === arg0.type) { arg0 = arg0.getValuesNoEmpty(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); } else if (cElementType.array === arg0.type) { arg0 = arg0.getMatrix(); } else if (cElementType.cellsRange3D === arg0.type) { arg0 = arg0.getMatrix()[0]; } else { return this.value = new cError(cErrorType.not_numeric); } if (cElementType.cellsRange === arg1.type || cElementType.cellsRange3D === arg1.type) { arg1 = arg1.cross(arguments[1]); } else if (cElementType.array === arg1.type) { arg1 = arg1.getElement(0); } arg1 = arg1.tocNumber(); return this.value = this._getValue(arg0, arg1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cLINEST() { cBaseFunction.call(this, "LINEST"); } cLINEST.prototype = Object.create(cBaseFunction.prototype); cLINEST.prototype.constructor = cLINEST; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cLOGEST() { cBaseFunction.call(this, "LOGEST"); } cLOGEST.prototype = Object.create(cBaseFunction.prototype); cLOGEST.prototype.constructor = cLOGEST; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cLOGINV() { this.name = "LOGINV"; this.value = null; this.argumentsCurrent = 0; } cLOGINV.prototype = Object.create(cBaseFunction.prototype); cLOGINV.prototype.constructor = cLOGINV; cLOGINV.prototype.argumentsMin = 3; cLOGINV.prototype.argumentsMax = 3; cLOGINV.prototype.Calculate = function (arg) { var arg0 = arg[0], arg1 = arg[1], arg2 = arg[2]; function loginv(x, mue, sigma) { if (sigma <= 0 || x <= 0 || x >= 1) { return new cError(cErrorType.not_numeric); } else { return new cNumber(Math.exp(mue + sigma * ( gaussinv(x) ))); } } if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } else if (arg0 instanceof cArray) { arg0 = arg0.getElement(0); } if (arg1 instanceof cArea || arg1 instanceof cArea3D) { arg1 = arg1.cross(arguments[1]); } else if (arg1 instanceof cArray) { arg1 = arg1.getElement(0); } if (arg2 instanceof cArea || arg2 instanceof cArea3D) { arg2 = arg2.cross(arguments[1]); } else if (arg2 instanceof cArray) { arg2 = arg2.getElement(0); } arg0 = arg0.tocNumber(); arg1 = arg1.tocNumber(); arg2 = arg2.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } if (arg1 instanceof cError) { return this.value = arg1; } if (arg2 instanceof cError) { return this.value = arg2; } return this.value = loginv(arg0.getValue(), arg1.getValue(), arg2.getValue()); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cLOGNORM_DIST() { this.name = "LOGNORM.DIST"; this.value = null; this.argumentsCurrent = 0; } cLOGNORM_DIST.prototype = Object.create(cBaseFunction.prototype); cLOGNORM_DIST.prototype.constructor = cLOGNORM_DIST; cLOGNORM_DIST.prototype.argumentsMin = 4; cLOGNORM_DIST.prototype.argumentsMax = 4; cLOGNORM_DIST.prototype.isXLFN = true; cLOGNORM_DIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var normdist = function(argArray){ var x = argArray[0]; var mue = argArray[1]; var sigma = argArray[2]; var bCumulative = argArray[3]; var res = null; if (sigma <= 0.0) { return new cError(cErrorType.not_numeric); } if (bCumulative) { if (x <= 0){ res = 0; }else{ res = 0.5 + gauss((Math.ln(x) - mue) / sigma); } } else{ if (x <= 0){ return new cError(cErrorType.not_numeric); }else{ res = phi((Math.log(x) - mue) / sigma) / sigma / x; } } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, normdist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cLOGNORM_INV() { this.name = "LOGNORM.INV"; this.value = null; this.argumentsCurrent = 0; } cLOGNORM_INV.prototype = Object.create(cBaseFunction.prototype); cLOGNORM_INV.prototype.constructor = cLOGNORM_INV; cLOGNORM_INV.prototype.argumentsMin = 3; cLOGNORM_INV.prototype.argumentsMax = 3; cLOGNORM_INV.prototype.isXLFN = true; cLOGNORM_INV.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var normdist = function(argArray){ var fP = argArray[0]; var fMue = argArray[1]; var fSigma = argArray[2]; var res = null; if ( fSigma <= 0.0 || fP <= 0.0 || fP >= 1.0 ){ return new cError(cErrorType.not_numeric); }else{ res = Math.exp( fMue + fSigma * gaussinv( fP )); } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, normdist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cLOGNORMDIST() { this.name = "LOGNORMDIST"; this.value = null; this.argumentsCurrent = 0; } cLOGNORMDIST.prototype = Object.create(cBaseFunction.prototype); cLOGNORMDIST.prototype.constructor = cLOGNORMDIST; cLOGNORMDIST.prototype.argumentsMin = 3; cLOGNORMDIST.prototype.argumentsMax = 3; cLOGNORMDIST.prototype.Calculate = function (arg) { var arg0 = arg[0], arg1 = arg[1], arg2 = arg[2]; function normdist(x, mue, sigma) { if (sigma <= 0 || x <= 0) { return new cError(cErrorType.not_numeric); } else { return new cNumber(0.5 + gauss((Math.ln(x) - mue) / sigma)); } } if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } else if (arg0 instanceof cArray) { arg0 = arg0.getElement(0); } if (arg1 instanceof cArea || arg1 instanceof cArea3D) { arg1 = arg1.cross(arguments[1]); } else if (arg1 instanceof cArray) { arg1 = arg1.getElement(0); } if (arg2 instanceof cArea || arg2 instanceof cArea3D) { arg2 = arg2.cross(arguments[1]); } else if (arg2 instanceof cArray) { arg2 = arg2.getElement(0); } arg0 = arg0.tocNumber(); arg1 = arg1.tocNumber(); arg2 = arg2.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } if (arg1 instanceof cError) { return this.value = arg1; } if (arg2 instanceof cError) { return this.value = arg2; } return this.value = normdist(arg0.getValue(), arg1.getValue(), arg2.getValue()); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cMAX() { this.name = "MAX"; this.value = null; this.argumentsCurrent = 0; } cMAX.prototype = Object.create(cBaseFunction.prototype); cMAX.prototype.constructor = cMAX; cMAX.prototype.argumentsMin = 1; cMAX.prototype.Calculate = function (arg) { var v, element, argIVal, max = Number.NEGATIVE_INFINITY; for (var i = 0; i < this.argumentsCurrent; i++) { element = arg[i]; argIVal = element.getValue(); if (cElementType.cell === element.type || cElementType.cell3D === element.type) { if (!this.checkExclude || !element.isHidden(this.excludeHiddenRows)) { if (cElementType.error === argIVal.type) { return this.value = argIVal; } if (cElementType.number === argIVal.type) { v = argIVal.tocNumber(); if (v.getValue() > max) { max = v.getValue(); } } } } else if (cElementType.cellsRange === element.type || cElementType.cellsRange3D === element.type) { var argArr = element.getValue(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); for (var j = 0; j < argArr.length; j++) { if (cElementType.number === argArr[j].type) { v = argArr[j].tocNumber(); if (v.getValue() > max) { max = v.getValue(); } } else if (cElementType.error === argArr[j].type) { return this.value = argArr[j]; } } } else if (cElementType.error === element.type) { return this.value = element; } else if (cElementType.string === element.type) { v = element.tocNumber(); if (cElementType.number === v.type) { if (v.getValue() > max) { max = v.getValue(); } } } else if (cElementType.bool === element.type || cElementType.empty === element.type) { v = element.tocNumber(); if (v.getValue() > max) { max = v.getValue(); } } else if (cElementType.array === element.type) { element.foreach(function (elem) { if (cElementType.number === elem.type) { if (elem.getValue() > max) { max = elem.getValue(); } } else if (cElementType.error === elem.type) { max = elem; return true; } }); if (cElementType.error === max.type) { return this.value = max; } } else { if (element.getValue() > max) { max = element.getValue(); } } } return this.value = (max === Number.NEGATIVE_INFINITY ? new cNumber(0) : new cNumber(max)); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cMAXA() { this.name = "MAXA"; this.value = null; this.argumentsCurrent = 0; } cMAXA.prototype = Object.create(cBaseFunction.prototype); cMAXA.prototype.constructor = cMAXA; cMAXA.prototype.argumentsMin = 1; cMAXA.prototype.Calculate = function (arg) { var argI, argIVal, max = Number.NEGATIVE_INFINITY, v; for (var i = 0; i < this.argumentsCurrent; i++) { argI = arg[i]; argIVal = argI.getValue(); if (argI instanceof cRef || argI instanceof cRef3D) { if (argIVal instanceof cError) { return this.value = argIVal; } v = argIVal.tocNumber(); if (v instanceof cNumber && v.getValue() > max) { max = v.getValue(); } } else if (argI instanceof cArea || argI instanceof cArea3D) { var argArr = argI.getValue(); for (var j = 0; j < argArr.length; j++) { if (argArr[j] instanceof cError) { return this.value = argArr[j]; } v = argArr[j].tocNumber(); if (v instanceof cNumber && v.getValue() > max) { max = v.getValue(); } } } else if (argI instanceof cError) { return this.value = argI; } else if (argI instanceof cString) { v = argI.tocNumber(); if (v instanceof cNumber) { if (v.getValue() > max) { max = v.getValue(); } } } else if (argI instanceof cBool || argI instanceof cEmpty) { v = argI.tocNumber(); if (v.getValue() > max) { max = v.getValue(); } } else if (argI instanceof cArray) { argI.foreach(function (elem) { if (elem instanceof cError) { max = elem; return true; } elem = elem.tocNumber(); if (elem instanceof cNumber && elem.getValue() > max) { max = elem.getValue(); } }); if (max instanceof cError) { return this.value = max; } } else { if (argI.getValue() > max) { max = argI.getValue(); } } } return this.value = ( max === Number.NEGATIVE_INFINITY ? new cNumber(0) : new cNumber(max) ) }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cMAXIFS() { this.name = "MAXIFS"; this.value = null; this.argumentsCurrent = 0; } cMAXIFS.prototype = Object.create(cBaseFunction.prototype); cMAXIFS.prototype.constructor = cMAXIFS; cMAXIFS.prototype.argumentsMin = 3; cMAXIFS.prototype.isXLFN = true; cMAXIFS.prototype.Calculate = function (arg) { var arg0 = arg[0]; if (cElementType.cell !== arg0.type && cElementType.cell3D !== arg0.type && cElementType.cellsRange !== arg0.type) { if (cElementType.cellsRange3D === arg0.type) { arg0 = arg0.tocArea(); if (!arg0) { return this.value = new cError(cErrorType.wrong_value_type); } } else { return this.value = new cError(cErrorType.wrong_value_type); } } var arg0Matrix = arg0.getMatrix(); var i, j, arg1, arg2, matchingInfo; for (var k = 1; k < arg.length; k += 2) { arg1 = arg[k]; arg2 = arg[k + 1]; if (cElementType.cell !== arg1.type && cElementType.cell3D !== arg1.type && cElementType.cellsRange !== arg1.type) { if (cElementType.cellsRange3D === arg1.type) { arg1 = arg1.tocArea(); if (!arg1) { return this.value = new cError(cErrorType.wrong_value_type); } } else { return this.value = new cError(cErrorType.wrong_value_type); } } if (cElementType.cellsRange === arg2.type || cElementType.cellsRange3D === arg2.type) { arg2 = arg2.cross(arguments[1]); } else if (cElementType.array === arg2.type) { arg2 = arg2.getElementRowCol(0, 0); } arg2 = arg2.tocString(); if (cElementType.string !== arg2.type) { return this.value = new cError(cErrorType.wrong_value_type); } matchingInfo = AscCommonExcel.matchingValue(arg2.toString()); var arg1Matrix = arg1.getMatrix(); if (arg0Matrix.length !== arg1Matrix.length) { return this.value = new cError(cErrorType.wrong_value_type); } //compare for (i = 0; i < arg1Matrix.length; ++i) { if (arg0Matrix[i].length !== arg1Matrix[i].length) { return this.value = new cError(cErrorType.wrong_value_type); } for (j = 0; j < arg1Matrix[i].length; ++j) { if (arg0Matrix[i][j] && !AscCommonExcel.matching(arg1Matrix[i][j], matchingInfo)) { //MS считает в данном случае, что значение 0 (из диапазона условий) соответсвует условию = "" if(!(null === matchingInfo.op && "" === matchingInfo.val.value && 0 === arg1Matrix[i][j].value)){ arg0Matrix[i][j] = null; } } } } } var resArr = []; var valMatrix0; for (i = 0; i < arg0Matrix.length; ++i) { for (j = 0; j < arg0Matrix[i].length; ++j) { if ((valMatrix0 = arg0Matrix[i][j]) && cElementType.number === valMatrix0.type) { resArr.push(valMatrix0.getValue()); } } } if(0 === resArr.length){ return this.value = new cNumber(0); } resArr.sort(function(a, b) { return b - a; }); return this.value = new cNumber(resArr[0]); }; cMAXIFS.prototype.checkArguments = function () { return 1 === this.argumentsCurrent % 2 && cBaseFunction.prototype.checkArguments.apply(this, arguments); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cMINIFS() { this.name = "MINIFS"; this.value = null; this.argumentsCurrent = 0; } cMINIFS.prototype = Object.create(cBaseFunction.prototype); cMINIFS.prototype.constructor = cMINIFS; cMINIFS.prototype.argumentsMin = 3; cMINIFS.prototype.isXLFN = true; cMINIFS.prototype.Calculate = function (arg) { var arg0 = arg[0]; if (cElementType.cell !== arg0.type && cElementType.cell3D !== arg0.type && cElementType.cellsRange !== arg0.type) { if (cElementType.cellsRange3D === arg0.type) { arg0 = arg0.tocArea(); if (!arg0) { return this.value = new cError(cErrorType.wrong_value_type); } } else { return this.value = new cError(cErrorType.wrong_value_type); } } var arg0Matrix = arg0.getMatrix(); var i, j, arg1, arg2, matchingInfo; for (var k = 1; k < arg.length; k += 2) { arg1 = arg[k]; arg2 = arg[k + 1]; if (cElementType.cell !== arg1.type && cElementType.cell3D !== arg1.type && cElementType.cellsRange !== arg1.type) { if (cElementType.cellsRange3D === arg1.type) { arg1 = arg1.tocArea(); if (!arg1) { return this.value = new cError(cErrorType.wrong_value_type); } } else { return this.value = new cError(cErrorType.wrong_value_type); } } if (cElementType.cellsRange === arg2.type || cElementType.cellsRange3D === arg2.type) { arg2 = arg2.cross(arguments[1]); } else if (cElementType.array === arg2.type) { arg2 = arg2.getElementRowCol(0, 0); } arg2 = arg2.tocString(); if (cElementType.string !== arg2.type) { return this.value = new cError(cErrorType.wrong_value_type); } matchingInfo = AscCommonExcel.matchingValue(arg2.toString()); var arg1Matrix = arg1.getMatrix(); if (arg0Matrix.length !== arg1Matrix.length) { return this.value = new cError(cErrorType.wrong_value_type); } //compare for (i = 0; i < arg1Matrix.length; ++i) { if (arg0Matrix[i].length !== arg1Matrix[i].length) { return this.value = new cError(cErrorType.wrong_value_type); } for (j = 0; j < arg1Matrix[i].length; ++j) { if (arg0Matrix[i][j] && !AscCommonExcel.matching(arg1Matrix[i][j], matchingInfo)) { //MS считает в данном случае, что значение 0 (из диапазона условий) соответсвует условию = "" if(!(null === matchingInfo.op && "" === matchingInfo.val.value && 0 === arg1Matrix[i][j].value)){ arg0Matrix[i][j] = null; } } } } } var resArr = []; var valMatrix0; for (i = 0; i < arg0Matrix.length; ++i) { for (j = 0; j < arg0Matrix[i].length; ++j) { if ((valMatrix0 = arg0Matrix[i][j]) && cElementType.number === valMatrix0.type) { resArr.push(valMatrix0.getValue()); } } } if(0 === resArr.length){ return this.value = new cNumber(0); } resArr.sort(function(a, b) { return a - b; }); return this.value = new cNumber(resArr[0]); }; cMINIFS.prototype.checkArguments = function () { return 1 === this.argumentsCurrent % 2 && cBaseFunction.prototype.checkArguments.apply(this, arguments); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cMEDIAN() { this.name = "MEDIAN"; this.value = null; this.argumentsCurrent = 0; } cMEDIAN.prototype = Object.create(cBaseFunction.prototype); cMEDIAN.prototype.constructor = cMEDIAN; cMEDIAN.prototype.argumentsMin = 1; cMEDIAN.prototype.Calculate = function (arg) { function median(x) { var medArr = [], t; for (var i = 0; i < x.length; i++) { t = x[i].tocNumber(); if (t instanceof cNumber) { medArr.push(t.getValue()) } } medArr.sort(fSortAscending); if (medArr.length < 1) { return new cError(cErrorType.wrong_value_type); } else { if (medArr.length % 2) { return new cNumber(medArr[(medArr.length - 1) / 2]); } else { return new cNumber((medArr[medArr.length / 2 - 1] + medArr[medArr.length / 2]) / 2); } } } var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber) { arr0.push(a); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString) { continue; } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = median(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cMIN() { this.name = "MIN"; this.value = null; this.argumentsCurrent = 0; } cMIN.prototype = Object.create(cBaseFunction.prototype); cMIN.prototype.constructor = cMIN; cMIN.prototype.argumentsMin = 1; cMIN.prototype.Calculate = function (arg) { var v, element, argIVal, min = Number.POSITIVE_INFINITY; for (var i = 0; i < this.argumentsCurrent; i++) { element = arg[i]; argIVal = element.getValue(); if (cElementType.cell === element.type || cElementType.cell3D === element.type) { if (!this.checkExclude || !element.isHidden(this.excludeHiddenRows)) { if (cElementType.error === argIVal.type) { return this.value = argIVal; } if (cElementType.number === argIVal.type) { v = argIVal.tocNumber(); if (v.getValue() < min) { min = v.getValue(); } } } } else if (cElementType.cellsRange === element.type || cElementType.cellsRange3D === element.type) { var argArr = element.getValue(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); for (var j = 0; j < argArr.length; j++) { if (cElementType.number === argArr[j].type) { v = argArr[j].tocNumber(); if (v.getValue() < min) { min = v.getValue(); } continue; } else if (cElementType.error === argArr[j].type) { return this.value = argArr[j]; } } } else if (cElementType.error === element.type) { return this.value = element; } else if (cElementType.string === element.type) { v = element.tocNumber(); if (cElementType.number === v.type) { if (v.getValue() < min) { min = v.getValue(); } } } else if (cElementType.bool === element.type || cElementType.empty === element.type) { v = element.tocNumber(); if (v.getValue() < min) { min = v.getValue(); } } else if (cElementType.array === element.type) { element.foreach(function (elem) { if (cElementType.number === elem.type) { if (elem.getValue() < min) { min = elem.getValue(); } } else if (cElementType.error === elem.type) { min = elem; return true; } }); if (cElementType.error === min.type) { return this.value = min; } } else { if (element.getValue() < min) { min = element.getValue(); } } } return this.value = ( min === Number.POSITIVE_INFINITY ? new cNumber(0) : new cNumber(min) ); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cMINA() { this.name = "MINA"; this.value = null; this.argumentsCurrent = 0; } cMINA.prototype = Object.create(cBaseFunction.prototype); cMINA.prototype.constructor = cMINA; cMINA.prototype.argumentsMin = 1; cMINA.prototype.Calculate = function (arg) { var argI, argIVal, min = Number.POSITIVE_INFINITY, v; for (var i = 0; i < this.argumentsCurrent; i++) { argI = arg[i]; argIVal = argI.getValue(); if (argI instanceof cRef || argI instanceof cRef3D) { if (argIVal instanceof cError) { return this.value = argIVal; } v = argIVal.tocNumber(); if (v instanceof cNumber && v.getValue() < min) { min = v.getValue(); } } else if (argI instanceof cArea || argI instanceof cArea3D) { var argArr = argI.getValue(); for (var j = 0; j < argArr.length; j++) { if (argArr[j] instanceof cError) { return this.value = argArr[j]; } v = argArr[j].tocNumber(); if (v instanceof cNumber && v.getValue() < min) { min = v.getValue(); } } } else if (argI instanceof cError) { return this.value = argI; } else if (argI instanceof cString) { v = argI.tocNumber(); if (v instanceof cNumber) { if (v.getValue() < min) { min = v.getValue(); } } } else if (argI instanceof cBool || argI instanceof cEmpty) { v = argI.tocNumber(); if (v.getValue() < min) { min = v.getValue(); } } else if (argI instanceof cArray) { argI.foreach(function (elem) { if (elem instanceof cError) { min = elem; return true; } elem = elem.tocNumber(); if (elem instanceof cNumber && elem.getValue() < min) { min = elem.getValue(); } }); if (min instanceof cError) { return this.value = min; } } else { if (argI.getValue() < min) { min = argI.getValue(); } } } return this.value = ( min === Number.POSITIVE_INFINITY ? new cNumber(0) : new cNumber(min) ); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cMODE() { this.name = "MODE"; this.value = null; this.argumentsCurrent = 0; } cMODE.prototype = Object.create(cBaseFunction.prototype); cMODE.prototype.constructor = cMODE; cMODE.prototype.argumentsMin = 1; cMODE.prototype.Calculate = function (arg) { function mode(x) { var medArr = [], t, i; for (i = 0; i < x.length; i++) { t = x[i].tocNumber(); if (t instanceof cNumber) { medArr.push(t.getValue()) } } medArr.sort(fSortAscending); if (medArr.length < 1) { return new cError(cErrorType.wrong_value_type); } else { var nMaxIndex = 0, nMax = 1, nCount = 1, nOldVal = medArr[0]; for (i = 1; i < medArr.length; i++) { if (medArr[i] == nOldVal) { nCount++; } else { nOldVal = medArr[i]; if (nCount > nMax) { nMax = nCount; nMaxIndex = i - 1; } nCount = 1; } } if (nCount > nMax) { nMax = nCount; nMaxIndex = i - 1; } if (nMax == 1 && nCount == 1) { return new cError(cErrorType.wrong_value_type); } else if (nMax == 1) { return new cNumber(nOldVal); } else { return new cNumber(medArr[nMaxIndex]); } } } var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber) { arr0.push(a); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString) { continue; } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = mode(arr0); }; /** * @constructor * @extends {cPERCENTILE} */ //TODO разницы в работе функций cMODE_MULT и cMODE не нашёл, но в LO обработки немного разные. проверить! function cMODE_MULT() { cMODE.call(this); this.name = "MODE.MULT"; } cMODE_MULT.prototype = Object.create(cMODE.prototype); cMODE_MULT.prototype.constructor = cMODE_MULT; cMODE_MULT.prototype.isXLFN = true; /** * @constructor * @extends {cPERCENTILE} */ function cMODE_SNGL() { cMODE.call(this); this.name = "MODE.SNGL"; } cMODE_SNGL.prototype = Object.create(cMODE.prototype); cMODE_SNGL.prototype.constructor = cMODE_SNGL; cMODE_SNGL.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cNEGBINOMDIST() { cBaseFunction.call(this, "NEGBINOMDIST"); } cNEGBINOMDIST.prototype = Object.create(cBaseFunction.prototype); cNEGBINOMDIST.prototype.constructor = cNEGBINOMDIST; cNEGBINOMDIST.prototype.argumentsMin = 3; cNEGBINOMDIST.prototype.argumentsMax = 3; cNEGBINOMDIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function negbinomdist(argArray) { var x = argArray[0]; var r = argArray[1]; var p = argArray[2]; if (x < 0 || r < 1 || p < 0 || p > 1) { return new cError(cErrorType.not_numeric); } else { return new cNumber(Math.binomCoeff(x + r - 1, r - 1) * Math.pow(p, r) * Math.pow(1 - p, x)); } } return this.value = this._findArrayInNumberArguments(oArguments, negbinomdist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cNEGBINOM_DIST() { cBaseFunction.call(this, "NEGBINOM.DIST"); } cNEGBINOM_DIST.prototype = Object.create(cBaseFunction.prototype); cNEGBINOM_DIST.prototype.constructor = cNEGBINOM_DIST; cNEGBINOM_DIST.prototype.argumentsMin = 4; cNEGBINOM_DIST.prototype.argumentsMax = 4; cNEGBINOM_DIST.prototype.isXLFN = true; cNEGBINOM_DIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function negbinomdist(argArray) { var x = parseInt(argArray[0]); var r = parseInt(argArray[1]); var p = argArray[2]; var bCumulative = argArray[3]; if (x < 0 || r < 1 || p < 0 || p > 1) { return new cError(cErrorType.not_numeric); } var res; if ( bCumulative ){ res = 1 - getBetaDist( 1 - p, x + 1, r ); }else{ res = Math.binomCoeff(x + r - 1, r - 1) * Math.pow(p, r) * Math.pow(1 - p, x); } return isNaN(res) ? new cError(cErrorType.not_numeric) : new cNumber(res); } return this.value = this._findArrayInNumberArguments(oArguments, negbinomdist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cNORMDIST() { this.name = "NORMDIST"; this.value = null; this.argumentsCurrent = 0; } cNORMDIST.prototype = Object.create(cBaseFunction.prototype); cNORMDIST.prototype.constructor = cNORMDIST; cNORMDIST.prototype.argumentsMin = 4; cNORMDIST.prototype.argumentsMax = 4; cNORMDIST.prototype.Calculate = function (arg) { var arg0 = arg[0], arg1 = arg[1], arg2 = arg[2], arg3 = arg[3]; function normdist(x, mue, sigma, kum) { if (sigma <= 0) { return new cError(cErrorType.not_numeric); } if (kum) { return new cNumber(integralPhi((x - mue) / sigma)); } else { return new cNumber(phi((x - mue) / sigma) / sigma); } } if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } else if (arg0 instanceof cArray) { arg0 = arg0.getElement(0); } if (arg1 instanceof cArea || arg1 instanceof cArea3D) { arg1 = arg1.cross(arguments[1]); } else if (arg1 instanceof cArray) { arg1 = arg1.getElement(0); } if (arg2 instanceof cArea || arg2 instanceof cArea3D) { arg2 = arg2.cross(arguments[1]); } else if (arg2 instanceof cArray) { arg2 = arg2.getElement(0); } if (arg3 instanceof cArea || arg3 instanceof cArea3D) { arg3 = arg3.cross(arguments[1]); } else if (arg3 instanceof cArray) { arg3 = arg3.getElement(0); } arg0 = arg0.tocNumber(); arg1 = arg1.tocNumber(); arg2 = arg2.tocNumber(); arg3 = arg3.tocBool(); if (arg0 instanceof cError) { return this.value = arg0; } if (arg1 instanceof cError) { return this.value = arg1; } if (arg2 instanceof cError) { return this.value = arg2; } if (arg3 instanceof cError) { return this.value = arg3; } return this.value = normdist(arg0.getValue(), arg1.getValue(), arg2.getValue(), arg3.toBool()); }; /** * @constructor * @extends {cPERCENTILE} */ function cNORM_DIST() { cNORMDIST.call(this); this.name = "NORM.DIST"; } cNORM_DIST.prototype = Object.create(cNORMDIST.prototype); cNORM_DIST.prototype.constructor = cNORM_DIST; cNORM_DIST.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cNORMINV() { this.name = "NORMINV"; this.value = null; this.argumentsCurrent = 0; } cNORMINV.prototype = Object.create(cBaseFunction.prototype); cNORMINV.prototype.constructor = cNORMINV; cNORMINV.prototype.argumentsMin = 3; cNORMINV.prototype.argumentsMax = 3; cNORMINV.prototype.Calculate = function (arg) { var arg0 = arg[0], arg1 = arg[1], arg2 = arg[2]; function norminv(x, mue, sigma) { if (sigma <= 0.0 || x <= 0.0 || x >= 1.0) { return new cError(cErrorType.not_numeric); } else { return new cNumber(gaussinv(x) * sigma + mue); } } if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } else if (arg0 instanceof cArray) { arg0 = arg0.getElement(0); } if (arg1 instanceof cArea || arg1 instanceof cArea3D) { arg1 = arg1.cross(arguments[1]); } else if (arg1 instanceof cArray) { arg1 = arg1.getElement(0); } if (arg2 instanceof cArea || arg2 instanceof cArea3D) { arg2 = arg2.cross(arguments[1]); } else if (arg2 instanceof cArray) { arg2 = arg2.getElement(0); } arg0 = arg0.tocNumber(); arg1 = arg1.tocNumber(); arg2 = arg2.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } if (arg1 instanceof cError) { return this.value = arg1; } if (arg2 instanceof cError) { return this.value = arg2; } return this.value = norminv(arg0.getValue(), arg1.getValue(), arg2.getValue()); }; /** * @constructor * @extends {cNORMINV} */ function cNORM_INV() { cNORMINV.call(this); this.name = "NORM.INV"; } cNORM_INV.prototype = Object.create(cNORMINV.prototype); cNORM_INV.prototype.constructor = cNORM_INV; cNORM_INV.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cNORMSDIST() { this.name = "NORMSDIST"; this.value = null; this.argumentsCurrent = 0; } cNORMSDIST.prototype = Object.create(cBaseFunction.prototype); cNORMSDIST.prototype.constructor = cNORMSDIST; cNORMSDIST.prototype.argumentsMin = 1; cNORMSDIST.prototype.argumentsMax = 1; cNORMSDIST.prototype.Calculate = function (arg) { var arg0 = arg[0]; if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } arg0 = arg0.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } else if (arg0 instanceof cArray) { arg0.foreach(function (elem, r, c) { if (elem instanceof cNumber) { var a = 0.5 + gauss(elem.getValue()); this.array[r][c] = isNaN(a) ? new cError(cErrorType.not_numeric) : new cNumber(a); } else { this.array[r][c] = new cError(cErrorType.wrong_value_type); } }) } else { var a = 0.5 + gauss(arg0.getValue()); return this.value = isNaN(a) ? new cError(cErrorType.not_numeric) : new cNumber(a); } return this.value = arg0; }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cNORM_S_DIST() { this.name = "NORM.S.DIST"; this.value = null; this.argumentsCurrent = 0; } cNORM_S_DIST.prototype = Object.create(cBaseFunction.prototype); cNORM_S_DIST.prototype.constructor = cNORM_S_DIST; cNORM_S_DIST.prototype.argumentsMin = 2; cNORM_S_DIST.prototype.argumentsMax = 2; cNORM_S_DIST.prototype.isXLFN = true; cNORM_S_DIST.prototype.numFormat = AscCommonExcel.cNumFormatNone; cNORM_S_DIST.prototype.Calculate = function (arg) { function normDistCalc(argArray) { var arg0 = argArray[0], arg1 = argArray[1]; var res; if(arg1){ res = 0.5 + gauss(arg0); }else{ res = Math.exp( - Math.pow( arg0, 2 ) / 2 ) / Math.sqrt( 2 * Math.PI ); } return isNaN(res) ? new cError(cErrorType.not_numeric) : new cNumber(res); } var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } return this.value = this._findArrayInNumberArguments(oArguments, normDistCalc); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cNORMSINV() { this.name = "NORMSINV"; this.value = null; this.argumentsCurrent = 0; } cNORMSINV.prototype = Object.create(cBaseFunction.prototype); cNORMSINV.prototype.constructor = cNORMSINV; cNORMSINV.prototype.argumentsMin = 1; cNORMSINV.prototype.argumentsMax = 1; cNORMSINV.prototype.Calculate = function (arg) { function normsinv(x) { if (x <= 0.0 || x >= 1.0) { return new cError(cErrorType.not_numeric); } else { return new cNumber(gaussinv(x)); } } var arg0 = arg[0]; if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } arg0 = arg0.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } else if (arg0 instanceof cArray) { arg0.foreach(function (elem, r, c) { if (elem instanceof cNumber) { var a = normsinv(elem.getValue()); this.array[r][c] = isNaN(a) ? new cError(cErrorType.not_available) : new cNumber(a); } else { this.array[r][c] = new cError(cErrorType.wrong_value_type); } }) } else { var a = normsinv(arg0.getValue()); return this.value = isNaN(a) ? new cError(cErrorType.not_available) : new cNumber(a); } return this.value = arg0; }; /** * @constructor * @extends {cNORMSINV} */ function cNORM_S_INV() { cNORMSINV.call(this); this.name = "NORM.S.INV"; } cNORM_S_INV.prototype = Object.create(cNORMSINV.prototype); cNORM_S_INV.prototype.constructor = cNORM_S_INV; cNORM_S_INV.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cPEARSON() { this.name = "PEARSON"; this.value = null; this.argumentsCurrent = 0; } cPEARSON.prototype = Object.create(cBaseFunction.prototype); cPEARSON.prototype.constructor = cPEARSON; cPEARSON.prototype.argumentsMin = 2; cPEARSON.prototype.argumentsMax = 2; cPEARSON.prototype.Calculate = function (arg) { function pearson(x, y) { var sumXDeltaYDelta = 0, sqrXDelta = 0, sqrYDelta = 0, _x = 0, _y = 0, xLength = 0, i; if (x.length != y.length) { return new cError(cErrorType.not_available); } for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } _x += x[i].getValue(); _y += y[i].getValue(); xLength++; } _x /= xLength; _y /= xLength; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } sumXDeltaYDelta += (x[i].getValue() - _x) * (y[i].getValue() - _y); sqrXDelta += (x[i].getValue() - _x) * (x[i].getValue() - _x); sqrYDelta += (y[i].getValue() - _y) * (y[i].getValue() - _y); } if (sqrXDelta == 0 || sqrYDelta == 0) { return new cError(cErrorType.division_by_zero); } else { return new cNumber(sumXDeltaYDelta / Math.sqrt(sqrXDelta * sqrYDelta)); } } var arg0 = arg[0], arg1 = arg[1], arr0 = [], arr1 = []; if (arg0 instanceof cArea) { arr0 = arg0.getValue(); } else if (arg0 instanceof cArray) { arg0.foreach(function (elem) { arr0.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } if (arg1 instanceof cArea) { arr1 = arg1.getValue(); } else if (arg1 instanceof cArray) { arg1.foreach(function (elem) { arr1.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } return this.value = pearson(arr0, arr1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cPERCENTILE() { this.name = "PERCENTILE"; this.value = null; this.argumentsCurrent = 0; } cPERCENTILE.prototype = Object.create(cBaseFunction.prototype); cPERCENTILE.prototype.constructor = cPERCENTILE; cPERCENTILE.prototype.argumentsMin = 2; cPERCENTILE.prototype.argumentsMax = 2; cPERCENTILE.prototype.numFormat = AscCommonExcel.cNumFormatNone; cPERCENTILE.prototype.Calculate = function (arg) { function percentile(argArray) { var tA = [], A = argArray[0], alpha = argArray[1]; for (var i = 0; i < A.length; i++) { for (var j = 0; j < A[i].length; j++) { if (A[i][j] instanceof cError) { return A[i][j]; } else if (A[i][j] instanceof cNumber) { tA.push(A[i][j].getValue()); } else if (A[i][j] instanceof cBool) { tA.push(A[i][j].tocNumber().getValue()); } } } return getPercentile(tA, alpha); } var oArguments = this._prepareArguments(arg, arguments[1], true, [cElementType.array]); var argClone = oArguments.args; argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } return this.value = this._findArrayInNumberArguments(oArguments, percentile); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cPERCENTILE_EXC() { this.name = "PERCENTILE.EXC"; this.value = null; this.argumentsCurrent = 0; } cPERCENTILE_EXC.prototype = Object.create(cBaseFunction.prototype); cPERCENTILE_EXC.prototype.constructor = cPERCENTILE_EXC; cPERCENTILE_EXC.prototype.argumentsMin = 2; cPERCENTILE_EXC.prototype.argumentsMax = 2; cPERCENTILE_EXC.prototype.isXLFN = true; cPERCENTILE_EXC.prototype.numFormat = AscCommonExcel.cNumFormatNone; cPERCENTILE_EXC.prototype.Calculate = function (arg) { function percentile(argArray) { var tA = [], A = argArray[0], alpha = argArray[1]; for (var i = 0; i < A.length; i++) { for (var j = 0; j < A[i].length; j++) { if (A[i][j] instanceof cError) { return A[i][j]; } else if (A[i][j] instanceof cNumber) { tA.push(A[i][j].getValue()); } else if (A[i][j] instanceof cBool) { tA.push(A[i][j].tocNumber().getValue()); } } } return getPercentileExclusive(tA, alpha); } var oArguments = this._prepareArguments(arg, arguments[1], true, [cElementType.array]); var argClone = oArguments.args; argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } return this.value = this._findArrayInNumberArguments(oArguments, percentile); }; /** * @constructor * @extends {cPERCENTILE} */ function cPERCENTILE_INC() { cPERCENTILE.call(this); this.name = "PERCENTILE.INC"; } cPERCENTILE_INC.prototype = Object.create(cPERCENTILE.prototype); cPERCENTILE_INC.prototype.constructor = cPERCENTILE_INC; cPERCENTILE_INC.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cPERCENTRANK() { this.name = "PERCENTRANK"; this.value = null; this.argumentsCurrent = 0; } cPERCENTRANK.prototype = Object.create(cBaseFunction.prototype); cPERCENTRANK.prototype.constructor = cPERCENTRANK; cPERCENTRANK.prototype.argumentsMin = 2; cPERCENTRANK.prototype.argumentsMax = 3; cPERCENTRANK.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true, [cElementType.array]); var argClone = oArguments.args; argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2] ? argClone[2].tocNumber() : new cNumber(3); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function calcPercenTrank(argArray) { var tA = [], A = argArray[0], fNum = argArray[1], k = argArray[2]; for (var i = 0; i < A.length; i++) { for (var j = 0; j < A[i].length; j++) { if (A[i][j] instanceof cError) { return A[i][j]; } else if (A[i][j] instanceof cNumber) { tA.push(A[i][j].getValue()); } else if (A[i][j] instanceof cBool) { tA.push(A[i][j].tocNumber().getValue()); } } } return percentrank(tA, fNum, k, true); } return this.value = this._findArrayInNumberArguments(oArguments, calcPercenTrank); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cPERCENTRANK_EXC() { this.name = "PERCENTRANK.EXC"; this.value = null; this.argumentsCurrent = 0; } cPERCENTRANK_EXC.prototype = Object.create(cBaseFunction.prototype); cPERCENTRANK_EXC.prototype.constructor = cPERCENTRANK_EXC; cPERCENTRANK_EXC.prototype.argumentsMin = 2; cPERCENTRANK_EXC.prototype.argumentsMax = 3; cPERCENTRANK_EXC.prototype.isXLFN = true; cPERCENTRANK_EXC.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true, [cElementType.array]); var argClone = oArguments.args; argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2] ? argClone[2].tocNumber() : new cNumber(3); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function calcPercenTrank(argArray) { var tA = [], A = argArray[0], fNum = argArray[1], k = argArray[2]; for (var i = 0; i < A.length; i++) { for (var j = 0; j < A[i].length; j++) { if (A[i][j] instanceof cError) { return A[i][j]; } else if (A[i][j] instanceof cNumber) { tA.push(A[i][j].getValue()); } else if (A[i][j] instanceof cBool) { tA.push(A[i][j].tocNumber().getValue()); } } } return percentrank(tA, fNum, k); } return this.value = this._findArrayInNumberArguments(oArguments, calcPercenTrank); }; /** * @constructor * @extends {cPERCENTRANK} */ function cPERCENTRANK_INC() { cPERCENTRANK.call(this); this.name = "PERCENTRANK.INC"; } cPERCENTRANK_INC.prototype = Object.create(cPERCENTRANK.prototype); cPERCENTRANK_INC.prototype.constructor = cPERCENTRANK_INC; cPERCENTRANK_INC.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cPERMUT() { this.name = "PERMUT"; this.value = null; this.argumentsCurrent = 0; } cPERMUT.prototype = Object.create(cBaseFunction.prototype); cPERMUT.prototype.constructor = cPERMUT; cPERMUT.prototype.argumentsMin = 2; cPERMUT.prototype.argumentsMax = 2; cPERMUT.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function permut(argArray) { var n = Math.floor(argArray[0]); var k = Math.floor(argArray[1]); if (n <= 0 || k <= 0 || n < k) { return new cError(cErrorType.not_numeric); } return new cNumber(Math.permut(n, k)); } return this.value = this._findArrayInNumberArguments(oArguments, permut); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cPERMUTATIONA() { this.name = "PERMUTATIONA"; this.value = null; this.argumentsCurrent = 0; } cPERMUTATIONA.prototype = Object.create(cBaseFunction.prototype); cPERMUTATIONA.prototype.constructor = cPERMUTATIONA; cPERMUTATIONA.prototype.argumentsMin = 2; cPERMUTATIONA.prototype.argumentsMax = 2; cPERMUTATIONA.prototype.isXLFN = true; cPERMUTATIONA.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function permutationa(argArray) { var n = Math.floor(argArray[0]); var k = Math.floor(argArray[1]); if (n < 0.0 || k < 0.0){ return new cError(cErrorType.not_numeric); } return new cNumber(Math.pow(n,k)); } return this.value = this._findArrayInNumberArguments(oArguments, permutationa); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cPHI() { this.name = "PHI"; this.value = null; this.argumentsCurrent = 0; } cPHI.prototype = Object.create(cBaseFunction.prototype); cPHI.prototype.constructor = cPHI; cPHI.prototype.argumentsMin = 1; cPHI.prototype.argumentsMax = 1; cPHI.prototype.isXLFN = true; cPHI.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function calcPhi(argArray) { var res = phi(argArray[0]); return isNaN(res) ? new cError(cErrorType.not_available) : new cNumber(res); } return this.value = this._findArrayInNumberArguments(oArguments, calcPhi); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cPOISSON() { this.name = "POISSON"; this.value = null; this.argumentsCurrent = 0; } cPOISSON.prototype = Object.create(cBaseFunction.prototype); cPOISSON.prototype.constructor = cPOISSON; cPOISSON.prototype.argumentsMin = 3; cPOISSON.prototype.argumentsMax = 3; cPOISSON.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function poisson(argArray) { var _x = parseInt(argArray[0]); var _l = argArray[1]; var f = argArray[2]; if (_x < 0 || _l < 0) { return new cError(cErrorType.not_numeric); } if (f) { var sum = 0; for (var k = 0; k <= _x; k++) { sum += Math.pow(_l, k) / Math.fact(k); } sum *= Math.exp(-_l); return new cNumber(sum); } else { return new cNumber(Math.exp(-_l) * Math.pow(_l, _x) / Math.fact(_x)); } } return this.value = this._findArrayInNumberArguments(oArguments, poisson); }; /** * @constructor * @extends {cPERCENTRANK} */ function cPOISSON_DIST() { cPOISSON.call(this); this.name = "POISSON.DIST"; } cPOISSON_DIST.prototype = Object.create(cPOISSON.prototype); cPOISSON_DIST.prototype.constructor = cPOISSON_DIST; cPOISSON_DIST.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cPROB() { this.name = "PROB"; this.value = null; this.argumentsCurrent = 0; } cPROB.prototype = Object.create(cBaseFunction.prototype); cPROB.prototype.constructor = cPROB; cPROB.prototype.argumentsMin = 3; cPROB.prototype.argumentsMax = 4; cPROB.prototype.numFormat = AscCommonExcel.cNumFormatNone; cPROB.prototype.Calculate = function (arg) { function prob(x, p, l, u) { var fUp, fLo; fLo = l.getValue(); if (u instanceof cEmpty) { fUp = fLo; } else { fUp = u.getValue(); } if (fLo > fUp) { var fTemp = fLo; fLo = fUp; fUp = fTemp; } var nC1 = x[0].length, nC2 = p[0].length, nR1 = x.length, nR2 = p.length; if (nC1 != nC2 || nR1 != nR2 || nC1 == 0 || nR1 == 0 || nC2 == 0 || nR2 == 0) { return new cError(cErrorType.not_available); } else { var fSum = 0, fRes = 0, bStop = false, fP, fW; for (var i = 0; i < nR1 && !bStop; i++) { for (var j = 0; j < nC1 && !bStop; j++) { if (x[i][j] instanceof cNumber && p[i][j] instanceof cNumber) { fP = p[i][j].getValue(); fW = x[i][j].getValue(); if (fP < 0.0 || fP > 1.0) { bStop = true; } else { fSum += fP; if (fW >= fLo && fW <= fUp) { fRes += fP; } } } else { return new cError(cErrorType.not_available); } } } if (bStop || Math.abs(fSum - 1.0) > 1.0E-7) { return new cError(cErrorType.not_available); } else { return new cNumber(fRes); } } } var arg0 = arg[0], arg1 = arg[1], arg2 = arg[2], arg3 = arg[3] ? arg[3] : new cEmpty(); if (arg0 instanceof cArea || arg0 instanceof cArray) { arg0 = arg0.getMatrix(); } else if (arg0 instanceof cArea3D) { arg0 = arg0.getMatrix()[0]; } else { return this.value = new cError(cErrorType.not_available); } if (arg1 instanceof cArea || arg1 instanceof cArray) { arg1 = arg1.getMatrix(); } else if (arg1 instanceof cArea3D) { arg1 = arg1.getMatrix()[0]; } else { return this.value = new cError(cErrorType.not_available); } if (arg2 instanceof cArea || arg2 instanceof cArea3D) { arg2 = arg2.cross(arguments[1]); } else if (arg2 instanceof cArray) { arg2 = arg2.getElement(0); } if (arg3 instanceof cArea || arg3 instanceof cArea3D) { arg3 = arg3.cross(arguments[1]); } else if (arg3 instanceof cArray) { arg3 = arg3.getElement(0); } arg2 = arg2.tocNumber(); if (!arg3 instanceof cEmpty) { arg3 = arg3.tocNumber(); } if (arg2 instanceof cError) { return this.value = arg2; } if (arg3 instanceof cError) { return this.value = arg3; } return this.value = prob(arg0, arg1, arg2, arg3); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cQUARTILE() { this.name = "QUARTILE"; this.value = null; this.argumentsCurrent = 0; } cQUARTILE.prototype = Object.create(cBaseFunction.prototype); cQUARTILE.prototype.constructor = cQUARTILE; cQUARTILE.prototype.argumentsMin = 2; cQUARTILE.prototype.argumentsMax = 2; cQUARTILE.prototype.numFormat = AscCommonExcel.cNumFormatNone; cQUARTILE.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true, [cElementType.array]); var argClone = oArguments.args; argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function quartile(argArray) { var A = argArray[0]; var fFlag = Math.floor(argArray[1]); var tA = []; for (var i = 0; i < A.length; i++) { for (var j = 0; j < A[i].length; j++) { if (A[i][j] instanceof cError) { return A[i][j]; } else if (A[i][j] instanceof cNumber || A[i][j] instanceof cEmpty) { tA.push(A[i][j].getValue()); } else if (A[i][j] instanceof cBool) { tA.push(A[i][j].tocNumber().getValue()); } } } var nSize = tA.length; if(tA.length < 1 || nSize === 0){ return new cError(cErrorType.not_available); }else if(fFlag < 0.0 || fFlag > 4.0){ return new cError(cErrorType.not_numeric); }else if(nSize === 1){ return new cNumber(tA[0]); } return fFlag === 2 ? getMedian( tA ) : getPercentile( tA, 0.25 * fFlag ); } return this.value = this._findArrayInNumberArguments(oArguments, quartile); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cQUARTILE_EXC() { this.name = "QUARTILE.EXC"; this.value = null; this.argumentsCurrent = 0; } cQUARTILE_EXC.prototype = Object.create(cBaseFunction.prototype); cQUARTILE_EXC.prototype.constructor = cQUARTILE_EXC; cQUARTILE_EXC.prototype.argumentsMin = 2; cQUARTILE_EXC.prototype.argumentsMax = 2; cQUARTILE_EXC.prototype.numFormat = AscCommonExcel.cNumFormatNone; cQUARTILE_EXC.prototype.isXLFN = true; cQUARTILE_EXC.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true, [cElementType.array]); var argClone = oArguments.args; argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function quartile(argArray) { var A = argArray[0]; var fFlag = Math.floor(argArray[1]); var tA = []; for (var i = 0; i < A.length; i++) { for (var j = 0; j < A[i].length; j++) { if (A[i][j] instanceof cError) { return A[i][j]; } else if (A[i][j] instanceof cNumber) { tA.push(A[i][j].getValue()); } else if (A[i][j] instanceof cBool) { tA.push(A[i][j].tocNumber().getValue()); } } } var nSize = tA.length; if(tA.length < 1 || nSize === 0){ return new cError(cErrorType.not_available); }else if(fFlag <= 0.0 || fFlag >= 4.0){ return new cError(cErrorType.not_numeric); }else if(nSize === 1){ return new cNumber(tA[0]); } return fFlag === 2 ? getMedian( tA ) : getPercentileExclusive( tA, 0.25 * fFlag ); } return this.value = this._findArrayInNumberArguments(oArguments, quartile); }; /** * @constructor * @extends {cQUARTILE} */ function cQUARTILE_INC() { cQUARTILE.call(this); this.name = "QUARTILE.INC"; } cQUARTILE_INC.prototype = Object.create(cQUARTILE.prototype); cQUARTILE_INC.prototype.constructor = cQUARTILE_INC; cQUARTILE_INC.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cRANK() { cBaseFunction.call(this, "RANK"); } cRANK.prototype = Object.create(cBaseFunction.prototype); cRANK.prototype.constructor = cRANK; cRANK.prototype.argumentsMin = 2; cRANK.prototype.argumentsMax = 3; cRANK.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true, [null, cElementType.array]); var argClone = oArguments.args; //1 argument - array argClone[0] = argClone[0].tocNumber(); argClone[2] = undefined !== argClone[2] ? argClone[2].tocNumber() : new cNumber(0); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcRank = function(argArray){ var number = argArray[0]; var ref = argArray[1]; var order = argArray[2]; var changedRef = []; for (var i = 0; i < ref.length; i++) { for (var j = 0; j < ref[i].length; j++) { if (ref[i][j] instanceof cError) { return ref[i][j]; } else if (ref[i][j] instanceof cNumber) { changedRef.push(ref[i][j].getValue()); } else if (ref[i][j] instanceof cBool) { changedRef.push(ref[i][j].tocNumber().getValue()); } } } if(!changedRef.length){ return new cError(cErrorType.wrong_value_type); } var res = rank(number, changedRef, order); return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcRank); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cRANK_AVG() { cBaseFunction.call(this, "RANK.AVG"); } cRANK_AVG.prototype = Object.create(cBaseFunction.prototype); cRANK_AVG.prototype.constructor = cRANK_AVG; cRANK_AVG.prototype.argumentsMin = 2; cRANK_AVG.prototype.argumentsMax = 3; cRANK_AVG.prototype.isXLFN = true; cRANK_AVG.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true, [null, cElementType.array]); var argClone = oArguments.args; //1 argument - array argClone[0] = argClone[0].tocNumber(); argClone[2] = undefined !== argClone[2] ? argClone[2].tocNumber() : new cNumber(0); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcRank = function(argArray){ var number = argArray[0]; var ref = argArray[1]; var order = argArray[2]; var changedRef = []; for (var i = 0; i < ref.length; i++) { for (var j = 0; j < ref[i].length; j++) { if (ref[i][j] instanceof cError) { return ref[i][j]; } else if (ref[i][j] instanceof cNumber) { changedRef.push(ref[i][j].getValue()); } else if (ref[i][j] instanceof cBool) { changedRef.push(ref[i][j].tocNumber().getValue()); } } } if(!changedRef.length){ return new cError(cErrorType.wrong_value_type); } var res = rank(number, changedRef, order, true); return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcRank); }; /** * @constructor * @extends {cRANK} */ function cRANK_EQ() { cRANK.call(this); this.name = "RANK.EQ"; } cRANK_EQ.prototype = Object.create(cRANK.prototype); cRANK_EQ.prototype.constructor = cRANK_EQ; cRANK_EQ.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cRSQ() { this.name = "RSQ"; this.value = null; this.argumentsCurrent = 0; } cRSQ.prototype = Object.create(cBaseFunction.prototype); cRSQ.prototype.constructor = cRSQ; cRSQ.prototype.argumentsMin = 2; cRSQ.prototype.argumentsMax = 2; cRSQ.prototype.Calculate = function (arg) { function rsq(x, y) { var sumXDeltaYDelta = 0, sqrXDelta = 0, sqrYDelta = 0, _x = 0, _y = 0, xLength = 0, i; if (x.length != y.length) { return new cError(cErrorType.not_available); } for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } _x += x[i].getValue(); _y += y[i].getValue(); xLength++; } _x /= xLength; _y /= xLength; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } sumXDeltaYDelta += (x[i].getValue() - _x) * (y[i].getValue() - _y); sqrXDelta += (x[i].getValue() - _x) * (x[i].getValue() - _x); sqrYDelta += (y[i].getValue() - _y) * (y[i].getValue() - _y); } if (sqrXDelta == 0 || sqrYDelta == 0) { return new cError(cErrorType.division_by_zero); } else { return new cNumber(Math.pow(sumXDeltaYDelta / Math.sqrt(sqrXDelta * sqrYDelta), 2)); } } var arg0 = arg[0], arg1 = arg[1], arr0 = [], arr1 = []; if (arg0 instanceof cArea) { arr0 = arg0.getValue(); } else if (arg0 instanceof cArray) { arg0.foreach(function (elem) { arr0.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } if (arg1 instanceof cArea) { arr1 = arg1.getValue(); } else if (arg1 instanceof cArray) { arg1.foreach(function (elem) { arr1.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } return this.value = rsq(arr0, arr1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cSKEW() { this.name = "SKEW"; this.value = null; this.argumentsCurrent = 0; } cSKEW.prototype = Object.create(cBaseFunction.prototype); cSKEW.prototype.constructor = cSKEW; cSKEW.prototype.argumentsMin = 1; cSKEW.prototype.Calculate = function (arg) { var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber) { arr0.push(a); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString) { continue; } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = skew(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cSKEW_P() { this.name = "SKEW.P"; this.value = null; this.argumentsCurrent = 0; } cSKEW_P.prototype = Object.create(cBaseFunction.prototype); cSKEW_P.prototype.constructor = cSKEW_P; cSKEW_P.prototype.argumentsMin = 1; cSKEW_P.prototype.isXLFN = true; cSKEW_P.prototype.Calculate = function (arg) { var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber) { arr0.push(a); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber) { arr0.push(elem); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString) { continue; } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = skew(arr0, true); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cSLOPE() { this.name = "SLOPE"; this.value = null; this.argumentsCurrent = 0; } cSLOPE.prototype = Object.create(cBaseFunction.prototype); cSLOPE.prototype.constructor = cSLOPE; cSLOPE.prototype.argumentsMin = 2; cSLOPE.prototype.argumentsMax = 2; cSLOPE.prototype.Calculate = function (arg) { function slope(y, x) { var sumXDeltaYDelta = 0, sqrXDelta = 0, _x = 0, _y = 0, xLength = 0, i; if (x.length != y.length) { return new cError(cErrorType.not_available); } for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } _x += x[i].getValue(); _y += y[i].getValue(); xLength++; } _x /= xLength; _y /= xLength; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } sumXDeltaYDelta += (x[i].getValue() - _x) * (y[i].getValue() - _y); sqrXDelta += (x[i].getValue() - _x) * (x[i].getValue() - _x); } if (sqrXDelta == 0) { return new cError(cErrorType.division_by_zero); } else { return new cNumber(sumXDeltaYDelta / sqrXDelta); } } var arg0 = arg[0], arg1 = arg[1], arr0 = [], arr1 = []; if (arg0 instanceof cArea) { arr0 = arg0.getValue(); } else if (arg0 instanceof cArray) { arg0.foreach(function (elem) { arr0.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } if (arg1 instanceof cArea) { arr1 = arg1.getValue(); } else if (arg1 instanceof cArray) { arg1.foreach(function (elem) { arr1.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } return this.value = slope(arr0, arr1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cSMALL() { this.name = "SMALL"; this.value = null; this.argumentsCurrent = 0; } cSMALL.prototype = Object.create(cBaseFunction.prototype); cSMALL.prototype.constructor = cSMALL; cSMALL.prototype.argumentsMin = 2; cSMALL.prototype.argumentsMax = 2; cSMALL.prototype.numFormat = AscCommonExcel.cNumFormatNone; cSMALL.prototype.Calculate = function (arg) { var retArr = new cArray(); function frequency(A, k) { var tA = []; for (var i = 0; i < A.length; i++) { for (var j = 0; j < A[i].length; j++) { if (A[i][j] instanceof cError) { return A[i][j]; } else if (A[i][j] instanceof cNumber) { tA.push(A[i][j].getValue()); } else if (A[i][j] instanceof cBool) { tA.push(A[i][j].tocNumber().getValue()); } } } tA.sort(fSortAscending); if (k.getValue() > tA.length || k.getValue() <= 0) { return new cError(cErrorType.not_available); } else { return new cNumber(tA[k.getValue() - 1]); } } function actionArray(elem, r, c) { var e = elem.tocNumber(); if (e instanceof cError) { retArr.addElement(e); } retArr.addElement(frequency(arg0, e)); } var arg0 = arg[0], arg1 = arg[1]; if (arg0 instanceof cArea || arg0 instanceof cArray) { arg0 = arg0.getMatrix(this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); } else if (arg0 instanceof cArea3D) { arg0 = arg0.getMatrix(this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg)[0]; } else { return this.value = new cError(cErrorType.not_numeric); } if (arg1 instanceof cArea || arg1 instanceof cArea3D) { arg1 = arg1.cross(arguments[1]); } else if (arg1 instanceof cArray) { // arg1 = arg1.getElement( 0 ); arg1.foreach(actionArray); return this.value = retArr; } return this.value = frequency(arg0, arg1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cSTANDARDIZE() { this.name = "STANDARDIZE"; this.value = null; this.argumentsCurrent = 0; } cSTANDARDIZE.prototype = Object.create(cBaseFunction.prototype); cSTANDARDIZE.prototype.constructor = cSTANDARDIZE; cSTANDARDIZE.prototype.argumentsMin = 3; cSTANDARDIZE.prototype.argumentsMax = 3; cSTANDARDIZE.prototype.Calculate = function (arg) { var arg0 = arg[0], arg1 = arg[1], arg2 = arg[2]; function standardize(x, mue, sigma) { if (sigma <= 0.0) { return new cError(cErrorType.not_numeric); } else { return new cNumber((x - mue) / sigma); } } if (arg0 instanceof cArea || arg0 instanceof cArea3D) { arg0 = arg0.cross(arguments[1]); } else if (arg0 instanceof cArray) { arg0 = arg0.getElement(0); } if (arg1 instanceof cArea || arg1 instanceof cArea3D) { arg1 = arg1.cross(arguments[1]); } else if (arg1 instanceof cArray) { arg1 = arg1.getElement(0); } if (arg2 instanceof cArea || arg2 instanceof cArea3D) { arg2 = arg2.cross(arguments[1]); } else if (arg2 instanceof cArray) { arg2 = arg2.getElement(0); } arg0 = arg0.tocNumber(); arg1 = arg1.tocNumber(); arg2 = arg2.tocNumber(); if (arg0 instanceof cError) { return this.value = arg0; } if (arg1 instanceof cError) { return this.value = arg1; } if (arg2 instanceof cError) { return this.value = arg2; } return this.value = standardize(arg0.getValue(), arg1.getValue(), arg2.getValue()); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cSTDEV() { this.name = "STDEV"; this.value = null; this.argumentsCurrent = 0; } cSTDEV.prototype = Object.create(cBaseFunction.prototype); cSTDEV.prototype.constructor = cSTDEV; cSTDEV.prototype.argumentsMin = 1; cSTDEV.prototype.numFormat = AscCommonExcel.cNumFormatNone; cSTDEV.prototype.Calculate = function (arg) { var i, element, count = 0, sum = new cNumber(0), member = []; for (i = 0; i < arg.length; i++) { element = arg[i]; if (cElementType.cell === element.type || cElementType.cell3D === element.type) { if (!this.checkExclude || !element.isHidden(this.excludeHiddenRows)) { var _argV = element.getValue(); if (cElementType.number === _argV.type) { member.push(_argV); sum = _func[sum.type][_argV.type](sum, _argV, "+"); count++; } } } else if (cElementType.cellsRange === element.type || cElementType.cellsRange3D === element.type) { var _argAreaValue = element.getValue(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); for (var j = 0; j < _argAreaValue.length; j++) { var __arg = _argAreaValue[j]; if (cElementType.number === __arg.type) { member.push(__arg); sum = _func[sum.type][__arg.type](sum, __arg, "+"); count++; } } } else if (cElementType.array === element.type) { element.foreach(function (elem) { var e = elem.tocNumber(); if (cElementType.number === e.type) { member.push(e); sum = _func[sum.type][e.type](sum, e, "+"); count++; } }) } else { element = element.tocNumber(); if (cElementType.number === element.type) { member.push(element); sum = _func[sum.type][element.type](sum, element, "+"); count++; } } } var average = sum.getValue() / count, res = 0, av; for (i = 0; i < member.length; i++) { av = member[i] - average; res += av * av; } if(1 === count){ return new cError(cErrorType.division_by_zero); } return this.value = new cNumber(Math.sqrt(res / (count - 1))); }; /** * @constructor * @extends {cSTDEV} */ function cSTDEV_S() { cSTDEV.call(this); this.name = "STDEV.S"; } cSTDEV_S.prototype = Object.create(cSTDEV.prototype); cSTDEV_S.prototype.constructor = cSTDEV_S; cSTDEV_S.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cSTDEVA() { this.name = "STDEVA"; this.value = null; this.argumentsCurrent = 0; } cSTDEVA.prototype = Object.create(cBaseFunction.prototype); cSTDEVA.prototype.constructor = cSTDEVA; cSTDEVA.prototype.argumentsMin = 1; cSTDEVA.prototype.Calculate = function (arg) { var count = 0, sum = new cNumber(0), member = [], i; for (i = 0; i < arg.length; i++) { var _arg = arg[i]; if (_arg instanceof cRef || _arg instanceof cRef3D) { var _argV = _arg.getValue().tocNumber(); if (_argV instanceof cNumber) { member.push(_argV); sum = _func[sum.type][_argV.type](sum, _argV, "+"); count++; } } else if (_arg instanceof cArea || _arg instanceof cArea3D) { var _argAreaValue = _arg.getValue(); for (var j = 0; j < _argAreaValue.length; j++) { var __arg = _argAreaValue[j].tocNumber(); if (__arg instanceof cNumber) { member.push(__arg); sum = _func[sum.type][__arg.type](sum, __arg, "+"); count++; } } } else if (_arg instanceof cArray) { _arg.foreach(function (elem) { var e = elem.tocNumber(); if (e instanceof cNumber) { member.push(e); sum = _func[sum.type][e.type](sum, e, "+"); count++; } }) } else { _arg = _arg.tocNumber(); if (_arg instanceof cNumber) { member.push(_arg); sum = _func[sum.type][_arg.type](sum, _arg, "+"); count++; } } } var average = sum.getValue() / count, res = 0, av; for (i = 0; i < member.length; i++) { av = member[i] - average; res += av * av; } return this.value = new cNumber(Math.sqrt(res / (count - 1))); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cSTDEVP() { this.name = "STDEVP"; this.value = null; this.argumentsCurrent = 0; } cSTDEVP.prototype = Object.create(cBaseFunction.prototype); cSTDEVP.prototype.constructor = cSTDEVP; cSTDEVP.prototype.argumentsMin = 1; cSTDEVP.prototype.Calculate = function (arg) { function _var(x) { var i, tA = [], sumSQRDeltaX = 0, _x = 0, xLength = 0; for (i = 0; i < x.length; i++) { if (cElementType.number === x[i].type) { _x += x[i].getValue(); tA.push(x[i].getValue()); xLength++; } else if (cElementType.error === x[i].type) { return x[i]; } } _x /= xLength; for (i = 0; i < x.length; i++) { sumSQRDeltaX += (tA[i] - _x) * (tA[i] - _x) } return new cNumber(isNaN(_x) ? new cError(cErrorType.division_by_zero) : Math.sqrt(sumSQRDeltaX / xLength)); } var element, arr0 = []; for (var j = 0; j < arg.length; j++) { element = arg[j]; if (cElementType.cellsRange === element.type || cElementType.cellsRange3D === element.type) { var _arrVal = element.getValue(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); _arrVal.forEach(function (elem) { if (cElementType.number === elem.type || cElementType.error === elem.type) { arr0.push(elem); } }); } else if (cElementType.cell === element.type || cElementType.cell3D === element.type) { if (!this.checkExclude || !element.isHidden(this.excludeHiddenRows)) { var a = element.getValue(); if (cElementType.number === a.type || cElementType.error === a.type) { arr0.push(a); } } } else if (cElementType.array === element.type) { element.foreach(function (elem) { if (cElementType.number === elem.type || cElementType.error === elem.type) { arr0.push(elem); } }); } else if (cElementType.number === element.type || cElementType.bool === element.type) { arr0.push(element.tocNumber()); } else if (cElementType.string === element.type || cElementType.empty === element.type) { arr0.push(new cNumber(0)); } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = _var(arr0); }; /** * @constructor * @extends {cSTDEVP} */ function cSTDEV_P() { cSTDEVP.call(this); this.name = "STDEV.P"; } cSTDEV_P.prototype = Object.create(cSTDEVP.prototype); cSTDEV_P.prototype.constructor = cSTDEV_P; cSTDEV_P.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cSTDEVPA() { this.name = "STDEVPA"; this.value = null; this.argumentsCurrent = 0; } cSTDEVPA.prototype = Object.create(cBaseFunction.prototype); cSTDEVPA.prototype.constructor = cSTDEVPA; cSTDEVPA.prototype.argumentsMin = 1; cSTDEVPA.prototype.Calculate = function (arg) { function _var(x) { var tA = [], sumSQRDeltaX = 0, _x = 0, xLength = 0, i; for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { _x += x[i].getValue(); tA.push(x[i].getValue()); xLength++; } else if (x[i] instanceof cError) { return x[i]; } } _x /= xLength; for (i = 0; i < x.length; i++) { sumSQRDeltaX += (tA[i] - _x) * (tA[i] - _x) } return new cNumber(Math.sqrt(sumSQRDeltaX / xLength)); } var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber || elem instanceof cError) { arr0.push(elem); } else if (elem instanceof cBool) { arr0.push(elem.tocNumber()); } else if (elem instanceof cString) { arr0.push(new cNumber(0)); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber || a instanceof cError) { arr0.push(a); } else if (a instanceof cBool) { arr0.push(a.tocNumber()); } else if (a instanceof cString) { arr0.push(new cNumber(0)); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber || elem instanceof cError) { arr0.push(elem); } else if (elem instanceof cBool) { arr0.push(elem.tocNumber()); } else if (elem instanceof cString) { arr0.push(new cNumber(0)); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString) { arr0.push(new cNumber(0)); } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = _var(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cSTEYX() { this.name = "STEYX"; this.value = null; this.argumentsCurrent = 0; } cSTEYX.prototype = Object.create(cBaseFunction.prototype); cSTEYX.prototype.constructor = cSTEYX; cSTEYX.prototype.argumentsMin = 2; cSTEYX.prototype.argumentsMax = 2; cSTEYX.prototype.Calculate = function (arg) { function steyx(y, x) { var sumXDeltaYDelta = 0, sqrXDelta = 0, sqrYDelta = 0, _x = 0, _y = 0, xLength = 0, i; if (x.length != y.length) { return new cError(cErrorType.not_available); } for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } _x += x[i].getValue(); _y += y[i].getValue(); xLength++; } _x /= xLength; _y /= xLength; for (i = 0; i < x.length; i++) { if (!( x[i] instanceof cNumber && y[i] instanceof cNumber )) { continue; } sumXDeltaYDelta += (x[i].getValue() - _x) * (y[i].getValue() - _y); sqrXDelta += (x[i].getValue() - _x) * (x[i].getValue() - _x); sqrYDelta += (y[i].getValue() - _y) * (y[i].getValue() - _y); } if (sqrXDelta == 0 || sqrYDelta == 0 || xLength < 3) { return new cError(cErrorType.division_by_zero); } else { return new cNumber(Math.sqrt( (1 / (xLength - 2)) * (sqrYDelta - sumXDeltaYDelta * sumXDeltaYDelta / sqrXDelta))); } } var arg0 = arg[0], arg1 = arg[1], arr0 = [], arr1 = []; if (arg0 instanceof cArea) { arr0 = arg0.getValue(); } else if (arg0 instanceof cArray) { arg0.foreach(function (elem) { arr0.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } if (arg1 instanceof cArea) { arr1 = arg1.getValue(); } else if (arg1 instanceof cArray) { arg1.foreach(function (elem) { arr1.push(elem); }); } else { return this.value = new cError(cErrorType.wrong_value_type); } return this.value = steyx(arr0, arr1); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cTDIST() { cBaseFunction.call(this, "TDIST"); } cTDIST.prototype = Object.create(cBaseFunction.prototype); cTDIST.prototype.constructor = cTDIST; cTDIST.prototype.argumentsMin = 3; cTDIST.prototype.argumentsMax = 3; cTDIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var T = argArray[0]; var fDF = argArray[1]; var nType = argArray[2]; var res = getTDist(T, fDF, nType); return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; if (argClone[1].getValue() < 1 || argClone[0].getValue() < 0 || (argClone[2].getValue() !== 1 && argClone[2].getValue() !== 2) ){ return this.value = new cError(cErrorType.not_numeric); } return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cT_DIST() { cBaseFunction.call(this, "T.DIST"); } cT_DIST.prototype = Object.create(cBaseFunction.prototype); cT_DIST.prototype.constructor = cT_DIST; cT_DIST.prototype.argumentsMin = 3; cT_DIST.prototype.argumentsMax = 3; cT_DIST.prototype.isXLFN = true; cT_DIST.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var T = argArray[0]; var fDF = argArray[1]; var bCumulative = argArray[2]; var res = getTDist(T, fDF, bCumulative ? 4 : 3); return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; if (argClone[1].getValue() < 1 ){ return this.value = new cError(cErrorType.not_numeric); } return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cT_DIST_2T() { cBaseFunction.call(this, "T.DIST.2T"); } cT_DIST_2T.prototype = Object.create(cBaseFunction.prototype); cT_DIST_2T.prototype.constructor = cT_DIST_2T; cT_DIST_2T.prototype.argumentsMin = 2; cT_DIST_2T.prototype.argumentsMax = 2; cT_DIST_2T.prototype.isXLFN = true; cT_DIST_2T.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var T = argArray[0]; var fDF = argArray[1]; if (fDF < 1 || T < 0){ return new cError(cErrorType.not_numeric); } var res = getTDist(T, fDF, 2); return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cT_DIST_RT() { cBaseFunction.call(this, "T.DIST.RT"); } cT_DIST_RT.prototype = Object.create(cBaseFunction.prototype); cT_DIST_RT.prototype.constructor = cT_DIST_RT; cT_DIST_RT.prototype.argumentsMin = 2; cT_DIST_RT.prototype.argumentsMax = 2; cT_DIST_RT.prototype.isXLFN = true; cT_DIST_RT.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var T = argArray[0]; var fDF = argArray[1]; if (fDF < 1){ return new cError(cErrorType.not_numeric); } var res = getTDist(T, fDF, 1); if ( T < 0 ){ res = 1 - res; } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cT_INV() { cBaseFunction.call(this, "T.INV"); } cT_INV.prototype = Object.create(cBaseFunction.prototype); cT_INV.prototype.constructor = cT_INV; cT_INV.prototype.argumentsMin = 2; cT_INV.prototype.argumentsMax = 2; cT_INV.prototype.isXLFN = true; cT_INV.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var fP = argArray[0]; var fDF = parseInt(argArray[1]); if ( fDF < 1.0 || fP <= 0.0 || fP > 1.0 ){ return new cError(cErrorType.not_numeric); } var aFunc, oVal, bConvError, res = null; if ( fP === 1.0 ){ return new cError(cErrorType.not_numeric); }else if(fP < 0.5){ aFunc = new TDISTFUNCTION(1 - fP, fDF, 4); oVal = iterateInverse(aFunc, fDF * 0.5, fDF); bConvError = oVal.bError; res = - oVal.val; }else{ aFunc = new TDISTFUNCTION(fP, fDF, 4); oVal = iterateInverse(aFunc, fDF * 0.5, fDF); bConvError = oVal.bError; res = oVal.val; } if (bConvError){ return new cError(cErrorType.not_numeric); } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cT_INV_2T() { cBaseFunction.call(this, "T.INV.2T"); } cT_INV_2T.prototype = Object.create(cBaseFunction.prototype); cT_INV_2T.prototype.constructor = cT_INV_2T; cT_INV_2T.prototype.argumentsMin = 2; cT_INV_2T.prototype.argumentsMax = 2; cT_INV_2T.prototype.isXLFN = true; cT_INV_2T.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTDist = function(argArray){ var fP = argArray[0]; var fDF = parseInt(argArray[1]); //ms игнорирует услвие fP > 1. сделал как в документации if ( fDF < 1.0 || fP <= 0 || fP > 1 ){ return new cError(cErrorType.not_numeric); } var aFunc = new TDISTFUNCTION(fP, fDF, 2); var oVal = iterateInverse(aFunc, fDF * 0.5, fDF); var bConvError = oVal.bError; var res = oVal.val; if (bConvError){ return new cError(cErrorType.not_numeric); } return null !== res && !isNaN(res) ? new cNumber(res) : new cError(cErrorType.wrong_value_type); }; return this.value = this._findArrayInNumberArguments(oArguments, calcTDist); }; /** * @constructor * @extends {cT_INV_2T} */ function cTINV() { cT_INV_2T.call(this); this.name = "TINV"; } cTINV.prototype = Object.create(cT_INV_2T.prototype); cTINV.prototype.constructor = cTINV; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cTREND() { cBaseFunction.call(this, "TREND"); } cTREND.prototype = Object.create(cBaseFunction.prototype); cTREND.prototype.constructor = cTREND; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cTRIMMEAN() { this.name = "TRIMMEAN"; this.value = null; this.argumentsCurrent = 0; } cTRIMMEAN.prototype = Object.create(cBaseFunction.prototype); cTRIMMEAN.prototype.constructor = cTRIMMEAN; cTRIMMEAN.prototype.argumentsMin = 2; cTRIMMEAN.prototype.argumentsMax = 2; cTRIMMEAN.prototype.Calculate = function (arg) { var arg2 = [arg[0], arg[1]]; //если первое значение строка if(cElementType.string === arg[0].type || cElementType.bool === arg[0].type){ return this.value = new cError(cErrorType.wrong_value_type); } //если первое значение число if(cElementType.number === arg[0].type){ arg2[0] = new cArray(); arg2[0].addElement(arg[0]); } var oArguments = this._prepareArguments(arg2, arguments[1], true, [cElementType.array]); var argClone = oArguments.args; argClone[1] = argClone[1].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTrimMean = function(argArray){ var arg0 = argArray[0]; var arg1 = argArray[1]; if (arg1 < 0.0 || arg1 >= 1.0){ return new cError(cErrorType.not_numeric); } var arr = []; for (var i = 0; i < arg0.length; i++) { for (var j = 0; j < arg0[i].length; j++) { if (cElementType.number === arg0[i][j].type) { arr.push(arg0[i][j].getValue()); } } } var aSortArray = arr.sort(fSortAscending); var nSize = aSortArray.length; if (nSize == 0){ return new cError(cErrorType.not_numeric); }else{ var nIndex = Math.floor(arg1 * nSize); if (nIndex % 2 !== 0){ nIndex--; } nIndex /= 2; var fSum = 0.0; for (var i = nIndex; i < nSize-nIndex; i++){ fSum += aSortArray[i]; } return new cNumber(fSum / (nSize - 2*nIndex)); } }; return this.value = this._findArrayInNumberArguments(oArguments, calcTrimMean); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cTTEST() { this.name = "TTEST"; this.value = null; this.argumentsCurrent = 0; } cTTEST.prototype = Object.create(cBaseFunction.prototype); cTTEST.prototype.constructor = cTTEST; cTTEST.prototype.argumentsMin = 4; cTTEST.prototype.argumentsMax = 4; cTTEST.prototype.Calculate = function (arg) { var arg2 = [arg[0], arg[1], arg[2], arg[3]]; //если первое или второе значение строка if(cElementType.string === arg[0].type || cElementType.bool === arg[0].type){ return this.value = new cError(cErrorType.wrong_value_type); } if(cElementType.string === arg[1].type || cElementType.bool === arg[1].type){ return this.value = new cError(cErrorType.wrong_value_type); } //если первое или второе значение число if(cElementType.number === arg[0].type){ arg2[0] = new cArray(); arg2[0].addElement(arg[0]); } if(cElementType.number === arg[1].type){ arg2[1] = new cArray(); arg2[1].addElement(arg[1]); } var oArguments = this._prepareArguments(arg2, arguments[1], true, [cElementType.array, cElementType.array]); var argClone = oArguments.args; argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3].tocNumber();//bool var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcTTest = function(argArray){ var arg0 = argArray[0]; var arg1 = argArray[1]; var arg2 = parseInt(argArray[2]); var arg3 = parseInt(argArray[3]); if(!(arg2 === 1 || arg2 === 2)){ return new cError(cErrorType.not_numeric); } return tTest(arg0, arg1, arg2, arg3); }; return this.value = this._findArrayInNumberArguments(oArguments, calcTTest); }; /** * @constructor * @extends {cTTEST} */ function cT_TEST() { cTTEST.call(this); this.name = "T.TEST"; } cT_TEST.prototype = Object.create(cTTEST.prototype); cT_TEST.prototype.constructor = cT_TEST; cT_TEST.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cVAR() { this.name = "VAR"; this.value = null; this.argumentsCurrent = 0; } cVAR.prototype = Object.create(cBaseFunction.prototype); cVAR.prototype.constructor = cVAR; cVAR.prototype.argumentsMin = 1; cVAR.prototype.Calculate = function (arg) { function _var(x) { if (x.length < 1) { return new cError(cErrorType.division_by_zero); } var i, tA = [], sumSQRDeltaX = 0, _x = 0, xLength = 0; for (i = 0; i < x.length; i++) { if (cElementType.number === x[i].type) { _x += x[i].getValue(); tA.push(x[i].getValue()); xLength++; } else if (cElementType.error === x[i].type) { return x[i]; } } _x /= xLength; for (i = 0; i < x.length; i++) { sumSQRDeltaX += (tA[i] - _x) * (tA[i] - _x) } return new cNumber(sumSQRDeltaX / (xLength - 1)) } var element, arr0 = []; for (var j = 0; j < arg.length; j++) { element = arg[j]; if (cElementType.cellsRange === element.type || cElementType.cellsRange3D === element.type) { var _arrVal = element.getValue(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); _arrVal.forEach(function (elem) { if (cElementType.number === elem.type || cElementType.error === elem.type) { arr0.push(elem); } }); } else if (cElementType.cell === element.type || cElementType.cell3D === element.type) { if (!this.checkExclude || !element.isHidden(this.excludeHiddenRows)) { var a = element.getValue(); if (cElementType.number === a.type || cElementType.error === a.type) { arr0.push(a); } } } else if (cElementType.array === element.type) { element.foreach(function (elem) { if (cElementType.number === elem.type || cElementType.error === elem.type) { arr0.push(elem); } }); } else if (cElementType.number === element.type || cElementType.bool === element.type) { arr0.push(element.tocNumber()); } else if (cElementType.string === element.type || cElementType.empty === element.type) { continue; } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = _var(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cVARA() { this.name = "VARA"; this.value = null; this.argumentsCurrent = 0; } cVARA.prototype = Object.create(cBaseFunction.prototype); cVARA.prototype.constructor = cVARA; cVARA.prototype.argumentsMin = 1; cVARA.prototype.Calculate = function (arg) { function _var(x) { if (x.length < 1) { return new cError(cErrorType.division_by_zero); } var tA = [], sumSQRDeltaX = 0, _x = 0, xLength = 0, i; for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { _x += x[i].getValue(); tA.push(x[i].getValue()); xLength++; } else if (x[i] instanceof cError) { return x[i]; } } _x /= xLength; for (i = 0; i < x.length; i++) { sumSQRDeltaX += (tA[i] - _x) * (tA[i] - _x) } return new cNumber(sumSQRDeltaX / (xLength - 1)) } var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber || elem instanceof cError) { arr0.push(elem); } else if (elem instanceof cBool) { arr0.push(elem.tocNumber()); } else if (elem instanceof cString) { arr0.push(new cNumber(0)); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber || a instanceof cError) { arr0.push(a); } else if (a instanceof cBool) { arr0.push(a.tocNumber()); } else if (a instanceof cString) { arr0.push(new cNumber(0)); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber || elem instanceof cError) { arr0.push(elem); } else if (elem instanceof cBool) { arr0.push(elem.tocNumber()); } else if (a instanceof cString) { arr0.push(new cNumber(0)); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString) { arr0.push(new cNumber(0)); } else if (arg[j] instanceof cError) { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = _var(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cVARP() { this.name = "VARP"; this.value = null; this.argumentsCurrent = 0; } cVARP.prototype = Object.create(cBaseFunction.prototype); cVARP.prototype.constructor = cVARP; cVARP.prototype.argumentsMin = 1; cVARP.prototype.Calculate = function (arg) { function _var(x) { if (x.length < 1) { return new cError(cErrorType.division_by_zero); } var tA = [], sumSQRDeltaX = 0, _x = 0, xLength = 0, i; for (i = 0; i < x.length; i++) { if (cElementType.number === x[i].type) { _x += x[i].getValue(); tA.push(x[i].getValue()); xLength++; } else if (cElementType.error === x[i].type) { return x[i]; } } _x /= xLength; for (i = 0; i < x.length; i++) { sumSQRDeltaX += (tA[i] - _x) * (tA[i] - _x); } return new cNumber(sumSQRDeltaX / xLength); } var element, arr0 = []; for (var j = 0; j < arg.length; j++) { element = arg[j]; if (cElementType.cellsRange === element.type || cElementType.cellsRange3D === element.type) { var _arrVal = element.getValue(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); _arrVal.forEach(function (elem) { if (cElementType.number === elem.type || cElementType.error === elem.type) { arr0.push(elem); } }); } else if (cElementType.cell === element.type || cElementType.cell3D === element.type) { if (!this.checkExclude || !element.isHidden(this.excludeHiddenRows)) { var a = element.getValue(); if (cElementType.number === a.type || cElementType.error === a.type) { arr0.push(a); } } } else if (cElementType.array === element.type) { element.foreach(function (elem) { if (cElementType.number === elem.type || cElementType.error === elem.type) { arr0.push(elem); } }); } else if (cElementType.number === element.type || cElementType.bool === element.type) { arr0.push(element.tocNumber()); } else if (cElementType.string === element.type || cElementType.empty === element.type) { arr0.push(new cNumber(0)); } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = _var(arr0); }; /** * @constructor * @extends {cVARP} */ function cVAR_P() { cVARP.call(this); this.name = "VAR.P"; } cVAR_P.prototype = Object.create(cVARP.prototype); cVAR_P.prototype.constructor = cVAR_P; cVAR_P.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cVAR_S() { this.name = "VAR.S"; this.value = null; this.argumentsCurrent = 0; } cVAR_S.prototype = Object.create(cBaseFunction.prototype); cVAR_S.prototype.constructor = cVAR_S; cVAR_S.prototype.argumentsMin = 1; cVAR_S.prototype.isXLFN = true; cVAR_S.prototype.Calculate = function (arg) { function _var(x) { if (x.length <= 1) { return new cError(cErrorType.division_by_zero); } var tA = [], sumSQRDeltaX = 0, _x = 0, xLength = 0, i; for (i = 0; i < x.length; i++) { if (cElementType.number === x[i].type) { _x += x[i].getValue(); tA.push(x[i].getValue()); xLength++; } else if (cElementType.error === x[i].type) { return x[i]; } } _x /= xLength; for (i = 0; i < x.length; i++) { sumSQRDeltaX += (tA[i] - _x) * (tA[i] - _x); } return new cNumber(sumSQRDeltaX / (xLength - 1)); } var element, arr0 = []; for (var j = 0; j < arg.length; j++) { element = arg[j]; if (cElementType.cellsRange === element.type || cElementType.cellsRange3D === element.type) { var _arrVal = element.getValue(this.checkExclude, this.excludeHiddenRows, this.excludeErrorsVal, this.excludeNestedStAg); _arrVal.forEach(function (elem) { if (cElementType.number === elem.type || cElementType.error === elem.type) { arr0.push(elem); } }); } else if (cElementType.cell === element.type || cElementType.cell3D === element.type) { if (!this.checkExclude || !element.isHidden(this.excludeHiddenRows)) { var a = element.getValue(); if (cElementType.number === a.type || cElementType.error === a.type) { arr0.push(a); } } } else if (cElementType.array === element.type) { element.foreach(function (elem) { if (cElementType.number === elem.type || cElementType.error === elem.type) { arr0.push(elem); } }); } else if (cElementType.number === element.type || cElementType.bool === element.type) { arr0.push(element.tocNumber()); } else if (cElementType.string === element.type || cElementType.empty === element.type) { arr0.push(new cNumber(0)); } else { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = _var(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cVARdotP() { this.name = "VAR.P"; this.value = null; this.argumentsCurrent = 0; } cVARdotP.prototype = Object.create(cBaseFunction.prototype); cVARdotP.prototype.constructor = cVARdotP; cVARdotP.prototype.argumentsMin = 1; cVARdotP.prototype.Calculate = cVARP.prototype.Calculate; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cVARPA() { this.name = "VARPA"; this.value = null; this.argumentsCurrent = 0; } cVARPA.prototype = Object.create(cBaseFunction.prototype); cVARPA.prototype.constructor = cVARPA; cVARPA.prototype.argumentsMin = 1; cVARPA.prototype.Calculate = function (arg) { function _var(x) { if (x.length < 1) { return new cError(cErrorType.division_by_zero); } var tA = [], sumSQRDeltaX = 0, _x = 0, xLength = 0, i; for (i = 0; i < x.length; i++) { if (x[i] instanceof cNumber) { _x += x[i].getValue(); tA.push(x[i].getValue()); xLength++; } else if (x[i] instanceof cError) { return x[i]; } } _x /= xLength; for (i = 0; i < x.length; i++) { sumSQRDeltaX += (tA[i] - _x) * (tA[i] - _x) } return new cNumber(sumSQRDeltaX / xLength); } var arr0 = []; for (var j = 0; j < this.getArguments(); j++) { if (arg[j] instanceof cArea || arg[j] instanceof cArea3D) { arg[j].foreach2(function (elem) { if (elem instanceof cNumber || elem instanceof cError) { arr0.push(elem); } else if (elem instanceof cBool) { arr0.push(elem.tocNumber()); } else if (elem instanceof cString) { arr0.push(new cNumber(0)); } }); } else if (arg[j] instanceof cRef || arg[j] instanceof cRef3D) { var a = arg[j].getValue(); if (a instanceof cNumber || a instanceof cError) { arr0.push(a); } else if (a instanceof cBool) { arr0.push(a.tocNumber()); } else if (a instanceof cString) { arr0.push(new cNumber(0)); } } else if (arg[j] instanceof cArray) { arg[j].foreach(function (elem) { if (elem instanceof cNumber || elem instanceof cError) { arr0.push(elem); } else if (elem instanceof cBool) { arr0.push(elem.tocNumber()); } else if (elem instanceof cString) { arr0.push(new cNumber(0)); } }); } else if (arg[j] instanceof cNumber || arg[j] instanceof cBool) { arr0.push(arg[j].tocNumber()); } else if (arg[j] instanceof cString) { arr0.push(new cNumber(0)); } else if (elem instanceof cError) { return this.value = new cError(cErrorType.wrong_value_type); } } return this.value = _var(arr0); }; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cWEIBULL() { this.name = "WEIBULL"; this.value = null; this.argumentsCurrent = 0; } cWEIBULL.prototype = Object.create(cBaseFunction.prototype); cWEIBULL.prototype.constructor = cWEIBULL; cWEIBULL.prototype.argumentsMin = 4; cWEIBULL.prototype.argumentsMax = 4; cWEIBULL.prototype.Calculate = function (arg) { var oArguments = this._prepareArguments(arg, arguments[1], true); var argClone = oArguments.args; argClone[0] = argClone[0].tocNumber(); argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2].tocNumber(); argClone[3] = argClone[3].tocNumber(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } var calcWeibull = function(argArray){ var x = argArray[0]; var alpha = argArray[1]; var beta = argArray[2]; var kum = argArray[3]; var res; if (alpha <= 0 || beta <= 0 || x < 0){ return new cError(cErrorType.not_numeric); } else if (kum === 0){ res = alpha / Math.pow(beta,alpha) * Math.pow(x,alpha-1.0) * Math.exp(-Math.pow(x/beta,alpha)); }else{ res = 1.0 - Math.exp(-Math.pow(x / beta, alpha)); } return new cNumber(res); }; return this.value = this._findArrayInNumberArguments(oArguments, calcWeibull); }; /** * @constructor * @extends {cRANK} */ function cWEIBULL_DIST() { cWEIBULL.call(this); this.name = "WEIBULL.DIST"; } cWEIBULL_DIST.prototype = Object.create(cWEIBULL.prototype); cWEIBULL_DIST.prototype.constructor = cWEIBULL_DIST; cWEIBULL_DIST.prototype.isXLFN = true; /** * @constructor * @extends {AscCommonExcel.cBaseFunction} */ function cZTEST() { this.name = "ZTEST"; this.value = null; this.argumentsCurrent = 0; } cZTEST.prototype = Object.create(cBaseFunction.prototype); cZTEST.prototype.constructor = cZTEST; cZTEST.prototype.argumentsMin = 2; cZTEST.prototype.argumentsMax = 3; cZTEST.prototype.Calculate = function (arg) { var arg2 = arg[2] ? [arg[0], arg[1], arg[2]] : [arg[0], arg[1]]; //если первое или второе значение строка if(cElementType.string === arg[0].type || cElementType.bool === arg[0].type){ return this.value = new cError(cErrorType.wrong_value_type); } //если первое или второе значение число if(cElementType.number === arg[0].type){ arg2[0] = new cArray(); arg2[0].addElement(arg[0]); } var oArguments = this._prepareArguments(arg2, arguments[1], true, [cElementType.array]); var argClone = oArguments.args; argClone[1] = argClone[1].tocNumber(); argClone[2] = argClone[2] ? argClone[2].tocNumber() : new AscCommonExcel.cUndefined(); var argError; if (argError = this._checkErrorArg(argClone)) { return this.value = argError; } function calcZTest(argArray) { var arg0 = argArray[0]; var x = argArray[1]; var sigma = argArray[2]; if ( sigma !== undefined && sigma <= 0 ){ return new cError(cErrorType.not_numeric); } var nC1 = arg0.length; var nR1 = arg0[0].length; var fSum = 0.0; var fSumSqr = 0.0; var fVal; var rValCount = 0.0; for (var i = 0; i < nC1; i++){ for (var j = 0; j < nR1; j++){ if(cElementType.number !== arg0[i][j].type || cElementType.number !== arg0[i][j].type){ continue; } fVal = arg0[i][j].getValue(); fSum += fVal; fSumSqr += fVal*fVal; rValCount++; } } var res; if (rValCount <= 1.0){ return new cError(cErrorType.division_by_zero); }else{ var mue = fSum / rValCount; if (undefined === sigma){ sigma = (fSumSqr - fSum * fSum / rValCount) / (rValCount - 1.0); res = 0.5 - gauss((mue - x) / Math.sqrt(sigma / rValCount)); }else{ res = 0.5 - gauss((mue - x) * Math.sqrt(rValCount) / sigma); } } return new cNumber(res); } return this.value = this._findArrayInNumberArguments(oArguments, calcZTest); }; /** * @constructor * @extends {cZTEST} */ function cZ_TEST() { cZTEST.call(this); this.name = "Z.TEST"; } cZ_TEST.prototype = Object.create(cZTEST.prototype); cZ_TEST.prototype.constructor = cZ_TEST; cZ_TEST.prototype.isXLFN = true; //----------------------------------------------------------export---------------------------------------------------- window['AscCommonExcel'] = window['AscCommonExcel'] || {}; window['AscCommonExcel'].phi = phi; window['AscCommonExcel'].gauss = gauss; window['AscCommonExcel'].gaussinv = gaussinv; window['AscCommonExcel'].getPercentile = getPercentile; window['AscCommonExcel'].cAVERAGE = cAVERAGE; window['AscCommonExcel'].cCOUNT = cCOUNT; window['AscCommonExcel'].cCOUNTA = cCOUNTA; window['AscCommonExcel'].cMAX = cMAX; window['AscCommonExcel'].cMIN = cMIN; window['AscCommonExcel'].cSTDEV = cSTDEV; window['AscCommonExcel'].cSTDEVP = cSTDEVP; window['AscCommonExcel'].cVAR = cVAR; window['AscCommonExcel'].cVARP = cVARP; window['AscCommonExcel'].cLARGE = cLARGE; window['AscCommonExcel'].cSMALL = cSMALL; window['AscCommonExcel'].cMEDIAN = cMEDIAN; window['AscCommonExcel'].cSTDEV_S = cSTDEV_S; window['AscCommonExcel'].cSTDEV_P = cSTDEV_P; window['AscCommonExcel'].cVAR_S = cVAR_S; window['AscCommonExcel'].cVAR_P = cVAR_P; window['AscCommonExcel'].cMODE_SNGL = cMODE_SNGL; window['AscCommonExcel'].cPERCENTILE_INC = cPERCENTILE_INC; window['AscCommonExcel'].cQUARTILE_INC = cQUARTILE_INC; window['AscCommonExcel'].cPERCENTILE_EXC = cPERCENTILE_EXC; window['AscCommonExcel'].cQUARTILE_EXC = cQUARTILE_EXC; })(window);
+ for forecast functions
cell/model/FormulaObjects/statisticalFunctions.js
+ for forecast functions
<ide><path>ell/model/FormulaObjects/statisticalFunctions.js <ide> <ide> ScETSForecastCalculation.prototype.PreprocessDataRange = function( rMatX, rMatY, rSmplInPrd, bDataCompletion, nAggregation, rTMat, eETSType ) <ide> { <del> this.bEDS = ( rSmplInPrd == 0 ); <add> this.bEDS = ( rSmplInPrd === 0 ); <ide> this.bAdditive = /*( eETSType == etsAdd || eETSType == etsPIAdd || eETSType == etsStatAdd )*/true; <ide> <ide> this.mnCount = rMatX.length; <ide> } <ide> } <ide> <del> if ( rSmplInPrd != 1 ){ <add> if ( rSmplInPrd !== 1 ){ <ide> this.mnSmplInPrd = rSmplInPrd; <ide> }else { <ide> this.mnSmplInPrd = this.CalcPeriodLen(); <del> if ( this.mnSmplInPrd == 1 ){ <add> if ( this.mnSmplInPrd === 1 ){ <ide> this.bEDS = true; // period length 1 means no periodic data: EDS suffices <ide> } <ide> } <ide> var pTMat = argClone[0]; <ide> var pMatY = argClone[1]; <ide> var pMatX = argClone[2]; <del> var nSmplInPrd = argClone[3]; <del> var bDataCompletion = argClone[4]; <del> var nAggregation = argClone[5]; <del> <add> var nSmplInPrd = argClone[3].getValue(); <add> var bDataCompletion = argClone[4].getValue(); <add> var nAggregation = argClone[5].getValue(); <ide> <ide> <ide> var aETSCalc = new ScETSForecastCalculation( pMatX.length );
JavaScript
mit
95a69ec8e0784f0108c9db41e92edec1cebbaf24
0
goldenratio/youtube-to-XBMC,goldenratio/youtube-to-XBMC
/** * Content Script * @author: Karthik VJ */ if(ENABLE_CONSOLE == false) { var console = console || {}; console.log = function() {}; } ;(function() { var pathName = window.location.pathname; var template_main = '<div class="xbmc_control">$header $play_all $sep $play_now</div>'; var template_header = 'YouTube to XBMC:'; var template_playnow = '<a href="#" rel="$pid" class="xbmc_playNow" title="Play Now - YouTube to XBMC" onclick="return false;">Play Now</a> | <a href="#" rel="$qid" class="xbmc_queue" title="Add to Queue - YouTube to XBMC" onclick="return false;">[+] Add to Queue</a>'; var template_playnow_sidebar = '<span rel="$pid" class="xbmc_playNow xbmc_link" title="Play Now - YouTube to XBMC" onclick="return false;">Play Now</span> | <span rel="$qid" class="xbmc_queue xbmc_link" title="Add to Queue - YouTube to XBMC" onclick="return false;">[+] Add to Queue</span>'; var template_playall = '<a href="#" rel="$lid" class="xbmc_playlist" title="Play All - YouTube to XBMC" onclick="return false;">Play All</a>'; var template_playall_sidebar = '<span rel="$lid" class="xbmc_playlist xbmc_link" title="Play All - YouTube to XBMC" onclick="return false;">Play All</span>'; var timer; console.log("pathName, " + pathName); var RpcService = function() { this.playVideoOnXBMC = function(vId) { chrome.extension.sendMessage({message: "playVideo", videoId: vId}, function(response) { console.log("video sent! " + response); }); }; this.queueVideoToXBMC = function(vId) { chrome.extension.sendMessage({message: "queueVideo", videoId: vId}, function(response) { console.log("inject script >> video sent! " + response); if(response == ResultData.OK) { toastr.success("Added to Queue!"); } else { toastr.error("Error! Can't Add to Queue!"); } }); }; this.playListOnXBMC = function(listId, videoId) { chrome.extension.sendMessage({message: "playList", listId: listId, videoId: videoId}, function(response) { console.log("list sent! " + response); }); }; }; var Utils = new function() { this.findPropertyFromString = function(str, property) { //console.log("findPropertyFromString, str = " + str); //console.log("findPropertyFromString, property = " + property); property = property + "="; var index = str.indexOf('?'); str = str.substring(index + 1); //console.log("index = " + index); //console.log("str = " + str); var list = str.split('&'); //console.log("list.length, " + list.length); for(var i = 0; i < list.length; i++) { if(list[i].search(property) == 0) { return list[i].replace(property, ""); } } return 0; } }; this.injectLinks = function() { console.log("injectLinks"); // (home / subscription on home page), search page, video manager, user page, user browse video, Popular on YouTube, Popular on youtube right side, video list (on video page), play list page $(".feed-item-content, .yt-lockup2-content, .vm-video-info-container, .yt-tile-visible, .channels-content-item, .lohp-category-shelf-item, .lohp-large-shelf-container, .lohp-medium-shelf-content, .lohp-vertical-shelf-item-content, .video-list-item, .playlist-video-item, .yt-lockup-content, .recent-activity-snippet").each(function(index) { var alreadyAdded = false; $(this).find(".xbmc_control").each(function(xIndex) { alreadyAdded = true; return false; }); if(alreadyAdded) { return; // continue } console.log(index); var videoPathString; var listId; var videoId; // (home / subscription on home page), search page, video manager, (user page / user browse video / Popular on YouTube) $(this).find(".feed-video-title, .yt-uix-tile-link, .vm-video-title-content, .yt-uix-sessionlink").each(function(vIndex) { //console.log("video link, " + vIndex + ", " + $(this).attr("href")); videoPathString = $(this).attr("href"); return false; }); if(videoPathString) { console.log("videoPathString, " + videoPathString); var mainTemplate = template_main; // just a single video videoId = Utils.findPropertyFromString(videoPathString, "v"); if(videoId == 0) { videoId = Utils.findPropertyFromString(videoPathString, "video_id"); } if(videoId == 0) { videoId = Utils.findPropertyFromString(videoPathString, "video_ids"); videoId = decodeURIComponent(videoId); var vIndex = Utils.findPropertyFromString(videoPathString, "index"); if(vIndex < videoId.length) { videoId = videoId.split(",")[vIndex]; } } var copyTemp = template_playnow; var copyHeader = template_header; if(videoId != 0) { console.log("videoId, " +videoId); if($(this).hasClass("video-list-item") || $(this).hasClass("playlist-video-item")) { copyTemp = template_playnow_sidebar; } if($(this).hasClass("channels-content-item")) { copyHeader = ""; } copyTemp = copyTemp.replace("$pid", videoId); copyTemp = copyTemp.replace("$qid", videoId); mainTemplate = mainTemplate.replace("$play_now", copyTemp); //mainTemplate = mainTemplate.replace("$sep", "|"); //$(this).prepend(copyTemp); } else { //mainTemplate = mainTemplate.replace("$sep", ""); mainTemplate = mainTemplate.replace("$play_now", ""); } // find play list id listId = Utils.findPropertyFromString(videoPathString, "list"); var listTemp = template_playall; if(listId) { if($(this).hasClass("video-list-item") || $(this).hasClass("playlist-video-item")) { listTemp = template_playall_sidebar; } // it is play list if(videoId != 0) { // there is video too listId = listId + " " + videoId; mainTemplate = mainTemplate.replace("$sep", "|"); } else { // just play list mainTemplate = mainTemplate.replace("$sep", ""); } listTemp = listTemp.replace("$lid", listId); mainTemplate = mainTemplate.replace("$play_all", listTemp); //$(this).prepend(copyTemp); } else { mainTemplate = mainTemplate.replace("$sep", ""); mainTemplate = mainTemplate.replace("$play_all", ""); } mainTemplate = mainTemplate.replace("$header", copyHeader); ////// if(listId != 0 || videoId !=0) { $(this).prepend(mainTemplate); } listId = 0; videoId = 0; } }); $("#content").bind('DOMNodeInserted', function(event) { //console.log("DOM updated!"); var element = event.target; //console.log("element, " + element.tagName); clearInterval(timer); timer = setInterval(function(){ clearInterval(timer); $("#content").unbind('DOMNodeInserted'); injectLinks(); }, 2000) }); }; this.initListeners = function() { // click event listeners $(document).on('click', '.xbmc_playlist', function(event) { console.log("playlist, " + $(this).attr("rel")); var listId = $(this).attr("rel"); if(listId) { var listData = listId.split(" "); //console.log(listData[0]); //console.log(listData[1]); rpc.playListOnXBMC(listData[0], listData[1]); event.preventDefault(); } }); $(document).on('click', '.xbmc_playNow', function(event) { console.log("play single video, " + $(this).attr("rel")); rpc.playVideoOnXBMC($(this).attr("rel")); event.preventDefault(); }); $(document).on('click', '.xbmc_queue', function(event) { console.log("queue single video, " + $(this).attr("rel")); rpc.queueVideoToXBMC($(this).attr("rel")); event.preventDefault(); }); } ///////////////////////////// var rpc = new RpcService(); this.initListeners(); //////////////////////////// if(pathName == "/watch") { console.log("window.location, " + window.location); var loc = window.location.toString(); var mainVideoId = Utils.findPropertyFromString(loc, "v"); //alert("mainVideoId, " + mainVideoId); var mainTemplate = template_main; if(mainVideoId != 0) { var copyTemp = template_playnow.replace("$pid", mainVideoId); copyTemp = copyTemp.replace("$qid", mainVideoId); mainTemplate = mainTemplate.replace("$play_now", copyTemp); } else { mainTemplate = mainTemplate.replace("$play_now", ""); } var listId = Utils.findPropertyFromString(loc, "list"); if(listId != 0) { if(mainVideoId != 0) { listId = listId + " " + mainVideoId; } copyTemp = template_playall.replace("$lid", listId); mainTemplate = mainTemplate.replace("$play_all", copyTemp); mainTemplate = mainTemplate.replace("$sep", "|"); } else { mainTemplate = mainTemplate.replace("$sep", ""); mainTemplate = mainTemplate.replace("$play_all", ""); } mainTemplate = mainTemplate.replace("$header", template_header); if(listId != 0 || videoId !=0) { $("#watch7-headline").prepend(mainTemplate); } injectLinks(); } else if(pathName.indexOf("/embed") == 0) { var videoId = pathName.replace("/embed/", ""); console.log("videoId, " + videoId); var copyTemp = template_playnow.replace("$pid", videoId); copyTemp = copyTemp.replace("$qid", videoId); var mainTemplate = template_main; mainTemplate = mainTemplate.replace("$play_all", ""); mainTemplate = mainTemplate.replace("$sep", ""); mainTemplate = mainTemplate.replace("$play_now", copyTemp); mainTemplate = mainTemplate.replace("$header", template_header); $(".html5-info-panel").append(mainTemplate); } else if(pathName == "/share_popup") { var loc = window.location.toString(); var mainVideoId = Utils.findPropertyFromString(loc, "v"); var mainTemplate = template_main; if(mainVideoId != 0) { var copyTemp = template_playnow.replace("$pid", mainVideoId); copyTemp = copyTemp.replace("$qid", mainVideoId); mainTemplate = mainTemplate.replace("$play_now", copyTemp); mainTemplate = mainTemplate.replace("$sep", ""); mainTemplate = mainTemplate.replace("$play_all", ""); mainTemplate = mainTemplate.replace("$header", template_header); $("#page").prepend(mainTemplate); } } else { injectLinks(); } }());
src/js/injectXBMC.js
/** * Content Script * @author: Karthik VJ */ if(ENABLE_CONSOLE == false) { var console = console || {}; console.log = function() {}; } ;(function() { var pathName = window.location.pathname; var template_main = '<div class="xbmc_control">$header $play_all $sep $play_now</div>'; var template_header = 'YouTube to XBMC:'; var template_playnow = '<a href="#" rel="$pid" class="xbmc_playNow" title="Play Now - YouTube to XBMC" onclick="return false;">Play Now</a> | <a href="#" rel="$qid" class="xbmc_queue" title="Add to Queue - YouTube to XBMC" onclick="return false;">[+] Add to Queue</a>'; var template_playnow_sidebar = '<span rel="$pid" class="xbmc_playNow xbmc_link" title="Play Now - YouTube to XBMC" onclick="return false;">Play Now</span> | <span rel="$qid" class="xbmc_queue xbmc_link" title="Add to Queue - YouTube to XBMC" onclick="return false;">[+] Add to Queue</span>'; var template_playall = '<a href="#" rel="$lid" class="xbmc_playlist" title="Play All - YouTube to XBMC" onclick="return false;">Play All</a>'; var template_playall_sidebar = '<span rel="$lid" class="xbmc_playlist xbmc_link" title="Play All - YouTube to XBMC" onclick="return false;">Play All</span>'; var timer; console.log("pathName, " + pathName); var RpcService = function() { this.playVideoOnXBMC = function(vId) { chrome.extension.sendMessage({message: "playVideo", videoId: vId}, function(response) { console.log("video sent! " + response); }); }; this.queueVideoToXBMC = function(vId) { chrome.extension.sendMessage({message: "queueVideo", videoId: vId}, function(response) { console.log("inject script >> video sent! " + response); if(response == ResultData.OK) { toastr.success("Added to Queue!"); } else { toastr.error("Error! Can't Add to Queue!"); } }); }; this.playListOnXBMC = function(listId, videoId) { chrome.extension.sendMessage({message: "playList", listId: listId, videoId: videoId}, function(response) { console.log("list sent! " + response); }); }; }; var Utils = new function() { this.findPropertyFromString = function(str, property) { //console.log("findPropertyFromString, str = " + str); //console.log("findPropertyFromString, property = " + property); property = property + "="; var index = str.indexOf('?'); str = str.substring(index + 1); //console.log("index = " + index); //console.log("str = " + str); var list = str.split('&'); //console.log("list.length, " + list.length); for(var i = 0; i < list.length; i++) { if(list[i].search(property) == 0) { return list[i].replace(property, ""); } } return 0; } }; this.injectLinks = function() { console.log("injectLinks"); // (home / subscription on home page), search page, video manager, user page, user browse video, Popular on YouTube, Popular on youtube right side, video list (on video page), play list page $(".feed-item-content, .yt-lockup2-content, .vm-video-info-container, .yt-tile-visible, .channels-content-item, .lohp-category-shelf-item, .lohp-large-shelf-container, .lohp-medium-shelf-content, .lohp-vertical-shelf-item-content, .video-list-item, .playlist-video-item, .yt-lockup-content, .recent-activity-snippet").each(function(index) { var alreadyAdded = false; $(this).find(".xbmc_control").each(function(xIndex) { alreadyAdded = true; return false; }); if(alreadyAdded) { return; // continue } console.log(index); var videoPathString; var listId; var videoId; // (home / subscription on home page), search page, video manager, (user page / user browse video / Popular on YouTube) $(this).find(".feed-video-title, .yt-uix-tile-link, .vm-video-title-content, .yt-uix-sessionlink").each(function(vIndex) { //console.log("video link, " + vIndex + ", " + $(this).attr("href")); videoPathString = $(this).attr("href"); return false; }); if(videoPathString) { console.log("videoPathString, " + videoPathString); var mainTemplate = template_main; // just a single video videoId = Utils.findPropertyFromString(videoPathString, "v"); if(videoId == 0) { videoId = Utils.findPropertyFromString(videoPathString, "video_id"); } if(videoId == 0) { videoId = Utils.findPropertyFromString(videoPathString, "video_ids"); videoId = decodeURIComponent(videoId); videoId = videoId.split(",")[0]; } var copyTemp = template_playnow; var copyHeader = template_header; if(videoId != 0) { console.log("videoId, " +videoId); if($(this).hasClass("video-list-item") || $(this).hasClass("playlist-video-item")) { copyTemp = template_playnow_sidebar; } if($(this).hasClass("channels-content-item")) { copyHeader = ""; } copyTemp = copyTemp.replace("$pid", videoId); copyTemp = copyTemp.replace("$qid", videoId); mainTemplate = mainTemplate.replace("$play_now", copyTemp); //mainTemplate = mainTemplate.replace("$sep", "|"); //$(this).prepend(copyTemp); } else { //mainTemplate = mainTemplate.replace("$sep", ""); mainTemplate = mainTemplate.replace("$play_now", ""); } // find play list id listId = Utils.findPropertyFromString(videoPathString, "list"); var listTemp = template_playall; if(listId) { if($(this).hasClass("video-list-item") || $(this).hasClass("playlist-video-item")) { listTemp = template_playall_sidebar; } // it is play list if(videoId != 0) { // there is video too listId = listId + " " + videoId; mainTemplate = mainTemplate.replace("$sep", "|"); } else { // just play list mainTemplate = mainTemplate.replace("$sep", ""); } listTemp = listTemp.replace("$lid", listId); mainTemplate = mainTemplate.replace("$play_all", listTemp); //$(this).prepend(copyTemp); } else { mainTemplate = mainTemplate.replace("$sep", ""); mainTemplate = mainTemplate.replace("$play_all", ""); } mainTemplate = mainTemplate.replace("$header", copyHeader); ////// if(listId != 0 || videoId !=0) { $(this).prepend(mainTemplate); } listId = 0; videoId = 0; } }); $("#content").bind('DOMNodeInserted', function(event) { //console.log("DOM updated!"); var element = event.target; //console.log("element, " + element.tagName); clearInterval(timer); timer = setInterval(function(){ clearInterval(timer); $("#content").unbind('DOMNodeInserted'); injectLinks(); }, 2000) }); }; this.initListeners = function() { // click event listeners $(document).on('click', '.xbmc_playlist', function(event) { console.log("playlist, " + $(this).attr("rel")); var listId = $(this).attr("rel"); if(listId) { var listData = listId.split(" "); //console.log(listData[0]); //console.log(listData[1]); rpc.playListOnXBMC(listData[0], listData[1]); event.preventDefault(); } }); $(document).on('click', '.xbmc_playNow', function(event) { console.log("play single video, " + $(this).attr("rel")); rpc.playVideoOnXBMC($(this).attr("rel")); event.preventDefault(); }); $(document).on('click', '.xbmc_queue', function(event) { console.log("queue single video, " + $(this).attr("rel")); rpc.queueVideoToXBMC($(this).attr("rel")); event.preventDefault(); }); } ///////////////////////////// var rpc = new RpcService(); this.initListeners(); //////////////////////////// if(pathName == "/watch") { console.log("window.location, " + window.location); var loc = window.location.toString(); var mainVideoId = Utils.findPropertyFromString(loc, "v"); //alert("mainVideoId, " + mainVideoId); var mainTemplate = template_main; if(mainVideoId != 0) { var copyTemp = template_playnow.replace("$pid", mainVideoId); copyTemp = copyTemp.replace("$qid", mainVideoId); mainTemplate = mainTemplate.replace("$play_now", copyTemp); } else { mainTemplate = mainTemplate.replace("$play_now", ""); } var listId = Utils.findPropertyFromString(loc, "list"); if(listId != 0) { if(mainVideoId != 0) { listId = listId + " " + mainVideoId; } copyTemp = template_playall.replace("$lid", listId); mainTemplate = mainTemplate.replace("$play_all", copyTemp); mainTemplate = mainTemplate.replace("$sep", "|"); } else { mainTemplate = mainTemplate.replace("$sep", ""); mainTemplate = mainTemplate.replace("$play_all", ""); } mainTemplate = mainTemplate.replace("$header", template_header); if(listId != 0 || videoId !=0) { $("#watch7-headline").prepend(mainTemplate); } injectLinks(); } else if(pathName.indexOf("/embed") == 0) { var videoId = pathName.replace("/embed/", ""); console.log("videoId, " + videoId); var copyTemp = template_playnow.replace("$pid", videoId); copyTemp = copyTemp.replace("$qid", videoId); var mainTemplate = template_main; mainTemplate = mainTemplate.replace("$play_all", ""); mainTemplate = mainTemplate.replace("$sep", ""); mainTemplate = mainTemplate.replace("$play_now", copyTemp); mainTemplate = mainTemplate.replace("$header", template_header); $(".html5-info-panel").append(mainTemplate); } else if(pathName == "/share_popup") { var loc = window.location.toString(); var mainVideoId = Utils.findPropertyFromString(loc, "v"); var mainTemplate = template_main; if(mainVideoId != 0) { var copyTemp = template_playnow.replace("$pid", mainVideoId); copyTemp = copyTemp.replace("$qid", mainVideoId); mainTemplate = mainTemplate.replace("$play_now", copyTemp); mainTemplate = mainTemplate.replace("$sep", ""); mainTemplate = mainTemplate.replace("$play_all", ""); mainTemplate = mainTemplate.replace("$header", template_header); $("#page").prepend(mainTemplate); } } else { injectLinks(); } }());
- refactor >> support for "video_ids" url type
src/js/injectXBMC.js
- refactor >> support for "video_ids" url type
<ide><path>rc/js/injectXBMC.js <ide> { <ide> videoId = Utils.findPropertyFromString(videoPathString, "video_ids"); <ide> videoId = decodeURIComponent(videoId); <del> videoId = videoId.split(",")[0]; <add> var vIndex = Utils.findPropertyFromString(videoPathString, "index"); <add> if(vIndex < videoId.length) <add> { <add> videoId = videoId.split(",")[vIndex]; <add> } <add> <ide> } <ide> <ide> var copyTemp = template_playnow;
JavaScript
mit
05bc71d5626e85a1c76d7373e242acb1d1fa5a2e
0
pguth/prependify
var through = require('through2') module.exports = prependify function prependify (b, text) { if (typeof(text) === 'object') { text = text[Object.keys(text)[0]].join(' '); } b.on('bundle', function () { var first = true b.pipeline.get('wrap').push( through.obj(function (buf, _, next) { if (first) { this.push(text) first = false } this.push(buf) next() }) ) }) }
index.js
var through = require('through2') module.exports = prependify function prependify (b, text) { b.on('bundle', function () { var first = true b.pipeline.get('wrap').push( through.obj(function (buf, _, next) { if (first) { this.push(text) first = false } this.push(buf) next() }) ) }) }
allows commandline
index.js
allows commandline
<ide><path>ndex.js <ide> module.exports = prependify <ide> <ide> function prependify (b, text) { <add> if (typeof(text) === 'object') { <add> text = text[Object.keys(text)[0]].join(' '); <add> } <add> <ide> b.on('bundle', function () { <ide> var first = true <ide> b.pipeline.get('wrap').push(
Java
mit
70e923fd65f1b474964dfb3ab88b5df66a23db8c
0
FortressBuilder/JOML,FortressBuilder/JOML,JOML-CI/JOML,roquendm/JOML,JOML-CI/JOML,JOML-CI/JOML,roquendm/JOML
/* * (C) Copyright 2015 Richard Greenlees Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.joml; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.text.DecimalFormat; import java.text.NumberFormat; /** * Contains the definition of a 4x4 Matrix of floats, and associated functions to transform * it. The matrix is column-major to match OpenGL's interpretation, and it looks like this: * <p> * m00 m10 m20 m30<br> * m01 m11 m21 m31<br> * m02 m12 m22 m32<br> * m03 m13 m23 m33<br> * * @author Richard Greenlees * @author Kai Burjack */ public class Matrix4f implements Externalizable { private static final long serialVersionUID = 1L; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} or return * value of {@link #isAabInsideFrustum(float, float, float, float, float, float) isAabInsideFrustum()} or * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * identifying the plane with equation <tt>x=-1</tt> when using the identity matrix. */ public static final int PLANE_NX = 0; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} or return * value of {@link #isAabInsideFrustum(float, float, float, float, float, float) isAabInsideFrustum()} or * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * identifying the plane with equation <tt>x=1</tt> when using the identity matrix. */ public static final int PLANE_PX = 1; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} or return * value of {@link #isAabInsideFrustum(float, float, float, float, float, float) isAabInsideFrustum()} or * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * identifying the plane with equation <tt>y=-1</tt> when using the identity matrix. */ public static final int PLANE_NY= 2; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} or return * value of {@link #isAabInsideFrustum(float, float, float, float, float, float) isAabInsideFrustum()} or * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * identifying the plane with equation <tt>y=1</tt> when using the identity matrix. */ public static final int PLANE_PY = 3; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} or return * value of {@link #isAabInsideFrustum(float, float, float, float, float, float) isAabInsideFrustum()} or * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * identifying the plane with equation <tt>z=-1</tt> when using the identity matrix. */ public static final int PLANE_NZ = 4; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} or return * value of {@link #isAabInsideFrustum(float, float, float, float, float, float) isAabInsideFrustum()} or * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * identifying the plane with equation <tt>z=1</tt> when using the identity matrix. */ public static final int PLANE_PZ = 5; /** * The value in a bitmask for * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * that identifies the plane with equation <tt>x=-1</tt> when using the identity matrix. */ public static final int PLANE_MASK_NX = 1<<PLANE_NX; /** * The value in a bitmask for * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * that identifies the plane with equation <tt>x=1</tt> when using the identity matrix. */ public static final int PLANE_MASK_PX = 1<<PLANE_PX; /** * The value in a bitmask for * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * that identifies the plane with equation <tt>y=-1</tt> when using the identity matrix. */ public static final int PLANE_MASK_NY = 1<<PLANE_NY; /** * The value in a bitmask for * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * that identifies the plane with equation <tt>y=1</tt> when using the identity matrix. */ public static final int PLANE_MASK_PY = 1<<PLANE_PY; /** * The value in a bitmask for * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * that identifies the plane with equation <tt>z=-1</tt> when using the identity matrix. */ public static final int PLANE_MASK_NZ = 1<<PLANE_NZ; /** * The value in a bitmask for * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * that identifies the plane with equation <tt>z=1</tt> when using the identity matrix. */ public static final int PLANE_MASK_PZ = 1<<PLANE_PZ; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(-1, -1, -1)</tt> when using the identity matrix. */ public static final int CORNER_NXNYNZ = 0; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(1, -1, -1)</tt> when using the identity matrix. */ public static final int CORNER_PXNYNZ = 1; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(1, 1, -1)</tt> when using the identity matrix. */ public static final int CORNER_PXPYNZ = 2; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(-1, 1, -1)</tt> when using the identity matrix. */ public static final int CORNER_NXPYNZ = 3; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(1, -1, 1)</tt> when using the identity matrix. */ public static final int CORNER_PXNYPZ = 4; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(-1, -1, 1)</tt> when using the identity matrix. */ public static final int CORNER_NXNYPZ = 5; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(-1, 1, 1)</tt> when using the identity matrix. */ public static final int CORNER_NXPYPZ = 6; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(1, 1, 1)</tt> when using the identity matrix. */ public static final int CORNER_PXPYPZ = 7; public float m00, m10, m20, m30; public float m01, m11, m21, m31; public float m02, m12, m22, m32; public float m03, m13, m23, m33; /** * Create a new {@link Matrix4f} and set it to {@link #identity() identity}. */ public Matrix4f() { super(); identity(); } /** * Create a new {@link Matrix4f} by setting its uppper left 3x3 submatrix to the values of the given {@link Matrix3f} * and the rest to identity. * * @param mat * the {@link Matrix3f} */ public Matrix4f(Matrix3f mat) { m00 = mat.m00; m01 = mat.m01; m02 = mat.m02; m10 = mat.m10; m11 = mat.m11; m12 = mat.m12; m20 = mat.m20; m21 = mat.m21; m22 = mat.m22; m33 = 1.0f; } /** * Create a new {@link Matrix4f} and make it a copy of the given matrix. * * @param mat * the {@link Matrix4f} to copy the values from */ public Matrix4f(Matrix4f mat) { m00 = mat.m00; m01 = mat.m01; m02 = mat.m02; m03 = mat.m03; m10 = mat.m10; m11 = mat.m11; m12 = mat.m12; m13 = mat.m13; m20 = mat.m20; m21 = mat.m21; m22 = mat.m22; m23 = mat.m23; m30 = mat.m30; m31 = mat.m31; m32 = mat.m32; m33 = mat.m33; } /** * Create a new 4x4 matrix using the supplied float values. * * @param m00 * the value of m00 * @param m01 * the value of m01 * @param m02 * the value of m02 * @param m03 * the value of m03 * @param m10 * the value of m10 * @param m11 * the value of m11 * @param m12 * the value of m12 * @param m13 * the value of m13 * @param m20 * the value of m20 * @param m21 * the value of m21 * @param m22 * the value of m22 * @param m23 * the value of m23 * @param m30 * the value of m30 * @param m31 * the value of m31 * @param m32 * the value of m32 * @param m33 * the value of m33 */ public Matrix4f(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13; this.m20 = m20; this.m21 = m21; this.m22 = m22; this.m23 = m23; this.m30 = m30; this.m31 = m31; this.m32 = m32; this.m33 = m33; } /** * Create a new {@link Matrix4f} by reading its 16 float components from the given {@link FloatBuffer} * at the buffer's current position. * <p> * That FloatBuffer is expected to hold the values in column-major order. * <p> * The buffer's position will not be changed by this method. * * @param buffer * the {@link FloatBuffer} to read the matrix values from */ public Matrix4f(FloatBuffer buffer) { int pos = buffer.position(); m00 = buffer.get(pos); m01 = buffer.get(pos+1); m02 = buffer.get(pos+2); m03 = buffer.get(pos+3); m10 = buffer.get(pos+4); m11 = buffer.get(pos+5); m12 = buffer.get(pos+6); m13 = buffer.get(pos+7); m20 = buffer.get(pos+8); m21 = buffer.get(pos+9); m22 = buffer.get(pos+10); m23 = buffer.get(pos+11); m30 = buffer.get(pos+12); m31 = buffer.get(pos+13); m32 = buffer.get(pos+14); m33 = buffer.get(pos+15); } /** * Reset this matrix to the identity. * * @return this */ public Matrix4f identity() { m00 = 1.0f; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 1.0f; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = 1.0f; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Store the values of the given matrix <code>m</code> into <code>this</code> matrix. * * @see #Matrix4f(Matrix4f) * @see #get(Matrix4f) * * @param m * the matrix to copy the values from * @return this */ public Matrix4f set(Matrix4f m) { m00 = m.m00; m01 = m.m01; m02 = m.m02; m03 = m.m03; m10 = m.m10; m11 = m.m11; m12 = m.m12; m13 = m.m13; m20 = m.m20; m21 = m.m21; m22 = m.m22; m23 = m.m23; m30 = m.m30; m31 = m.m31; m32 = m.m32; m33 = m.m33; return this; } /** * Set the upper left 3x3 submatrix of this {@link Matrix4f} to the given {@link Matrix3f} * and the rest to identity. * * @see #Matrix4f(Matrix3f) * * @param mat * the {@link Matrix3f} * @return this */ public Matrix4f set(Matrix3f mat) { m00 = mat.m00; m01 = mat.m01; m02 = mat.m02; m03 = 0.0f; m10 = mat.m10; m11 = mat.m11; m12 = mat.m12; m13 = 0.0f; m20 = mat.m20; m21 = mat.m21; m22 = mat.m22; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be equivalent to the rotation specified by the given {@link AxisAngle4f}. * * @param axisAngle * the {@link AxisAngle4f} * @return this */ public Matrix4f set(AxisAngle4f axisAngle) { float x = axisAngle.x; float y = axisAngle.y; float z = axisAngle.z; double angle = axisAngle.angle; double n = Math.sqrt(x*x + y*y + z*z); n = 1/n; x *= n; y *= n; z *= n; double c = Math.cos(angle); double s = Math.sin(angle); double omc = 1.0 - c; m00 = (float)(c + x*x*omc); m11 = (float)(c + y*y*omc); m22 = (float)(c + z*z*omc); double tmp1 = x*y*omc; double tmp2 = z*s; m10 = (float)(tmp1 - tmp2); m01 = (float)(tmp1 + tmp2); tmp1 = x*z*omc; tmp2 = y*s; m20 = (float)(tmp1 + tmp2); m02 = (float)(tmp1 - tmp2); tmp1 = y*z*omc; tmp2 = x*s; m21 = (float)(tmp1 - tmp2); m12 = (float)(tmp1 + tmp2); m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be equivalent to the rotation specified by the given {@link Quaternionf}. * * @see Quaternionf#get(Matrix4f) * * @param q * the {@link Quaternionf} * @return this */ public Matrix4f set(Quaternionf q) { q.get(this); return this; } /** * Multiply this matrix by the supplied <code>right</code> matrix and store the result in <code>this</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the <code>right</code> matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * transformation of the right matrix will be applied first! * * @param right * the right operand of the matrix multiplication * @return this */ public Matrix4f mul(Matrix4f right) { return mul(right, this); } /** * Multiply this matrix by the supplied <code>right</code> matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the <code>right</code> matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * transformation of the right matrix will be applied first! * * @param right * the right operand of the matrix multiplication * @param dest * the destination matrix, which will hold the result * @return this */ public Matrix4f mul(Matrix4f right, Matrix4f dest) { if (this != dest && right != dest) { dest.m00 = m00 * right.m00 + m10 * right.m01 + m20 * right.m02 + m30 * right.m03; dest.m01 = m01 * right.m00 + m11 * right.m01 + m21 * right.m02 + m31 * right.m03; dest.m02 = m02 * right.m00 + m12 * right.m01 + m22 * right.m02 + m32 * right.m03; dest.m03 = m03 * right.m00 + m13 * right.m01 + m23 * right.m02 + m33 * right.m03; dest.m10 = m00 * right.m10 + m10 * right.m11 + m20 * right.m12 + m30 * right.m13; dest.m11 = m01 * right.m10 + m11 * right.m11 + m21 * right.m12 + m31 * right.m13; dest.m12 = m02 * right.m10 + m12 * right.m11 + m22 * right.m12 + m32 * right.m13; dest.m13 = m03 * right.m10 + m13 * right.m11 + m23 * right.m12 + m33 * right.m13; dest.m20 = m00 * right.m20 + m10 * right.m21 + m20 * right.m22 + m30 * right.m23; dest.m21 = m01 * right.m20 + m11 * right.m21 + m21 * right.m22 + m31 * right.m23; dest.m22 = m02 * right.m20 + m12 * right.m21 + m22 * right.m22 + m32 * right.m23; dest.m23 = m03 * right.m20 + m13 * right.m21 + m23 * right.m22 + m33 * right.m23; dest.m30 = m00 * right.m30 + m10 * right.m31 + m20 * right.m32 + m30 * right.m33; dest.m31 = m01 * right.m30 + m11 * right.m31 + m21 * right.m32 + m31 * right.m33; dest.m32 = m02 * right.m30 + m12 * right.m31 + m22 * right.m32 + m32 * right.m33; dest.m33 = m03 * right.m30 + m13 * right.m31 + m23 * right.m32 + m33 * right.m33; } else { dest.set(m00 * right.m00 + m10 * right.m01 + m20 * right.m02 + m30 * right.m03, m01 * right.m00 + m11 * right.m01 + m21 * right.m02 + m31 * right.m03, m02 * right.m00 + m12 * right.m01 + m22 * right.m02 + m32 * right.m03, m03 * right.m00 + m13 * right.m01 + m23 * right.m02 + m33 * right.m03, m00 * right.m10 + m10 * right.m11 + m20 * right.m12 + m30 * right.m13, m01 * right.m10 + m11 * right.m11 + m21 * right.m12 + m31 * right.m13, m02 * right.m10 + m12 * right.m11 + m22 * right.m12 + m32 * right.m13, m03 * right.m10 + m13 * right.m11 + m23 * right.m12 + m33 * right.m13, m00 * right.m20 + m10 * right.m21 + m20 * right.m22 + m30 * right.m23, m01 * right.m20 + m11 * right.m21 + m21 * right.m22 + m31 * right.m23, m02 * right.m20 + m12 * right.m21 + m22 * right.m22 + m32 * right.m23, m03 * right.m20 + m13 * right.m21 + m23 * right.m22 + m33 * right.m23, m00 * right.m30 + m10 * right.m31 + m20 * right.m32 + m30 * right.m33, m01 * right.m30 + m11 * right.m31 + m21 * right.m32 + m31 * right.m33, m02 * right.m30 + m12 * right.m31 + m22 * right.m32 + m32 * right.m33, m03 * right.m30 + m13 * right.m31 + m23 * right.m32 + m33 * right.m33); } return this; } /** * Multiply this matrix by the top 4x3 submatrix of the supplied <code>right</code> matrix and store the result in <code>this</code>. * This method assumes that the last row of <code>right</code> is equal to <tt>(0, 0, 0, 1)</tt>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the <code>right</code> matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * transformation of the right matrix will be applied first! * * @param right * the right operand of the matrix multiplication (the last row is assumed to be <tt>(0, 0, 0, 1)</tt>) * @return this */ public Matrix4f mul4x3(Matrix4f right) { return mul4x3(right, this); } /** * Multiply this matrix by the top 4x3 submatrix of the supplied <code>right</code> matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the <code>right</code> matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * transformation of the right matrix will be applied first! * * @param right * the right operand of the matrix multiplication (the last row is assumed to be <tt>(0, 0, 0, 1)</tt>) * @param dest * the destination matrix, which will hold the result * @return this */ public Matrix4f mul4x3(Matrix4f right, Matrix4f dest) { if (this != dest && right != dest) { dest.m00 = m00 * right.m00 + m10 * right.m01 + m20 * right.m02; dest.m01 = m01 * right.m00 + m11 * right.m01 + m21 * right.m02; dest.m02 = m02 * right.m00 + m12 * right.m01 + m22 * right.m02; dest.m03 = m03 * right.m00 + m13 * right.m01 + m23 * right.m02; dest.m10 = m00 * right.m10 + m10 * right.m11 + m20 * right.m12; dest.m11 = m01 * right.m10 + m11 * right.m11 + m21 * right.m12; dest.m12 = m02 * right.m10 + m12 * right.m11 + m22 * right.m12; dest.m13 = m03 * right.m10 + m13 * right.m11 + m23 * right.m12; dest.m20 = m00 * right.m20 + m10 * right.m21 + m20 * right.m22; dest.m21 = m01 * right.m20 + m11 * right.m21 + m21 * right.m22; dest.m22 = m02 * right.m20 + m12 * right.m21 + m22 * right.m22; dest.m23 = m03 * right.m20 + m13 * right.m21 + m23 * right.m22; dest.m30 = m00 * right.m30 + m10 * right.m31 + m20 * right.m32 + m30; dest.m31 = m01 * right.m30 + m11 * right.m31 + m21 * right.m32 + m31; dest.m32 = m02 * right.m30 + m12 * right.m31 + m22 * right.m32 + m32; dest.m33 = m03 * right.m30 + m13 * right.m31 + m23 * right.m32 + m33; } else { dest.set(m00 * right.m00 + m10 * right.m01 + m20 * right.m02, m01 * right.m00 + m11 * right.m01 + m21 * right.m02, m02 * right.m00 + m12 * right.m01 + m22 * right.m02, m03 * right.m00 + m13 * right.m01 + m23 * right.m02, m00 * right.m10 + m10 * right.m11 + m20 * right.m12, m01 * right.m10 + m11 * right.m11 + m21 * right.m12, m02 * right.m10 + m12 * right.m11 + m22 * right.m12, m03 * right.m10 + m13 * right.m11 + m23 * right.m12, m00 * right.m20 + m10 * right.m21 + m20 * right.m22, m01 * right.m20 + m11 * right.m21 + m21 * right.m22, m02 * right.m20 + m12 * right.m21 + m22 * right.m22, m03 * right.m20 + m13 * right.m21 + m23 * right.m22, m00 * right.m30 + m10 * right.m31 + m20 * right.m32 + m30, m01 * right.m30 + m11 * right.m31 + m21 * right.m32 + m31, m02 * right.m30 + m12 * right.m31 + m22 * right.m32 + m32, m03 * right.m30 + m13 * right.m31 + m23 * right.m32 + m33); } return this; } /** * Set the values within this matrix to the supplied float values. The matrix will look like this:<br><br> * * m00, m10, m20, m30<br> * m01, m11, m21, m31<br> * m02, m12, m22, m32<br> * m03, m13, m23, m33 * * @param m00 * the new value of m00 * @param m01 * the new value of m01 * @param m02 * the new value of m02 * @param m03 * the new value of m03 * @param m10 * the new value of m10 * @param m11 * the new value of m11 * @param m12 * the new value of m12 * @param m13 * the new value of m13 * @param m20 * the new value of m20 * @param m21 * the new value of m21 * @param m22 * the new value of m22 * @param m23 * the new value of m23 * @param m30 * the new value of m30 * @param m31 * the new value of m31 * @param m32 * the new value of m32 * @param m33 * the new value of m33 * @return this */ public Matrix4f set(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13; this.m20 = m20; this.m21 = m21; this.m22 = m22; this.m23 = m23; this.m30 = m30; this.m31 = m31; this.m32 = m32; this.m33 = m33; return this; } /** * Set the values in the matrix using a float array that contains the matrix elements in column-major order. * <p> * The results will look like this:<br><br> * * 0, 4, 8, 12<br> * 1, 5, 9, 13<br> * 2, 6, 10, 14<br> * 3, 7, 11, 15<br> * * @see #set(float[]) * * @param m * the array to read the matrix values from * @param off * the offset into the array * @return this */ public Matrix4f set(float m[], int off) { m00 = m[off+0]; m01 = m[off+1]; m02 = m[off+2]; m03 = m[off+3]; m10 = m[off+4]; m11 = m[off+5]; m12 = m[off+6]; m13 = m[off+7]; m20 = m[off+8]; m21 = m[off+9]; m22 = m[off+10]; m23 = m[off+11]; m30 = m[off+12]; m31 = m[off+13]; m32 = m[off+14]; m33 = m[off+15]; return this; } /** * Set the values in the matrix using a float array that contains the matrix elements in column-major order. * <p> * The results will look like this:<br><br> * * 0, 4, 8, 12<br> * 1, 5, 9, 13<br> * 2, 6, 10, 14<br> * 3, 7, 11, 15<br> * * @see #set(float[], int) * * @param m * the array to read the matrix values from * @return this */ public Matrix4f set(float m[]) { return set(m, 0); } /** * Set the values of this matrix by reading 16 float values from the given {@link FloatBuffer} in column-major order, * starting at its current position. * <p> * The FloatBuffer is expected to contain the values in column-major order. * <p> * The position of the FloatBuffer will not be changed by this method. * * @param buffer * the FloatBuffer to read the matrix values from in column-major order * @return this */ public Matrix4f set(FloatBuffer buffer) { int pos = buffer.position(); m00 = buffer.get(pos); m01 = buffer.get(pos+1); m02 = buffer.get(pos+2); m03 = buffer.get(pos+3); m10 = buffer.get(pos+4); m11 = buffer.get(pos+5); m12 = buffer.get(pos+6); m13 = buffer.get(pos+7); m20 = buffer.get(pos+8); m21 = buffer.get(pos+9); m22 = buffer.get(pos+10); m23 = buffer.get(pos+11); m30 = buffer.get(pos+12); m31 = buffer.get(pos+13); m32 = buffer.get(pos+14); m33 = buffer.get(pos+15); return this; } /** * Set the values of this matrix by reading 16 float values from the given {@link ByteBuffer} in column-major order, * starting at its current position. * <p> * The ByteBuffer is expected to contain the values in column-major order. * <p> * The position of the ByteBuffer will not be changed by this method. * * @param buffer * the ByteBuffer to read the matrix values from in column-major order * @return this */ public Matrix4f set(ByteBuffer buffer) { int pos = buffer.position(); m00 = buffer.getFloat(pos); m01 = buffer.getFloat(pos+4); m02 = buffer.getFloat(pos+8); m03 = buffer.getFloat(pos+12); m10 = buffer.getFloat(pos+16); m11 = buffer.getFloat(pos+20); m12 = buffer.getFloat(pos+24); m13 = buffer.getFloat(pos+28); m20 = buffer.getFloat(pos+32); m21 = buffer.getFloat(pos+36); m22 = buffer.getFloat(pos+40); m23 = buffer.getFloat(pos+44); m30 = buffer.getFloat(pos+48); m31 = buffer.getFloat(pos+52); m32 = buffer.getFloat(pos+56); m33 = buffer.getFloat(pos+60); return this; } /** * Return the determinant of this matrix. * * @return the determinant */ public float determinant() { return (m00 * m11 - m01 * m10) * (m22 * m33 - m23 * m32) - (m00 * m12 - m02 * m10) * (m21 * m33 - m23 * m31) + (m00 * m13 - m03 * m10) * (m21 * m32 - m22 * m31) + (m01 * m12 - m02 * m11) * (m20 * m33 - m23 * m30) - (m01 * m13 - m03 * m11) * (m20 * m32 - m22 * m30) + (m02 * m13 - m03 * m12) * (m20 * m31 - m21 * m30); } /** * Return the determinant of the top-left 3x3 submatrix of this matrix. * * @return the determinant */ public float determinant3x3() { return m00 * m11 * m22 + m10 * m21 * m02 + m20 * m01 * m12 - m20 * m11 * m02 - m00 * m21 * m12 - m10 * m01 * m22; } /** * Invert this matrix and write the result into <code>dest</code>. * * @param dest * will hold the result * @return this */ public Matrix4f invert(Matrix4f dest) { float s = determinant(); if (s == 0.0f) { dest.set(this); return this; } s = 1.0f / s; if (this != dest) { dest.m00 = (m11 * (m22 * m33 - m23 * m32) + m12 * (m23 * m31 - m21 * m33) + m13 * (m21 * m32 - m22 * m31)) * s; dest.m01 = (m21 * (m02 * m33 - m03 * m32) + m22 * (m03 * m31 - m01 * m33) + m23 * (m01 * m32 - m02 * m31)) * s; dest.m02 = (m31 * (m02 * m13 - m03 * m12) + m32 * (m03 * m11 - m01 * m13) + m33 * (m01 * m12 - m02 * m11)) * s; dest.m03 = (m01 * (m13 * m22 - m12 * m23) + m02 * (m11 * m23 - m13 * m21) + m03 * (m12 * m21 - m11 * m22)) * s; dest.m10 = (m12 * (m20 * m33 - m23 * m30) + m13 * (m22 * m30 - m20 * m32) + m10 * (m23 * m32 - m22 * m33)) * s; dest.m11 = (m22 * (m00 * m33 - m03 * m30) + m23 * (m02 * m30 - m00 * m32) + m20 * (m03 * m32 - m02 * m33)) * s; dest.m12 = (m32 * (m00 * m13 - m03 * m10) + m33 * (m02 * m10 - m00 * m12) + m30 * (m03 * m12 - m02 * m13)) * s; dest.m13 = (m02 * (m13 * m20 - m10 * m23) + m03 * (m10 * m22 - m12 * m20) + m00 * (m12 * m23 - m13 * m22)) * s; dest.m20 = (m13 * (m20 * m31 - m21 * m30) + m10 * (m21 * m33 - m23 * m31) + m11 * (m23 * m30 - m20 * m33)) * s; dest.m21 = (m23 * (m00 * m31 - m01 * m30) + m20 * (m01 * m33 - m03 * m31) + m21 * (m03 * m30 - m00 * m33)) * s; dest.m22 = (m33 * (m00 * m11 - m01 * m10) + m30 * (m01 * m13 - m03 * m11) + m31 * (m03 * m10 - m00 * m13)) * s; dest.m23 = (m03 * (m11 * m20 - m10 * m21) + m00 * (m13 * m21 - m11 * m23) + m01 * (m10 * m23 - m13 * m20)) * s; dest.m30 = (m10 * (m22 * m31 - m21 * m32) + m11 * (m20 * m32 - m22 * m30) + m12 * (m21 * m30 - m20 * m31)) * s; dest.m31 = (m20 * (m02 * m31 - m01 * m32) + m21 * (m00 * m32 - m02 * m30) + m22 * (m01 * m30 - m00 * m31)) * s; dest.m32 = (m30 * (m02 * m11 - m01 * m12) + m31 * (m00 * m12 - m02 * m10) + m32 * (m01 * m10 - m00 * m11)) * s; dest.m33 = (m00 * (m11 * m22 - m12 * m21) + m01 * (m12 * m20 - m10 * m22) + m02 * (m10 * m21 - m11 * m20)) * s; } else { dest.set((m11 * (m22 * m33 - m23 * m32) + m12 * (m23 * m31 - m21 * m33) + m13 * (m21 * m32 - m22 * m31)) * s, (m21 * (m02 * m33 - m03 * m32) + m22 * (m03 * m31 - m01 * m33) + m23 * (m01 * m32 - m02 * m31)) * s, (m31 * (m02 * m13 - m03 * m12) + m32 * (m03 * m11 - m01 * m13) + m33 * (m01 * m12 - m02 * m11)) * s, (m01 * (m13 * m22 - m12 * m23) + m02 * (m11 * m23 - m13 * m21) + m03 * (m12 * m21 - m11 * m22)) * s, (m12 * (m20 * m33 - m23 * m30) + m13 * (m22 * m30 - m20 * m32) + m10 * (m23 * m32 - m22 * m33)) * s, (m22 * (m00 * m33 - m03 * m30) + m23 * (m02 * m30 - m00 * m32) + m20 * (m03 * m32 - m02 * m33)) * s, (m32 * (m00 * m13 - m03 * m10) + m33 * (m02 * m10 - m00 * m12) + m30 * (m03 * m12 - m02 * m13)) * s, (m02 * (m13 * m20 - m10 * m23) + m03 * (m10 * m22 - m12 * m20) + m00 * (m12 * m23 - m13 * m22)) * s, (m13 * (m20 * m31 - m21 * m30) + m10 * (m21 * m33 - m23 * m31) + m11 * (m23 * m30 - m20 * m33)) * s, (m23 * (m00 * m31 - m01 * m30) + m20 * (m01 * m33 - m03 * m31) + m21 * (m03 * m30 - m00 * m33)) * s, (m33 * (m00 * m11 - m01 * m10) + m30 * (m01 * m13 - m03 * m11) + m31 * (m03 * m10 - m00 * m13)) * s, (m03 * (m11 * m20 - m10 * m21) + m00 * (m13 * m21 - m11 * m23) + m01 * (m10 * m23 - m13 * m20)) * s, (m10 * (m22 * m31 - m21 * m32) + m11 * (m20 * m32 - m22 * m30) + m12 * (m21 * m30 - m20 * m31)) * s, (m20 * (m02 * m31 - m01 * m32) + m21 * (m00 * m32 - m02 * m30) + m22 * (m01 * m30 - m00 * m31)) * s, (m30 * (m02 * m11 - m01 * m12) + m31 * (m00 * m12 - m02 * m10) + m32 * (m01 * m10 - m00 * m11)) * s, (m00 * (m11 * m22 - m12 * m21) + m01 * (m12 * m20 - m10 * m22) + m02 * (m10 * m21 - m11 * m20)) * s ); } return this; } /** * Invert this matrix. * * @return this */ public Matrix4f invert() { return invert(this); } /** * Transpose this matrix and store the result in <code>dest</code>. * * @param dest * will hold the result * @return this */ public Matrix4f transpose(Matrix4f dest) { if (this != dest) { dest.m00 = m00; dest.m01 = m10; dest.m02 = m20; dest.m03 = m30; dest.m10 = m01; dest.m11 = m11; dest.m12 = m21; dest.m13 = m31; dest.m20 = m02; dest.m21 = m12; dest.m22 = m22; dest.m23 = m32; dest.m30 = m03; dest.m31 = m13; dest.m32 = m23; dest.m33 = m33; } else { dest.set(m00, m10, m20, m30, m01, m11, m21, m31, m02, m12, m22, m32, m03, m13, m23, m33); } return this; } /** * Transpose only the top-left 3x3 submatrix of this matrix and set the rest of the matrix elements to identity. * * @return this */ public Matrix4f transpose3x3() { return transpose3x3(this); } /** * Transpose only the top-left 3x3 submatrix of this matrix and store the result in <code>dest</code>. * <p> * All other matrix elements of <code>dest</code> will be set to identity. * * @param dest * will hold the result * @return this */ public Matrix4f transpose3x3(Matrix4f dest) { if (this != dest) { dest.m00 = m00; dest.m01 = m10; dest.m02 = m20; dest.m03 = 0.0f; dest.m10 = m01; dest.m11 = m11; dest.m12 = m21; dest.m13 = 0.0f; dest.m20 = m02; dest.m21 = m12; dest.m22 = m22; dest.m23 = 0.0f; dest.m30 = 0.0f; dest.m31 = 0.0f; dest.m32 = 0.0f; dest.m33 = 1.0f; } else { dest.set(m00, m10, m20, 0.0f, m01, m11, m21, 0.0f, m02, m12, m22, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } return this; } /** * Transpose only the top-left 3x3 submatrix of this matrix and store the result in <code>dest</code>. * * @param dest * will hold the result * @return this */ public Matrix4f transpose3x3(Matrix3f dest) { dest.m00 = m00; dest.m01 = m10; dest.m02 = m20; dest.m10 = m01; dest.m11 = m11; dest.m12 = m21; dest.m20 = m02; dest.m21 = m12; dest.m22 = m22; return this; } /** * Transpose this matrix. * * @return this */ public Matrix4f transpose() { return transpose(this); } /** * Set this matrix to be a simple translation matrix. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional translation. * <p> * If you want to post-multiply a translation transformation directly to a * matrix, you can use {@link #translate(float, float, float) translate()} instead. * * @see #translate(float, float, float) * * @param x * the offset to translate in x * @param y * the offset to translate in y * @param z * the offset to translate in z * @return this */ public Matrix4f translation(float x, float y, float z) { m00 = 1.0f; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 1.0f; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = 1.0f; m23 = 0.0f; m30 = x; m31 = y; m32 = z; m33 = 1.0f; return this; } /** * Set this matrix to be a simple translation matrix. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional translation. * <p> * If you want to post-multiply a translation transformation directly to a * matrix, you can use {@link #translate(Vector3f) translate()} instead. * * @see #translate(float, float, float) * * @param offset * the offsets in x, y and z to translate * @return this */ public Matrix4f translation(Vector3f offset) { return translation(offset.x, offset.y, offset.z); } /** * Set only the translation components of this matrix <tt>(m30, m31, m32)</tt> to the given values <tt>(x, y, z)</tt>. * <p> * Note that this will only work properly for orthogonal matrices (without any perspective). * <p> * To build a translation matrix instead, use {@link #translation(float, float, float)}. * To apply a translation to another matrix, use {@link #translate(float, float, float)}. * * @see #translation(float, float, float) * @see #translate(float, float, float) * * @param x * the offset to translate in x * @param y * the offset to translate in y * @param z * the offset to translate in z * @return this */ public Matrix4f setTranslation(float x, float y, float z) { m30 = x; m31 = y; m32 = z; return this; } /** * Set only the translation components of this matrix <tt>(m30, m31, m32)</tt> to the values <tt>(xyz.x, xyz.y, xyz.z)</tt>. * <p> * Note that this will only work properly for orthogonal matrices (without any perspective). * <p> * To build a translation matrix instead, use {@link #translation(Vector3f)}. * To apply a translation to another matrix, use {@link #translate(Vector3f)}. * * @see #translation(Vector3f) * @see #translate(Vector3f) * * @param xyz * the units to translate in <tt>(x, y, z)</tt> * @return this */ public Matrix4f setTranslation(Vector3f xyz) { m30 = xyz.x; m31 = xyz.y; m32 = xyz.z; return this; } /** * Get only the translation components of this matrix <tt>(m30, m31, m32)</tt> and store them in the given vector <code>xyz</code>. * * @param xyz * will hold the translation components of this matrix * @return this */ public Matrix4f getTranslation(Vector3f xyz) { xyz.x = m30; xyz.y = m31; xyz.z = m32; return this; } /** * Return a string representation of this matrix. * <p> * This method creates a new {@link DecimalFormat} on every invocation with the format string "<tt> 0.000E0; -</tt>". * * @return the string representation */ public String toString() { DecimalFormat formatter = new DecimalFormat(" 0.000E0; -"); //$NON-NLS-1$ return toString(formatter).replaceAll("E(\\d+)", "E+$1"); //$NON-NLS-1$ //$NON-NLS-2$ } /** * Return a string representation of this matrix by formatting the matrix elements with the given {@link NumberFormat}. * * @param formatter * the {@link NumberFormat} used to format the matrix values with * @return the string representation */ public String toString(NumberFormat formatter) { return formatter.format(m00) + formatter.format(m10) + formatter.format(m20) + formatter.format(m30) + "\n" //$NON-NLS-1$ + formatter.format(m01) + formatter.format(m11) + formatter.format(m21) + formatter.format(m31) + "\n" //$NON-NLS-1$ + formatter.format(m02) + formatter.format(m12) + formatter.format(m22) + formatter.format(m32) + "\n" //$NON-NLS-1$ + formatter.format(m03) + formatter.format(m13) + formatter.format(m23) + formatter.format(m33) + "\n"; //$NON-NLS-1$ } /** * Get the current values of <code>this</code> matrix and store them into * <code>dest</code>. * <p> * This is the reverse method of {@link #set(Matrix4f)} and allows to obtain * intermediate calculation results when chaining multiple transformations. * * @see #set(Matrix4f) * * @param dest * the destination matrix * @return this */ public Matrix4f get(Matrix4f dest) { dest.set(this); return this; } /** * Get the rotational component of <code>this</code> matrix and store the represented rotation * into the given {@link AxisAngle4f}. * * @see AxisAngle4f#set(Matrix4f) * * @param dest * the destination {@link AxisAngle4f} * @return this */ public Matrix4f get(AxisAngle4f dest) { dest.set(this); return this; } /** * Get the rotational component of <code>this</code> matrix and store the represented rotation * into the given {@link Quaternionf}. * * @see Quaternionf#set(Matrix4f) * * @param dest * the destination {@link Quaternionf} * @return this */ public Matrix4f get(Quaternionf dest) { dest.set(this); return this; } /** * Get the rotational component of <code>this</code> matrix and store the represented rotation * into the given {@link Quaterniond}. * * @see Quaterniond#set(Matrix4f) * * @param dest * the destination {@link Quaterniond} * @return this */ public Matrix4f get(Quaterniond dest) { dest.set(this); return this; } /** * Store this matrix in column-major order into the supplied {@link FloatBuffer} at the current * buffer {@link FloatBuffer#position() position}. * <p> * This method will not increment the position of the given FloatBuffer. * <p> * If you want to specify the offset into the FloatBuffer at which * the matrix is stored, you can use {@link #get(int, FloatBuffer)}, taking * the absolute position as parameter. * * @see #get(int, FloatBuffer) * * @param buffer * will receive the values of this matrix in column-major order at its current position * @return this */ public Matrix4f get(FloatBuffer buffer) { return get(buffer.position(), buffer); } /** * Store this matrix in column-major order into the supplied {@link FloatBuffer} starting at the specified * absolute buffer position/index. * <p> * This method will not increment the position of the given FloatBuffer. * * @param index * the absolute position into the FloatBuffer * @param buffer * will receive the values of this matrix in column-major order * @return this */ public Matrix4f get(int index, FloatBuffer buffer) { buffer.put(index, m00); buffer.put(index+1, m01); buffer.put(index+2, m02); buffer.put(index+3, m03); buffer.put(index+4, m10); buffer.put(index+5, m11); buffer.put(index+6, m12); buffer.put(index+7, m13); buffer.put(index+8, m20); buffer.put(index+9, m21); buffer.put(index+10, m22); buffer.put(index+11, m23); buffer.put(index+12, m30); buffer.put(index+13, m31); buffer.put(index+14, m32); buffer.put(index+15, m33); return this; } /** * Store this matrix in column-major order into the supplied {@link ByteBuffer} at the current * buffer {@link ByteBuffer#position() position}. * <p> * This method will not increment the position of the given ByteBuffer. * <p> * If you want to specify the offset into the ByteBuffer at which * the matrix is stored, you can use {@link #get(int, ByteBuffer)}, taking * the absolute position as parameter. * * @see #get(int, ByteBuffer) * * @param buffer * will receive the values of this matrix in column-major order at its current position * @return this */ public Matrix4f get(ByteBuffer buffer) { return get(buffer.position(), buffer); } /** * Store this matrix in column-major order into the supplied {@link ByteBuffer} starting at the specified * absolute buffer position/index. * <p> * This method will not increment the position of the given ByteBuffer. * * @param index * the absolute position into the ByteBuffer * @param buffer * will receive the values of this matrix in column-major order * @return this */ public Matrix4f get(int index, ByteBuffer buffer) { buffer.putFloat(index, m00); buffer.putFloat(index+4, m01); buffer.putFloat(index+8, m02); buffer.putFloat(index+12, m03); buffer.putFloat(index+16, m10); buffer.putFloat(index+20, m11); buffer.putFloat(index+24, m12); buffer.putFloat(index+28, m13); buffer.putFloat(index+32, m20); buffer.putFloat(index+36, m21); buffer.putFloat(index+40, m22); buffer.putFloat(index+44, m23); buffer.putFloat(index+48, m30); buffer.putFloat(index+52, m31); buffer.putFloat(index+56, m32); buffer.putFloat(index+60, m33); return this; } /** * Store the transpose of this matrix in column-major order into the supplied {@link FloatBuffer} at the current * buffer {@link FloatBuffer#position() position}. * <p> * This method will not increment the position of the given FloatBuffer. * <p> * If you want to specify the offset into the FloatBuffer at which * the matrix is stored, you can use {@link #getTransposed(int, FloatBuffer)}, taking * the absolute position as parameter. * * @see #getTransposed(int, FloatBuffer) * * @param buffer * will receive the values of this matrix in column-major order at its current position * @return this */ public Matrix4f getTransposed(FloatBuffer buffer) { return getTransposed(buffer.position(), buffer); } /** * Store the transpose of this matrix in column-major order into the supplied {@link FloatBuffer} starting at the specified * absolute buffer position/index. * <p> * This method will not increment the position of the given FloatBuffer. * * @param index * the absolute position into the FloatBuffer * @param buffer * will receive the values of this matrix in column-major order * @return this */ public Matrix4f getTransposed(int index, FloatBuffer buffer) { buffer.put(index, m00); buffer.put(index+1, m10); buffer.put(index+2, m20); buffer.put(index+3, m30); buffer.put(index+4, m01); buffer.put(index+5, m11); buffer.put(index+6, m21); buffer.put(index+7, m31); buffer.put(index+8, m02); buffer.put(index+9, m12); buffer.put(index+10, m22); buffer.put(index+11, m32); buffer.put(index+12, m03); buffer.put(index+13, m13); buffer.put(index+14, m23); buffer.put(index+15, m33); return this; } /** * Store the transpose of this matrix in column-major order into the supplied {@link ByteBuffer} at the current * buffer {@link ByteBuffer#position() position}. * <p> * This method will not increment the position of the given ByteBuffer. * <p> * If you want to specify the offset into the ByteBuffer at which * the matrix is stored, you can use {@link #getTransposed(int, ByteBuffer)}, taking * the absolute position as parameter. * * @see #getTransposed(int, ByteBuffer) * * @param buffer * will receive the values of this matrix in column-major order at its current position * @return this */ public Matrix4f getTransposed(ByteBuffer buffer) { return getTransposed(buffer.position(), buffer); } /** * Store the transpose of this matrix in column-major order into the supplied {@link ByteBuffer} starting at the specified * absolute buffer position/index. * <p> * This method will not increment the position of the given ByteBuffer. * * @param index * the absolute position into the ByteBuffer * @param buffer * will receive the values of this matrix in column-major order * @return this */ public Matrix4f getTransposed(int index, ByteBuffer buffer) { buffer.putFloat(index, m00); buffer.putFloat(index+4, m10); buffer.putFloat(index+8, m20); buffer.putFloat(index+12, m30); buffer.putFloat(index+16, m01); buffer.putFloat(index+20, m11); buffer.putFloat(index+24, m21); buffer.putFloat(index+28, m31); buffer.putFloat(index+32, m02); buffer.putFloat(index+36, m12); buffer.putFloat(index+40, m22); buffer.putFloat(index+44, m32); buffer.putFloat(index+48, m03); buffer.putFloat(index+52, m13); buffer.putFloat(index+56, m23); buffer.putFloat(index+60, m33); return this; } /** * Store this matrix into the supplied float array in column-major order. * * @param arr * the array to write the matrix values into * @param offset * the offset into the array * @return this */ public Matrix4f get(float[] arr, int offset) { arr[offset+0] = m00; arr[offset+1] = m01; arr[offset+2] = m02; arr[offset+3] = m03; arr[offset+4] = m10; arr[offset+5] = m11; arr[offset+6] = m12; arr[offset+7] = m13; arr[offset+8] = m20; arr[offset+9] = m21; arr[offset+10] = m22; arr[offset+11] = m23; arr[offset+12] = m30; arr[offset+13] = m31; arr[offset+14] = m32; arr[offset+15] = m33; return this; } /** * Update the given {@link FrustumCuller} with <code>this</code> matrix. * <p> * This will result in the frustum culler recalculating <code>this</code> matrix's frustum planes. * * @see FrustumCuller#set(Matrix4f) * * @param culler * the {@link FrustumCuller} to update * @return this */ public Matrix4f get(FrustumCuller culler) { culler.set(this); return this; } /** * Update the given {@link FrustumRayBuilder} with <code>this</code> matrix. * <p> * This will result in the recalculation of <code>this</code> matrix's frustum. * * @see FrustumRayBuilder#set(Matrix4f) * * @param frustumRayBuilder * the {@link FrustumRayBuilder} to update * @return this */ public Matrix4f get(FrustumRayBuilder frustumRayBuilder) { frustumRayBuilder.set(this); return this; } /** * Set all the values within this matrix to <code>0</code>. * * @return this */ public Matrix4f zero() { m00 = 0.0f; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 0.0f; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = 0.0f; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 0.0f; return this; } /** * Set this matrix to be a simple scale matrix, which scales all axes uniformly by the given factor. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional scaling. * <p> * If you want to post-multiply a scaling transformation directly to a * matrix, you can use {@link #scale(float) scale()} instead. * * @see #scale(float) * * @param factor * the scale factor in x, y and z * @return this */ public Matrix4f scaling(float factor) { m00 = factor; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = factor; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = factor; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be a simple scale matrix. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional scaling. * <p> * If you want to post-multiply a scaling transformation directly to a * matrix, you can use {@link #scale(float, float, float) scale()} instead. * * @see #scale(float, float, float) * * @param x * the scale in x * @param y * the scale in y * @param z * the scale in z * @return this */ public Matrix4f scaling(float x, float y, float z) { m00 = x; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = y; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = z; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be a simple scale matrix which scales the base axes by <tt>xyz.x</tt>, <tt>xyz.y</tt> and <tt>xyz.z</tt> respectively. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional scaling. * <p> * In order to post-multiply a scaling transformation directly to a * matrix use {@link #scale(Vector3f) scale()} instead. * * @see #scale(Vector3f) * * @param xyz * the scale in x, y and z respectively * @return this */ public Matrix4f scaling(Vector3f xyz) { return scaling(xyz.x, xyz.y, xyz.z); } /** * Set this matrix to a rotation matrix which rotates the given radians about a given axis. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional rotation. * <p> * If you want to post-multiply a rotation transformation directly to a * matrix, you can use {@link #rotate(float, Vector3f) rotate()} instead. * * @see #rotate(float, Vector3f) * * @param angle * the angle in radians * @param axis * the axis to rotate about (needs to be {@link Vector3f#normalize() normalized}) * @return this */ public Matrix4f rotation(float angle, Vector3f axis) { return rotation(angle, axis.x, axis.y, axis.z); } /** * Set this matrix to a rotation transformation using the given {@link AxisAngle4f}. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional rotation. * <p> * In order to apply the rotation transformation to an existing transformation, * use {@link #rotate(AxisAngle4f) rotate()} instead. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(AxisAngle4f) * * @param axisAngle * the {@link AxisAngle4f} (needs to be {@link AxisAngle4f#normalize() normalized}) * @return this */ public Matrix4f rotation(AxisAngle4f axisAngle) { return rotation(axisAngle.angle, axisAngle.x, axisAngle.y, axisAngle.z); } /** * Set this matrix to a rotation matrix which rotates the given radians about a given axis. * <p> * The axis described by the three components needs to be a unit vector. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional rotation. * <p> * In order to apply the rotation transformation to an existing transformation, * use {@link #rotate(float, float, float, float) rotate()} instead. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(float, float, float, float) * * @param angle * the angle in radians * @param x * the x-component of the rotation axis * @param y * the y-component of the rotation axis * @param z * the z-component of the rotation axis * @return this */ public Matrix4f rotation(float angle, float x, float y, float z) { float cos = (float) Math.cos(angle); float sin = (float) Math.sin(angle); float C = 1.0f - cos; m00 = cos + x * x * C; m10 = x * y * C - z * sin; m20 = x * z * C + y * sin; m30 = 0.0f; m01 = y * x * C + z * sin; m11 = cos + y * y * C; m21 = y * z * C - x * sin; m31 = 0.0f; m02 = z * x * C - y * sin; m12 = z * y * C + x * sin; m22 = cos + z * z * C; m32 = 0.0f; m03 = 0.0f; m13 = 0.0f; m23 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to a rotation transformation about the X axis. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotationX(float ang) { float cos = (float) Math.cos(ang); float sin = (float) Math.sin(ang); m00 = 1.0f; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = cos; m12 = sin; m13 = 0.0f; m20 = 0.0f; m21 = -sin; m22 = cos; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to a rotation transformation about the Y axis. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotationY(float ang) { float cos = (float) Math.cos(ang); float sin = (float) Math.sin(ang); m00 = cos; m01 = 0.0f; m02 = -sin; m03 = 0.0f; m10 = 0.0f; m11 = 1.0f; m12 = 0.0f; m13 = 0.0f; m20 = sin; m21 = 0.0f; m22 = cos; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to a rotation transformation about the Z axis. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotationZ(float ang) { float cos = (float) Math.cos(ang); float sin = (float) Math.sin(ang); m00 = cos; m01 = sin; m02 = 0.0f; m03 = 0.0f; m10 = -sin; m11 = cos; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = 0.0f; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to the rotation transformation of the given {@link Quaternionf}. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional rotation. * <p> * In order to apply the rotation transformation to an existing transformation, * use {@link #rotate(Quaternionf) rotate()} instead. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> * * @see #rotate(Quaternionf) * * @param quat * the {@link Quaternionf} * @return this */ public Matrix4f rotation(Quaternionf quat) { float q00 = 2.0f * quat.x * quat.x; float q11 = 2.0f * quat.y * quat.y; float q22 = 2.0f * quat.z * quat.z; float q01 = 2.0f * quat.x * quat.y; float q02 = 2.0f * quat.x * quat.z; float q03 = 2.0f * quat.x * quat.w; float q12 = 2.0f * quat.y * quat.z; float q13 = 2.0f * quat.y * quat.w; float q23 = 2.0f * quat.z * quat.w; m00 = 1.0f - q11 - q22; m01 = q01 + q23; m02 = q02 - q13; m03 = 0.0f; m10 = q01 - q23; m11 = 1.0f - q22 - q00; m12 = q12 + q03; m13 = 0.0f; m20 = q02 + q13; m21 = q12 - q03; m22 = 1.0f - q11 - q00; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set <code>this</code> matrix to <tt>T * R * S</tt>, where <tt>T</tt> is a translation by the given <tt>(tx, ty, tz)</tt>, * <tt>R</tt> is a rotation transformation specified by the quaternion <tt>(qx, qy, qz, qw)</tt>, and <tt>S</tt> is a scaling transformation * which scales the three axes x, y and z by <tt>(sx, sy, sz)</tt>. * <p> * When transforming a vector by the resulting matrix the scaling transformation will be applied first, then the rotation and * at last the translation. * <p> * This method is equivalent to calling: <tt>translation(tx, ty, tz).rotate(quat).scale(sx, sy, sz)</tt> * * @see #translation(float, float, float) * @see #rotate(Quaternionf) * @see #scale(float, float, float) * * @param tx * the number of units by which to translate the x-component * @param ty * the number of units by which to translate the y-component * @param tz * the number of units by which to translate the z-component * @param qx * the x-coordinate of the vector part of the quaternion * @param qy * the y-coordinate of the vector part of the quaternion * @param qz * the z-coordinate of the vector part of the quaternion * @param qw * the scalar part of the quaternion * @param sx * the scaling factor for the x-axis * @param sy * the scaling factor for the y-axis * @param sz * the scaling factor for the z-axis * @return this */ public Matrix4f translationRotateScale(float tx, float ty, float tz, float qx, float qy, float qz, float qw, float sx, float sy, float sz) { float dqx = 2.0f * qx, dqy = 2.0f * qy, dqz = 2.0f * qz; float q00 = dqx * qx; float q11 = dqy * qy; float q22 = dqz * qz; float q01 = dqx * qy; float q02 = dqx * qz; float q03 = dqx * qw; float q12 = dqy * qz; float q13 = dqy * qw; float q23 = dqz * qw; m00 = sx - (q11 + q22) * sx; m01 = (q01 + q23) * sx; m02 = (q02 - q13) * sx; m03 = 0.0f; m10 = (q01 - q23) * sy; m11 = sy - (q22 + q00) * sy; m12 = (q12 + q03) * sy; m13 = 0.0f; m20 = (q02 + q13) * sz; m21 = (q12 - q03) * sz; m22 = sz - (q11 + q00) * sz; m23 = 0.0f; m30 = tx; m31 = ty; m32 = tz; m33 = 1.0f; return this; } /** * Set <code>this</code> matrix to <tt>T * R * S</tt>, where <tt>T</tt> is the given <code>translation</code>, * <tt>R</tt> is a rotation transformation specified by the given quaternion, and <tt>S</tt> is a scaling transformation * which scales the axes by <code>scale</code>. * <p> * When transforming a vector by the resulting matrix the scaling transformation will be applied first, then the rotation and * at last the translation. * <p> * This method is equivalent to calling: <tt>translation(translation).rotate(quat).scale(scale)</tt> * * @see #translation(Vector3f) * @see #rotate(Quaternionf) * * @param translation * the translation * @param quat * the quaternion representing a rotation * @param scale * the scaling factors * @return this */ public Matrix4f translationRotateScale(Vector3f translation, Quaternionf quat, Vector3f scale) { return translationRotateScale(translation.x, translation.y, translation.z, quat.x, quat.y, quat.z, quat.w, scale.x, scale.y, scale.z); } /** * Set <code>this</code> matrix to <tt>T * R</tt>, where <tt>T</tt> is a translation by the given <tt>(tx, ty, tz)</tt> and * <tt>R</tt> is a rotation transformation specified by the given quaternion. * <p> * When transforming a vector by the resulting matrix the rotation transformation will be applied first and then the translation. * <p> * This method is equivalent to calling: <tt>translation(tx, ty, tz).rotate(quat)</tt> * * @see #translation(float, float, float) * @see #rotate(Quaternionf) * * @param tx * the number of units by which to translate the x-component * @param ty * the number of units by which to translate the y-component * @param tz * the number of units by which to translate the z-component * @param quat * the quaternion representing a rotation * @return this */ public Matrix4f translationRotate(float tx, float ty, float tz, Quaternionf quat) { float qx = 2.0f * quat.x, qy = 2.0f * quat.y, qz = 2.0f * quat.z; float q00 = qx * quat.x; float q11 = qy * quat.y; float q22 = qz * quat.z; float q01 = qx * quat.y; float q02 = qx * quat.z; float q03 = qx * quat.w; float q12 = qy * quat.z; float q13 = qy * quat.w; float q23 = qz * quat.w; m00 = 1.0f - (q11 + q22); m01 = q01 + q23; m02 = q02 - q13; m03 = 0.0f; m10 = q01 - q23; m11 = 1.0f - (q22 + q00); m12 = q12 + q03; m13 = 0.0f; m20 = q02 + q13; m21 = q12 - q03; m22 = 1.0f - (q11 + q00); m23 = 0.0f; m30 = tx; m31 = ty; m32 = tz; m33 = 1.0f; return this; } /** * Set the upper 3x3 matrix of this {@link Matrix4f} to the given {@link Matrix3f} and the rest to the identity. * * @param mat * the 3x3 matrix * @return this */ public Matrix4f setMatrix3(Matrix3f mat) { m00 = mat.m00; m01 = mat.m01; m02 = mat.m02; m03 = 0.0f; m10 = mat.m10; m11 = mat.m11; m12 = mat.m12; m13 = 0.0f; m20 = mat.m20; m21 = mat.m21; m22 = mat.m22; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Transform/multiply the given vector by this matrix and store the result in that vector. * * @see Vector4f#mul(Matrix4f) * * @param v * the vector to transform and to hold the final result * @return this */ public Matrix4f transform(Vector4f v) { v.mul(this); return this; } /** * Transform/multiply the given vector by this matrix and store the result in <code>dest</code>. * * @see Vector4f#mul(Matrix4f, Vector4f) * * @param v * the vector to transform * @param dest * will contain the result * @return this */ public Matrix4f transform(Vector4f v, Vector4f dest) { v.mul(this, dest); return this; } /** * Transform/multiply the given 3D-vector, as if it was a 4D-vector with w=1, by * this matrix and store the result in that vector. * <p> * The given 3D-vector is treated as a 4D-vector with its w-component being 1.0, so it * will represent a point/location in 3D-space rather than a direction. This method is therefore * not suited for perspective projection transformations as it will not save the * <tt>w</tt> component of the transformed vector. * For perspective projection use {@link #transform(Vector4f)}. * <p> * In order to store the result in another vector, use {@link #transform(Vector3f, Vector3f)}. * * @see #transform(Vector3f, Vector3f) * @see #transform(Vector4f) * * @param v * the vector to transform and to hold the final result * @return this */ public Matrix4f transform(Vector3f v) { v.set(m00 * v.x + m10 * v.y + m20 * v.z + m30, m01 * v.x + m11 * v.y + m21 * v.z + m31, m02 * v.x + m12 * v.y + m22 * v.z + m32); return this; } /** * Transform/multiply the given 3D-vector, as if it was a 4D-vector with w=1, by * this matrix and store the result in <code>dest</code>. * <p> * The given 3D-vector is treated as a 4D-vector with its w-component being 1.0, so it * will represent a point/location in 3D-space rather than a direction. This method is therefore * not suited for perspective projection transformations as it will not save the * <tt>w</tt> component of the transformed vector. * For perspective projection use {@link #transform(Vector4f, Vector4f)}. * <p> * In order to store the result in the same vector, use {@link #transform(Vector3f)}. * * @see #transform(Vector3f) * @see #transform(Vector4f, Vector4f) * * @param v * the vector to transform * @param dest * will hold the result * @return this */ public Matrix4f transform(Vector3f v, Vector3f dest) { dest.x = m00 * v.x + m10 * v.y + m20 * v.z + m30; dest.y = m01 * v.x + m11 * v.y + m21 * v.z + m31; dest.z = m02 * v.x + m12 * v.y + m22 * v.z + m32; return this; } /** * Apply scaling to the this matrix by scaling the base axes by the given <tt>xyz.x</tt>, * <tt>xyz.y</tt> and <tt>xyz.z</tt> factors, respectively and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code> * , the scaling will be applied first! * * @param xyz * the factors of the x, y and z component, respectively * @param dest * will hold the result * @return this */ public Matrix4f scale(Vector3f xyz, Matrix4f dest) { return scale(xyz.x, xyz.y, xyz.z, dest); } /** * Apply scaling to this matrix by scaling the base axes by the given <tt>xyz.x</tt>, * <tt>xyz.y</tt> and <tt>xyz.z</tt> factors, respectively. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * scaling will be applied first! * * @param xyz * the factors of the x, y and z component, respectively * @return this */ public Matrix4f scale(Vector3f xyz) { return scale(xyz.x, xyz.y, xyz.z, this); } /** * Apply scaling to this matrix by uniformly scaling all base axes by the given <code>xyz</code> factor * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * scaling will be applied first! * <p> * Individual scaling of all three axes can be applied using {@link #scale(float, float, float, Matrix4f)}. * * @see #scale(float, float, float, Matrix4f) * * @param xyz * the factor for all components * @param dest * will hold the result * @return this */ public Matrix4f scale(float xyz, Matrix4f dest) { return scale(xyz, xyz, xyz, dest); } /** * Apply scaling to this matrix by uniformly scaling all base axes by the given <code>xyz</code> factor. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * scaling will be applied first! * <p> * Individual scaling of all three axes can be applied using {@link #scale(float, float, float)}. * * @see #scale(float, float, float) * * @param xyz * the factor for all components * @return this */ public Matrix4f scale(float xyz) { return scale(xyz, xyz, xyz); } /** * Apply scaling to the this matrix by scaling the base axes by the given x, * y and z factors and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code> * , the scaling will be applied first! * * @param x * the factor of the x component * @param y * the factor of the y component * @param z * the factor of the z component * @param dest * will hold the result * @return this */ public Matrix4f scale(float x, float y, float z, Matrix4f dest) { // scale matrix elements: // m00 = x, m11 = y, m22 = z // m33 = 1 // all others = 0 dest.m00 = m00 * x; dest.m01 = m01 * x; dest.m02 = m02 * x; dest.m03 = m03 * x; dest.m10 = m10 * y; dest.m11 = m11 * y; dest.m12 = m12 * y; dest.m13 = m13 * y; dest.m20 = m20 * z; dest.m21 = m21 * z; dest.m22 = m22 * z; dest.m23 = m23 * z; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return this; } /** * Apply scaling to this matrix by scaling the base axes by the given x, * y and z factors. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * scaling will be applied first! * * @param x * the factor of the x component * @param y * the factor of the y component * @param z * the factor of the z component * @return this */ public Matrix4f scale(float x, float y, float z) { return scale(x, y, z, this); } /** * Apply rotation about the X axis to this matrix by rotating the given amount of radians * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @param dest * will hold the result * @return this */ public Matrix4f rotateX(float ang, Matrix4f dest) { float cos = (float) Math.cos(ang); float sin = (float) Math.sin(ang); float rm11 = cos; float rm12 = sin; float rm21 = -sin; float rm22 = cos; // add temporaries for dependent values float nm10 = m10 * rm11 + m20 * rm12; float nm11 = m11 * rm11 + m21 * rm12; float nm12 = m12 * rm11 + m22 * rm12; float nm13 = m13 * rm11 + m23 * rm12; // set non-dependent values directly dest.m20 = m10 * rm21 + m20 * rm22; dest.m21 = m11 * rm21 + m21 * rm22; dest.m22 = m12 * rm21 + m22 * rm22; dest.m23 = m13 * rm21 + m23 * rm22; // set other values dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m00 = m00; dest.m01 = m01; dest.m02 = m02; dest.m03 = m03; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return this; } /** * Apply rotation about the X axis to this matrix by rotating the given amount of radians. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotateX(float ang) { return rotateX(ang, this); } /** * Apply rotation about the Y axis to this matrix by rotating the given amount of radians * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @param dest * will hold the result * @return this */ public Matrix4f rotateY(float ang, Matrix4f dest) { float cos = (float) Math.cos(ang); float sin = (float) Math.sin(ang); float rm00 = cos; float rm02 = -sin; float rm20 = sin; float rm22 = cos; // add temporaries for dependent values float nm00 = m00 * rm00 + m20 * rm02; float nm01 = m01 * rm00 + m21 * rm02; float nm02 = m02 * rm00 + m22 * rm02; float nm03 = m03 * rm00 + m23 * rm02; // set non-dependent values directly dest.m20 = m00 * rm20 + m20 * rm22; dest.m21 = m01 * rm20 + m21 * rm22; dest.m22 = m02 * rm20 + m22 * rm22; dest.m23 = m03 * rm20 + m23 * rm22; // set other values dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = m10; dest.m11 = m11; dest.m12 = m12; dest.m13 = m13; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return this; } /** * Apply rotation about the Y axis to this matrix by rotating the given amount of radians. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotateY(float ang) { return rotateY(ang, this); } /** * Apply rotation about the Z axis to this matrix by rotating the given amount of radians * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @param dest * will hold the result * @return this */ public Matrix4f rotateZ(float ang, Matrix4f dest) { float cos = (float) Math.cos(ang); float sin = (float) Math.sin(ang); float rm00 = cos; float rm01 = sin; float rm10 = -sin; float rm11 = cos; // add temporaries for dependent values float nm00 = m00 * rm00 + m10 * rm01; float nm01 = m01 * rm00 + m11 * rm01; float nm02 = m02 * rm00 + m12 * rm01; float nm03 = m03 * rm00 + m13 * rm01; // set non-dependent values directly dest.m10 = m00 * rm10 + m10 * rm11; dest.m11 = m01 * rm10 + m11 * rm11; dest.m12 = m02 * rm10 + m12 * rm11; dest.m13 = m03 * rm10 + m13 * rm11; // set other values dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m20 = m20; dest.m21 = m21; dest.m22 = m22; dest.m23 = m23; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return this; } /** * Apply rotation about the Z axis to this matrix by rotating the given amount of radians. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotateZ(float ang) { return rotateZ(ang, this); } /** * Apply rotation to this matrix by rotating the given amount of radians * about the given axis specified as x, y and z components and store the result in <code>dest</code>. * <p> * The axis described by the three components needs to be a unit vector. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * In order to set the matrix to a rotation matrix without post-multiplying the rotation * transformation, use {@link #rotation(float, float, float, float) rotation()}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> * * @see #rotation(float, float, float, float) * * @param ang * the angle in radians * @param x * the x component of the axis * @param y * the y component of the axis * @param z * the z component of the axis * @param dest * will hold the result * @return this */ public Matrix4f rotate(float ang, float x, float y, float z, Matrix4f dest) { float s = (float) Math.sin(ang); float c = (float) Math.cos(ang); float C = 1.0f - c; // rotation matrix elements: // m30, m31, m32, m03, m13, m23 = 0 // m33 = 1 float rm00 = x * x * C + c; float rm01 = y * x * C + z * s; float rm02 = z * x * C - y * s; float rm10 = x * y * C - z * s; float rm11 = y * y * C + c; float rm12 = z * y * C + x * s; float rm20 = x * z * C + y * s; float rm21 = y * z * C - x * s; float rm22 = z * z * C + c; // add temporaries for dependent values float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; // set non-dependent values directly dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; // set other values dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return this; } /** * Apply rotation to this matrix by rotating the given amount of radians * about the given axis specified as x, y and z components. * <p> * The axis described by the three components needs to be a unit vector. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * In order to set the matrix to a rotation matrix without post-multiplying the rotation * transformation, use {@link #rotation(float, float, float, float) rotation()}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> * * @see #rotation(float, float, float, float) * * @param ang * the angle in radians * @param x * the x component of the axis * @param y * the y component of the axis * @param z * the z component of the axis * @return this */ public Matrix4f rotate(float ang, float x, float y, float z) { return rotate(ang, x, y, z, this); } /** * Apply a translation to this matrix by translating by the given number of * units in x, y and z. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>M * T</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>M * T * v</code>, the translation will be applied first! * <p> * In order to set the matrix to a translation transformation without post-multiplying * it, use {@link #translation(Vector3f)}. * * @see #translation(Vector3f) * * @param offset * the number of units in x, y and z by which to translate * @return this */ public Matrix4f translate(Vector3f offset) { return translate(offset.x, offset.y, offset.z); } /** * Apply a translation to this matrix by translating by the given number of * units in x, y and z and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>M * T</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>M * T * v</code>, the translation will be applied first! * <p> * In order to set the matrix to a translation transformation without post-multiplying * it, use {@link #translation(Vector3f)}. * * @see #translation(Vector3f) * * @param offset * the number of units in x, y and z by which to translate * @param dest * will hold the result * @return this */ public Matrix4f translate(Vector3f offset, Matrix4f dest) { return translate(offset.x, offset.y, offset.z, dest); } /** * Apply a translation to this matrix by translating by the given number of * units in x, y and z and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>M * T</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>M * T * v</code>, the translation will be applied first! * <p> * In order to set the matrix to a translation transformation without post-multiplying * it, use {@link #translation(float, float, float)}. * * @see #translation(float, float, float) * * @param x * the offset to translate in x * @param y * the offset to translate in y * @param z * the offset to translate in z * @param dest * will hold the result * @return this */ public Matrix4f translate(float x, float y, float z, Matrix4f dest) { // translation matrix elements: // m00, m11, m22, m33 = 1 // m30 = x, m31 = y, m32 = z // all others = 0 dest.m00 = m00; dest.m01 = m01; dest.m02 = m02; dest.m03 = m03; dest.m10 = m10; dest.m11 = m11; dest.m12 = m12; dest.m13 = m13; dest.m20 = m20; dest.m21 = m21; dest.m22 = m22; dest.m23 = m23; dest.m30 = m00 * x + m10 * y + m20 * z + m30; dest.m31 = m01 * x + m11 * y + m21 * z + m31; dest.m32 = m02 * x + m12 * y + m22 * z + m32; dest.m33 = m03 * x + m13 * y + m23 * z + m33; return this; } /** * Apply a translation to this matrix by translating by the given number of * units in x, y and z. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>M * T</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>M * T * v</code>, the translation will be applied first! * <p> * In order to set the matrix to a translation transformation without post-multiplying * it, use {@link #translation(float, float, float)}. * * @see #translation(float, float, float) * * @param x * the offset to translate in x * @param y * the offset to translate in y * @param z * the offset to translate in z * @return this */ public Matrix4f translate(float x, float y, float z) { Matrix4f c = this; // translation matrix elements: // m00, m11, m22, m33 = 1 // m30 = x, m31 = y, m32 = z // all others = 0 c.m30 = c.m00 * x + c.m10 * y + c.m20 * z + c.m30; c.m31 = c.m01 * x + c.m11 * y + c.m21 * z + c.m31; c.m32 = c.m02 * x + c.m12 * y + c.m22 * z + c.m32; c.m33 = c.m03 * x + c.m13 * y + c.m23 * z + c.m33; return this; } public void writeExternal(ObjectOutput out) throws IOException { out.writeFloat(m00); out.writeFloat(m01); out.writeFloat(m02); out.writeFloat(m03); out.writeFloat(m10); out.writeFloat(m11); out.writeFloat(m12); out.writeFloat(m13); out.writeFloat(m20); out.writeFloat(m21); out.writeFloat(m22); out.writeFloat(m23); out.writeFloat(m30); out.writeFloat(m31); out.writeFloat(m32); out.writeFloat(m33); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { m00 = in.readFloat(); m01 = in.readFloat(); m02 = in.readFloat(); m03 = in.readFloat(); m10 = in.readFloat(); m11 = in.readFloat(); m12 = in.readFloat(); m13 = in.readFloat(); m20 = in.readFloat(); m21 = in.readFloat(); m22 = in.readFloat(); m23 = in.readFloat(); m30 = in.readFloat(); m31 = in.readFloat(); m32 = in.readFloat(); m33 = in.readFloat(); } /** * Apply an orthographic projection transformation to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to an orthographic projection without post-multiplying it, * use {@link #setOrtho(float, float, float, float, float, float) setOrtho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrtho(float, float, float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param dest * will hold the result * @return this */ public Matrix4f ortho(float left, float right, float bottom, float top, float zNear, float zFar, Matrix4f dest) { // calculate right matrix elements float rm00 = 2.0f / (right - left); float rm11 = 2.0f / (top - bottom); float rm22 = -2.0f / (zFar - zNear); float rm30 = -(right + left) / (right - left); float rm31 = -(top + bottom) / (top - bottom); float rm32 = -(zFar + zNear) / (zFar - zNear); // perform optimized multiplication // compute the last column first, because other rows do not depend on it dest.m30 = m00 * rm30 + m10 * rm31 + m20 * rm32 + m30; dest.m31 = m01 * rm30 + m11 * rm31 + m21 * rm32 + m31; dest.m32 = m02 * rm30 + m12 * rm31 + m22 * rm32 + m32; dest.m33 = m03 * rm30 + m13 * rm31 + m23 * rm32 + m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m20 = m20 * rm22; dest.m21 = m21 * rm22; dest.m22 = m22 * rm22; dest.m23 = m23 * rm22; return this; } /** * Apply an orthographic projection transformation to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to an orthographic projection without post-multiplying it, * use {@link #setOrtho(float, float, float, float, float, float) setOrtho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrtho(float, float, float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @return this */ public Matrix4f ortho(float left, float right, float bottom, float top, float zNear, float zFar) { return ortho(left, right, bottom, top, zNear, zFar, this); } /** * Set this matrix to be an orthographic projection transformation. * <p> * In order to apply the orthographic projection to an already existing transformation, * use {@link #ortho(float, float, float, float, float, float) ortho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #ortho(float, float, float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @return this */ public Matrix4f setOrtho(float left, float right, float bottom, float top, float zNear, float zFar) { m00 = 2.0f / (right - left); m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 2.0f / (top - bottom); m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = -2.0f / (zFar - zNear); m23 = 0.0f; m30 = -(right + left) / (right - left); m31 = -(top + bottom) / (top - bottom); m32 = -(zFar + zNear) / (zFar - zNear); m33 = 1.0f; return this; } /** * Apply a symmetric orthographic projection transformation to this matrix and store the result in <code>dest</code>. * <p> * This method is equivalent to calling {@link #ortho(float, float, float, float, float, float, Matrix4f) ortho()} with * <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to a symmetric orthographic projection without post-multiplying it, * use {@link #setOrthoSymmetric(float, float, float, float) setOrthoSymmetric()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrthoSymmetric(float, float, float, float) * * @param width * the distance between the right and left frustum edges * @param height * the distance between the top and bottom frustum edges * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param dest * will hold the result * @return this */ public Matrix4f orthoSymmetric(float width, float height, float zNear, float zFar, Matrix4f dest) { // calculate right matrix elements float rm00 = 2.0f / width; float rm11 = 2.0f / height; float rm22 = -2.0f / (zFar - zNear); float rm32 = -(zFar + zNear) / (zFar - zNear); // perform optimized multiplication // compute the last column first, because other rows do not depend on it dest.m30 = m20 * rm32 + m30; dest.m31 = m21 * rm32 + m31; dest.m32 = m22 * rm32 + m32; dest.m33 = m23 * rm32 + m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m20 = m20 * rm22; dest.m21 = m21 * rm22; dest.m22 = m22 * rm22; dest.m23 = m23 * rm22; return this; } /** * Apply a symmetric orthographic projection transformation to this matrix. * <p> * This method is equivalent to calling {@link #ortho(float, float, float, float, float, float) ortho()} with * <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to a symmetric orthographic projection without post-multiplying it, * use {@link #setOrthoSymmetric(float, float, float, float) setOrthoSymmetric()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrthoSymmetric(float, float, float, float) * * @param width * the distance between the right and left frustum edges * @param height * the distance between the top and bottom frustum edges * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @return this */ public Matrix4f orthoSymmetric(float width, float height, float zNear, float zFar) { return orthoSymmetric(width, height, zNear, zFar, this); } /** * Set this matrix to be a symmetric orthographic projection transformation. * <p> * This method is equivalent to calling {@link #setOrtho(float, float, float, float, float, float) setOrtho()} with * <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. * <p> * In order to apply the symmetric orthographic projection to an already existing transformation, * use {@link #orthoSymmetric(float, float, float, float) orthoSymmetric()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #orthoSymmetric(float, float, float, float) * * @param width * the distance between the right and left frustum edges * @param height * the distance between the top and bottom frustum edges * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @return this */ public Matrix4f setOrthoSymmetric(float width, float height, float zNear, float zFar) { m00 = 2.0f / width; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 2.0f / height; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = -2.0f / (zFar - zNear); m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = -(zFar + zNear) / (zFar - zNear); m33 = 1.0f; return this; } /** * Apply an orthographic projection transformation to this matrix and store the result in <code>dest</code>. * <p> * This method is equivalent to calling {@link #ortho(float, float, float, float, float, float, Matrix4f) ortho()} with * <code>zNear=-1</code> and <code>zFar=+1</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to an orthographic projection without post-multiplying it, * use {@link #setOrtho2D(float, float, float, float) setOrtho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #ortho(float, float, float, float, float, float, Matrix4f) * @see #setOrtho2D(float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param dest * will hold the result * @return this */ public Matrix4f ortho2D(float left, float right, float bottom, float top, Matrix4f dest) { // calculate right matrix elements float rm00 = 2.0f / (right - left); float rm11 = 2.0f / (top - bottom); float rm30 = -(right + left) / (right - left); float rm31 = -(top + bottom) / (top - bottom); // perform optimized multiplication // compute the last column first, because other rows do not depend on it dest.m30 = m00 * rm30 + m10 * rm31 + m30; dest.m31 = m01 * rm30 + m11 * rm31 + m31; dest.m32 = m02 * rm30 + m12 * rm31 + m32; dest.m33 = m03 * rm30 + m13 * rm31 + m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m20 = -m20; dest.m21 = -m21; dest.m22 = -m22; dest.m23 = -m23; return this; } /** * Apply an orthographic projection transformation to this matrix. * <p> * This method is equivalent to calling {@link #ortho(float, float, float, float, float, float) ortho()} with * <code>zNear=-1</code> and <code>zFar=+1</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to an orthographic projection without post-multiplying it, * use {@link #setOrtho2D(float, float, float, float) setOrtho2D()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #ortho(float, float, float, float, float, float) * @see #setOrtho2D(float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @return this */ public Matrix4f ortho2D(float left, float right, float bottom, float top) { return ortho2D(left, right, bottom, top, this); } /** * Set this matrix to be an orthographic projection transformation. * <p> * This method is equivalent to calling {@link #setOrtho(float, float, float, float, float, float) setOrtho()} with * <code>zNear=-1</code> and <code>zFar=+1</code>. * <p> * In order to apply the orthographic projection to an already existing transformation, * use {@link #ortho2D(float, float, float, float) ortho2D()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrtho(float, float, float, float, float, float) * @see #ortho2D(float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @return this */ public Matrix4f setOrtho2D(float left, float right, float bottom, float top) { m00 = 2.0f / (right - left); m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 2.0f / (top - bottom); m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = -1.0f; m23 = 0.0f; m30 = -(right + left) / (right - left); m31 = -(top + bottom) / (top - bottom); m32 = 0.0f; m33 = 1.0f; return this; } /** * Apply a rotation transformation to this matrix to make <code>-z</code> point along <code>dir</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookalong rotation matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the * lookalong rotation transformation will be applied first! * <p> * This is equivalent to calling * {@link #lookAt(Vector3f, Vector3f, Vector3f) lookAt} * with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to set the matrix to a lookalong transformation without post-multiplying it, * use {@link #setLookAlong(Vector3f, Vector3f) setLookAlong()}. * * @see #lookAlong(float, float, float, float, float, float) * @see #lookAt(Vector3f, Vector3f, Vector3f) * @see #setLookAlong(Vector3f, Vector3f) * * @param dir * the direction in space to look along * @param up * the direction of 'up' * @return this */ public Matrix4f lookAlong(Vector3f dir, Vector3f up) { return lookAlong(dir.x, dir.y, dir.z, up.x, up.y, up.z, this); } /** * Apply a rotation transformation to this matrix to make <code>-z</code> point along <code>dir</code> * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookalong rotation matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the * lookalong rotation transformation will be applied first! * <p> * This is equivalent to calling * {@link #lookAt(Vector3f, Vector3f, Vector3f) lookAt} * with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to set the matrix to a lookalong transformation without post-multiplying it, * use {@link #setLookAlong(Vector3f, Vector3f) setLookAlong()}. * * @see #lookAlong(float, float, float, float, float, float) * @see #lookAt(Vector3f, Vector3f, Vector3f) * @see #setLookAlong(Vector3f, Vector3f) * * @param dir * the direction in space to look along * @param up * the direction of 'up' * @param dest * will hold the result * @return this */ public Matrix4f lookAlong(Vector3f dir, Vector3f up, Matrix4f dest) { return lookAlong(dir.x, dir.y, dir.z, up.x, up.y, up.z, dest); } /** * Apply a rotation transformation to this matrix to make <code>-z</code> point along <code>dir</code> * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookalong rotation matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the * lookalong rotation transformation will be applied first! * <p> * This is equivalent to calling * {@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt()} * with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to set the matrix to a lookalong transformation without post-multiplying it, * use {@link #setLookAlong(float, float, float, float, float, float) setLookAlong()} * * @see #lookAt(float, float, float, float, float, float, float, float, float) * @see #setLookAlong(float, float, float, float, float, float) * * @param dirX * the x-coordinate of the direction to look along * @param dirY * the y-coordinate of the direction to look along * @param dirZ * the z-coordinate of the direction to look along * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @param dest * will hold the result * @return this */ public Matrix4f lookAlong(float dirX, float dirY, float dirZ, float upX, float upY, float upZ, Matrix4f dest) { // Normalize direction float dirLength = (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); float dirnX = dirX / dirLength; float dirnY = dirY / dirLength; float dirnZ = dirZ / dirLength; // right = direction x up float rightX, rightY, rightZ; rightX = dirnY * upZ - dirnZ * upY; rightY = dirnZ * upX - dirnX * upZ; rightZ = dirnX * upY - dirnY * upX; // normalize right float rightLength = (float) Math.sqrt(rightX * rightX + rightY * rightY + rightZ * rightZ); rightX /= rightLength; rightY /= rightLength; rightZ /= rightLength; // up = right x direction float upnX = rightY * dirnZ - rightZ * dirnY; float upnY = rightZ * dirnX - rightX * dirnZ; float upnZ = rightX * dirnY - rightY * dirnX; // calculate right matrix elements float rm00 = rightX; float rm01 = upnX; float rm02 = -dirnX; float rm10 = rightY; float rm11 = upnY; float rm12 = -dirnY; float rm20 = rightZ; float rm21 = upnZ; float rm22 = -dirnZ; // perform optimized matrix multiplication // introduce temporaries for dependent results float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; // set the rest of the matrix elements dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return this; } /** * Apply a rotation transformation to this matrix to make <code>-z</code> point along <code>dir</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookalong rotation matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the * lookalong rotation transformation will be applied first! * <p> * This is equivalent to calling * {@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt()} * with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to set the matrix to a lookalong transformation without post-multiplying it, * use {@link #setLookAlong(float, float, float, float, float, float) setLookAlong()} * * @see #lookAt(float, float, float, float, float, float, float, float, float) * @see #setLookAlong(float, float, float, float, float, float) * * @param dirX * the x-coordinate of the direction to look along * @param dirY * the y-coordinate of the direction to look along * @param dirZ * the z-coordinate of the direction to look along * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @return this */ public Matrix4f lookAlong(float dirX, float dirY, float dirZ, float upX, float upY, float upZ) { return lookAlong(dirX, dirY, dirZ, upX, upY, upZ, this); } /** * Set this matrix to a rotation transformation to make <code>-z</code> * point along <code>dir</code>. * <p> * This is equivalent to calling * {@link #setLookAt(Vector3f, Vector3f, Vector3f) setLookAt()} * with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to apply the lookalong transformation to any previous existing transformation, * use {@link #lookAlong(Vector3f, Vector3f)}. * * @see #setLookAlong(Vector3f, Vector3f) * @see #lookAlong(Vector3f, Vector3f) * * @param dir * the direction in space to look along * @param up * the direction of 'up' * @return this */ public Matrix4f setLookAlong(Vector3f dir, Vector3f up) { return setLookAlong(dir.x, dir.y, dir.z, up.x, up.y, up.z); } /** * Set this matrix to a rotation transformation to make <code>-z</code> * point along <code>dir</code>. * <p> * This is equivalent to calling * {@link #setLookAt(float, float, float, float, float, float, float, float, float) * setLookAt()} with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to apply the lookalong transformation to any previous existing transformation, * use {@link #lookAlong(float, float, float, float, float, float) lookAlong()} * * @see #setLookAlong(float, float, float, float, float, float) * @see #lookAlong(float, float, float, float, float, float) * * @param dirX * the x-coordinate of the direction to look along * @param dirY * the y-coordinate of the direction to look along * @param dirZ * the z-coordinate of the direction to look along * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @return this */ public Matrix4f setLookAlong(float dirX, float dirY, float dirZ, float upX, float upY, float upZ) { // Normalize direction float dirLength = (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); float dirnX = dirX / dirLength; float dirnY = dirY / dirLength; float dirnZ = dirZ / dirLength; // right = direction x up float rightX, rightY, rightZ; rightX = dirnY * upZ - dirnZ * upY; rightY = dirnZ * upX - dirnX * upZ; rightZ = dirnX * upY - dirnY * upX; // normalize right float rightLength = (float) Math.sqrt(rightX * rightX + rightY * rightY + rightZ * rightZ); rightX /= rightLength; rightY /= rightLength; rightZ /= rightLength; // up = right x direction float upnX = rightY * dirnZ - rightZ * dirnY; float upnY = rightZ * dirnX - rightX * dirnZ; float upnZ = rightX * dirnY - rightY * dirnX; m00 = rightX; m01 = upnX; m02 = -dirnX; m03 = 0.0f; m10 = rightY; m11 = upnY; m12 = -dirnY; m13 = 0.0f; m20 = rightZ; m21 = upnZ; m22 = -dirnZ; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be a "lookat" transformation for a right-handed coordinate system, that aligns * <code>-z</code> with <code>center - eye</code>. * <p> * If you do not want to use {@link Vector3f} instances but simple floats * like in the GLU function, you can use * {@link #setLookAt(float, float, float, float, float, float, float, float, float) setLookAt()} * instead. * <p> * In order to apply the lookat transformation to a previous existing transformation, * use {@link #lookAt(Vector3f, Vector3f, Vector3f) lookAt()}. * * @see #setLookAt(float, float, float, float, float, float, float, float, float) * @see #lookAt(Vector3f, Vector3f, Vector3f) * * @param eye * the position of the camera * @param center * the point in space to look at * @param up * the direction of 'up' * @return this */ public Matrix4f setLookAt(Vector3f eye, Vector3f center, Vector3f up) { return setLookAt(eye.x, eye.y, eye.z, center.x, center.y, center.z, up.x, up.y, up.z); } /** * Set this matrix to be a "lookat" transformation for a right-handed coordinate system, * that aligns <code>-z</code> with <code>center - eye</code>. * <p> * In order to apply the lookat transformation to a previous existing transformation, * use {@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt}. * * @see #setLookAt(Vector3f, Vector3f, Vector3f) * @see #lookAt(float, float, float, float, float, float, float, float, float) * * @param eyeX * the x-coordinate of the eye/camera location * @param eyeY * the y-coordinate of the eye/camera location * @param eyeZ * the z-coordinate of the eye/camera location * @param centerX * the x-coordinate of the point to look at * @param centerY * the y-coordinate of the point to look at * @param centerZ * the z-coordinate of the point to look at * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @return this */ public Matrix4f setLookAt(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { // Compute direction from position to lookAt float dirX, dirY, dirZ; dirX = centerX - eyeX; dirY = centerY - eyeY; dirZ = centerZ - eyeZ; // Normalize direction float dirLength = (float) Math.sqrt( (centerX - eyeX) * (centerX - eyeX) + (centerY - eyeY) * (centerY - eyeY) + (centerZ - eyeZ) * (centerZ - eyeZ)); dirX /= dirLength; dirY /= dirLength; dirZ /= dirLength; // right = direction x up float rightX, rightY, rightZ; rightX = dirY * upZ - dirZ * upY; rightY = dirZ * upX - dirX * upZ; rightZ = dirX * upY - dirY * upX; // normalize right float rightLength = (float) Math.sqrt(rightX * rightX + rightY * rightY + rightZ * rightZ); rightX /= rightLength; rightY /= rightLength; rightZ /= rightLength; // up = right x direction float upnX = rightY * dirZ - rightZ * dirY; float upnY = rightZ * dirX - rightX * dirZ; float upnZ = rightX * dirY - rightY * dirX; m00 = rightX; m01 = upnX; m02 = -dirX; m03 = 0.0f; m10 = rightY; m11 = upnY; m12 = -dirY; m13 = 0.0f; m20 = rightZ; m21 = upnZ; m22 = -dirZ; m23 = 0.0f; m30 = -rightX * eyeX - rightY * eyeY - rightZ * eyeZ; m31 = -upnX * eyeX - upnY * eyeY - upnZ * eyeZ; m32 = dirX * eyeX + dirY * eyeY + dirZ * eyeZ; m33 = 1.0f; return this; } /** * Apply a "lookat" transformation to this matrix for a right-handed coordinate system, * that aligns <code>-z</code> with <code>center - eye</code> and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAt(Vector3f, Vector3f, Vector3f)}. * * @see #lookAt(float, float, float, float, float, float, float, float, float) * @see #setLookAlong(Vector3f, Vector3f) * * @param eye * the position of the camera * @param center * the point in space to look at * @param up * the direction of 'up' * @param dest * will hold the result * @return this */ public Matrix4f lookAt(Vector3f eye, Vector3f center, Vector3f up, Matrix4f dest) { return lookAt(eye.x, eye.y, eye.z, center.x, center.y, center.z, up.x, up.y, up.z, dest); } /** * Apply a "lookat" transformation to this matrix for a right-handed coordinate system, * that aligns <code>-z</code> with <code>center - eye</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAt(Vector3f, Vector3f, Vector3f)}. * * @see #lookAt(float, float, float, float, float, float, float, float, float) * @see #setLookAlong(Vector3f, Vector3f) * * @param eye * the position of the camera * @param center * the point in space to look at * @param up * the direction of 'up' * @return this */ public Matrix4f lookAt(Vector3f eye, Vector3f center, Vector3f up) { return lookAt(eye.x, eye.y, eye.z, center.x, center.y, center.z, up.x, up.y, up.z, this); } /** * Apply a "lookat" transformation to this matrix for a right-handed coordinate system, * that aligns <code>-z</code> with <code>center - eye</code> and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAt(float, float, float, float, float, float, float, float, float) setLookAt()}. * * @see #lookAt(Vector3f, Vector3f, Vector3f) * @see #setLookAt(float, float, float, float, float, float, float, float, float) * * @param eyeX * the x-coordinate of the eye/camera location * @param eyeY * the y-coordinate of the eye/camera location * @param eyeZ * the z-coordinate of the eye/camera location * @param centerX * the x-coordinate of the point to look at * @param centerY * the y-coordinate of the point to look at * @param centerZ * the z-coordinate of the point to look at * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @param dest * will hold the result * @return this */ public Matrix4f lookAt(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ, Matrix4f dest) { // Compute direction from position to lookAt float dirX, dirY, dirZ; dirX = centerX - eyeX; dirY = centerY - eyeY; dirZ = centerZ - eyeZ; // Normalize direction float dirLength = (float) Math.sqrt( (eyeX - centerX) * (eyeX - centerX) + (eyeY - centerY) * (eyeY - centerY) + (eyeZ - centerZ) * (eyeZ - centerZ)); dirX /= dirLength; dirY /= dirLength; dirZ /= dirLength; // right = direction x up float rightX, rightY, rightZ; rightX = dirY * upZ - dirZ * upY; rightY = dirZ * upX - dirX * upZ; rightZ = dirX * upY - dirY * upX; // normalize right float rightLength = (float) Math.sqrt(rightX * rightX + rightY * rightY + rightZ * rightZ); rightX /= rightLength; rightY /= rightLength; rightZ /= rightLength; // up = right x direction float upnX = rightY * dirZ - rightZ * dirY; float upnY = rightZ * dirX - rightX * dirZ; float upnZ = rightX * dirY - rightY * dirX; // calculate right matrix elements float rm00 = rightX; float rm01 = upnX; float rm02 = -dirX; float rm10 = rightY; float rm11 = upnY; float rm12 = -dirY; float rm20 = rightZ; float rm21 = upnZ; float rm22 = -dirZ; float rm30 = -rightX * eyeX - rightY * eyeY - rightZ * eyeZ; float rm31 = -upnX * eyeX - upnY * eyeY - upnZ * eyeZ; float rm32 = dirX * eyeX + dirY * eyeY + dirZ * eyeZ; // perform optimized matrix multiplication // compute last column first, because others do not depend on it dest.m30 = m00 * rm30 + m10 * rm31 + m20 * rm32 + m30; dest.m31 = m01 * rm30 + m11 * rm31 + m21 * rm32 + m31; dest.m32 = m02 * rm30 + m12 * rm31 + m22 * rm32 + m32; dest.m33 = m03 * rm30 + m13 * rm31 + m23 * rm32 + m33; // introduce temporaries for dependent results float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; // set the rest of the matrix elements dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; return this; } /** * Apply a "lookat" transformation to this matrix for a right-handed coordinate system, * that aligns <code>-z</code> with <code>center - eye</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAt(float, float, float, float, float, float, float, float, float) setLookAt()}. * * @see #lookAt(Vector3f, Vector3f, Vector3f) * @see #setLookAt(float, float, float, float, float, float, float, float, float) * * @param eyeX * the x-coordinate of the eye/camera location * @param eyeY * the y-coordinate of the eye/camera location * @param eyeZ * the z-coordinate of the eye/camera location * @param centerX * the x-coordinate of the point to look at * @param centerY * the y-coordinate of the point to look at * @param centerZ * the z-coordinate of the point to look at * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @return this */ public Matrix4f lookAt(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { return lookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ, this); } /** * Apply a symmetric perspective projection frustum transformation to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, * then the new matrix will be <code>M * P</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * P * v</code>, * the perspective projection will be applied first! * <p> * This method first computes the frustum corners using the specified parameters and then makes use of * {@link #frustum(float, float, float, float, float, float) frustum()} to finally apply the frustum * transformation. * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setPerspective(float, float, float, float) setPerspective}. * * @see #frustum(float, float, float, float, float, float) * @see #setPerspective(float, float, float, float) * * @param fovy * the vertical field of view in radians * @param aspect * the aspect ratio (i.e. width / height) * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param dest * will hold the result * @return this */ public Matrix4f perspective(float fovy, float aspect, float zNear, float zFar, Matrix4f dest) { float h = (float) Math.tan(fovy * 0.5f) * zNear; float w = h * aspect; // calculate right matrix elements float rm00 = zNear / w; float rm11 = zNear / h; float rm22 = -(zFar + zNear) / (zFar - zNear); float rm32 = -2.0f * zFar * zNear / (zFar - zNear); // perform optimized matrix multiplication float nm20 = m20 * rm22 - m30; float nm21 = m21 * rm22 - m31; float nm22 = m22 * rm22 - m32; float nm23 = m23 * rm22 - m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m30 = m20 * rm32; dest.m31 = m21 * rm32; dest.m32 = m22 * rm32; dest.m33 = m23 * rm32; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; return this; } /** * Apply a symmetric perspective projection frustum transformation to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, * then the new matrix will be <code>M * P</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * P * v</code>, * the perspective projection will be applied first! * <p> * This method first computes the frustum corners using the specified parameters and then makes use of * {@link #frustum(float, float, float, float, float, float) frustum()} to finally apply the frustum * transformation. * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setPerspective(float, float, float, float) setPerspective}. * * @see #frustum(float, float, float, float, float, float) * @see #setPerspective(float, float, float, float) * * @param fovy * the vertical field of view in radians * @param aspect * the aspect ratio (i.e. width / height) * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @return this */ public Matrix4f perspective(float fovy, float aspect, float zNear, float zFar) { return perspective(fovy, aspect, zNear, zFar, this); } /** * Set this matrix to be a symmetric perspective projection frustum transformation. * <p> * This method first computes the frustum corners using the specified parameters and then makes use of * {@link #setFrustum(float, float, float, float, float, float) setFrustum()} to finally apply the frustum * transformation. * <p> * In order to apply the perspective projection transformation to an existing transformation, * use {@link #perspective(float, float, float, float) perspective()}. * * @see #setFrustum(float, float, float, float, float, float) * @see #perspective(float, float, float, float) * * @param fovy * the vertical field of view in radians * @param aspect * the aspect ratio (i.e. width / height) * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @return this */ public Matrix4f setPerspective(float fovy, float aspect, float zNear, float zFar) { float h = (float) Math.tan(fovy * 0.5f) * zNear; float w = h * aspect; m00 = zNear / w; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = zNear / h; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = -(zFar + zNear) / (zFar - zNear); m23 = -1.0f; m30 = 0.0f; m31 = 0.0f; m32 = -2.0f * zFar * zNear / (zFar - zNear); m33 = 0.0f; return this; } /** * Apply an arbitrary perspective projection frustum transformation to this matrix * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>F</code> the frustum matrix, * then the new matrix will be <code>M * F</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * F * v</code>, * the frustum transformation will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setFrustum(float, float, float, float, float, float) setFrustum()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #setFrustum(float, float, float, float, float, float) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * the distance along the z-axis to the near clipping plane * @param zFar * the distance along the z-axis to the far clipping plane * @param dest * will hold the result * @return this */ public Matrix4f frustum(float left, float right, float bottom, float top, float zNear, float zFar, Matrix4f dest) { // calculate right matrix elements float rm00 = 2.0f * zNear / (right - left); float rm11 = 2.0f * zNear / (top - bottom); float rm20 = (right + left) / (right - left); float rm21 = (top + bottom) / (top - bottom); float rm22 = -(zFar + zNear) / (zFar - zNear); float rm32 = -2.0f * zFar * zNear / (zFar - zNear); // perform optimized matrix multiplication float nm20 = m00 * rm20 + m10 * rm21 + m20 * rm22 - m30; float nm21 = m01 * rm20 + m11 * rm21 + m21 * rm22 - m31; float nm22 = m02 * rm20 + m12 * rm21 + m22 * rm22 - m32; float nm23 = m03 * rm20 + m13 * rm21 + m23 * rm22 - m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m30 = m20 * rm32; dest.m31 = m21 * rm32; dest.m32 = m22 * rm32; dest.m33 = m23 * rm32; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return this; } /** * Apply an arbitrary perspective projection frustum transformation to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>F</code> the frustum matrix, * then the new matrix will be <code>M * F</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * F * v</code>, * the frustum transformation will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setFrustum(float, float, float, float, float, float) setFrustum()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #setFrustum(float, float, float, float, float, float) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * the distance along the z-axis to the near clipping plane * @param zFar * the distance along the z-axis to the far clipping plane * @return this */ public Matrix4f frustum(float left, float right, float bottom, float top, float zNear, float zFar) { return frustum(left, right, bottom, top, zNear, zFar, this); } /** * Set this matrix to be an arbitrary perspective projection frustum transformation. * <p> * In order to apply the perspective frustum transformation to an existing transformation, * use {@link #frustum(float, float, float, float, float, float) frustum()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #frustum(float, float, float, float, float, float) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * the distance along the z-axis to the near clipping plane * @param zFar * the distance along the z-axis to the far clipping plane * @return this */ public Matrix4f setFrustum(float left, float right, float bottom, float top, float zNear, float zFar) { m00 = 2.0f * zNear / (right - left); m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 2.0f * zNear / (top - bottom); m12 = 0.0f; m13 = 0.0f; m20 = (right + left) / (right - left); m21 = (top + bottom) / (top - bottom); m22 = -(zFar + zNear) / (zFar - zNear); m23 = -1.0f; m30 = 0.0f; m31 = 0.0f; m32 = -2.0f * zFar * zNear / (zFar - zNear); m33 = 0.0f; return this; } /** * Apply the rotation transformation of the given {@link Quaternionf} to this matrix and store * the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>Q</code> the rotation matrix obtained from the given quaternion, * then the new matrix will be <code>M * Q</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * Q * v</code>, * the quaternion rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(Quaternionf)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> * * @see #rotation(Quaternionf) * * @param quat * the {@link Quaternionf} * @param dest * will hold the result * @return this */ public Matrix4f rotate(Quaternionf quat, Matrix4f dest) { float q00 = 2.0f * quat.x * quat.x; float q11 = 2.0f * quat.y * quat.y; float q22 = 2.0f * quat.z * quat.z; float q01 = 2.0f * quat.x * quat.y; float q02 = 2.0f * quat.x * quat.z; float q03 = 2.0f * quat.x * quat.w; float q12 = 2.0f * quat.y * quat.z; float q13 = 2.0f * quat.y * quat.w; float q23 = 2.0f * quat.z * quat.w; float rm00 = 1.0f - q11 - q22; float rm01 = q01 + q23; float rm02 = q02 - q13; float rm10 = q01 - q23; float rm11 = 1.0f - q22 - q00; float rm12 = q12 + q03; float rm20 = q02 + q13; float rm21 = q12 - q03; float rm22 = 1.0f - q11 - q00; float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return this; } /** * Apply the rotation transformation of the given {@link Quaternionf} to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>Q</code> the rotation matrix obtained from the given quaternion, * then the new matrix will be <code>M * Q</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * Q * v</code>, * the quaternion rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(Quaternionf)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> * * @see #rotation(Quaternionf) * * @param quat * the {@link Quaternionf} * @return this */ public Matrix4f rotate(Quaternionf quat) { return rotate(quat, this); } /** * Apply a rotation transformation, rotating about the given {@link AxisAngle4f}, to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>A</code> the rotation matrix obtained from the given {@link AxisAngle4f}, * then the new matrix will be <code>M * A</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * A * v</code>, * the {@link AxisAngle4f} rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(AxisAngle4f)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(float, float, float, float) * @see #rotation(AxisAngle4f) * * @param axisAngle * the {@link AxisAngle4f} (needs to be {@link AxisAngle4f#normalize() normalized}) * @return this */ public Matrix4f rotate(AxisAngle4f axisAngle) { return rotate(axisAngle.angle, axisAngle.x, axisAngle.y, axisAngle.z); } /** * Apply a rotation transformation, rotating about the given {@link AxisAngle4f} and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>A</code> the rotation matrix obtained from the given {@link AxisAngle4f}, * then the new matrix will be <code>M * A</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * A * v</code>, * the {@link AxisAngle4f} rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(AxisAngle4f)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(float, float, float, float) * @see #rotation(AxisAngle4f) * * @param axisAngle * the {@link AxisAngle4f} (needs to be {@link AxisAngle4f#normalize() normalized}) * @param dest * will hold the result * @return this */ public Matrix4f rotate(AxisAngle4f axisAngle, Matrix4f dest) { return rotate(axisAngle.angle, axisAngle.x, axisAngle.y, axisAngle.z, dest); } /** * Apply a rotation transformation, rotating the given radians about the specified axis, to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>A</code> the rotation matrix obtained from the given axis-angle, * then the new matrix will be <code>M * A</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * A * v</code>, * the axis-angle rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(float, Vector3f)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(float, float, float, float) * @see #rotation(float, Vector3f) * * @param angle * the angle in radians * @param axis * the rotation axis (needs to be {@link Vector3f#normalize() normalized}) * @return this */ public Matrix4f rotate(float angle, Vector3f axis) { return rotate(angle, axis.x, axis.y, axis.z); } /** * Apply a rotation transformation, rotating the given radians about the specified axis and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>A</code> the rotation matrix obtained from the given axis-angle, * then the new matrix will be <code>M * A</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * A * v</code>, * the axis-angle rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(float, Vector3f)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(float, float, float, float) * @see #rotation(float, Vector3f) * * @param angle * the angle in radians * @param axis * the rotation axis (needs to be {@link Vector3f#normalize() normalized}) * @param dest * will hold the result * @return this */ public Matrix4f rotate(float angle, Vector3f axis, Matrix4f dest) { return rotate(angle, axis.x, axis.y, axis.z, dest); } /** * Unproject the given window coordinates <tt>(winX, winY, winZ)</tt> by <code>this</code> matrix using the specified viewport. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by the inverse of <code>this</code> matrix. * <p> * The depth range of <tt>winZ</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * As a necessary computation step for unprojecting, this method computes the inverse of <code>this</code> matrix and stores * it into the <code>inverseOut</code> parameter matrix. In order to avoid computing the matrix inverse with every * invocation, the inverse of <code>this</code> matrix can be built once outside and then the method {@link #unprojectInv(float, float, float, IntBuffer, Vector4f) unprojectInv()} * can be invoked on it. * * @see #unprojectInv(float, float, float, IntBuffer, Vector4f) * * @param winX * the x-coordinate in window coordinates (pixels) * @param winY * the y-coordinate in window coordinates (pixels) * @param winZ * the z-coordinate, which is the depth value in <tt>[0..1]</tt> * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param inverseOut * will hold the inverse of <code>this</code> after the method returns * @param dest * will hold the unprojected position * @return this */ public Matrix4f unproject(float winX, float winY, float winZ, IntBuffer viewport, Matrix4f inverseOut, Vector4f dest) { this.invert(inverseOut); inverseOut.unprojectInv(winX, winY, winZ, viewport, dest); return this; } /** * Unproject the given window coordinates <tt>(winX, winY, winZ)</tt> by <code>this</code> matrix using the specified viewport. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by the inverse of <code>this</code> matrix. * <p> * The depth range of <tt>winZ</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * As a necessary computation step for unprojecting, this method computes the inverse of <code>this</code> matrix and stores * it into the <code>inverseOut</code> parameter matrix. In order to avoid computing the matrix inverse with every * invocation, the inverse of <code>this</code> matrix can be built once outside and then the method {@link #unprojectInv(float, float, float, IntBuffer, Vector4f) unprojectInv()} * can be invoked on it. * * @see #unprojectInv(float, float, float, IntBuffer, Vector3f) * * @param winX * the x-coordinate in window coordinates (pixels) * @param winY * the y-coordinate in window coordinates (pixels) * @param winZ * the z-coordinate, which is the depth value in <tt>[0..1]</tt> * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param inverseOut * will hold the inverse of <code>this</code> after the method returns * @param dest * will hold the unprojected position * @return this */ public Matrix4f unproject(float winX, float winY, float winZ, IntBuffer viewport, Matrix4f inverseOut, Vector3f dest) { this.invert(inverseOut); inverseOut.unprojectInv(winX, winY, winZ, viewport, dest); return this; } /** * Unproject the given window coordinates <code>winCoords</code> by <code>this</code> matrix using the specified viewport. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by the inverse of <code>this</code> matrix. * <p> * The depth range of <tt>winCoords.z</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * As a necessary computation step for unprojecting, this method computes the inverse of <code>this</code> matrix and stores * it into the <code>inverseOut</code> parameter matrix. In order to avoid computing the matrix inverse with every * invocation, the inverse of <code>this</code> matrix can be built once outside and then the method {@link #unprojectInv(float, float, float, IntBuffer, Vector4f) unprojectInv()} * can be invoked on it. * * @see #unprojectInv(float, float, float, IntBuffer, Vector4f) * @see #unproject(float, float, float, IntBuffer, Matrix4f, Vector4f) * * @param winCoords * the window coordinates to unproject * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param inverseOut * will hold the inverse of <code>this</code> after the method returns * @param dest * will hold the unprojected position * @return this */ public Matrix4f unproject(Vector3f winCoords, IntBuffer viewport, Matrix4f inverseOut, Vector4f dest) { return unproject(winCoords.x, winCoords.y, winCoords.z, viewport, inverseOut, dest); } /** * Unproject the given window coordinates <code>winCoords</code> by <code>this</code> matrix using the specified viewport. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by the inverse of <code>this</code> matrix. * <p> * The depth range of <tt>winCoords.z</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * As a necessary computation step for unprojecting, this method computes the inverse of <code>this</code> matrix and stores * it into the <code>inverseOut</code> parameter matrix. In order to avoid computing the matrix inverse with every * invocation, the inverse of <code>this</code> matrix can be built once outside and then the method {@link #unprojectInv(float, float, float, IntBuffer, Vector3f) unprojectInv()} * can be invoked on it. * * @see #unprojectInv(float, float, float, IntBuffer, Vector3f) * @see #unproject(float, float, float, IntBuffer, Matrix4f, Vector3f) * * @param winCoords * the window coordinates to unproject * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param inverseOut * will hold the inverse of <code>this</code> after the method returns * @param dest * will hold the unprojected position * @return this */ public Matrix4f unproject(Vector3f winCoords, IntBuffer viewport, Matrix4f inverseOut, Vector3f dest) { return unproject(winCoords.x, winCoords.y, winCoords.z, viewport, inverseOut, dest); } /** * Unproject the given window coordinates <code>winCoords</code> by <code>this</code> matrix using the specified viewport. * <p> * This method differs from {@link #unproject(Vector3f, IntBuffer, Matrix4f, Vector4f) unproject()} * in that it assumes that <code>this</code> is already the inverse matrix of the original projection matrix. * It exists to avoid recomputing the matrix inverse with every invocation. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by <code>this</code> matrix. * <p> * The depth range of <tt>winCoords.z</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * * @see #unproject(Vector3f, IntBuffer, Matrix4f, Vector4f) * * @param winCoords * the window coordinates to unproject * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return this */ public Matrix4f unprojectInv(Vector3f winCoords, IntBuffer viewport, Vector4f dest) { return unprojectInv(winCoords.x, winCoords.y, winCoords.z, viewport, dest); } /** * Unproject the given window coordinates <tt>(winX, winY, winZ)</tt> by <code>this</code> matrix using the specified viewport. * <p> * This method differs from {@link #unproject(float, float, float, IntBuffer, Matrix4f, Vector4f) unproject()} * in that it assumes that <code>this</code> is already the inverse matrix of the original projection matrix. * It exists to avoid recomputing the matrix inverse with every invocation. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by <code>this</code> matrix. * <p> * The depth range of <tt>winZ</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * * @see #unproject(float, float, float, IntBuffer, Matrix4f, Vector4f) * * @param winX * the x-coordinate in window coordinates (pixels) * @param winY * the y-coordinate in window coordinates (pixels) * @param winZ * the z-coordinate, which is the depth value in <tt>[0..1]</tt> * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return this */ public Matrix4f unprojectInv(float winX, float winY, float winZ, IntBuffer viewport, Vector4f dest) { int pos = viewport.position(); float ndcX = (winX-viewport.get(pos))/viewport.get(pos+2)*2.0f-1.0f; float ndcY = (winY-viewport.get(pos+1))/viewport.get(pos+3)*2.0f-1.0f; float ndcZ = 2.0f*winZ-1.0f; dest.x = m00 * ndcX + m10 * ndcY + m20 * ndcZ + m30; dest.y = m01 * ndcX + m11 * ndcY + m21 * ndcZ + m31; dest.z = m02 * ndcX + m12 * ndcY + m22 * ndcZ + m32; dest.w = m03 * ndcX + m13 * ndcY + m23 * ndcZ + m33; dest.div(dest.w); return this; } /** * Unproject the given window coordinates <code>winCoords</code> by <code>this</code> matrix using the specified viewport. * <p> * This method differs from {@link #unproject(Vector3f, IntBuffer, Matrix4f, Vector3f) unproject()} * in that it assumes that <code>this</code> is already the inverse matrix of the original projection matrix. * It exists to avoid recomputing the matrix inverse with every invocation. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by <code>this</code> matrix. * <p> * The depth range of <tt>winCoords.z</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * * @see #unproject(Vector3f, IntBuffer, Matrix4f, Vector3f) * * @param winCoords * the window coordinates to unproject * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return this */ public Matrix4f unprojectInv(Vector3f winCoords, IntBuffer viewport, Vector3f dest) { return unprojectInv(winCoords.x, winCoords.y, winCoords.z, viewport, dest); } /** * Unproject the given window coordinates <tt>(winX, winY, winZ)</tt> by <code>this</code> matrix using the specified viewport. * <p> * This method differs from {@link #unproject(float, float, float, IntBuffer, Matrix4f, Vector3f) unproject()} * in that it assumes that <code>this</code> is already the inverse matrix of the original projection matrix. * It exists to avoid recomputing the matrix inverse with every invocation. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by <code>this</code> matrix. * <p> * The depth range of <tt>winZ</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * * @see #unproject(float, float, float, IntBuffer, Matrix4f, Vector3f) * * @param winX * the x-coordinate in window coordinates (pixels) * @param winY * the y-coordinate in window coordinates (pixels) * @param winZ * the z-coordinate, which is the depth value in <tt>[0..1]</tt> * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return this */ public Matrix4f unprojectInv(float winX, float winY, float winZ, IntBuffer viewport, Vector3f dest) { int pos = viewport.position(); float ndcX = (winX-viewport.get(pos))/viewport.get(pos+2)*2.0f-1.0f; float ndcY = (winY-viewport.get(pos+1))/viewport.get(pos+3)*2.0f-1.0f; float ndcZ = 2.0f*winZ-1.0f; dest.x = m00 * ndcX + m10 * ndcY + m20 * ndcZ + m30; dest.y = m01 * ndcX + m11 * ndcY + m21 * ndcZ + m31; dest.z = m02 * ndcX + m12 * ndcY + m22 * ndcZ + m32; float w = m03 * ndcX + m13 * ndcY + m23 * ndcZ + m33; dest.div(w); return this; } /** * Unproject the given window coordinates <tt>(winX, winY, winZ)</tt> by the given <code>view</code> and <code>projection</code> matrices using the specified viewport. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by the inverse of <code>projection * view</code>. * <p> * The depth range of <tt>winZ</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * As a necessary computation step for unprojecting, this method computes the inverse of <code>projection * view</code> and stores * it into the <code>inverseOut</code> parameter matrix. In order to avoid computing the matrix inverse with every * invocation, the inverse of both matrices can be built once outside and then the method {@link #unprojectInv(float, float, float, IntBuffer, Vector4f) unprojectInv()} * can be invoked on it. * * @see #unprojectInv(float, float, float, IntBuffer, Vector4f) * * @param winX * the x-coordinate in window coordinates (pixels) * @param winY * the y-coordinate in window coordinates (pixels) * @param winZ * the z-coordinate, which is the depth value in <tt>[0..1]</tt> * @param projection * the projection matrix * @param view * the view matrix * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param inverseOut * will hold the inverse of <code>projection * view</code> after the method returns * @param dest * will hold the unprojected position */ public static void unproject(float winX, float winY, float winZ, Matrix4f projection, Matrix4f view, IntBuffer viewport, Matrix4f inverseOut, Vector4f dest) { inverseOut.set(projection).mul(view).invert().unprojectInv(winX, winY, winZ, viewport, dest); } /** * Unproject the given window coordinates <code>winCoords</code> by the given <code>view</code> and <code>projection</code> matrices using the specified viewport. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by the inverse of <code>projection * view</code>. * <p> * The depth range of <tt>winCoords.z</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * As a necessary computation step for unprojecting, this method computes the inverse of <code>projection * view</code> and stores * it into the <code>inverseOut</code> parameter matrix. In order to avoid computing the matrix inverse with every * invocation, the inverse of both matrices can be built once outside and then the method {@link #unprojectInv(float, float, float, IntBuffer, Vector4f) unprojectInv()} * can be invoked on it. * * @see #unprojectInv(float, float, float, IntBuffer, Vector4f) * * @param winCoords * the window coordinate to unproject * @param projection * the projection matrix * @param view * the view matrix * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param inverseOut * will hold the inverse of <code>projection * view</code> after the method returns * @param dest * will hold the unprojected position */ public static void unproject(Vector3f winCoords, Matrix4f projection, Matrix4f view, IntBuffer viewport, Matrix4f inverseOut, Vector4f dest) { unproject(winCoords.x, winCoords.y, winCoords.z, projection, view, viewport, inverseOut, dest); } /** * Project the given <tt>(x, y, z)</tt> position via <code>this</code> matrix using the specified viewport * and store the resulting window coordinates in <code>winCoordsDest</code>. * <p> * This method transforms the given coordinates by <code>this</code> matrix including perspective division to * obtain normalized device coordinates, and then translates these into window coordinates by using the * given <code>viewport</code> settings <tt>[x, y, width, height]</tt>. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * The depth range of the returned <code>winCoordsDest.z</code> will be <tt>[0..1]</tt>, which is also the OpenGL default. * * @param x * the x-coordinate of the position to project * @param y * the y-coordinate of the position to project * @param z * the z-coordinate of the position to project * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param winCoordsDest * will hold the projected window coordinates * @return this */ public Matrix4f project(float x, float y, float z, IntBuffer viewport, Vector4f winCoordsDest) { winCoordsDest.x = m00 * x + m10 * y + m20 * z + m30; winCoordsDest.y = m01 * x + m11 * y + m21 * z + m31; winCoordsDest.z = m02 * x + m12 * y + m22 * z + m32; winCoordsDest.w = m03 * x + m13 * y + m23 * z + m33; int pos = viewport.position(); winCoordsDest.div(winCoordsDest.w); winCoordsDest.x = (winCoordsDest.x*0.5f+0.5f) * viewport.get(pos+2) + viewport.get(pos); winCoordsDest.y = (winCoordsDest.y*0.5f+0.5f) * viewport.get(pos+3) + viewport.get(pos+1); winCoordsDest.z = (1.0f+winCoordsDest.z)*0.5f; return this; } /** * Project the given <tt>(x, y, z)</tt> position via <code>this</code> matrix using the specified viewport * and store the resulting window coordinates in <code>winCoordsDest</code>. * <p> * This method transforms the given coordinates by <code>this</code> matrix including perspective division to * obtain normalized device coordinates, and then translates these into window coordinates by using the * given <code>viewport</code> settings <tt>[x, y, width, height]</tt>. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * The depth range of the returned <code>winCoordsDest.z</code> will be <tt>[0..1]</tt>, which is also the OpenGL default. * * @param x * the x-coordinate of the position to project * @param y * the y-coordinate of the position to project * @param z * the z-coordinate of the position to project * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param winCoordsDest * will hold the projected window coordinates * @return this */ public Matrix4f project(float x, float y, float z, IntBuffer viewport, Vector3f winCoordsDest) { winCoordsDest.x = m00 * x + m10 * y + m20 * z + m30; winCoordsDest.y = m01 * x + m11 * y + m21 * z + m31; winCoordsDest.z = m02 * x + m12 * y + m22 * z + m32; float w = m03 * x + m13 * y + m23 * z + m33; int pos = viewport.position(); winCoordsDest.div(w); winCoordsDest.x = (winCoordsDest.x*0.5f+0.5f) * viewport.get(pos+2) + viewport.get(pos); winCoordsDest.y = (winCoordsDest.y*0.5f+0.5f) * viewport.get(pos+3) + viewport.get(pos+1); winCoordsDest.z = (1.0f+winCoordsDest.z)*0.5f; return this; } /** * Project the given <code>position</code> via <code>this</code> matrix using the specified viewport * and store the resulting window coordinates in <code>winCoordsDest</code>. * <p> * This method transforms the given coordinates by <code>this</code> matrix including perspective division to * obtain normalized device coordinates, and then translates these into window coordinates by using the * given <code>viewport</code> settings <tt>[x, y, width, height]</tt>. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * The depth range of the returned <code>winCoordsDest.z</code> will be <tt>[0..1]</tt>, which is also the OpenGL default. * * @see #project(float, float, float, IntBuffer, Vector4f) * * @param position * the position to project into window coordinates * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param winCoordsDest * will hold the projected window coordinates * @return this */ public Matrix4f project(Vector3f position, IntBuffer viewport, Vector4f winCoordsDest) { return project(position.x, position.y, position.z, viewport, winCoordsDest); } /** * Project the given <code>position</code> via <code>this</code> matrix using the specified viewport * and store the resulting window coordinates in <code>winCoordsDest</code>. * <p> * This method transforms the given coordinates by <code>this</code> matrix including perspective division to * obtain normalized device coordinates, and then translates these into window coordinates by using the * given <code>viewport</code> settings <tt>[x, y, width, height]</tt>. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * The depth range of the returned <code>winCoordsDest.z</code> will be <tt>[0..1]</tt>, which is also the OpenGL default. * * @see #project(float, float, float, IntBuffer, Vector4f) * * @param position * the position to project into window coordinates * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param winCoordsDest * will hold the projected window coordinates * @return this */ public Matrix4f project(Vector3f position, IntBuffer viewport, Vector3f winCoordsDest) { return project(position.x, position.y, position.z, viewport, winCoordsDest); } /** * Project the given <tt>(x, y, z)</tt> position via the given <code>view</code> and <code>projection</code> matrices using the specified viewport * and store the resulting window coordinates in <code>winCoordsDest</code>. * <p> * This method transforms the given coordinates by <code>projection * view</code> including perspective division to * obtain normalized device coordinates, and then translates these into window coordinates by using the * given <code>viewport</code> settings <tt>[x, y, width, height]</tt>. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * The depth range of the returned <code>winCoordsDest.z</code> will be <tt>[0..1]</tt>, which is also the OpenGL default. * * @param x * the x-coordinate of the position to project * @param y * the y-coordinate of the position to project * @param z * the z-coordinate of the position to project * @param projection * the projection matrix * @param view * the view matrix * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param winCoordsDest * will hold the projected window coordinates */ public static void project(float x, float y, float z, Matrix4f projection, Matrix4f view, IntBuffer viewport, Vector4f winCoordsDest) { winCoordsDest.set(x, y, z, 1.0f); view.transform(winCoordsDest); projection.transform(winCoordsDest); int pos = viewport.position(); winCoordsDest.div(winCoordsDest.w); winCoordsDest.x = (winCoordsDest.x*0.5f+0.5f) * viewport.get(pos+2) + viewport.get(pos); winCoordsDest.y = (winCoordsDest.y*0.5f+0.5f) * viewport.get(pos+3) + viewport.get(pos+1); winCoordsDest.z = (1.0f+winCoordsDest.z)*0.5f; } /** * Project the given <code>position</code> via the given <code>view</code> and <code>projection</code> matrices using the specified viewport * and store the resulting window coordinates in <code>winCoordsDest</code>. * <p> * This method transforms the given coordinates by <code>projection * view</code> including perspective division to * obtain normalized device coordinates, and then translates these into window coordinates by using the * given <code>viewport</code> settings <tt>[x, y, width, height]</tt>. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * The depth range of the returned <code>winCoordsDest.z</code> will be <tt>[0..1]</tt>, which is also the OpenGL default. * * @see #project(float, float, float, Matrix4f, Matrix4f, IntBuffer, Vector4f) * * @param position * the position to project into window coordinates * @param projection * the projection matrix * @param view * the view matrix * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param winCoordsDest * will hold the projected window coordinates */ public static void project(Vector3f position, Matrix4f projection, Matrix4f view, IntBuffer viewport, Vector4f winCoordsDest) { project(position.x, position.y, position.z, projection, view, viewport, winCoordsDest); } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the equation <tt>x*a + y*b + z*c + d = 0</tt> and store the result in <code>dest</code>. * <p> * The vector <tt>(a, b, c)</tt> must be a unit vector. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb281733(v=vs.85).aspx">msdn.microsoft.com</a> * * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @param dest * will hold the result * @return this */ public Matrix4f reflect(float a, float b, float c, float d, Matrix4f dest) { float rm00 = 1.0f - 2.0f * a * a; float rm01 = -2.0f * a * b; float rm02 = -2.0f * a * c; float rm10 = -2.0f * a * b; float rm11 = 1.0f - 2.0f * b * b; float rm12 = -2.0f * b * c; float rm20 = -2.0f * a * c; float rm21 = -2.0f * b * c; float rm22 = 1.0f - 2.0f * c * c; float rm30 = -2.0f * a * d; float rm31 = -2.0f * b * d; float rm32 = -2.0f * c * d; // matrix multiplication dest.m30 = m00 * rm30 + m10 * rm31 + m20 * rm32 + m30; dest.m31 = m01 * rm30 + m11 * rm31 + m21 * rm32 + m31; dest.m32 = m02 * rm30 + m12 * rm31 + m22 * rm32 + m32; dest.m33 = m03 * rm30 + m13 * rm31 + m23 * rm32 + m33; float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; return this; } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the equation <tt>x*a + y*b + z*c + d = 0</tt>. * <p> * The vector <tt>(a, b, c)</tt> must be a unit vector. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb281733(v=vs.85).aspx">msdn.microsoft.com</a> * * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @return this */ public Matrix4f reflect(float a, float b, float c, float d) { return reflect(a, b, c, d, this); } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the plane normal and a point on the plane. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param nx * the x-coordinate of the plane normal * @param ny * the y-coordinate of the plane normal * @param nz * the z-coordinate of the plane normal * @param px * the x-coordinate of a point on the plane * @param py * the y-coordinate of a point on the plane * @param pz * the z-coordinate of a point on the plane * @return this */ public Matrix4f reflect(float nx, float ny, float nz, float px, float py, float pz) { return reflect(nx, ny, nz, px, py, pz, this); } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the plane normal and a point on the plane, and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param nx * the x-coordinate of the plane normal * @param ny * the y-coordinate of the plane normal * @param nz * the z-coordinate of the plane normal * @param px * the x-coordinate of a point on the plane * @param py * the y-coordinate of a point on the plane * @param pz * the z-coordinate of a point on the plane * @param dest * will hold the result * @return this */ public Matrix4f reflect(float nx, float ny, float nz, float px, float py, float pz, Matrix4f dest) { float length = (float) Math.sqrt(nx * nx + ny * ny + nz * nz); float nnx = nx / length; float nny = ny / length; float nnz = nz / length; /* See: http://mathworld.wolfram.com/Plane.html */ return reflect(nnx, nny, nnz, -nnx * px - nny * py - nnz * pz, dest); } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the plane normal and a point on the plane. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param normal * the plane normal * @param point * a point on the plane * @return this */ public Matrix4f reflect(Vector3f normal, Vector3f point) { return reflect(normal.x, normal.y, normal.z, point.x, point.y, point.z); } /** * Apply a mirror/reflection transformation to this matrix that reflects about a plane * specified via the plane orientation and a point on the plane. * <p> * This method can be used to build a reflection transformation based on the orientation of a mirror object in the scene. * It is assumed that the default mirror plane's normal is <tt>(0, 0, 1)</tt>. So, if the given {@link Quaternionf} is * the identity (does not apply any additional rotation), the reflection plane will be <tt>z=0</tt>, offset by the given <code>point</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param orientation * the plane orientation * @param point * a point on the plane * @return this */ public Matrix4f reflect(Quaternionf orientation, Vector3f point) { return reflect(orientation, point, this); } /** * Apply a mirror/reflection transformation to this matrix that reflects about a plane * specified via the plane orientation and a point on the plane, and store the result in <code>dest</code>. * <p> * This method can be used to build a reflection transformation based on the orientation of a mirror object in the scene. * It is assumed that the default mirror plane's normal is <tt>(0, 0, 1)</tt>. So, if the given {@link Quaternionf} is * the identity (does not apply any additional rotation), the reflection plane will be <tt>z=0</tt>, offset by the given <code>point</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param orientation * the plane orientation * @param point * a point on the plane * @param dest * will hold the result * @return this */ public Matrix4f reflect(Quaternionf orientation, Vector3f point, Matrix4f dest) { double num1 = orientation.x * 2.0; double num2 = orientation.y * 2.0; double num3 = orientation.z * 2.0; float normalX = (float) (orientation.x * num3 + orientation.w * num2); float normalY = (float) (orientation.y * num3 - orientation.w * num1); float normalZ = (float) (1.0 - (orientation.x * num1 + orientation.y * num2)); return reflect(normalX, normalY, normalZ, point.x, point.y, point.z, dest); } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the plane normal and a point on the plane, and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param normal * the plane normal * @param point * a point on the plane * @param dest * will hold the result * @return this */ public Matrix4f reflect(Vector3f normal, Vector3f point, Matrix4f dest) { return reflect(normal.x, normal.y, normal.z, point.x, point.y, point.z, dest); } /** * Set this matrix to a mirror/reflection transformation that reflects about the given plane * specified via the equation <tt>x*a + y*b + z*c + d = 0</tt>. * <p> * The vector <tt>(a, b, c)</tt> must be a unit vector. * <p> * Reference: <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb281733(v=vs.85).aspx">msdn.microsoft.com</a> * * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @return this */ public Matrix4f reflection(float a, float b, float c, float d) { m00 = 1.0f - 2.0f * a * a; m01 = -2.0f * a * b; m02 = -2.0f * a * c; m03 = 0.0f; m10 = -2.0f * a * b; m11 = 1.0f - 2.0f * b * b; m12 = -2.0f * b * c; m13 = 0.0f; m20 = -2.0f * a * c; m21 = -2.0f * b * c; m22 = 1.0f - 2.0f * c * c; m23 = 0.0f; m30 = -2.0f * a * d; m31 = -2.0f * b * d; m32 = -2.0f * c * d; m33 = 1.0f; return this; } /** * Set this matrix to a mirror/reflection transformation that reflects about the given plane * specified via the plane normal and a point on the plane. * * @param nx * the x-coordinate of the plane normal * @param ny * the y-coordinate of the plane normal * @param nz * the z-coordinate of the plane normal * @param px * the x-coordinate of a point on the plane * @param py * the y-coordinate of a point on the plane * @param pz * the z-coordinate of a point on the plane * @return this */ public Matrix4f reflection(float nx, float ny, float nz, float px, float py, float pz) { float length = (float) Math.sqrt(nx * nx + ny * ny + nz * nz); float nnx = nx / length; float nny = ny / length; float nnz = nz / length; /* See: http://mathworld.wolfram.com/Plane.html */ return reflection(nnx, nny, nnz, -nnx * px - nny * py - nnz * pz); } /** * Set this matrix to a mirror/reflection transformation that reflects about the given plane * specified via the plane normal and a point on the plane. * * @param normal * the plane normal * @param point * a point on the plane * @return this */ public Matrix4f reflection(Vector3f normal, Vector3f point) { return reflection(normal.x, normal.y, normal.z, point.x, point.y, point.z); } /** * Set this matrix to a mirror/reflection transformation that reflects about a plane * specified via the plane orientation and a point on the plane. * <p> * This method can be used to build a reflection transformation based on the orientation of a mirror object in the scene. * It is assumed that the default mirror plane's normal is <tt>(0, 0, 1)</tt>. So, if the given {@link Quaternionf} is * the identity (does not apply any additional rotation), the reflection plane will be <tt>z=0</tt>, offset by the given <code>point</code>. * * @param orientation * the plane orientation * @param point * a point on the plane * @return this */ public Matrix4f reflection(Quaternionf orientation, Vector3f point) { double num1 = orientation.x * 2.0; double num2 = orientation.y * 2.0; double num3 = orientation.z * 2.0; float normalX = (float) (orientation.x * num3 + orientation.w * num2); float normalY = (float) (orientation.y * num3 - orientation.w * num1); float normalZ = (float) (1.0 - (orientation.x * num1 + orientation.y * num2)); return reflection(normalX, normalY, normalZ, point.x, point.y, point.z); } /** * Get the row at the given <code>row</code> index, starting with <code>0</code>. * * @param row * the row index in <tt>[0..3]</tt> * @param dest * will hold the row components * @throws IndexOutOfBoundsException if <code>row</code> is not in <tt>[0..3]</tt> */ public void getRow(int row, Vector4f dest) throws IndexOutOfBoundsException { switch (row) { case 0: dest.x = m00; dest.y = m10; dest.z = m20; dest.w = m30; break; case 1: dest.x = m01; dest.y = m11; dest.z = m21; dest.w = m31; break; case 2: dest.x = m02; dest.y = m12; dest.z = m22; dest.w = m32; break; case 3: dest.x = m03; dest.y = m13; dest.z = m23; dest.w = m33; break; default: throw new IndexOutOfBoundsException(); } } /** * Get the column at the given <code>column</code> index, starting with <code>0</code>. * * @param column * the column index in <tt>[0..3]</tt> * @param dest * will hold the column components * @throws IndexOutOfBoundsException if <code>column</code> is not in <tt>[0..3]</tt> */ public void getColumn(int column, Vector4f dest) throws IndexOutOfBoundsException { switch (column) { case 0: dest.x = m00; dest.y = m01; dest.z = m02; dest.w = m03; break; case 1: dest.x = m10; dest.y = m11; dest.z = m12; dest.w = m13; break; case 2: dest.x = m20; dest.y = m21; dest.z = m22; dest.w = m23; break; case 3: dest.x = m30; dest.y = m31; dest.z = m32; dest.w = m32; break; default: throw new IndexOutOfBoundsException(); } } /** * Return the specified {@link Matrix4f}. * <p> * When using method chaining in a fluent interface style, this method can be used to switch * the <i>context object</i>, on which further method invocations operate, to be the given matrix. * * @param other * the {@link Matrix4f} to return * @return that matrix */ public Matrix4f with(Matrix4f other) { return other; } /** * Return the specified {@link Matrix4d}. * <p> * When using method chaining in a fluent interface style, this method can be used to switch * the <i>context object</i>, on which further method invocations operate, to be the given matrix. * * @param other * the {@link Matrix4d} to return * @return that matrix */ public Matrix4d with(Matrix4d other) { return other; } /** * Return the specified {@link Vector3f}. * <p> * When using method chaining in a fluent interface style, this method can be used to switch * the <i>context object</i>, on which further method invocations operate, to be the given vector. * * @param v * the {@link Vector3f} to return * @return that vector */ public Vector3f with(Vector3f v) { return v; } /** * Return the specified {@link Vector4f}. * <p> * When using method chaining in a fluent interface style, this method can be used to switch * the <i>context object</i>, on which further method invocations operate, to be the given vector. * * @param v * the {@link Vector4f} to return * @return that vector */ public Vector4f with(Vector4f v) { return v; } /** * Return the specified {@link Quaternionf}. * <p> * When using method chaining in a fluent interface style, this method can be used to switch * the <i>context object</i>, on which further method invocations operate, to be the given quaternion. * * @param q * the {@link Quaternionf} to return * @return that quaternion */ public Quaternionf with(Quaternionf q) { return q; } /** * Return the specified {@link Quaterniond}. * <p> * When using method chaining in a fluent interface style, this method can be used to switch * the <i>context object</i>, on which further method invocations operate, to be the given quaternion. * * @param q * the {@link Quaterniond} to return * @return that quaternion */ public Quaterniond with(Quaterniond q) { return q; } /** * Return the specified {@link AxisAngle4f}. * <p> * When using method chaining in a fluent interface style, this method can be used to switch * the <i>context object</i>, on which further method invocations operate, to be the given {@link AxisAngle4f}. * * @param a * the {@link AxisAngle4f} to return * @return that quaternion */ public AxisAngle4f with(AxisAngle4f a) { return a; } /** * Return the specified {@link Matrix3f}. * <p> * When using method chaining in a fluent interface style, this method can be used to switch * the <i>context object</i>, on which further method invocations operate, to be the given matrix. * * @param m * the {@link Matrix3f} to return * @return that matrix */ public Matrix3f with(Matrix3f m) { return m; } /** * Compute a normal matrix from the top-left 3x3 submatrix of <code>this</code> * and store it into the top-left 3x3 submatrix of <code>dest</code>. * All other values of <code>dest</code> will be set to {@link #identity() identity}. * <p> * The normal matrix of <tt>m</tt> is the transpose of the inverse of <tt>m</tt>. * In the special case of an orthonormal 3x3 matrix (one that maps any two perpendicular * unit vectors to another pair of perpendicular unit vectors) only the transpose is * computed. * * @param dest * will hold the result * @return this */ public Matrix4f normal(Matrix4f dest) { // see: http://mathworld.wolfram.com/OrthogonalMatrix.html float det = determinant3x3(); float diff = Math.abs(Math.abs(det) - 1.0f); if (diff < 1E-8f) { /* * The fast path, if only 1:1:1 scaling is being used. * In this case, the inverse is the transpose and we can * just return 'this'. */ dest.m00 = m00; dest.m01 = m01; dest.m02 = m02; dest.m03 = 0.0f; dest.m10 = m10; dest.m11 = m11; dest.m12 = m12; dest.m13 = 0.0f; dest.m20 = m20; dest.m21 = m21; dest.m22 = m22; dest.m23 = 0.0f; dest.m30 = 0.0f; dest.m31 = 0.0f; dest.m32 = 0.0f; dest.m33 = 1.0f; return this; } /* The general case */ float s = 1.0f / det; /* Invert and transpose in one go */ dest.set((m11 * m22 - m21 * m12) * s, -(m10 * m22 - m20 * m12) * s, (m10 * m21 - m20 * m11) * s, 0.0f, -(m01 * m22 - m21 * m02) * s, (m00 * m22 - m20 * m02) * s, -(m00 * m21 - m20 * m01) * s, 0.0f, (m01 * m12 - m11 * m02) * s, -(m00 * m12 - m10 * m02) * s, (m00 * m11 - m10 * m01) * s, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); return this; } /** * Compute a normal matrix from the top-left 3x3 submatrix of <code>this</code> * and store it into <code>dest</code>. * <p> * The normal matrix of <tt>m</tt> is the transpose of the inverse of <tt>m</tt>. * In the special case of an orthonormal 3x3 matrix (one that maps any two perpendicular * unit vectors to another pair of perpendicular unit vectors) only the transpose is * computed. * * @param dest * will hold the result * @return this */ public Matrix4f normal(Matrix3f dest) { // see: http://mathworld.wolfram.com/OrthogonalMatrix.html float det = determinant3x3(); float diff = Math.abs(Math.abs(det) - 1.0f); if (diff < 1E-8f) { /* * The fast path, if only 1:1:1 scaling is being used. * In this case, the inverse is the transpose and we can * just return 'this'. */ dest.m00 = m00; dest.m01 = m01; dest.m02 = m02; dest.m10 = m10; dest.m11 = m11; dest.m12 = m12; dest.m20 = m20; dest.m21 = m21; dest.m22 = m22; return this; } /* The general case */ float s = 1.0f / det; /* Invert and transpose in one go */ dest.m00 = (m11 * m22 - m21 * m12) * s; dest.m01 = -(m10 * m22 - m20 * m12) * s; dest.m02 = (m10 * m21 - m20 * m11) * s; dest.m10 = -(m01 * m22 - m21 * m02) * s; dest.m11 = (m00 * m22 - m20 * m02) * s; dest.m12 = -(m00 * m21 - m20 * m01) * s; dest.m20 = (m01 * m12 - m11 * m02) * s; dest.m21 = -(m00 * m12 - m10 * m02) * s; dest.m22 = (m00 * m11 - m10 * m01) * s; return this; } /** * Normalize the upper left 3x3 submatrix of this matrix. * <p> * The resulting matrix will map unit vectors to unit vectors, though a pair of orthogonal input unit * vectors need not be mapped to a pair of orthogonal output vectors if the original matrix was not orthogonal itself * (i.e. had <i>skewing</i>). * * @return this */ public Matrix4f normalize3x3() { return normalize3x3(this); } /** * Normalize the upper left 3x3 submatrix of this matrix and store the result in <code>dest</code>. * <p> * The resulting matrix will map unit vectors to unit vectors, though a pair of orthogonal input unit * vectors need not be mapped to a pair of orthogonal output vectors if the original matrix was not orthogonal itself * (i.e. had <i>skewing</i>). * * @param dest * will hold the result * @return this */ public Matrix4f normalize3x3(Matrix4f dest) { float xlen = (float) Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02); float ylen = (float) Math.sqrt(m10 * m10 + m11 * m11 + m12 * m12); float zlen = (float) Math.sqrt(m20 * m20 + m21 * m21 + m22 * m22); dest.m00 = m00 / xlen; dest.m01 = m01 / xlen; dest.m02 = m02 / xlen; dest.m10 = m10 / ylen; dest.m11 = m11 / ylen; dest.m12 = m12 / ylen; dest.m20 = m20 / zlen; dest.m21 = m21 / zlen; dest.m22 = m22 / zlen; return this; } /** * Normalize the upper left 3x3 submatrix of this matrix and store the result in <code>dest</code>. * <p> * The resulting matrix will map unit vectors to unit vectors, though a pair of orthogonal input unit * vectors need not be mapped to a pair of orthogonal output vectors if the original matrix was not orthogonal itself * (i.e. had <i>skewing</i>). * * @param dest * will hold the result * @return this */ public Matrix4f normalize3x3(Matrix3f dest) { float xlen = (float) Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02); float ylen = (float) Math.sqrt(m10 * m10 + m11 * m11 + m12 * m12); float zlen = (float) Math.sqrt(m20 * m20 + m21 * m21 + m22 * m22); dest.m00 = m00 / xlen; dest.m01 = m01 / xlen; dest.m02 = m02 / xlen; dest.m10 = m10 / ylen; dest.m11 = m11 / ylen; dest.m12 = m12 / ylen; dest.m20 = m20 / zlen; dest.m21 = m21 / zlen; dest.m22 = m22 / zlen; return this; } /** * Calculate a frustum plane of <code>this</code> matrix, which * can be a projection matrix or a combined modelview-projection matrix, and store the result * in the given <code>planeEquation</code>. * <p> * Generally, this method computes the frustum plane in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * The frustum plane will be given in the form of a general plane equation: * <tt>a*x + b*y + c*z + d = 0</tt>, where the given {@link Vector4f} components will * hold the <tt>(a, b, c, d)</tt> values of the equation. * <p> * The plane normal, which is <tt>(a, b, c)</tt>, is directed "inwards" of the frustum. * Any plane/point test using <tt>a*x + b*y + c*z + d</tt> therefore will yield a result greater than zero * if the point is within the frustum (i.e. at the <i>positive</i> side of the frustum plane). * <p> * Reference: <a href="http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @param plane * one of the six possible planes, given as numeric constants * {@link #PLANE_NX}, {@link #PLANE_PX}, * {@link #PLANE_NY}, {@link #PLANE_PY}, * {@link #PLANE_NZ} and {@link #PLANE_PZ} * @param planeEquation * will hold the computed plane equation. * The plane equation will be normalized, meaning that <tt>(a, b, c)</tt> will be a unit vector * @return this */ public Matrix4f frustumPlane(int plane, Vector4f planeEquation) { switch (plane) { case PLANE_NX: planeEquation.set(m03 + m00, m13 + m10, m23 + m20, m33 + m30).normalize3(); break; case PLANE_PX: planeEquation.set(m03 - m00, m13 - m10, m23 - m20, m33 - m30).normalize3(); break; case PLANE_NY: planeEquation.set(m03 + m01, m13 + m11, m23 + m21, m33 + m31).normalize3(); break; case PLANE_PY: planeEquation.set(m03 - m01, m13 - m11, m23 - m21, m33 - m31).normalize3(); break; case PLANE_NZ: planeEquation.set(m03 + m02, m13 + m12, m23 + m22, m33 + m32).normalize3(); break; case PLANE_PZ: planeEquation.set(m03 - m02, m13 - m12, m23 - m22, m33 - m32).normalize3(); break; default: throw new IllegalArgumentException("plane"); //$NON-NLS-1$ } return this; } /** * Compute the corner coordinates of the frustum defined by <code>this</code> matrix, which * can be a projection matrix or a combined modelview-projection matrix, and store the result * in the given <code>point</code>. * <p> * Generally, this method computes the frustum corners in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * Reference: <a href="http://geomalgorithms.com/a05-_intersect-1.html">http://geomalgorithms.com</a> * <p> * Reference: <a href="http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @param corner * one of the eight possible corners, given as numeric constants * {@link #CORNER_NXNYNZ}, {@link #CORNER_PXNYNZ}, {@link #CORNER_PXPYNZ}, {@link #CORNER_NXPYNZ}, * {@link #CORNER_PXNYPZ}, {@link #CORNER_NXNYPZ}, {@link #CORNER_NXPYPZ}, {@link #CORNER_PXPYPZ} * @param point * will hold the resulting corner point coordinates * @return this */ public Matrix4f frustumCorner(int corner, Vector3f point) { float d1, d2, d3; float n1x, n1y, n1z, n2x, n2y, n2z, n3x, n3y, n3z; switch (corner) { case CORNER_NXNYNZ: // left, bottom, near n1x = m03 + m00; n1y = m13 + m10; n1z = m23 + m20; d1 = m33 + m30; // left n2x = m03 + m01; n2y = m13 + m11; n2z = m23 + m21; d2 = m33 + m31; // bottom n3x = m03 + m02; n3y = m13 + m12; n3z = m23 + m22; d3 = m33 + m32; // near break; case CORNER_PXNYNZ: // right, bottom, near n1x = m03 - m00; n1y = m13 - m10; n1z = m23 - m20; d1 = m33 - m30; // right n2x = m03 + m01; n2y = m13 + m11; n2z = m23 + m21; d2 = m33 + m31; // bottom n3x = m03 + m02; n3y = m13 + m12; n3z = m23 + m22; d3 = m33 + m32; // near break; case CORNER_PXPYNZ: // right, top, near n1x = m03 - m00; n1y = m13 - m10; n1z = m23 - m20; d1 = m33 - m30; // right n2x = m03 - m01; n2y = m13 - m11; n2z = m23 - m21; d2 = m33 - m31; // top n3x = m03 + m02; n3y = m13 + m12; n3z = m23 + m22; d3 = m33 + m32; // near break; case CORNER_NXPYNZ: // left, top, near n1x = m03 + m00; n1y = m13 + m10; n1z = m23 + m20; d1 = m33 + m30; // left n2x = m03 - m01; n2y = m13 - m11; n2z = m23 - m21; d2 = m33 - m31; // top n3x = m03 + m02; n3y = m13 + m12; n3z = m23 + m22; d3 = m33 + m32; // near break; case CORNER_PXNYPZ: // right, bottom, far n1x = m03 - m00; n1y = m13 - m10; n1z = m23 - m20; d1 = m33 - m30; // right n2x = m03 + m01; n2y = m13 + m11; n2z = m23 + m21; d2 = m33 + m31; // bottom n3x = m03 - m02; n3y = m13 - m12; n3z = m23 - m22; d3 = m33 - m32; // far break; case CORNER_NXNYPZ: // left, bottom, far n1x = m03 + m00; n1y = m13 + m10; n1z = m23 + m20; d1 = m33 + m30; // left n2x = m03 + m01; n2y = m13 + m11; n2z = m23 + m21; d2 = m33 + m31; // bottom n3x = m03 - m02; n3y = m13 - m12; n3z = m23 - m22; d3 = m33 - m32; // far break; case CORNER_NXPYPZ: // left, top, far n1x = m03 + m00; n1y = m13 + m10; n1z = m23 + m20; d1 = m33 + m30; // left n2x = m03 - m01; n2y = m13 - m11; n2z = m23 - m21; d2 = m33 - m31; // top n3x = m03 - m02; n3y = m13 - m12; n3z = m23 - m22; d3 = m33 - m32; // far break; case CORNER_PXPYPZ: // right, top, far n1x = m03 - m00; n1y = m13 - m10; n1z = m23 - m20; d1 = m33 - m30; // right n2x = m03 - m01; n2y = m13 - m11; n2z = m23 - m21; d2 = m33 - m31; // top n3x = m03 - m02; n3y = m13 - m12; n3z = m23 - m22; d3 = m33 - m32; // far break; default: throw new IllegalArgumentException("corner"); //$NON-NLS-1$ } float c23x, c23y, c23z; c23x = n2y * n3z - n2z * n3y; c23y = n2z * n3x - n2x * n3z; c23z = n2x * n3y - n2y * n3x; float c31x, c31y, c31z; c31x = n3y * n1z - n3z * n1y; c31y = n3z * n1x - n3x * n1z; c31z = n3x * n1y - n3y * n1x; float c12x, c12y, c12z; c12x = n1y * n2z - n1z * n2y; c12y = n1z * n2x - n1x * n2z; c12z = n1x * n2y - n1y * n2x; float dot = n1x * c23x + n1y * c23y + n1z * c23z; point.x = (-c23x * d1 - c31x * d2 - c12x * d3) / dot; point.y = (-c23y * d1 - c31y * d2 - c12y * d3) / dot; point.z = (-c23z * d1 - c31z * d2 - c12z * d3) / dot; return this; } /** * Compute the eye/origin of the perspective frustum transformation defined by <code>this</code> matrix, * which can be a projection matrix or a combined modelview-projection matrix, and store the result * in the given <code>origin</code>. * <p> * Note that this method will only work using perspective projections obtained via one of the * perspective methods, such as {@link #perspective(float, float, float, float) perspective()} * or {@link #frustum(float, float, float, float, float, float) frustum()}. * <p> * Generally, this method computes the origin in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * Reference: <a href="http://geomalgorithms.com/a05-_intersect-1.html">http://geomalgorithms.com</a> * <p> * Reference: <a href="http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @param origin * will hold the origin of the coordinate system before applying <code>this</code> * perspective projection transformation * @return this */ public Matrix4f perspectiveOrigin(Vector3f origin) { /* * Simply compute the intersection point of the left, right and top frustum plane. */ float d1, d2, d3; float n1x, n1y, n1z, n2x, n2y, n2z, n3x, n3y, n3z; n1x = m03 + m00; n1y = m13 + m10; n1z = m23 + m20; d1 = m33 + m30; // left n2x = m03 - m00; n2y = m13 - m10; n2z = m23 - m20; d2 = m33 - m30; // right n3x = m03 - m01; n3y = m13 - m11; n3z = m23 - m21; d3 = m33 - m31; // top float c23x, c23y, c23z; c23x = n2y * n3z - n2z * n3y; c23y = n2z * n3x - n2x * n3z; c23z = n2x * n3y - n2y * n3x; float c31x, c31y, c31z; c31x = n3y * n1z - n3z * n1y; c31y = n3z * n1x - n3x * n1z; c31z = n3x * n1y - n3y * n1x; float c12x, c12y, c12z; c12x = n1y * n2z - n1z * n2y; c12y = n1z * n2x - n1x * n2z; c12z = n1x * n2y - n1y * n2x; float dot = n1x * c23x + n1y * c23y + n1z * c23z; origin.x = (-c23x * d1 - c31x * d2 - c12x * d3) / dot; origin.y = (-c23y * d1 - c31y * d2 - c12y * d3) / dot; origin.z = (-c23z * d1 - c31z * d2 - c12z * d3) / dot; return this; } /** * Return the vertical field-of-view angle in radians of this perspective transformation matrix. * <p> * Note that this method will only work using perspective projections obtained via one of the * perspective methods, such as {@link #perspective(float, float, float, float) perspective()} * or {@link #frustum(float, float, float, float, float, float) frustum()}. * <p> * For orthogonal transformations this method will return <tt>0.0</tt>. * <p> * Reference: <a href="http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @return the vertical field-of-view angle in radians */ public float perspectiveFov() { /* * Compute the angle between the bottom and top frustum plane normals. */ float n1x, n1y, n1z, n2x, n2y, n2z; n1x = m03 + m01; n1y = m13 + m11; n1z = m23 + m21; // bottom n2x = m01 - m03; n2y = m11 - m13; n2z = m21 - m23; // top float n1len = (float) Math.sqrt(n1x * n1x + n1y * n1y + n1z * n1z); float n2len = (float) Math.sqrt(n2x * n2x + n2y * n2y + n2z * n2z); return (float) Math.acos((n1x * n2x + n1y * n2y + n1z * n2z) / (n1len * n2len)); } /** * Determine whether the given point is within the viewing frustum * defined by <code>this</code> matrix. * <p> * This method computes the frustum planes in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * If multiple points are to be tested on the same frustum, create a {@link FrustumCuller} from this matrix instead. * * @see #frustumPlane(int, Vector4f) * @see #isPointInsideFrustum(float, float, float) * * @param point * the point to test * @return <code>true</code> if the given point is inside the clipping frustum; <code>false</code> otherwise */ public boolean isPointInsideFrustum(Vector3f point) { return isPointInsideFrustum(point.x, point.y, point.z); } /** * Determine whether the given point <tt>(x, y, z)</tt> is within the viewing frustum defined by <code>this</code> matrix. * <p> * This method computes the frustum planes in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * If multiple points are to be tested on the same frustum, create a {@link FrustumCuller} from this matrix instead. * <p> * Reference: <a href="http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @see #frustumPlane(int, Vector4f) * @see #isPointInsideFrustum(Vector3f) * * @param x * the x-coordinate of the point * @param y * the y-coordinate of the point * @param z * the z-coordinate of the point * @return <code>true</code> if the given point is inside the clipping frustum; <code>false</code> otherwise */ public boolean isPointInsideFrustum(float x, float y, float z) { return ((m03 + m00) * x + (m13 + m10) * y + (m23 + m20) * z + (m33 + m30) >= 0 && (m03 - m00) * x + (m13 - m10) * y + (m23 - m20) * z + (m33 - m30) >= 0 && (m03 + m01) * x + (m13 + m11) * y + (m23 + m21) * z + (m33 + m31) >= 0 && (m03 - m01) * x + (m13 - m11) * y + (m23 - m21) * z + (m33 - m31) >= 0 && (m03 + m02) * x + (m13 + m12) * y + (m23 + m22) * z + (m33 + m32) >= 0 && (m03 - m02) * x + (m13 - m12) * y + (m23 - m22) * z + (m33 - m32) >= 0); } /** * Determine whether the given sphere is partly or completely within the viewing frustum defined by <code>this</code> matrix. * <p> * This method computes the frustum planes in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * If multiple spheres are to be tested on the same frustum, create a {@link FrustumCuller} from this matrix instead. * * @see #frustumPlane(int, Vector4f) * @see #isSphereInsideFrustum(float, float, float, float) * * @param center * the sphere's center * @param radius * the sphere's radius * @return <code>true</code> if the given sphere is partly or completely inside the clipping frustum; * <code>false</code> otherwise */ public boolean isSphereInsideFrustum(Vector3f center, float radius) { return isSphereInsideFrustum(center.x, center.y, center.z, radius); } /** * Determine whether the given sphere is partly or completely within the viewing frustum defined by <code>this</code> matrix. * <p> * This method computes the frustum planes in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * The algorithm implemented by this method is conservative. This means that in certain circumstances a <i>false positive</i> * can occur, when the method returns <tt>true</tt> for spheres that are actually not visible. * See <a href="http://iquilezles.org/www/articles/frustumcorrect/frustumcorrect.htm">iquilezles.org</a> for an examination of this problem. * <p> * If multiple spheres are to be tested on the same frustum, create a {@link FrustumCuller} from this matrix instead. * <p> * Reference: <a href="http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @see #frustumPlane(int, Vector4f) * @see #isSphereInsideFrustum(Vector3f, float) * * @param x * the x-coordinate of the sphere's center * @param y * the y-coordinate of the sphere's center * @param z * the z-coordinate of the sphere's center * @param r * the sphere's radius * @return <code>true</code> if the given sphere is partly or completely inside the clipping frustum; * <code>false</code> otherwise */ public boolean isSphereInsideFrustum(float x, float y, float z, float r) { return ((m03 + m00) * x + (m13 + m10) * y + (m23 + m20) * z + (m33 + m30) >= -r * Math.sqrt((m03 + m00) * (m03 + m00) + (m13 + m10) * (m13 + m10) + (m23 + m20) * (m23 + m20)) && (m03 - m00) * x + (m13 - m10) * y + (m23 - m20) * z + (m33 - m30) >= -r * Math.sqrt((m03 - m00) * (m03 - m00) + (m13 - m10) * (m13 - m10) + (m23 - m20) * (m23 - m20)) && (m03 + m01) * x + (m13 + m11) * y + (m23 + m21) * z + (m33 + m31) >= -r * Math.sqrt((m03 + m01) * (m03 + m01) + (m13 + m11) * (m13 + m11) + (m23 + m21) * (m23 + m21)) && (m03 - m01) * x + (m13 - m11) * y + (m23 - m21) * z + (m33 - m31) >= -r * Math.sqrt((m03 - m01) * (m03 - m01) + (m13 - m11) * (m13 - m11) + (m23 - m21) * (m23 - m21)) && (m03 + m02) * x + (m13 + m12) * y + (m23 + m22) * z + (m33 + m32) >= -r * Math.sqrt((m03 + m02) * (m03 + m02) + (m13 + m12) * (m13 + m12) + (m23 + m22) * (m23 + m22)) && (m03 - m02) * x + (m13 - m12) * y + (m23 - m22) * z + (m33 - m32) >= -r * Math.sqrt((m03 - m02) * (m03 - m02) + (m13 - m12) * (m13 - m12) + (m23 - m22) * (m23 - m22))); } /** * Determine whether the given axis-aligned box is partly or completely within the viewing frustum defined by <code>this</code> matrix * and, if the box is not inside this frustum, return the index of the plane that culled it. * The box is specified via its <code>min</code> and <code>max</code> corner coordinates. * <p> * This method computes the frustum planes in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * The algorithm implemented by this method is conservative. This means that in certain circumstances a <i>false positive</i> * can occur, when the method returns <tt>true</tt> for boxes that are actually not visible. * See <a href="http://iquilezles.org/www/articles/frustumcorrect/frustumcorrect.htm">iquilezles.org</a> for an examination of this problem. * <p> * If multiple boxes are to be tested on the same frustum, create a {@link FrustumCuller} from this matrix instead. * * @see #frustumPlane(int, Vector4f) * @see #isAabInsideFrustum(float, float, float, float, float, float) * * @param min * the minimum corner coordinates of the axis-aligned box * @param max * the maximum corner coordinates of the axis-aligned box * @return the index of the first plane that culled the box, if the box does not intersect the frustum; * or <tt>-1</tt> if the box intersects the frustum. The plane index is one of * {@link #PLANE_NX}, {@link #PLANE_PX}, * {@link #PLANE_NY}, {@link #PLANE_PY}, * {@link #PLANE_NZ} and {@link #PLANE_PZ} */ public int isAabInsideFrustum(Vector3f min, Vector3f max) { return isAabInsideFrustum(min.x, min.y, min.z, max.x, max.y, max.z); } /** * Determine whether the given axis-aligned box is partly or completely within the viewing frustum defined by <code>this</code> matrix * and, if the box is not inside this frustum, return the index of the plane that culled it. * The box is specified via its min and max corner coordinates. * <p> * This method computes the frustum planes in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * The algorithm implemented by this method is conservative. This means that in certain circumstances a <i>false positive</i> * can occur, when the method returns <tt>true</tt> for boxes that are actually not visible. * See <a href="http://iquilezles.org/www/articles/frustumcorrect/frustumcorrect.htm">iquilezles.org</a> for an examination of this problem. * <p> * If multiple boxes are to be tested on the same frustum, create a {@link FrustumCuller} from this matrix instead. * <p> * Reference: <a href="http://www.cescg.org/CESCG-2002/DSykoraJJelinek/">Efficient View Frustum Culling</a> * <p> * Reference: <a href="http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @see #frustumPlane(int, Vector4f) * @see #isAabInsideFrustum(Vector3f, Vector3f) * * @param minX * the x-coordinate of the minimum corner * @param minY * the y-coordinate of the minimum corner * @param minZ * the z-coordinate of the minimum corner * @param maxX * the x-coordinate of the maximum corner * @param maxY * the y-coordinate of the maximum corner * @param maxZ * the z-coordinate of the maximum corner * @return the index of the first plane that culled the box, if the box does not intersect the frustum; * or <tt>-1</tt> if the box intersects the frustum. The plane index is one of * {@link #PLANE_NX}, {@link #PLANE_PX}, * {@link #PLANE_NY}, {@link #PLANE_PY}, * {@link #PLANE_NZ} and {@link #PLANE_PZ} */ public int isAabInsideFrustum(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { /* * This is an implementation of the "2.4 Basic intersection test" of the mentioned site. * It does not distinguish between partially inside and fully inside, though, so the test with the 'p' vertex is omitted. * * In addition to the algorithm in the paper, this method also returns the index of the first plane that culled the box * or -1 if the box intersects the frustum. */ int plane = 0; if ((m03 + m00) * (m03 + m00 < 0 ? minX : maxX) + (m13 + m10) * (m13 + m10 < 0 ? minY : maxY) + (m23 + m20) * (m23 + m20 < 0 ? minZ : maxZ) >= -m33 - m30 && ++plane != 0 && (m03 - m00) * (m03 - m00 < 0 ? minX : maxX) + (m13 - m10) * (m13 - m10 < 0 ? minY : maxY) + (m23 - m20) * (m23 - m20 < 0 ? minZ : maxZ) >= -m33 + m30 && ++plane != 0 && (m03 + m01) * (m03 + m01 < 0 ? minX : maxX) + (m13 + m11) * (m13 + m11 < 0 ? minY : maxY) + (m23 + m21) * (m23 + m21 < 0 ? minZ : maxZ) >= -m33 - m31 && ++plane != 0 && (m03 - m01) * (m03 - m01 < 0 ? minX : maxX) + (m13 - m11) * (m13 - m11 < 0 ? minY : maxY) + (m23 - m21) * (m23 - m21 < 0 ? minZ : maxZ) >= -m33 + m31 && ++plane != 0 && (m03 + m02) * (m03 + m02 < 0 ? minX : maxX) + (m13 + m12) * (m13 + m12 < 0 ? minY : maxY) + (m23 + m22) * (m23 + m22 < 0 ? minZ : maxZ) >= -m33 - m32 && ++plane != 0 && (m03 - m02) * (m03 - m02 < 0 ? minX : maxX) + (m13 - m12) * (m13 - m12 < 0 ? minY : maxY) + (m23 - m22) * (m23 - m22 < 0 ? minZ : maxZ) >= -m33 + m32) return -1; return plane; } /** * Determine whether the given axis-aligned box is partly or completely within the viewing frustum defined by <code>this</code> matrix * and, if the box is not inside this frustum, return the index of the plane that culled it. * The box is specified via its <code>min</code> and <code>max</code> corner coordinates. * <p> * This method differs from {@link #isAabInsideFrustum(Vector3f, Vector3f) isAabInsideFrustum()} in that * it allows to mask-off planes that should not be calculated. For example, in order to only test a box against the * left frustum plane, use a mask of {@link #PLANE_MASK_NX}. Or in order to test all planes <i>except</i> the left plane, use * a mask of <tt>(~0 ^ PLANE_MASK_NX)</tt>. * <p> * This method computes the frustum planes in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * The algorithm implemented by this method is conservative. This means that in certain circumstances a <i>false positive</i> * can occur, when the method returns <tt>true</tt> for boxes that are actually not visible. * See <a href="http://iquilezles.org/www/articles/frustumcorrect/frustumcorrect.htm">iquilezles.org</a> for an examination of this problem. * <p> * If multiple boxes are to be tested on the same frustum, create a {@link FrustumCuller} from this matrix instead. * * @see #frustumPlane(int, Vector4f) * @see #isAabInsideFrustumMasked(float, float, float, float, float, float, int) * * @param min * the minimum corner coordinates of the axis-aligned box * @param max * the maximum corner coordinates of the axis-aligned box * @param mask * contains as bitset all the planes that should be tested. This value can be any combination of * {@link #PLANE_MASK_NX}, {@link #PLANE_MASK_PY}, * {@link #PLANE_MASK_NY}, {@link #PLANE_MASK_PY}, * {@link #PLANE_MASK_NZ} and {@link #PLANE_MASK_PZ} * @return the index of the first plane that culled the box, if the box does not intersect the frustum; * or <tt>-1</tt> if the box intersects the frustum. The plane index is one of * {@link #PLANE_NX}, {@link #PLANE_PX}, * {@link #PLANE_NY}, {@link #PLANE_PY}, * {@link #PLANE_NZ} and {@link #PLANE_PZ} */ public int isAabInsideFrustumMasked(Vector3f min, Vector3f max, int mask) { return isAabInsideFrustumMasked(min.x, min.y, min.z, max.x, max.y, max.z, mask); } /** * Determine whether the given axis-aligned box is partly or completely within the viewing frustum defined by <code>this</code> matrix * and, if the box is not inside this frustum, return the index of the plane that culled it. * The box is specified via its min and max corner coordinates. * <p> * This method differs from {@link #isAabInsideFrustum(float, float, float, float, float, float) isAabInsideFrustum()} in that * it allows to mask-off planes that should not be calculated. For example, in order to only test a box against the * left frustum plane, use a mask of {@link #PLANE_MASK_NX}. Or in order to test all planes <i>except</i> the left plane, use * a mask of <tt>(~0 ^ PLANE_MASK_NX)</tt>. * <p> * This method computes the frustum planes in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * The algorithm implemented by this method is conservative. This means that in certain circumstances a <i>false positive</i> * can occur, when the method returns <tt>true</tt> for boxes that are actually not visible. * See <a href="http://iquilezles.org/www/articles/frustumcorrect/frustumcorrect.htm">iquilezles.org</a> for an examination of this problem. * <p> * If multiple boxes are to be tested on the same frustum, create a {@link FrustumCuller} from this matrix instead. * <p> * Reference: <a href="http://www.cescg.org/CESCG-2002/DSykoraJJelinek/">Efficient View Frustum Culling</a> * <p> * Reference: <a href="http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @see #frustumPlane(int, Vector4f) * @see #isAabInsideFrustumMasked(Vector3f, Vector3f, int) * * @param minX * the x-coordinate of the minimum corner * @param minY * the y-coordinate of the minimum corner * @param minZ * the z-coordinate of the minimum corner * @param maxX * the x-coordinate of the maximum corner * @param maxY * the y-coordinate of the maximum corner * @param maxZ * the z-coordinate of the maximum corner * @param mask * contains as bitset all the planes that should be tested. This value can be any combination of * {@link #PLANE_MASK_NX}, {@link #PLANE_MASK_PY}, * {@link #PLANE_MASK_NY}, {@link #PLANE_MASK_PY}, * {@link #PLANE_MASK_NZ} and {@link #PLANE_MASK_PZ} * @return the index of the first plane that culled the box, if the box does not intersect the frustum; * or <tt>-1</tt> if the box intersects the frustum. The plane index is one of * {@link #PLANE_NX}, {@link #PLANE_PX}, * {@link #PLANE_NY}, {@link #PLANE_PY}, * {@link #PLANE_NZ} and {@link #PLANE_PZ} */ public int isAabInsideFrustumMasked(float minX, float minY, float minZ, float maxX, float maxY, float maxZ, int mask) { /* * This is an implementation of the "2.5 Plane masking and coherency" of the mentioned site. * It does not distinguish between partially inside and fully inside, though, so the test with the 'p' vertex is omitted. * * In addition to the algorithm in the paper, this method also returns the index of the first plane that culled the box * or -1 if the box intersects the frustum. */ int plane = 0; if (((mask & PLANE_MASK_NX) == 0 || (m03 + m00) * (m03 + m00 < 0 ? minX : maxX) + (m13 + m10) * (m13 + m10 < 0 ? minY : maxY) + (m23 + m20) * (m23 + m20 < 0 ? minZ : maxZ) >= -m33 - m30) && ++plane != 0 && ((mask & PLANE_MASK_PX) == 0 || (m03 - m00) * (m03 - m00 < 0 ? minX : maxX) + (m13 - m10) * (m13 - m10 < 0 ? minY : maxY) + (m23 - m20) * (m23 - m20 < 0 ? minZ : maxZ) >= -m33 + m30) && ++plane != 0 && ((mask & PLANE_MASK_NY) == 0 || (m03 + m01) * (m03 + m01 < 0 ? minX : maxX) + (m13 + m11) * (m13 + m11 < 0 ? minY : maxY) + (m23 + m21) * (m23 + m21 < 0 ? minZ : maxZ) >= -m33 - m31) && ++plane != 0 && ((mask & PLANE_MASK_PY) == 0 || (m03 - m01) * (m03 - m01 < 0 ? minX : maxX) + (m13 - m11) * (m13 - m11 < 0 ? minY : maxY) + (m23 - m21) * (m23 - m21 < 0 ? minZ : maxZ) >= -m33 + m31) && ++plane != 0 && ((mask & PLANE_MASK_NZ) == 0 || (m03 + m02) * (m03 + m02 < 0 ? minX : maxX) + (m13 + m12) * (m13 + m12 < 0 ? minY : maxY) + (m23 + m22) * (m23 + m22 < 0 ? minZ : maxZ) >= -m33 - m32) && ++plane != 0 && ((mask & PLANE_MASK_PZ) == 0 || (m03 - m02) * (m03 - m02 < 0 ? minX : maxX) + (m13 - m12) * (m13 - m12 < 0 ? minY : maxY) + (m23 - m22) * (m23 - m22 < 0 ? minZ : maxZ) >= -m33 + m32)) return -1; return plane; } /** * Obtain the direction of a ray starting at the center of the coordinate system and going * through the near frustum plane. * <p> * This method computes the <code>dir</code> vector in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * The parameters <code>x</code> and <code>y</code> are used to interpolate the generated ray direction * from the bottom-left to the top-right frustum corners. * <p> * For optimal efficiency when building many ray directions over the whole frustum, * it is recommended to use this method only in order to compute the four corner rays at * <tt>(0, 0)</tt>, <tt>(1, 0)</tt>, <tt>(0, 1)</tt> and <tt>(1, 1)</tt> * and then bilinearly interpolating between them; or to use the {@link FrustumRayBuilder}. * <p> * Reference: <a href="http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @param x * the interpolation factor along the left-to-right frustum planes, within <tt>[0..1]</tt> * @param y * the interpolation factor along the bottom-to-top frustum planes, within <tt>[0..1]</tt> * @param dir * will hold the normalized ray direction in the local frame of the coordinate system before * transforming to homogeneous clipping space using <code>this</code> matrix * @return this */ public Matrix4f frustumRayDir(float x, float y, Vector3f dir) { /* * This method works by first obtaining the frustum plane normals, * then building the cross product to obtain the corner rays, * and finall bilinearly interpolating to obtain the desired direction. * The code below uses a condense form of doing all this making use * of some mathematical identities to simplify the overall expression. */ float a = m10 * m23, b = m13 * m21, c = m10 * m21, d = m11 * m23, e = m13 * m20, f = m11 * m20; float g = m03 * m20, h = m01 * m23, i = m01 * m20, j = m03 * m21, k = m00 * m23, l = m00 * m21; float m = m00 * m13, n = m03 * m11, o = m00 * m11, p = m01 * m13, q = m03 * m10, r = m01 * m10; float m1x, m1y, m1z; m1x = (d + e + f - a - b - c) * (1.0f - y) + (a - b - c + d - e + f) * y; m1y = (j + k + l - g - h - i) * (1.0f - y) + (g - h - i + j - k + l) * y; m1z = (p + q + r - m - n - o) * (1.0f - y) + (m - n - o + p - q + r) * y; float m2x, m2y, m2z; m2x = (b - c - d + e + f - a) * (1.0f - y) + (a + b - c - d - e + f) * y; m2y = (h - i - j + k + l - g) * (1.0f - y) + (g + h - i - j - k + l) * y; m2z = (n - o - p + q + r - m) * (1.0f - y) + (m + n - o - p - q + r) * y; dir.x = m1x * (1.0f - x) + m2x * x; dir.y = m1y * (1.0f - x) + m2y * x; dir.z = m1z * (1.0f - x) + m2z * x; dir.normalize(); return this; } /** * Obtain the direction of <tt>+Z</tt> before the orthogonal transformation represented by * <code>this</code> matrix is applied. * <p> * This method uses the rotation component of the top-left 3x3 submatrix to obtain the direction * that is transformed to <tt>+Z</tt> by <code>this</code> matrix. * <p> * Reference: <a href="http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/threeD/">http://www.euclideanspace.com</a> * * @param dir * will hold the direction of <tt>+Z</tt> * @return this */ public Matrix4f positiveZ(Vector3f dir) { dir.x = m10 * m21 - m11 * m20; dir.y = m20 * m01 - m21 * m00; dir.z = m00 * m11 - m01 * m10; dir.normalize(); return this; } /** * Obtain the direction of <tt>+X</tt> before the orthogonal transformation represented by * <code>this</code> matrix is applied. * <p> * This method uses the rotation component of the top-left 3x3 submatrix to obtain the direction * that is transformed to <tt>+X</tt> by <code>this</code> matrix. * <p> * Reference: <a href="http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/threeD/">http://www.euclideanspace.com</a> * * @param dir * will hold the direction of <tt>+X</tt> * @return this */ public Matrix4f positiveX(Vector3f dir) { dir.x = m11 * m22 - m12 * m21; dir.y = m02 * m21 - m01 * m22; dir.z = m01 * m12 - m02 * m11; dir.normalize(); return this; } /** * Obtain the direction of <tt>+Y</tt> before the orthogonal transformation represented by * <code>this</code> matrix is applied. * <p> * This method uses the rotation component of the top-left 3x3 submatrix to obtain the direction * that is transformed to <tt>+Y</tt> by <code>this</code> matrix. * <p> * Reference: <a href="http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/threeD/">http://www.euclideanspace.com</a> * * @param dir * will hold the direction of <tt>+Y</tt> * @return this */ public Matrix4f positiveY(Vector3f dir) { dir.x = m12 * m20 - m10 * m22; dir.y = m00 * m22 - m02 * m20; dir.z = m02 * m10 - m00 * m12; dir.normalize(); return this; } /** * Apply a projection transformation to this matrix that projects onto the plane specified via the general plane equation * <tt>x*a + y*b + z*c + d = 0</tt> as if casting a shadow from a given light position/direction <code>light</code>. * <p> * If the <code>light</code>'s w-component is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="ftp://ftp.sgi.com/opengl/contrib/blythe/advanced99/notes/node192.html">ftp.sgi.com</a> * * @param light * the light's vector * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @return this */ public Matrix4f shadow(Vector4f light, float a, float b, float c, float d) { return shadow(light.x, light.y, light.z, light.w, a, b, c, d, this); } /** * Apply a projection transformation to this matrix that projects onto the plane specified via the general plane equation * <tt>x*a + y*b + z*c + d = 0</tt> as if casting a shadow from a given light position/direction <code>light</code> * and store the result in <code>dest</code>. * <p> * If the <code>light</code>'s w-component is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="ftp://ftp.sgi.com/opengl/contrib/blythe/advanced99/notes/node192.html">ftp.sgi.com</a> * * @param light * the light's vector * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @param dest * will hold the result * @return this */ public Matrix4f shadow(Vector4f light, float a, float b, float c, float d, Matrix4f dest) { return shadow(light.x, light.y, light.z, light.w, a, b, c, d, dest); } /** * Apply a projection transformation to this matrix that projects onto the plane specified via the general plane equation * <tt>x*a + y*b + z*c + d = 0</tt> as if casting a shadow from a given light position/direction <tt>(lightX, lightY, lightZ, lightW)</tt>. * <p> * If <code>lightW</code> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="ftp://ftp.sgi.com/opengl/contrib/blythe/advanced99/notes/node192.html">ftp.sgi.com</a> * * @param lightX * the x-component of the light's vector * @param lightY * the y-component of the light's vector * @param lightZ * the z-component of the light's vector * @param lightW * the w-component of the light's vector * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @return this */ public Matrix4f shadow(float lightX, float lightY, float lightZ, float lightW, float a, float b, float c, float d) { return shadow(lightX, lightY, lightZ, lightW, a, b, c, d, this); } /** * Apply a projection transformation to this matrix that projects onto the plane specified via the general plane equation * <tt>x*a + y*b + z*c + d = 0</tt> as if casting a shadow from a given light position/direction <tt>(lightX, lightY, lightZ, lightW)</tt> * and store the result in <code>dest</code>. * <p> * If <code>lightW</code> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="ftp://ftp.sgi.com/opengl/contrib/blythe/advanced99/notes/node192.html">ftp.sgi.com</a> * * @param lightX * the x-component of the light's vector * @param lightY * the y-component of the light's vector * @param lightZ * the z-component of the light's vector * @param lightW * the w-component of the light's vector * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @param dest * will hold the result * @return this */ public Matrix4f shadow(float lightX, float lightY, float lightZ, float lightW, float a, float b, float c, float d, Matrix4f dest) { // normalize plane float planeLen = (float) Math.sqrt(a*a + b*b + c*c); float an = a / planeLen; float bn = b / planeLen; float cn = c / planeLen; float dn = d / planeLen; float dot = an * lightX + bn * lightY + cn * lightZ + dn * lightW; // compute right matrix elements float rm00 = dot - an * lightX; float rm01 = -an * lightY; float rm02 = -an * lightZ; float rm03 = -an * lightW; float rm10 = -bn * lightX; float rm11 = dot - bn * lightY; float rm12 = -bn * lightZ; float rm13 = -bn * lightW; float rm20 = -cn * lightX; float rm21 = -cn * lightY; float rm22 = dot - cn * lightZ; float rm23 = -cn * lightW; float rm30 = -dn * lightX; float rm31 = -dn * lightY; float rm32 = -dn * lightZ; float rm33 = dot - dn * lightW; // matrix multiplication float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02 + m30 * rm03; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02 + m31 * rm03; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02 + m32 * rm03; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02 + m33 * rm03; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12 + m30 * rm13; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12 + m31 * rm13; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12 + m32 * rm13; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12 + m33 * rm13; float nm20 = m00 * rm20 + m10 * rm21 + m20 * rm22 + m30 * rm23; float nm21 = m01 * rm20 + m11 * rm21 + m21 * rm22 + m31 * rm23; float nm22 = m02 * rm20 + m12 * rm21 + m22 * rm22 + m32 * rm23; float nm23 = m03 * rm20 + m13 * rm21 + m23 * rm22 + m33 * rm23; dest.m30 = m00 * rm30 + m10 * rm31 + m20 * rm32 + m30 * rm33; dest.m31 = m01 * rm30 + m11 * rm31 + m21 * rm32 + m31 * rm33; dest.m32 = m02 * rm30 + m12 * rm31 + m22 * rm32 + m32 * rm33; dest.m33 = m03 * rm30 + m13 * rm31 + m23 * rm32 + m33 * rm33; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; return this; } /** * Apply a projection transformation to this matrix that projects onto the plane with the general plane equation * <tt>y = 0</tt> as if casting a shadow from a given light position/direction <code>light</code> * and store the result in <code>dest</code>. * <p> * Before the shadow projection is applied, the plane is transformed via the specified <code>planeTransformation</code>. * <p> * If <code>lightW</code> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * * @param light * the light's vector * @param planeTransform * the transformation to transform the implied plane <tt>y = 0</tt> before applying the projection * @param dest * will hold the result * @return this */ public Matrix4f shadow(Vector4f light, Matrix4f planeTransform, Matrix4f dest) { // compute plane equation by transforming (y = 0) float a = planeTransform.m10; float b = planeTransform.m11; float c = planeTransform.m12; float d = -a * planeTransform.m30 - b * planeTransform.m31 - c * planeTransform.m32; return shadow(light.x, light.y, light.z, light.w, a, b, c, d, dest); } /** * Apply a projection transformation to this matrix that projects onto the plane with the general plane equation * <tt>y = 0</tt> as if casting a shadow from a given light position/direction <code>light</code>. * <p> * Before the shadow projection is applied, the plane is transformed via the specified <code>planeTransformation</code>. * <p> * If <code>lightW</code> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * * @param light * the light's vector * @param planeTransform * the transformation to transform the implied plane <tt>y = 0</tt> before applying the projection * @return this */ public Matrix4f shadow(Vector4f light, Matrix4f planeTransform) { return shadow(light, planeTransform, this); } }
src/org/joml/Matrix4f.java
/* * (C) Copyright 2015 Richard Greenlees Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.joml; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.text.DecimalFormat; import java.text.NumberFormat; /** * Contains the definition of a 4x4 Matrix of floats, and associated functions to transform * it. The matrix is column-major to match OpenGL's interpretation, and it looks like this: * <p> * m00 m10 m20 m30<br> * m01 m11 m21 m31<br> * m02 m12 m22 m32<br> * m03 m13 m23 m33<br> * * @author Richard Greenlees * @author Kai Burjack */ public class Matrix4f implements Externalizable { private static final long serialVersionUID = 1L; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} or return * value of {@link #isAabInsideFrustum(float, float, float, float, float, float) isAabInsideFrustum()} or * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * identifying the plane with equation <tt>x=-1</tt> when using the identity matrix. */ public static final int PLANE_NX = 0; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} or return * value of {@link #isAabInsideFrustum(float, float, float, float, float, float) isAabInsideFrustum()} or * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * identifying the plane with equation <tt>x=1</tt> when using the identity matrix. */ public static final int PLANE_PX = 1; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} or return * value of {@link #isAabInsideFrustum(float, float, float, float, float, float) isAabInsideFrustum()} or * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * identifying the plane with equation <tt>y=-1</tt> when using the identity matrix. */ public static final int PLANE_NY= 2; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} or return * value of {@link #isAabInsideFrustum(float, float, float, float, float, float) isAabInsideFrustum()} or * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * identifying the plane with equation <tt>y=1</tt> when using the identity matrix. */ public static final int PLANE_PY = 3; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} or return * value of {@link #isAabInsideFrustum(float, float, float, float, float, float) isAabInsideFrustum()} or * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * identifying the plane with equation <tt>z=-1</tt> when using the identity matrix. */ public static final int PLANE_NZ = 4; /** * Argument to the first parameter of {@link #frustumPlane(int, Vector4f)} or return * value of {@link #isAabInsideFrustum(float, float, float, float, float, float) isAabInsideFrustum()} or * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * identifying the plane with equation <tt>z=1</tt> when using the identity matrix. */ public static final int PLANE_PZ = 5; /** * The value in a bitmask for * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * that identifies the plane with equation <tt>x=-1</tt> when using the identity matrix. */ public static final int PLANE_MASK_NX = 1<<PLANE_NX; /** * The value in a bitmask for * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * that identifies the plane with equation <tt>x=1</tt> when using the identity matrix. */ public static final int PLANE_MASK_PX = 1<<PLANE_PX; /** * The value in a bitmask for * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * that identifies the plane with equation <tt>y=-1</tt> when using the identity matrix. */ public static final int PLANE_MASK_NY = 1<<PLANE_NY; /** * The value in a bitmask for * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * that identifies the plane with equation <tt>y=1</tt> when using the identity matrix. */ public static final int PLANE_MASK_PY = 1<<PLANE_PY; /** * The value in a bitmask for * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * that identifies the plane with equation <tt>z=-1</tt> when using the identity matrix. */ public static final int PLANE_MASK_NZ = 1<<PLANE_NZ; /** * The value in a bitmask for * {@link #isAabInsideFrustumMasked(float, float, float, float, float, float, int) isAabInsideFrustumMasked()} * that identifies the plane with equation <tt>z=1</tt> when using the identity matrix. */ public static final int PLANE_MASK_PZ = 1<<PLANE_PZ; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(-1, -1, -1)</tt> when using the identity matrix. */ public static final int CORNER_NXNYNZ = 0; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(1, -1, -1)</tt> when using the identity matrix. */ public static final int CORNER_PXNYNZ = 1; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(1, 1, -1)</tt> when using the identity matrix. */ public static final int CORNER_PXPYNZ = 2; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(-1, 1, -1)</tt> when using the identity matrix. */ public static final int CORNER_NXPYNZ = 3; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(1, -1, 1)</tt> when using the identity matrix. */ public static final int CORNER_PXNYPZ = 4; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(-1, -1, 1)</tt> when using the identity matrix. */ public static final int CORNER_NXNYPZ = 5; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(-1, 1, 1)</tt> when using the identity matrix. */ public static final int CORNER_NXPYPZ = 6; /** * Argument to the first parameter of {@link #frustumCorner(int, Vector3f)} * identifying the corner <tt>(1, 1, 1)</tt> when using the identity matrix. */ public static final int CORNER_PXPYPZ = 7; public float m00, m10, m20, m30; public float m01, m11, m21, m31; public float m02, m12, m22, m32; public float m03, m13, m23, m33; /** * Create a new {@link Matrix4f} and set it to {@link #identity() identity}. */ public Matrix4f() { super(); identity(); } /** * Create a new {@link Matrix4f} by setting its uppper left 3x3 submatrix to the values of the given {@link Matrix3f} * and the rest to identity. * * @param mat * the {@link Matrix3f} */ public Matrix4f(Matrix3f mat) { m00 = mat.m00; m01 = mat.m01; m02 = mat.m02; m10 = mat.m10; m11 = mat.m11; m12 = mat.m12; m20 = mat.m20; m21 = mat.m21; m22 = mat.m22; m33 = 1.0f; } /** * Create a new {@link Matrix4f} and make it a copy of the given matrix. * * @param mat * the {@link Matrix4f} to copy the values from */ public Matrix4f(Matrix4f mat) { m00 = mat.m00; m01 = mat.m01; m02 = mat.m02; m03 = mat.m03; m10 = mat.m10; m11 = mat.m11; m12 = mat.m12; m13 = mat.m13; m20 = mat.m20; m21 = mat.m21; m22 = mat.m22; m23 = mat.m23; m30 = mat.m30; m31 = mat.m31; m32 = mat.m32; m33 = mat.m33; } /** * Create a new 4x4 matrix using the supplied float values. * * @param m00 * the value of m00 * @param m01 * the value of m01 * @param m02 * the value of m02 * @param m03 * the value of m03 * @param m10 * the value of m10 * @param m11 * the value of m11 * @param m12 * the value of m12 * @param m13 * the value of m13 * @param m20 * the value of m20 * @param m21 * the value of m21 * @param m22 * the value of m22 * @param m23 * the value of m23 * @param m30 * the value of m30 * @param m31 * the value of m31 * @param m32 * the value of m32 * @param m33 * the value of m33 */ public Matrix4f(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13; this.m20 = m20; this.m21 = m21; this.m22 = m22; this.m23 = m23; this.m30 = m30; this.m31 = m31; this.m32 = m32; this.m33 = m33; } /** * Create a new {@link Matrix4f} by reading its 16 float components from the given {@link FloatBuffer} * at the buffer's current position. * <p> * That FloatBuffer is expected to hold the values in column-major order. * <p> * The buffer's position will not be changed by this method. * * @param buffer * the {@link FloatBuffer} to read the matrix values from */ public Matrix4f(FloatBuffer buffer) { int pos = buffer.position(); m00 = buffer.get(pos); m01 = buffer.get(pos+1); m02 = buffer.get(pos+2); m03 = buffer.get(pos+3); m10 = buffer.get(pos+4); m11 = buffer.get(pos+5); m12 = buffer.get(pos+6); m13 = buffer.get(pos+7); m20 = buffer.get(pos+8); m21 = buffer.get(pos+9); m22 = buffer.get(pos+10); m23 = buffer.get(pos+11); m30 = buffer.get(pos+12); m31 = buffer.get(pos+13); m32 = buffer.get(pos+14); m33 = buffer.get(pos+15); } /** * Reset this matrix to the identity. * * @return this */ public Matrix4f identity() { m00 = 1.0f; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 1.0f; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = 1.0f; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Store the values of the given matrix <code>m</code> into <code>this</code> matrix. * * @see #Matrix4f(Matrix4f) * @see #get(Matrix4f) * * @param m * the matrix to copy the values from * @return this */ public Matrix4f set(Matrix4f m) { m00 = m.m00; m01 = m.m01; m02 = m.m02; m03 = m.m03; m10 = m.m10; m11 = m.m11; m12 = m.m12; m13 = m.m13; m20 = m.m20; m21 = m.m21; m22 = m.m22; m23 = m.m23; m30 = m.m30; m31 = m.m31; m32 = m.m32; m33 = m.m33; return this; } /** * Set the upper left 3x3 submatrix of this {@link Matrix4f} to the given {@link Matrix3f} * and the rest to identity. * * @see #Matrix4f(Matrix3f) * * @param mat * the {@link Matrix3f} * @return this */ public Matrix4f set(Matrix3f mat) { m00 = mat.m00; m01 = mat.m01; m02 = mat.m02; m03 = 0.0f; m10 = mat.m10; m11 = mat.m11; m12 = mat.m12; m13 = 0.0f; m20 = mat.m20; m21 = mat.m21; m22 = mat.m22; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be equivalent to the rotation specified by the given {@link AxisAngle4f}. * * @param axisAngle * the {@link AxisAngle4f} * @return this */ public Matrix4f set(AxisAngle4f axisAngle) { float x = axisAngle.x; float y = axisAngle.y; float z = axisAngle.z; double angle = axisAngle.angle; double n = Math.sqrt(x*x + y*y + z*z); n = 1/n; x *= n; y *= n; z *= n; double c = Math.cos(angle); double s = Math.sin(angle); double omc = 1.0 - c; m00 = (float)(c + x*x*omc); m11 = (float)(c + y*y*omc); m22 = (float)(c + z*z*omc); double tmp1 = x*y*omc; double tmp2 = z*s; m10 = (float)(tmp1 - tmp2); m01 = (float)(tmp1 + tmp2); tmp1 = x*z*omc; tmp2 = y*s; m20 = (float)(tmp1 + tmp2); m02 = (float)(tmp1 - tmp2); tmp1 = y*z*omc; tmp2 = x*s; m21 = (float)(tmp1 - tmp2); m12 = (float)(tmp1 + tmp2); m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be equivalent to the rotation specified by the given {@link Quaternionf}. * * @see Quaternionf#get(Matrix4f) * * @param q * the {@link Quaternionf} * @return this */ public Matrix4f set(Quaternionf q) { q.get(this); return this; } /** * Multiply this matrix by the supplied <code>right</code> matrix and store the result in <code>this</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the <code>right</code> matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * transformation of the right matrix will be applied first! * * @param right * the right operand of the matrix multiplication * @return this */ public Matrix4f mul(Matrix4f right) { return mul(right, this); } /** * Multiply this matrix by the supplied <code>right</code> matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the <code>right</code> matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * transformation of the right matrix will be applied first! * * @param right * the right operand of the matrix multiplication * @param dest * the destination matrix, which will hold the result * @return this */ public Matrix4f mul(Matrix4f right, Matrix4f dest) { if (this != dest && right != dest) { dest.m00 = m00 * right.m00 + m10 * right.m01 + m20 * right.m02 + m30 * right.m03; dest.m01 = m01 * right.m00 + m11 * right.m01 + m21 * right.m02 + m31 * right.m03; dest.m02 = m02 * right.m00 + m12 * right.m01 + m22 * right.m02 + m32 * right.m03; dest.m03 = m03 * right.m00 + m13 * right.m01 + m23 * right.m02 + m33 * right.m03; dest.m10 = m00 * right.m10 + m10 * right.m11 + m20 * right.m12 + m30 * right.m13; dest.m11 = m01 * right.m10 + m11 * right.m11 + m21 * right.m12 + m31 * right.m13; dest.m12 = m02 * right.m10 + m12 * right.m11 + m22 * right.m12 + m32 * right.m13; dest.m13 = m03 * right.m10 + m13 * right.m11 + m23 * right.m12 + m33 * right.m13; dest.m20 = m00 * right.m20 + m10 * right.m21 + m20 * right.m22 + m30 * right.m23; dest.m21 = m01 * right.m20 + m11 * right.m21 + m21 * right.m22 + m31 * right.m23; dest.m22 = m02 * right.m20 + m12 * right.m21 + m22 * right.m22 + m32 * right.m23; dest.m23 = m03 * right.m20 + m13 * right.m21 + m23 * right.m22 + m33 * right.m23; dest.m30 = m00 * right.m30 + m10 * right.m31 + m20 * right.m32 + m30 * right.m33; dest.m31 = m01 * right.m30 + m11 * right.m31 + m21 * right.m32 + m31 * right.m33; dest.m32 = m02 * right.m30 + m12 * right.m31 + m22 * right.m32 + m32 * right.m33; dest.m33 = m03 * right.m30 + m13 * right.m31 + m23 * right.m32 + m33 * right.m33; } else { dest.set(m00 * right.m00 + m10 * right.m01 + m20 * right.m02 + m30 * right.m03, m01 * right.m00 + m11 * right.m01 + m21 * right.m02 + m31 * right.m03, m02 * right.m00 + m12 * right.m01 + m22 * right.m02 + m32 * right.m03, m03 * right.m00 + m13 * right.m01 + m23 * right.m02 + m33 * right.m03, m00 * right.m10 + m10 * right.m11 + m20 * right.m12 + m30 * right.m13, m01 * right.m10 + m11 * right.m11 + m21 * right.m12 + m31 * right.m13, m02 * right.m10 + m12 * right.m11 + m22 * right.m12 + m32 * right.m13, m03 * right.m10 + m13 * right.m11 + m23 * right.m12 + m33 * right.m13, m00 * right.m20 + m10 * right.m21 + m20 * right.m22 + m30 * right.m23, m01 * right.m20 + m11 * right.m21 + m21 * right.m22 + m31 * right.m23, m02 * right.m20 + m12 * right.m21 + m22 * right.m22 + m32 * right.m23, m03 * right.m20 + m13 * right.m21 + m23 * right.m22 + m33 * right.m23, m00 * right.m30 + m10 * right.m31 + m20 * right.m32 + m30 * right.m33, m01 * right.m30 + m11 * right.m31 + m21 * right.m32 + m31 * right.m33, m02 * right.m30 + m12 * right.m31 + m22 * right.m32 + m32 * right.m33, m03 * right.m30 + m13 * right.m31 + m23 * right.m32 + m33 * right.m33); } return this; } /** * Multiply this matrix by the top 4x3 submatrix of the supplied <code>right</code> matrix and store the result in <code>this</code>. * This method assumes that the last row of <code>right</code> is equal to <tt>(0, 0, 0, 1)</tt>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the <code>right</code> matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * transformation of the right matrix will be applied first! * * @param right * the right operand of the matrix multiplication (the last row is assumed to be <tt>(0, 0, 0, 1)</tt>) * @return this */ public Matrix4f mul4x3(Matrix4f right) { return mul4x3(right, this); } /** * Multiply this matrix by the top 4x3 submatrix of the supplied <code>right</code> matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the <code>right</code> matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * transformation of the right matrix will be applied first! * * @param right * the right operand of the matrix multiplication (the last row is assumed to be <tt>(0, 0, 0, 1)</tt>) * @param dest * the destination matrix, which will hold the result * @return this */ public Matrix4f mul4x3(Matrix4f right, Matrix4f dest) { if (this != dest && right != dest) { dest.m00 = m00 * right.m00 + m10 * right.m01 + m20 * right.m02; dest.m01 = m01 * right.m00 + m11 * right.m01 + m21 * right.m02; dest.m02 = m02 * right.m00 + m12 * right.m01 + m22 * right.m02; dest.m03 = m03 * right.m00 + m13 * right.m01 + m23 * right.m02; dest.m10 = m00 * right.m10 + m10 * right.m11 + m20 * right.m12; dest.m11 = m01 * right.m10 + m11 * right.m11 + m21 * right.m12; dest.m12 = m02 * right.m10 + m12 * right.m11 + m22 * right.m12; dest.m13 = m03 * right.m10 + m13 * right.m11 + m23 * right.m12; dest.m20 = m00 * right.m20 + m10 * right.m21 + m20 * right.m22; dest.m21 = m01 * right.m20 + m11 * right.m21 + m21 * right.m22; dest.m22 = m02 * right.m20 + m12 * right.m21 + m22 * right.m22; dest.m23 = m03 * right.m20 + m13 * right.m21 + m23 * right.m22; dest.m30 = m00 * right.m30 + m10 * right.m31 + m20 * right.m32 + m30; dest.m31 = m01 * right.m30 + m11 * right.m31 + m21 * right.m32 + m31; dest.m32 = m02 * right.m30 + m12 * right.m31 + m22 * right.m32 + m32; dest.m33 = m03 * right.m30 + m13 * right.m31 + m23 * right.m32 + m33; } else { dest.set(m00 * right.m00 + m10 * right.m01 + m20 * right.m02, m01 * right.m00 + m11 * right.m01 + m21 * right.m02, m02 * right.m00 + m12 * right.m01 + m22 * right.m02, m03 * right.m00 + m13 * right.m01 + m23 * right.m02, m00 * right.m10 + m10 * right.m11 + m20 * right.m12, m01 * right.m10 + m11 * right.m11 + m21 * right.m12, m02 * right.m10 + m12 * right.m11 + m22 * right.m12, m03 * right.m10 + m13 * right.m11 + m23 * right.m12, m00 * right.m20 + m10 * right.m21 + m20 * right.m22, m01 * right.m20 + m11 * right.m21 + m21 * right.m22, m02 * right.m20 + m12 * right.m21 + m22 * right.m22, m03 * right.m20 + m13 * right.m21 + m23 * right.m22, m00 * right.m30 + m10 * right.m31 + m20 * right.m32 + m30, m01 * right.m30 + m11 * right.m31 + m21 * right.m32 + m31, m02 * right.m30 + m12 * right.m31 + m22 * right.m32 + m32, m03 * right.m30 + m13 * right.m31 + m23 * right.m32 + m33); } return this; } /** * Set the values within this matrix to the supplied float values. The matrix will look like this:<br><br> * * m00, m10, m20, m30<br> * m01, m11, m21, m31<br> * m02, m12, m22, m32<br> * m03, m13, m23, m33 * * @param m00 * the new value of m00 * @param m01 * the new value of m01 * @param m02 * the new value of m02 * @param m03 * the new value of m03 * @param m10 * the new value of m10 * @param m11 * the new value of m11 * @param m12 * the new value of m12 * @param m13 * the new value of m13 * @param m20 * the new value of m20 * @param m21 * the new value of m21 * @param m22 * the new value of m22 * @param m23 * the new value of m23 * @param m30 * the new value of m30 * @param m31 * the new value of m31 * @param m32 * the new value of m32 * @param m33 * the new value of m33 * @return this */ public Matrix4f set(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13; this.m20 = m20; this.m21 = m21; this.m22 = m22; this.m23 = m23; this.m30 = m30; this.m31 = m31; this.m32 = m32; this.m33 = m33; return this; } /** * Set the values in the matrix using a float array that contains the matrix elements in column-major order. * <p> * The results will look like this:<br><br> * * 0, 4, 8, 12<br> * 1, 5, 9, 13<br> * 2, 6, 10, 14<br> * 3, 7, 11, 15<br> * * @see #set(float[]) * * @param m * the array to read the matrix values from * @param off * the offset into the array * @return this */ public Matrix4f set(float m[], int off) { m00 = m[off+0]; m01 = m[off+1]; m02 = m[off+2]; m03 = m[off+3]; m10 = m[off+4]; m11 = m[off+5]; m12 = m[off+6]; m13 = m[off+7]; m20 = m[off+8]; m21 = m[off+9]; m22 = m[off+10]; m23 = m[off+11]; m30 = m[off+12]; m31 = m[off+13]; m32 = m[off+14]; m33 = m[off+15]; return this; } /** * Set the values in the matrix using a float array that contains the matrix elements in column-major order. * <p> * The results will look like this:<br><br> * * 0, 4, 8, 12<br> * 1, 5, 9, 13<br> * 2, 6, 10, 14<br> * 3, 7, 11, 15<br> * * @see #set(float[], int) * * @param m * the array to read the matrix values from * @return this */ public Matrix4f set(float m[]) { return set(m, 0); } /** * Set the values of this matrix by reading 16 float values from the given {@link FloatBuffer} in column-major order, * starting at its current position. * <p> * The FloatBuffer is expected to contain the values in column-major order. * <p> * The position of the FloatBuffer will not be changed by this method. * * @param buffer * the FloatBuffer to read the matrix values from in column-major order * @return this */ public Matrix4f set(FloatBuffer buffer) { int pos = buffer.position(); m00 = buffer.get(pos); m01 = buffer.get(pos+1); m02 = buffer.get(pos+2); m03 = buffer.get(pos+3); m10 = buffer.get(pos+4); m11 = buffer.get(pos+5); m12 = buffer.get(pos+6); m13 = buffer.get(pos+7); m20 = buffer.get(pos+8); m21 = buffer.get(pos+9); m22 = buffer.get(pos+10); m23 = buffer.get(pos+11); m30 = buffer.get(pos+12); m31 = buffer.get(pos+13); m32 = buffer.get(pos+14); m33 = buffer.get(pos+15); return this; } /** * Set the values of this matrix by reading 16 float values from the given {@link ByteBuffer} in column-major order, * starting at its current position. * <p> * The ByteBuffer is expected to contain the values in column-major order. * <p> * The position of the ByteBuffer will not be changed by this method. * * @param buffer * the ByteBuffer to read the matrix values from in column-major order * @return this */ public Matrix4f set(ByteBuffer buffer) { int pos = buffer.position(); m00 = buffer.getFloat(pos); m01 = buffer.getFloat(pos+4); m02 = buffer.getFloat(pos+8); m03 = buffer.getFloat(pos+12); m10 = buffer.getFloat(pos+16); m11 = buffer.getFloat(pos+20); m12 = buffer.getFloat(pos+24); m13 = buffer.getFloat(pos+28); m20 = buffer.getFloat(pos+32); m21 = buffer.getFloat(pos+36); m22 = buffer.getFloat(pos+40); m23 = buffer.getFloat(pos+44); m30 = buffer.getFloat(pos+48); m31 = buffer.getFloat(pos+52); m32 = buffer.getFloat(pos+56); m33 = buffer.getFloat(pos+60); return this; } /** * Return the determinant of this matrix. * * @return the determinant */ public float determinant() { return (m00 * m11 - m01 * m10) * (m22 * m33 - m23 * m32) - (m00 * m12 - m02 * m10) * (m21 * m33 - m23 * m31) + (m00 * m13 - m03 * m10) * (m21 * m32 - m22 * m31) + (m01 * m12 - m02 * m11) * (m20 * m33 - m23 * m30) - (m01 * m13 - m03 * m11) * (m20 * m32 - m22 * m30) + (m02 * m13 - m03 * m12) * (m20 * m31 - m21 * m30); } /** * Return the determinant of the top-left 3x3 submatrix of this matrix. * * @return the determinant */ public float determinant3x3() { return m00 * m11 * m22 + m10 * m21 * m02 + m20 * m01 * m12 - m20 * m11 * m02 - m00 * m21 * m12 - m10 * m01 * m22; } /** * Invert this matrix and write the result into <code>dest</code>. * * @param dest * will hold the result * @return this */ public Matrix4f invert(Matrix4f dest) { float s = determinant(); if (s == 0.0f) { dest.set(this); return this; } s = 1.0f / s; if (this != dest) { dest.m00 = (m11 * (m22 * m33 - m23 * m32) + m12 * (m23 * m31 - m21 * m33) + m13 * (m21 * m32 - m22 * m31)) * s; dest.m01 = (m21 * (m02 * m33 - m03 * m32) + m22 * (m03 * m31 - m01 * m33) + m23 * (m01 * m32 - m02 * m31)) * s; dest.m02 = (m31 * (m02 * m13 - m03 * m12) + m32 * (m03 * m11 - m01 * m13) + m33 * (m01 * m12 - m02 * m11)) * s; dest.m03 = (m01 * (m13 * m22 - m12 * m23) + m02 * (m11 * m23 - m13 * m21) + m03 * (m12 * m21 - m11 * m22)) * s; dest.m10 = (m12 * (m20 * m33 - m23 * m30) + m13 * (m22 * m30 - m20 * m32) + m10 * (m23 * m32 - m22 * m33)) * s; dest.m11 = (m22 * (m00 * m33 - m03 * m30) + m23 * (m02 * m30 - m00 * m32) + m20 * (m03 * m32 - m02 * m33)) * s; dest.m12 = (m32 * (m00 * m13 - m03 * m10) + m33 * (m02 * m10 - m00 * m12) + m30 * (m03 * m12 - m02 * m13)) * s; dest.m13 = (m02 * (m13 * m20 - m10 * m23) + m03 * (m10 * m22 - m12 * m20) + m00 * (m12 * m23 - m13 * m22)) * s; dest.m20 = (m13 * (m20 * m31 - m21 * m30) + m10 * (m21 * m33 - m23 * m31) + m11 * (m23 * m30 - m20 * m33)) * s; dest.m21 = (m23 * (m00 * m31 - m01 * m30) + m20 * (m01 * m33 - m03 * m31) + m21 * (m03 * m30 - m00 * m33)) * s; dest.m22 = (m33 * (m00 * m11 - m01 * m10) + m30 * (m01 * m13 - m03 * m11) + m31 * (m03 * m10 - m00 * m13)) * s; dest.m23 = (m03 * (m11 * m20 - m10 * m21) + m00 * (m13 * m21 - m11 * m23) + m01 * (m10 * m23 - m13 * m20)) * s; dest.m30 = (m10 * (m22 * m31 - m21 * m32) + m11 * (m20 * m32 - m22 * m30) + m12 * (m21 * m30 - m20 * m31)) * s; dest.m31 = (m20 * (m02 * m31 - m01 * m32) + m21 * (m00 * m32 - m02 * m30) + m22 * (m01 * m30 - m00 * m31)) * s; dest.m32 = (m30 * (m02 * m11 - m01 * m12) + m31 * (m00 * m12 - m02 * m10) + m32 * (m01 * m10 - m00 * m11)) * s; dest.m33 = (m00 * (m11 * m22 - m12 * m21) + m01 * (m12 * m20 - m10 * m22) + m02 * (m10 * m21 - m11 * m20)) * s; } else { dest.set((m11 * (m22 * m33 - m23 * m32) + m12 * (m23 * m31 - m21 * m33) + m13 * (m21 * m32 - m22 * m31)) * s, (m21 * (m02 * m33 - m03 * m32) + m22 * (m03 * m31 - m01 * m33) + m23 * (m01 * m32 - m02 * m31)) * s, (m31 * (m02 * m13 - m03 * m12) + m32 * (m03 * m11 - m01 * m13) + m33 * (m01 * m12 - m02 * m11)) * s, (m01 * (m13 * m22 - m12 * m23) + m02 * (m11 * m23 - m13 * m21) + m03 * (m12 * m21 - m11 * m22)) * s, (m12 * (m20 * m33 - m23 * m30) + m13 * (m22 * m30 - m20 * m32) + m10 * (m23 * m32 - m22 * m33)) * s, (m22 * (m00 * m33 - m03 * m30) + m23 * (m02 * m30 - m00 * m32) + m20 * (m03 * m32 - m02 * m33)) * s, (m32 * (m00 * m13 - m03 * m10) + m33 * (m02 * m10 - m00 * m12) + m30 * (m03 * m12 - m02 * m13)) * s, (m02 * (m13 * m20 - m10 * m23) + m03 * (m10 * m22 - m12 * m20) + m00 * (m12 * m23 - m13 * m22)) * s, (m13 * (m20 * m31 - m21 * m30) + m10 * (m21 * m33 - m23 * m31) + m11 * (m23 * m30 - m20 * m33)) * s, (m23 * (m00 * m31 - m01 * m30) + m20 * (m01 * m33 - m03 * m31) + m21 * (m03 * m30 - m00 * m33)) * s, (m33 * (m00 * m11 - m01 * m10) + m30 * (m01 * m13 - m03 * m11) + m31 * (m03 * m10 - m00 * m13)) * s, (m03 * (m11 * m20 - m10 * m21) + m00 * (m13 * m21 - m11 * m23) + m01 * (m10 * m23 - m13 * m20)) * s, (m10 * (m22 * m31 - m21 * m32) + m11 * (m20 * m32 - m22 * m30) + m12 * (m21 * m30 - m20 * m31)) * s, (m20 * (m02 * m31 - m01 * m32) + m21 * (m00 * m32 - m02 * m30) + m22 * (m01 * m30 - m00 * m31)) * s, (m30 * (m02 * m11 - m01 * m12) + m31 * (m00 * m12 - m02 * m10) + m32 * (m01 * m10 - m00 * m11)) * s, (m00 * (m11 * m22 - m12 * m21) + m01 * (m12 * m20 - m10 * m22) + m02 * (m10 * m21 - m11 * m20)) * s ); } return this; } /** * Invert this matrix. * * @return this */ public Matrix4f invert() { return invert(this); } /** * Transpose this matrix and store the result in <code>dest</code>. * * @param dest * will hold the result * @return this */ public Matrix4f transpose(Matrix4f dest) { if (this != dest) { dest.m00 = m00; dest.m01 = m10; dest.m02 = m20; dest.m03 = m30; dest.m10 = m01; dest.m11 = m11; dest.m12 = m21; dest.m13 = m31; dest.m20 = m02; dest.m21 = m12; dest.m22 = m22; dest.m23 = m32; dest.m30 = m03; dest.m31 = m13; dest.m32 = m23; dest.m33 = m33; } else { dest.set(m00, m10, m20, m30, m01, m11, m21, m31, m02, m12, m22, m32, m03, m13, m23, m33); } return this; } /** * Transpose only the top-left 3x3 submatrix of this matrix and set the rest of the matrix elements to identity. * * @return this */ public Matrix4f transpose3x3() { return transpose3x3(this); } /** * Transpose only the top-left 3x3 submatrix of this matrix and store the result in <code>dest</code>. * <p> * All other matrix elements of <code>dest</code> will be set to identity. * * @param dest * will hold the result * @return this */ public Matrix4f transpose3x3(Matrix4f dest) { if (this != dest) { dest.m00 = m00; dest.m01 = m10; dest.m02 = m20; dest.m03 = 0.0f; dest.m10 = m01; dest.m11 = m11; dest.m12 = m21; dest.m13 = 0.0f; dest.m20 = m02; dest.m21 = m12; dest.m22 = m22; dest.m23 = 0.0f; dest.m30 = 0.0f; dest.m31 = 0.0f; dest.m32 = 0.0f; dest.m33 = 1.0f; } else { dest.set(m00, m10, m20, 0.0f, m01, m11, m21, 0.0f, m02, m12, m22, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } return this; } /** * Transpose only the top-left 3x3 submatrix of this matrix and store the result in <code>dest</code>. * * @param dest * will hold the result * @return this */ public Matrix4f transpose3x3(Matrix3f dest) { dest.m00 = m00; dest.m01 = m10; dest.m02 = m20; dest.m10 = m01; dest.m11 = m11; dest.m12 = m21; dest.m20 = m02; dest.m21 = m12; dest.m22 = m22; return this; } /** * Transpose this matrix. * * @return this */ public Matrix4f transpose() { return transpose(this); } /** * Set this matrix to be a simple translation matrix. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional translation. * <p> * If you want to post-multiply a translation transformation directly to a * matrix, you can use {@link #translate(float, float, float) translate()} instead. * * @see #translate(float, float, float) * * @param x * the offset to translate in x * @param y * the offset to translate in y * @param z * the offset to translate in z * @return this */ public Matrix4f translation(float x, float y, float z) { m00 = 1.0f; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 1.0f; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = 1.0f; m23 = 0.0f; m30 = x; m31 = y; m32 = z; m33 = 1.0f; return this; } /** * Set this matrix to be a simple translation matrix. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional translation. * <p> * If you want to post-multiply a translation transformation directly to a * matrix, you can use {@link #translate(Vector3f) translate()} instead. * * @see #translate(float, float, float) * * @param offset * the offsets in x, y and z to translate * @return this */ public Matrix4f translation(Vector3f offset) { return translation(offset.x, offset.y, offset.z); } /** * Set only the translation components of this matrix <tt>(m30, m31, m32)</tt> to the given values <tt>(x, y, z)</tt>. * <p> * Note that this will only work properly for orthogonal matrices (without any perspective). * <p> * To build a translation matrix instead, use {@link #translation(float, float, float)}. * To apply a translation to another matrix, use {@link #translate(float, float, float)}. * * @see #translation(float, float, float) * @see #translate(float, float, float) * * @param x * the offset to translate in x * @param y * the offset to translate in y * @param z * the offset to translate in z * @return this */ public Matrix4f setTranslation(float x, float y, float z) { m30 = x; m31 = y; m32 = z; return this; } /** * Set only the translation components of this matrix <tt>(m30, m31, m32)</tt> to the values <tt>(xyz.x, xyz.y, xyz.z)</tt>. * <p> * Note that this will only work properly for orthogonal matrices (without any perspective). * <p> * To build a translation matrix instead, use {@link #translation(Vector3f)}. * To apply a translation to another matrix, use {@link #translate(Vector3f)}. * * @see #translation(Vector3f) * @see #translate(Vector3f) * * @param xyz * the units to translate in <tt>(x, y, z)</tt> * @return this */ public Matrix4f setTranslation(Vector3f xyz) { m30 = xyz.x; m31 = xyz.y; m32 = xyz.z; return this; } /** * Get only the translation components of this matrix <tt>(m30, m31, m32)</tt> and store them in the given vector <code>xyz</code>. * * @param xyz * will hold the translation components of this matrix * @return this */ public Matrix4f getTranslation(Vector3f xyz) { xyz.x = m30; xyz.y = m31; xyz.z = m32; return this; } /** * Return a string representation of this matrix. * <p> * This method creates a new {@link DecimalFormat} on every invocation with the format string "<tt> 0.000E0; -</tt>". * * @return the string representation */ public String toString() { DecimalFormat formatter = new DecimalFormat(" 0.000E0; -"); //$NON-NLS-1$ return toString(formatter).replaceAll("E(\\d+)", "E+$1"); //$NON-NLS-1$ //$NON-NLS-2$ } /** * Return a string representation of this matrix by formatting the matrix elements with the given {@link NumberFormat}. * * @param formatter * the {@link NumberFormat} used to format the matrix values with * @return the string representation */ public String toString(NumberFormat formatter) { return formatter.format(m00) + formatter.format(m10) + formatter.format(m20) + formatter.format(m30) + "\n" //$NON-NLS-1$ + formatter.format(m01) + formatter.format(m11) + formatter.format(m21) + formatter.format(m31) + "\n" //$NON-NLS-1$ + formatter.format(m02) + formatter.format(m12) + formatter.format(m22) + formatter.format(m32) + "\n" //$NON-NLS-1$ + formatter.format(m03) + formatter.format(m13) + formatter.format(m23) + formatter.format(m33) + "\n"; //$NON-NLS-1$ } /** * Get the current values of <code>this</code> matrix and store them into * <code>dest</code>. * <p> * This is the reverse method of {@link #set(Matrix4f)} and allows to obtain * intermediate calculation results when chaining multiple transformations. * * @see #set(Matrix4f) * * @param dest * the destination matrix * @return this */ public Matrix4f get(Matrix4f dest) { dest.set(this); return this; } /** * Get the rotational component of <code>this</code> matrix and store the represented rotation * into the given {@link AxisAngle4f}. * * @see AxisAngle4f#set(Matrix4f) * * @param dest * the destination {@link AxisAngle4f} * @return this */ public Matrix4f get(AxisAngle4f dest) { dest.set(this); return this; } /** * Get the rotational component of <code>this</code> matrix and store the represented rotation * into the given {@link Quaternionf}. * * @see Quaternionf#set(Matrix4f) * * @param dest * the destination {@link Quaternionf} * @return this */ public Matrix4f get(Quaternionf dest) { dest.set(this); return this; } /** * Get the rotational component of <code>this</code> matrix and store the represented rotation * into the given {@link Quaterniond}. * * @see Quaterniond#set(Matrix4f) * * @param dest * the destination {@link Quaterniond} * @return this */ public Matrix4f get(Quaterniond dest) { dest.set(this); return this; } /** * Store this matrix in column-major order into the supplied {@link FloatBuffer} at the current * buffer {@link FloatBuffer#position() position}. * <p> * This method will not increment the position of the given FloatBuffer. * <p> * If you want to specify the offset into the FloatBuffer at which * the matrix is stored, you can use {@link #get(int, FloatBuffer)}, taking * the absolute position as parameter. * * @see #get(int, FloatBuffer) * * @param buffer * will receive the values of this matrix in column-major order at its current position * @return this */ public Matrix4f get(FloatBuffer buffer) { return get(buffer.position(), buffer); } /** * Store this matrix in column-major order into the supplied {@link FloatBuffer} starting at the specified * absolute buffer position/index. * <p> * This method will not increment the position of the given FloatBuffer. * * @param index * the absolute position into the FloatBuffer * @param buffer * will receive the values of this matrix in column-major order * @return this */ public Matrix4f get(int index, FloatBuffer buffer) { buffer.put(index, m00); buffer.put(index+1, m01); buffer.put(index+2, m02); buffer.put(index+3, m03); buffer.put(index+4, m10); buffer.put(index+5, m11); buffer.put(index+6, m12); buffer.put(index+7, m13); buffer.put(index+8, m20); buffer.put(index+9, m21); buffer.put(index+10, m22); buffer.put(index+11, m23); buffer.put(index+12, m30); buffer.put(index+13, m31); buffer.put(index+14, m32); buffer.put(index+15, m33); return this; } /** * Store this matrix in column-major order into the supplied {@link ByteBuffer} at the current * buffer {@link ByteBuffer#position() position}. * <p> * This method will not increment the position of the given ByteBuffer. * <p> * If you want to specify the offset into the ByteBuffer at which * the matrix is stored, you can use {@link #get(int, ByteBuffer)}, taking * the absolute position as parameter. * * @see #get(int, ByteBuffer) * * @param buffer * will receive the values of this matrix in column-major order at its current position * @return this */ public Matrix4f get(ByteBuffer buffer) { return get(buffer.position(), buffer); } /** * Store this matrix in column-major order into the supplied {@link ByteBuffer} starting at the specified * absolute buffer position/index. * <p> * This method will not increment the position of the given ByteBuffer. * * @param index * the absolute position into the ByteBuffer * @param buffer * will receive the values of this matrix in column-major order * @return this */ public Matrix4f get(int index, ByteBuffer buffer) { buffer.putFloat(index, m00); buffer.putFloat(index+4, m01); buffer.putFloat(index+8, m02); buffer.putFloat(index+12, m03); buffer.putFloat(index+16, m10); buffer.putFloat(index+20, m11); buffer.putFloat(index+24, m12); buffer.putFloat(index+28, m13); buffer.putFloat(index+32, m20); buffer.putFloat(index+36, m21); buffer.putFloat(index+40, m22); buffer.putFloat(index+44, m23); buffer.putFloat(index+48, m30); buffer.putFloat(index+52, m31); buffer.putFloat(index+56, m32); buffer.putFloat(index+60, m33); return this; } /** * Store the transpose of this matrix in column-major order into the supplied {@link FloatBuffer} at the current * buffer {@link FloatBuffer#position() position}. * <p> * This method will not increment the position of the given FloatBuffer. * <p> * If you want to specify the offset into the FloatBuffer at which * the matrix is stored, you can use {@link #getTransposed(int, FloatBuffer)}, taking * the absolute position as parameter. * * @see #getTransposed(int, FloatBuffer) * * @param buffer * will receive the values of this matrix in column-major order at its current position * @return this */ public Matrix4f getTransposed(FloatBuffer buffer) { return getTransposed(buffer.position(), buffer); } /** * Store the transpose of this matrix in column-major order into the supplied {@link FloatBuffer} starting at the specified * absolute buffer position/index. * <p> * This method will not increment the position of the given FloatBuffer. * * @param index * the absolute position into the FloatBuffer * @param buffer * will receive the values of this matrix in column-major order * @return this */ public Matrix4f getTransposed(int index, FloatBuffer buffer) { buffer.put(index, m00); buffer.put(index+1, m10); buffer.put(index+2, m20); buffer.put(index+3, m30); buffer.put(index+4, m01); buffer.put(index+5, m11); buffer.put(index+6, m21); buffer.put(index+7, m31); buffer.put(index+8, m02); buffer.put(index+9, m12); buffer.put(index+10, m22); buffer.put(index+11, m32); buffer.put(index+12, m03); buffer.put(index+13, m13); buffer.put(index+14, m23); buffer.put(index+15, m33); return this; } /** * Store the transpose of this matrix in column-major order into the supplied {@link ByteBuffer} at the current * buffer {@link ByteBuffer#position() position}. * <p> * This method will not increment the position of the given ByteBuffer. * <p> * If you want to specify the offset into the ByteBuffer at which * the matrix is stored, you can use {@link #getTransposed(int, ByteBuffer)}, taking * the absolute position as parameter. * * @see #getTransposed(int, ByteBuffer) * * @param buffer * will receive the values of this matrix in column-major order at its current position * @return this */ public Matrix4f getTransposed(ByteBuffer buffer) { return getTransposed(buffer.position(), buffer); } /** * Store the transpose of this matrix in column-major order into the supplied {@link ByteBuffer} starting at the specified * absolute buffer position/index. * <p> * This method will not increment the position of the given ByteBuffer. * * @param index * the absolute position into the ByteBuffer * @param buffer * will receive the values of this matrix in column-major order * @return this */ public Matrix4f getTransposed(int index, ByteBuffer buffer) { buffer.putFloat(index, m00); buffer.putFloat(index+4, m10); buffer.putFloat(index+8, m20); buffer.putFloat(index+12, m30); buffer.putFloat(index+16, m01); buffer.putFloat(index+20, m11); buffer.putFloat(index+24, m21); buffer.putFloat(index+28, m31); buffer.putFloat(index+32, m02); buffer.putFloat(index+36, m12); buffer.putFloat(index+40, m22); buffer.putFloat(index+44, m32); buffer.putFloat(index+48, m03); buffer.putFloat(index+52, m13); buffer.putFloat(index+56, m23); buffer.putFloat(index+60, m33); return this; } /** * Store this matrix into the supplied float array in column-major order. * * @param arr * the array to write the matrix values into * @param offset * the offset into the array * @return this */ public Matrix4f get(float[] arr, int offset) { arr[offset+0] = m00; arr[offset+1] = m01; arr[offset+2] = m02; arr[offset+3] = m03; arr[offset+4] = m10; arr[offset+5] = m11; arr[offset+6] = m12; arr[offset+7] = m13; arr[offset+8] = m20; arr[offset+9] = m21; arr[offset+10] = m22; arr[offset+11] = m23; arr[offset+12] = m30; arr[offset+13] = m31; arr[offset+14] = m32; arr[offset+15] = m33; return this; } /** * Update the given {@link FrustumCuller} with <code>this</code> matrix. * <p> * This will result in the frustum culler recalculating <code>this</code> matrix's frustum planes. * * @see FrustumCuller#set(Matrix4f) * * @param culler * the {@link FrustumCuller} to update * @return this */ public Matrix4f get(FrustumCuller culler) { culler.set(this); return this; } /** * Update the given {@link FrustumRayBuilder} with <code>this</code> matrix. * <p> * This will result in the recalculation of <code>this</code> matrix's frustum. * * @see FrustumRayBuilder#set(Matrix4f) * * @param frustumRayBuilder * the {@link FrustumRayBuilder} to update * @return this */ public Matrix4f get(FrustumRayBuilder frustumRayBuilder) { frustumRayBuilder.set(this); return this; } /** * Set all the values within this matrix to <code>0</code>. * * @return this */ public Matrix4f zero() { m00 = 0.0f; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 0.0f; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = 0.0f; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 0.0f; return this; } /** * Set this matrix to be a simple scale matrix, which scales all axes uniformly by the given factor. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional scaling. * <p> * If you want to post-multiply a scaling transformation directly to a * matrix, you can use {@link #scale(float) scale()} instead. * * @see #scale(float) * * @param factor * the scale factor in x, y and z * @return this */ public Matrix4f scaling(float factor) { m00 = factor; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = factor; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = factor; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be a simple scale matrix. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional scaling. * <p> * If you want to post-multiply a scaling transformation directly to a * matrix, you can use {@link #scale(float, float, float) scale()} instead. * * @see #scale(float, float, float) * * @param x * the scale in x * @param y * the scale in y * @param z * the scale in z * @return this */ public Matrix4f scaling(float x, float y, float z) { m00 = x; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = y; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = z; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be a simple scale matrix which scales the base axes by <tt>xyz.x</tt>, <tt>xyz.y</tt> and <tt>xyz.z</tt> respectively. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional scaling. * <p> * In order to post-multiply a scaling transformation directly to a * matrix use {@link #scale(Vector3f) scale()} instead. * * @see #scale(Vector3f) * * @param xyz * the scale in x, y and z respectively * @return this */ public Matrix4f scaling(Vector3f xyz) { return scaling(xyz.x, xyz.y, xyz.z); } /** * Set this matrix to a rotation matrix which rotates the given radians about a given axis. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional rotation. * <p> * If you want to post-multiply a rotation transformation directly to a * matrix, you can use {@link #rotate(float, Vector3f) rotate()} instead. * * @see #rotate(float, Vector3f) * * @param angle * the angle in radians * @param axis * the axis to rotate about (needs to be {@link Vector3f#normalize() normalized}) * @return this */ public Matrix4f rotation(float angle, Vector3f axis) { return rotation(angle, axis.x, axis.y, axis.z); } /** * Set this matrix to a rotation transformation using the given {@link AxisAngle4f}. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional rotation. * <p> * In order to apply the rotation transformation to an existing transformation, * use {@link #rotate(AxisAngle4f) rotate()} instead. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(AxisAngle4f) * * @param axisAngle * the {@link AxisAngle4f} (needs to be {@link AxisAngle4f#normalize() normalized}) * @return this */ public Matrix4f rotation(AxisAngle4f axisAngle) { return rotation(axisAngle.angle, axisAngle.x, axisAngle.y, axisAngle.z); } /** * Set this matrix to a rotation matrix which rotates the given radians about a given axis. * <p> * The axis described by the three components needs to be a unit vector. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional rotation. * <p> * In order to apply the rotation transformation to an existing transformation, * use {@link #rotate(float, float, float, float) rotate()} instead. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(float, float, float, float) * * @param angle * the angle in radians * @param x * the x-component of the rotation axis * @param y * the y-component of the rotation axis * @param z * the z-component of the rotation axis * @return this */ public Matrix4f rotation(float angle, float x, float y, float z) { float cos = (float) Math.cos(angle); float sin = (float) Math.sin(angle); float C = 1.0f - cos; m00 = cos + x * x * C; m10 = x * y * C - z * sin; m20 = x * z * C + y * sin; m30 = 0.0f; m01 = y * x * C + z * sin; m11 = cos + y * y * C; m21 = y * z * C - x * sin; m31 = 0.0f; m02 = z * x * C - y * sin; m12 = z * y * C + x * sin; m22 = cos + z * z * C; m32 = 0.0f; m03 = 0.0f; m13 = 0.0f; m23 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to a rotation transformation about the X axis. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotationX(float ang) { float cos = (float) Math.cos(ang); float sin = (float) Math.sin(ang); m00 = 1.0f; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = cos; m12 = sin; m13 = 0.0f; m20 = 0.0f; m21 = -sin; m22 = cos; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to a rotation transformation about the Y axis. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotationY(float ang) { float cos = (float) Math.cos(ang); float sin = (float) Math.sin(ang); m00 = cos; m01 = 0.0f; m02 = -sin; m03 = 0.0f; m10 = 0.0f; m11 = 1.0f; m12 = 0.0f; m13 = 0.0f; m20 = sin; m21 = 0.0f; m22 = cos; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to a rotation transformation about the Z axis. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotationZ(float ang) { float cos = (float) Math.cos(ang); float sin = (float) Math.sin(ang); m00 = cos; m01 = sin; m02 = 0.0f; m03 = 0.0f; m10 = -sin; m11 = cos; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = 0.0f; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to the rotation transformation of the given {@link Quaternionf}. * <p> * The resulting matrix can be multiplied against another transformation * matrix to obtain an additional rotation. * <p> * In order to apply the rotation transformation to an existing transformation, * use {@link #rotate(Quaternionf) rotate()} instead. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> * * @see #rotate(Quaternionf) * * @param quat * the {@link Quaternionf} * @return this */ public Matrix4f rotation(Quaternionf quat) { float q00 = 2.0f * quat.x * quat.x; float q11 = 2.0f * quat.y * quat.y; float q22 = 2.0f * quat.z * quat.z; float q01 = 2.0f * quat.x * quat.y; float q02 = 2.0f * quat.x * quat.z; float q03 = 2.0f * quat.x * quat.w; float q12 = 2.0f * quat.y * quat.z; float q13 = 2.0f * quat.y * quat.w; float q23 = 2.0f * quat.z * quat.w; m00 = 1.0f - q11 - q22; m01 = q01 + q23; m02 = q02 - q13; m03 = 0.0f; m10 = q01 - q23; m11 = 1.0f - q22 - q00; m12 = q12 + q03; m13 = 0.0f; m20 = q02 + q13; m21 = q12 - q03; m22 = 1.0f - q11 - q00; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set <code>this</code> matrix to <tt>T * R * S</tt>, where <tt>T</tt> is a translation by the given <tt>(tx, ty, tz)</tt>, * <tt>R</tt> is a rotation transformation specified by the quaternion <tt>(qx, qy, qz, qw)</tt>, and <tt>S</tt> is a scaling transformation * which scales the three axes x, y and z by <tt>(sx, sy, sz)</tt>. * <p> * When transforming a vector by the resulting matrix the scaling transformation will be applied first, then the rotation and * at last the translation. * <p> * This method is equivalent to calling: <tt>translation(tx, ty, tz).rotate(quat).scale(sx, sy, sz)</tt> * * @see #translation(float, float, float) * @see #rotate(Quaternionf) * @see #scale(float, float, float) * * @param tx * the number of units by which to translate the x-component * @param ty * the number of units by which to translate the y-component * @param tz * the number of units by which to translate the z-component * @param qx * the x-coordinate of the vector part of the quaternion * @param qy * the y-coordinate of the vector part of the quaternion * @param qz * the z-coordinate of the vector part of the quaternion * @param qw * the scalar part of the quaternion * @param sx * the scaling factor for the x-axis * @param sy * the scaling factor for the y-axis * @param sz * the scaling factor for the z-axis * @return this */ public Matrix4f translationRotateScale(float tx, float ty, float tz, float qx, float qy, float qz, float qw, float sx, float sy, float sz) { float dqx = 2.0f * qx, dqy = 2.0f * qy, dqz = 2.0f * qz; float q00 = dqx * qx; float q11 = dqy * qy; float q22 = dqz * qz; float q01 = dqx * qy; float q02 = dqx * qz; float q03 = dqx * qw; float q12 = dqy * qz; float q13 = dqy * qw; float q23 = dqz * qw; m00 = sx - (q11 + q22) * sx; m01 = (q01 + q23) * sx; m02 = (q02 - q13) * sx; m03 = 0.0f; m10 = (q01 - q23) * sy; m11 = sy - (q22 + q00) * sy; m12 = (q12 + q03) * sy; m13 = 0.0f; m20 = (q02 + q13) * sz; m21 = (q12 - q03) * sz; m22 = sz - (q11 + q00) * sz; m23 = 0.0f; m30 = tx; m31 = ty; m32 = tz; m33 = 1.0f; return this; } /** * Set <code>this</code> matrix to <tt>T * R * S</tt>, where <tt>T</tt> is the given <code>translation</code>, * <tt>R</tt> is a rotation transformation specified by the given quaternion, and <tt>S</tt> is a scaling transformation * which scales the axes by <code>scale</code>. * <p> * When transforming a vector by the resulting matrix the scaling transformation will be applied first, then the rotation and * at last the translation. * <p> * This method is equivalent to calling: <tt>translation(translation).rotate(quat).scale(scale)</tt> * * @see #translation(Vector3f) * @see #rotate(Quaternionf) * * @param translation * the translation * @param quat * the quaternion representing a rotation * @param scale * the scaling factors * @return this */ public Matrix4f translationRotateScale(Vector3f translation, Quaternionf quat, Vector3f scale) { return translationRotateScale(translation.x, translation.y, translation.z, quat.x, quat.y, quat.z, quat.w, scale.x, scale.y, scale.z); } /** * Set <code>this</code> matrix to <tt>T * R</tt>, where <tt>T</tt> is a translation by the given <tt>(tx, ty, tz)</tt> and * <tt>R</tt> is a rotation transformation specified by the given quaternion. * <p> * When transforming a vector by the resulting matrix the rotation transformation will be applied first and then the translation. * <p> * This method is equivalent to calling: <tt>translation(tx, ty, tz).rotate(quat)</tt> * * @see #translation(float, float, float) * @see #rotate(Quaternionf) * * @param tx * the number of units by which to translate the x-component * @param ty * the number of units by which to translate the y-component * @param tz * the number of units by which to translate the z-component * @param quat * the quaternion representing a rotation * @return this */ public Matrix4f translationRotate(float tx, float ty, float tz, Quaternionf quat) { float qx = 2.0f * quat.x, qy = 2.0f * quat.y, qz = 2.0f * quat.z; float q00 = qx * quat.x; float q11 = qy * quat.y; float q22 = qz * quat.z; float q01 = qx * quat.y; float q02 = qx * quat.z; float q03 = qx * quat.w; float q12 = qy * quat.z; float q13 = qy * quat.w; float q23 = qz * quat.w; m00 = 1.0f - (q11 + q22); m01 = q01 + q23; m02 = q02 - q13; m03 = 0.0f; m10 = q01 - q23; m11 = 1.0f - (q22 + q00); m12 = q12 + q03; m13 = 0.0f; m20 = q02 + q13; m21 = q12 - q03; m22 = 1.0f - (q11 + q00); m23 = 0.0f; m30 = tx; m31 = ty; m32 = tz; m33 = 1.0f; return this; } /** * Set the upper 3x3 matrix of this {@link Matrix4f} to the given {@link Matrix3f} and the rest to the identity. * * @param mat * the 3x3 matrix * @return this */ public Matrix4f setMatrix3(Matrix3f mat) { m00 = mat.m00; m01 = mat.m01; m02 = mat.m02; m03 = 0.0f; m10 = mat.m10; m11 = mat.m11; m12 = mat.m12; m13 = 0.0f; m20 = mat.m20; m21 = mat.m21; m22 = mat.m22; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Transform/multiply the given vector by this matrix and store the result in that vector. * * @see Vector4f#mul(Matrix4f) * * @param v * the vector to transform and to hold the final result * @return this */ public Matrix4f transform(Vector4f v) { v.mul(this); return this; } /** * Transform/multiply the given vector by this matrix and store the result in <code>dest</code>. * * @see Vector4f#mul(Matrix4f, Vector4f) * * @param v * the vector to transform * @param dest * will contain the result * @return this */ public Matrix4f transform(Vector4f v, Vector4f dest) { v.mul(this, dest); return this; } /** * Transform/multiply the given 3D-vector, as if it was a 4D-vector with w=1, by * this matrix and store the result in that vector. * <p> * The given 3D-vector is treated as a 4D-vector with its w-component being 1.0, so it * will represent a point/location in 3D-space rather than a direction. This method is therefore * not suited for perspective projection transformations as it will not save the * <tt>w</tt> component of the transformed vector. * For perspective projection use {@link #transform(Vector4f)}. * <p> * In order to store the result in another vector, use {@link #transform(Vector3f, Vector3f)}. * * @see #transform(Vector3f, Vector3f) * @see #transform(Vector4f) * * @param v * the vector to transform and to hold the final result * @return this */ public Matrix4f transform(Vector3f v) { v.set(m00 * v.x + m10 * v.y + m20 * v.z + m30, m01 * v.x + m11 * v.y + m21 * v.z + m31, m02 * v.x + m12 * v.y + m22 * v.z + m32); return this; } /** * Transform/multiply the given 3D-vector, as if it was a 4D-vector with w=1, by * this matrix and store the result in <code>dest</code>. * <p> * The given 3D-vector is treated as a 4D-vector with its w-component being 1.0, so it * will represent a point/location in 3D-space rather than a direction. This method is therefore * not suited for perspective projection transformations as it will not save the * <tt>w</tt> component of the transformed vector. * For perspective projection use {@link #transform(Vector4f, Vector4f)}. * <p> * In order to store the result in the same vector, use {@link #transform(Vector3f)}. * * @see #transform(Vector3f) * @see #transform(Vector4f, Vector4f) * * @param v * the vector to transform * @param dest * will hold the result * @return this */ public Matrix4f transform(Vector3f v, Vector3f dest) { dest.x = m00 * v.x + m10 * v.y + m20 * v.z + m30; dest.y = m01 * v.x + m11 * v.y + m21 * v.z + m31; dest.z = m02 * v.x + m12 * v.y + m22 * v.z + m32; return this; } /** * Apply scaling to the this matrix by scaling the base axes by the given <tt>xyz.x</tt>, * <tt>xyz.y</tt> and <tt>xyz.z</tt> factors, respectively and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code> * , the scaling will be applied first! * * @param xyz * the factors of the x, y and z component, respectively * @param dest * will hold the result * @return this */ public Matrix4f scale(Vector3f xyz, Matrix4f dest) { return scale(xyz.x, xyz.y, xyz.z, dest); } /** * Apply scaling to this matrix by scaling the base axes by the given <tt>xyz.x</tt>, * <tt>xyz.y</tt> and <tt>xyz.z</tt> factors, respectively. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * scaling will be applied first! * * @param xyz * the factors of the x, y and z component, respectively * @return this */ public Matrix4f scale(Vector3f xyz) { return scale(xyz.x, xyz.y, xyz.z, this); } /** * Apply scaling to this matrix by uniformly scaling all base axes by the given <code>xyz</code> factor * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * scaling will be applied first! * <p> * Individual scaling of all three axes can be applied using {@link #scale(float, float, float, Matrix4f)}. * * @see #scale(float, float, float, Matrix4f) * * @param xyz * the factor for all components * @param dest * will hold the result * @return this */ public Matrix4f scale(float xyz, Matrix4f dest) { return scale(xyz, xyz, xyz, dest); } /** * Apply scaling to this matrix by uniformly scaling all base axes by the given <code>xyz</code> factor. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * scaling will be applied first! * <p> * Individual scaling of all three axes can be applied using {@link #scale(float, float, float)}. * * @see #scale(float, float, float) * * @param xyz * the factor for all components * @return this */ public Matrix4f scale(float xyz) { return scale(xyz, xyz, xyz); } /** * Apply scaling to the this matrix by scaling the base axes by the given x, * y and z factors and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code> * , the scaling will be applied first! * * @param x * the factor of the x component * @param y * the factor of the y component * @param z * the factor of the z component * @param dest * will hold the result * @return this */ public Matrix4f scale(float x, float y, float z, Matrix4f dest) { // scale matrix elements: // m00 = x, m11 = y, m22 = z // m33 = 1 // all others = 0 dest.m00 = m00 * x; dest.m01 = m01 * x; dest.m02 = m02 * x; dest.m03 = m03 * x; dest.m10 = m10 * y; dest.m11 = m11 * y; dest.m12 = m12 * y; dest.m13 = m13 * y; dest.m20 = m20 * z; dest.m21 = m21 * z; dest.m22 = m22 * z; dest.m23 = m23 * z; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return this; } /** * Apply scaling to this matrix by scaling the base axes by the given x, * y and z factors. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * scaling will be applied first! * * @param x * the factor of the x component * @param y * the factor of the y component * @param z * the factor of the z component * @return this */ public Matrix4f scale(float x, float y, float z) { return scale(x, y, z, this); } /** * Apply rotation about the X axis to this matrix by rotating the given amount of radians * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @param dest * will hold the result * @return this */ public Matrix4f rotateX(float ang, Matrix4f dest) { float cos = (float) Math.cos(ang); float sin = (float) Math.sin(ang); float rm11 = cos; float rm12 = sin; float rm21 = -sin; float rm22 = cos; // add temporaries for dependent values float nm10 = m10 * rm11 + m20 * rm12; float nm11 = m11 * rm11 + m21 * rm12; float nm12 = m12 * rm11 + m22 * rm12; float nm13 = m13 * rm11 + m23 * rm12; // set non-dependent values directly dest.m20 = m10 * rm21 + m20 * rm22; dest.m21 = m11 * rm21 + m21 * rm22; dest.m22 = m12 * rm21 + m22 * rm22; dest.m23 = m13 * rm21 + m23 * rm22; // set other values dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m00 = m00; dest.m01 = m01; dest.m02 = m02; dest.m03 = m03; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return this; } /** * Apply rotation about the X axis to this matrix by rotating the given amount of radians. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotateX(float ang) { return rotateX(ang, this); } /** * Apply rotation about the Y axis to this matrix by rotating the given amount of radians * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @param dest * will hold the result * @return this */ public Matrix4f rotateY(float ang, Matrix4f dest) { float cos = (float) Math.cos(ang); float sin = (float) Math.sin(ang); float rm00 = cos; float rm02 = -sin; float rm20 = sin; float rm22 = cos; // add temporaries for dependent values float nm00 = m00 * rm00 + m20 * rm02; float nm01 = m01 * rm00 + m21 * rm02; float nm02 = m02 * rm00 + m22 * rm02; float nm03 = m03 * rm00 + m23 * rm02; // set non-dependent values directly dest.m20 = m00 * rm20 + m20 * rm22; dest.m21 = m01 * rm20 + m21 * rm22; dest.m22 = m02 * rm20 + m22 * rm22; dest.m23 = m03 * rm20 + m23 * rm22; // set other values dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = m10; dest.m11 = m11; dest.m12 = m12; dest.m13 = m13; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return this; } /** * Apply rotation about the Y axis to this matrix by rotating the given amount of radians. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotateY(float ang) { return rotateY(ang, this); } /** * Apply rotation about the Z axis to this matrix by rotating the given amount of radians * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @param dest * will hold the result * @return this */ public Matrix4f rotateZ(float ang, Matrix4f dest) { float cos = (float) Math.cos(ang); float sin = (float) Math.sin(ang); float rm00 = cos; float rm01 = sin; float rm10 = -sin; float rm11 = cos; // add temporaries for dependent values float nm00 = m00 * rm00 + m10 * rm01; float nm01 = m01 * rm00 + m11 * rm01; float nm02 = m02 * rm00 + m12 * rm01; float nm03 = m03 * rm00 + m13 * rm01; // set non-dependent values directly dest.m10 = m00 * rm10 + m10 * rm11; dest.m11 = m01 * rm10 + m11 * rm11; dest.m12 = m02 * rm10 + m12 * rm11; dest.m13 = m03 * rm10 + m13 * rm11; // set other values dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m20 = m20; dest.m21 = m21; dest.m22 = m22; dest.m23 = m23; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return this; } /** * Apply rotation about the Z axis to this matrix by rotating the given amount of radians. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations">http://en.wikipedia.org</a> * * @param ang * the angle in radians * @return this */ public Matrix4f rotateZ(float ang) { return rotateZ(ang, this); } /** * Apply rotation to this matrix by rotating the given amount of radians * about the given axis specified as x, y and z components and store the result in <code>dest</code>. * <p> * The axis described by the three components needs to be a unit vector. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * In order to set the matrix to a rotation matrix without post-multiplying the rotation * transformation, use {@link #rotation(float, float, float, float) rotation()}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> * * @see #rotation(float, float, float, float) * * @param ang * the angle in radians * @param x * the x component of the axis * @param y * the y component of the axis * @param z * the z component of the axis * @param dest * will hold the result * @return this */ public Matrix4f rotate(float ang, float x, float y, float z, Matrix4f dest) { float s = (float) Math.sin(ang); float c = (float) Math.cos(ang); float C = 1.0f - c; // rotation matrix elements: // m30, m31, m32, m03, m13, m23 = 0 // m33 = 1 float rm00 = x * x * C + c; float rm01 = y * x * C + z * s; float rm02 = z * x * C - y * s; float rm10 = x * y * C - z * s; float rm11 = y * y * C + c; float rm12 = z * y * C + x * s; float rm20 = x * z * C + y * s; float rm21 = y * z * C - x * s; float rm22 = z * z * C + c; // add temporaries for dependent values float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; // set non-dependent values directly dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; // set other values dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return this; } /** * Apply rotation to this matrix by rotating the given amount of radians * about the given axis specified as x, y and z components. * <p> * The axis described by the three components needs to be a unit vector. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * rotation will be applied first! * <p> * In order to set the matrix to a rotation matrix without post-multiplying the rotation * transformation, use {@link #rotation(float, float, float, float) rotation()}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> * * @see #rotation(float, float, float, float) * * @param ang * the angle in radians * @param x * the x component of the axis * @param y * the y component of the axis * @param z * the z component of the axis * @return this */ public Matrix4f rotate(float ang, float x, float y, float z) { return rotate(ang, x, y, z, this); } /** * Apply a translation to this matrix by translating by the given number of * units in x, y and z. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>M * T</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>M * T * v</code>, the translation will be applied first! * <p> * In order to set the matrix to a translation transformation without post-multiplying * it, use {@link #translation(Vector3f)}. * * @see #translation(Vector3f) * * @param offset * the number of units in x, y and z by which to translate * @return this */ public Matrix4f translate(Vector3f offset) { return translate(offset.x, offset.y, offset.z); } /** * Apply a translation to this matrix by translating by the given number of * units in x, y and z and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>M * T</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>M * T * v</code>, the translation will be applied first! * <p> * In order to set the matrix to a translation transformation without post-multiplying * it, use {@link #translation(Vector3f)}. * * @see #translation(Vector3f) * * @param offset * the number of units in x, y and z by which to translate * @param dest * will hold the result * @return this */ public Matrix4f translate(Vector3f offset, Matrix4f dest) { return translate(offset.x, offset.y, offset.z, dest); } /** * Apply a translation to this matrix by translating by the given number of * units in x, y and z and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>M * T</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>M * T * v</code>, the translation will be applied first! * <p> * In order to set the matrix to a translation transformation without post-multiplying * it, use {@link #translation(float, float, float)}. * * @see #translation(float, float, float) * * @param x * the offset to translate in x * @param y * the offset to translate in y * @param z * the offset to translate in z * @param dest * will hold the result * @return this */ public Matrix4f translate(float x, float y, float z, Matrix4f dest) { // translation matrix elements: // m00, m11, m22, m33 = 1 // m30 = x, m31 = y, m32 = z // all others = 0 dest.m00 = m00; dest.m01 = m01; dest.m02 = m02; dest.m03 = m03; dest.m10 = m10; dest.m11 = m11; dest.m12 = m12; dest.m13 = m13; dest.m20 = m20; dest.m21 = m21; dest.m22 = m22; dest.m23 = m23; dest.m30 = m00 * x + m10 * y + m20 * z + m30; dest.m31 = m01 * x + m11 * y + m21 * z + m31; dest.m32 = m02 * x + m12 * y + m22 * z + m32; dest.m33 = m03 * x + m13 * y + m23 * z + m33; return this; } /** * Apply a translation to this matrix by translating by the given number of * units in x, y and z. * <p> * If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation * matrix, then the new matrix will be <code>M * T</code>. So when * transforming a vector <code>v</code> with the new matrix by using * <code>M * T * v</code>, the translation will be applied first! * <p> * In order to set the matrix to a translation transformation without post-multiplying * it, use {@link #translation(float, float, float)}. * * @see #translation(float, float, float) * * @param x * the offset to translate in x * @param y * the offset to translate in y * @param z * the offset to translate in z * @return this */ public Matrix4f translate(float x, float y, float z) { Matrix4f c = this; // translation matrix elements: // m00, m11, m22, m33 = 1 // m30 = x, m31 = y, m32 = z // all others = 0 c.m30 = c.m00 * x + c.m10 * y + c.m20 * z + c.m30; c.m31 = c.m01 * x + c.m11 * y + c.m21 * z + c.m31; c.m32 = c.m02 * x + c.m12 * y + c.m22 * z + c.m32; c.m33 = c.m03 * x + c.m13 * y + c.m23 * z + c.m33; return this; } public void writeExternal(ObjectOutput out) throws IOException { out.writeFloat(m00); out.writeFloat(m01); out.writeFloat(m02); out.writeFloat(m03); out.writeFloat(m10); out.writeFloat(m11); out.writeFloat(m12); out.writeFloat(m13); out.writeFloat(m20); out.writeFloat(m21); out.writeFloat(m22); out.writeFloat(m23); out.writeFloat(m30); out.writeFloat(m31); out.writeFloat(m32); out.writeFloat(m33); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { m00 = in.readFloat(); m01 = in.readFloat(); m02 = in.readFloat(); m03 = in.readFloat(); m10 = in.readFloat(); m11 = in.readFloat(); m12 = in.readFloat(); m13 = in.readFloat(); m20 = in.readFloat(); m21 = in.readFloat(); m22 = in.readFloat(); m23 = in.readFloat(); m30 = in.readFloat(); m31 = in.readFloat(); m32 = in.readFloat(); m33 = in.readFloat(); } /** * Apply an orthographic projection transformation to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to an orthographic projection without post-multiplying it, * use {@link #setOrtho(float, float, float, float, float, float) setOrtho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrtho(float, float, float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param dest * will hold the result * @return this */ public Matrix4f ortho(float left, float right, float bottom, float top, float zNear, float zFar, Matrix4f dest) { // calculate right matrix elements float rm00 = 2.0f / (right - left); float rm11 = 2.0f / (top - bottom); float rm22 = -2.0f / (zFar - zNear); float rm30 = -(right + left) / (right - left); float rm31 = -(top + bottom) / (top - bottom); float rm32 = -(zFar + zNear) / (zFar - zNear); // perform optimized multiplication // compute the last column first, because other rows do not depend on it dest.m30 = m00 * rm30 + m10 * rm31 + m20 * rm32 + m30; dest.m31 = m01 * rm30 + m11 * rm31 + m21 * rm32 + m31; dest.m32 = m02 * rm30 + m12 * rm31 + m22 * rm32 + m32; dest.m33 = m03 * rm30 + m13 * rm31 + m23 * rm32 + m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m20 = m20 * rm22; dest.m21 = m21 * rm22; dest.m22 = m22 * rm22; dest.m23 = m23 * rm22; return this; } /** * Apply an orthographic projection transformation to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to an orthographic projection without post-multiplying it, * use {@link #setOrtho(float, float, float, float, float, float) setOrtho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrtho(float, float, float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @return this */ public Matrix4f ortho(float left, float right, float bottom, float top, float zNear, float zFar) { return ortho(left, right, bottom, top, zNear, zFar, this); } /** * Set this matrix to be an orthographic projection transformation. * <p> * In order to apply the orthographic projection to an already existing transformation, * use {@link #ortho(float, float, float, float, float, float) ortho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #ortho(float, float, float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @return this */ public Matrix4f setOrtho(float left, float right, float bottom, float top, float zNear, float zFar) { m00 = 2.0f / (right - left); m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 2.0f / (top - bottom); m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = -2.0f / (zFar - zNear); m23 = 0.0f; m30 = -(right + left) / (right - left); m31 = -(top + bottom) / (top - bottom); m32 = -(zFar + zNear) / (zFar - zNear); m33 = 1.0f; return this; } /** * Apply a symmetric orthographic projection transformation to this matrix and store the result in <code>dest</code>. * <p> * This method is equivalent to calling {@link #ortho(float, float, float, float, float, float, Matrix4f) ortho()} with * <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to a symmetric orthographic projection without post-multiplying it, * use {@link #setOrthoSymmetric(float, float, float, float) setOrthoSymmetric()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrthoSymmetric(float, float, float, float) * * @param width * the distance between the right and left frustum edges * @param height * the distance between the top and bottom frustum edges * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param dest * will hold the result * @return this */ public Matrix4f orthoSymmetric(float width, float height, float zNear, float zFar, Matrix4f dest) { // calculate right matrix elements float rm00 = 2.0f / width; float rm11 = 2.0f / height; float rm22 = -2.0f / (zFar - zNear); float rm32 = -(zFar + zNear) / (zFar - zNear); // perform optimized multiplication // compute the last column first, because other rows do not depend on it dest.m30 = m20 * rm32 + m30; dest.m31 = m21 * rm32 + m31; dest.m32 = m22 * rm32 + m32; dest.m33 = m23 * rm32 + m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m20 = m20 * rm22; dest.m21 = m21 * rm22; dest.m22 = m22 * rm22; dest.m23 = m23 * rm22; return this; } /** * Apply a symmetric orthographic projection transformation to this matrix. * <p> * This method is equivalent to calling {@link #ortho(float, float, float, float, float, float) ortho()} with * <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to a symmetric orthographic projection without post-multiplying it, * use {@link #setOrthoSymmetric(float, float, float, float) setOrthoSymmetric()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrthoSymmetric(float, float, float, float) * * @param width * the distance between the right and left frustum edges * @param height * the distance between the top and bottom frustum edges * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @return this */ public Matrix4f orthoSymmetric(float width, float height, float zNear, float zFar) { return orthoSymmetric(width, height, zNear, zFar, this); } /** * Set this matrix to be a symmetric orthographic projection transformation. * <p> * This method is equivalent to calling {@link #setOrtho(float, float, float, float, float, float) setOrtho()} with * <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. * <p> * In order to apply the symmetric orthographic projection to an already existing transformation, * use {@link #orthoSymmetric(float, float, float, float) orthoSymmetric()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #orthoSymmetric(float, float, float, float) * * @param width * the distance between the right and left frustum edges * @param height * the distance between the top and bottom frustum edges * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @return this */ public Matrix4f setOrthoSymmetric(float width, float height, float zNear, float zFar) { m00 = 2.0f / width; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 2.0f / height; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = -2.0f / (zFar - zNear); m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = -(zFar + zNear) / (zFar - zNear); m33 = 1.0f; return this; } /** * Apply an orthographic projection transformation to this matrix and store the result in <code>dest</code>. * <p> * This method is equivalent to calling {@link #ortho(float, float, float, float, float, float, Matrix4f) ortho()} with * <code>zNear=-1</code> and <code>zFar=+1</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to an orthographic projection without post-multiplying it, * use {@link #setOrtho2D(float, float, float, float) setOrtho()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #ortho(float, float, float, float, float, float, Matrix4f) * @see #setOrtho2D(float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @param dest * will hold the result * @return this */ public Matrix4f ortho2D(float left, float right, float bottom, float top, Matrix4f dest) { // calculate right matrix elements float rm00 = 2.0f / (right - left); float rm11 = 2.0f / (top - bottom); float rm30 = -(right + left) / (right - left); float rm31 = -(top + bottom) / (top - bottom); // perform optimized multiplication // compute the last column first, because other rows do not depend on it dest.m30 = m00 * rm30 + m10 * rm31 + m30; dest.m31 = m01 * rm30 + m11 * rm31 + m31; dest.m32 = m02 * rm30 + m12 * rm31 + m32; dest.m33 = m03 * rm30 + m13 * rm31 + m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m20 = -m20; dest.m21 = -m21; dest.m22 = -m22; dest.m23 = -m23; return this; } /** * Apply an orthographic projection transformation to this matrix. * <p> * This method is equivalent to calling {@link #ortho(float, float, float, float, float, float) ortho()} with * <code>zNear=-1</code> and <code>zFar=+1</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, * then the new matrix will be <code>M * O</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the * orthographic projection transformation will be applied first! * <p> * In order to set the matrix to an orthographic projection without post-multiplying it, * use {@link #setOrtho2D(float, float, float, float) setOrtho2D()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #ortho(float, float, float, float, float, float) * @see #setOrtho2D(float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @return this */ public Matrix4f ortho2D(float left, float right, float bottom, float top) { return ortho2D(left, right, bottom, top, this); } /** * Set this matrix to be an orthographic projection transformation. * <p> * This method is equivalent to calling {@link #setOrtho(float, float, float, float, float, float) setOrtho()} with * <code>zNear=-1</code> and <code>zFar=+1</code>. * <p> * In order to apply the orthographic projection to an already existing transformation, * use {@link #ortho2D(float, float, float, float) ortho2D()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> * * @see #setOrtho(float, float, float, float, float, float) * @see #ortho2D(float, float, float, float) * * @param left * the distance from the center to the left frustum edge * @param right * the distance from the center to the right frustum edge * @param bottom * the distance from the center to the bottom frustum edge * @param top * the distance from the center to the top frustum edge * @return this */ public Matrix4f setOrtho2D(float left, float right, float bottom, float top) { m00 = 2.0f / (right - left); m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 2.0f / (top - bottom); m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = -1.0f; m23 = 0.0f; m30 = -(right + left) / (right - left); m31 = -(top + bottom) / (top - bottom); m32 = 0.0f; m33 = 1.0f; return this; } /** * Apply a rotation transformation to this matrix to make <code>-z</code> point along <code>dir</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookalong rotation matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the * lookalong rotation transformation will be applied first! * <p> * This is equivalent to calling * {@link #lookAt(Vector3f, Vector3f, Vector3f) lookAt} * with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to set the matrix to a lookalong transformation without post-multiplying it, * use {@link #setLookAlong(Vector3f, Vector3f) setLookAlong()}. * * @see #lookAlong(float, float, float, float, float, float) * @see #lookAt(Vector3f, Vector3f, Vector3f) * @see #setLookAlong(Vector3f, Vector3f) * * @param dir * the direction in space to look along * @param up * the direction of 'up' * @return this */ public Matrix4f lookAlong(Vector3f dir, Vector3f up) { return lookAlong(dir.x, dir.y, dir.z, up.x, up.y, up.z, this); } /** * Apply a rotation transformation to this matrix to make <code>-z</code> point along <code>dir</code> * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookalong rotation matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the * lookalong rotation transformation will be applied first! * <p> * This is equivalent to calling * {@link #lookAt(Vector3f, Vector3f, Vector3f) lookAt} * with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to set the matrix to a lookalong transformation without post-multiplying it, * use {@link #setLookAlong(Vector3f, Vector3f) setLookAlong()}. * * @see #lookAlong(float, float, float, float, float, float) * @see #lookAt(Vector3f, Vector3f, Vector3f) * @see #setLookAlong(Vector3f, Vector3f) * * @param dir * the direction in space to look along * @param up * the direction of 'up' * @param dest * will hold the result * @return this */ public Matrix4f lookAlong(Vector3f dir, Vector3f up, Matrix4f dest) { return lookAlong(dir.x, dir.y, dir.z, up.x, up.y, up.z, dest); } /** * Apply a rotation transformation to this matrix to make <code>-z</code> point along <code>dir</code> * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookalong rotation matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the * lookalong rotation transformation will be applied first! * <p> * This is equivalent to calling * {@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt()} * with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to set the matrix to a lookalong transformation without post-multiplying it, * use {@link #setLookAlong(float, float, float, float, float, float) setLookAlong()} * * @see #lookAt(float, float, float, float, float, float, float, float, float) * @see #setLookAlong(float, float, float, float, float, float) * * @param dirX * the x-coordinate of the direction to look along * @param dirY * the y-coordinate of the direction to look along * @param dirZ * the z-coordinate of the direction to look along * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @param dest * will hold the result * @return this */ public Matrix4f lookAlong(float dirX, float dirY, float dirZ, float upX, float upY, float upZ, Matrix4f dest) { // Normalize direction float dirLength = (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); float dirnX = dirX / dirLength; float dirnY = dirY / dirLength; float dirnZ = dirZ / dirLength; // right = direction x up float rightX, rightY, rightZ; rightX = dirnY * upZ - dirnZ * upY; rightY = dirnZ * upX - dirnX * upZ; rightZ = dirnX * upY - dirnY * upX; // normalize right float rightLength = (float) Math.sqrt(rightX * rightX + rightY * rightY + rightZ * rightZ); rightX /= rightLength; rightY /= rightLength; rightZ /= rightLength; // up = right x direction float upnX = rightY * dirnZ - rightZ * dirnY; float upnY = rightZ * dirnX - rightX * dirnZ; float upnZ = rightX * dirnY - rightY * dirnX; // calculate right matrix elements float rm00 = rightX; float rm01 = upnX; float rm02 = -dirnX; float rm10 = rightY; float rm11 = upnY; float rm12 = -dirnY; float rm20 = rightZ; float rm21 = upnZ; float rm22 = -dirnZ; // perform optimized matrix multiplication // introduce temporaries for dependent results float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; // set the rest of the matrix elements dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return this; } /** * Apply a rotation transformation to this matrix to make <code>-z</code> point along <code>dir</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookalong rotation matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the * lookalong rotation transformation will be applied first! * <p> * This is equivalent to calling * {@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt()} * with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to set the matrix to a lookalong transformation without post-multiplying it, * use {@link #setLookAlong(float, float, float, float, float, float) setLookAlong()} * * @see #lookAt(float, float, float, float, float, float, float, float, float) * @see #setLookAlong(float, float, float, float, float, float) * * @param dirX * the x-coordinate of the direction to look along * @param dirY * the y-coordinate of the direction to look along * @param dirZ * the z-coordinate of the direction to look along * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @return this */ public Matrix4f lookAlong(float dirX, float dirY, float dirZ, float upX, float upY, float upZ) { return lookAlong(dirX, dirY, dirZ, upX, upY, upZ, this); } /** * Set this matrix to a rotation transformation to make <code>-z</code> * point along <code>dir</code>. * <p> * This is equivalent to calling * {@link #setLookAt(Vector3f, Vector3f, Vector3f) setLookAt()} * with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to apply the lookalong transformation to any previous existing transformation, * use {@link #lookAlong(Vector3f, Vector3f)}. * * @see #setLookAlong(Vector3f, Vector3f) * @see #lookAlong(Vector3f, Vector3f) * * @param dir * the direction in space to look along * @param up * the direction of 'up' * @return this */ public Matrix4f setLookAlong(Vector3f dir, Vector3f up) { return setLookAlong(dir.x, dir.y, dir.z, up.x, up.y, up.z); } /** * Set this matrix to a rotation transformation to make <code>-z</code> * point along <code>dir</code>. * <p> * This is equivalent to calling * {@link #setLookAt(float, float, float, float, float, float, float, float, float) * setLookAt()} with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>. * <p> * In order to apply the lookalong transformation to any previous existing transformation, * use {@link #lookAlong(float, float, float, float, float, float) lookAlong()} * * @see #setLookAlong(float, float, float, float, float, float) * @see #lookAlong(float, float, float, float, float, float) * * @param dirX * the x-coordinate of the direction to look along * @param dirY * the y-coordinate of the direction to look along * @param dirZ * the z-coordinate of the direction to look along * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @return this */ public Matrix4f setLookAlong(float dirX, float dirY, float dirZ, float upX, float upY, float upZ) { // Normalize direction float dirLength = (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); float dirnX = dirX / dirLength; float dirnY = dirY / dirLength; float dirnZ = dirZ / dirLength; // right = direction x up float rightX, rightY, rightZ; rightX = dirnY * upZ - dirnZ * upY; rightY = dirnZ * upX - dirnX * upZ; rightZ = dirnX * upY - dirnY * upX; // normalize right float rightLength = (float) Math.sqrt(rightX * rightX + rightY * rightY + rightZ * rightZ); rightX /= rightLength; rightY /= rightLength; rightZ /= rightLength; // up = right x direction float upnX = rightY * dirnZ - rightZ * dirnY; float upnY = rightZ * dirnX - rightX * dirnZ; float upnZ = rightX * dirnY - rightY * dirnX; m00 = rightX; m01 = upnX; m02 = -dirnX; m03 = 0.0f; m10 = rightY; m11 = upnY; m12 = -dirnY; m13 = 0.0f; m20 = rightZ; m21 = upnZ; m22 = -dirnZ; m23 = 0.0f; m30 = 0.0f; m31 = 0.0f; m32 = 0.0f; m33 = 1.0f; return this; } /** * Set this matrix to be a "lookat" transformation for a right-handed coordinate system, that aligns * <code>-z</code> with <code>center - eye</code>. * <p> * If you do not want to use {@link Vector3f} instances but simple floats * like in the GLU function, you can use * {@link #setLookAt(float, float, float, float, float, float, float, float, float) setLookAt()} * instead. * <p> * In order to apply the lookat transformation to a previous existing transformation, * use {@link #lookAt(Vector3f, Vector3f, Vector3f) lookAt()}. * * @see #setLookAt(float, float, float, float, float, float, float, float, float) * @see #lookAt(Vector3f, Vector3f, Vector3f) * * @param eye * the position of the camera * @param center * the point in space to look at * @param up * the direction of 'up' * @return this */ public Matrix4f setLookAt(Vector3f eye, Vector3f center, Vector3f up) { return setLookAt(eye.x, eye.y, eye.z, center.x, center.y, center.z, up.x, up.y, up.z); } /** * Set this matrix to be a "lookat" transformation for a right-handed coordinate system, * that aligns <code>-z</code> with <code>center - eye</code>. * <p> * In order to apply the lookat transformation to a previous existing transformation, * use {@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt}. * * @see #setLookAt(Vector3f, Vector3f, Vector3f) * @see #lookAt(float, float, float, float, float, float, float, float, float) * * @param eyeX * the x-coordinate of the eye/camera location * @param eyeY * the y-coordinate of the eye/camera location * @param eyeZ * the z-coordinate of the eye/camera location * @param centerX * the x-coordinate of the point to look at * @param centerY * the y-coordinate of the point to look at * @param centerZ * the z-coordinate of the point to look at * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @return this */ public Matrix4f setLookAt(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { // Compute direction from position to lookAt float dirX, dirY, dirZ; dirX = centerX - eyeX; dirY = centerY - eyeY; dirZ = centerZ - eyeZ; // Normalize direction float dirLength = (float) Math.sqrt( (centerX - eyeX) * (centerX - eyeX) + (centerY - eyeY) * (centerY - eyeY) + (centerZ - eyeZ) * (centerZ - eyeZ)); dirX /= dirLength; dirY /= dirLength; dirZ /= dirLength; // right = direction x up float rightX, rightY, rightZ; rightX = dirY * upZ - dirZ * upY; rightY = dirZ * upX - dirX * upZ; rightZ = dirX * upY - dirY * upX; // normalize right float rightLength = (float) Math.sqrt(rightX * rightX + rightY * rightY + rightZ * rightZ); rightX /= rightLength; rightY /= rightLength; rightZ /= rightLength; // up = right x direction float upnX = rightY * dirZ - rightZ * dirY; float upnY = rightZ * dirX - rightX * dirZ; float upnZ = rightX * dirY - rightY * dirX; m00 = rightX; m01 = upnX; m02 = -dirX; m03 = 0.0f; m10 = rightY; m11 = upnY; m12 = -dirY; m13 = 0.0f; m20 = rightZ; m21 = upnZ; m22 = -dirZ; m23 = 0.0f; m30 = -rightX * eyeX - rightY * eyeY - rightZ * eyeZ; m31 = -upnX * eyeX - upnY * eyeY - upnZ * eyeZ; m32 = dirX * eyeX + dirY * eyeY + dirZ * eyeZ; m33 = 1.0f; return this; } /** * Apply a "lookat" transformation to this matrix for a right-handed coordinate system, * that aligns <code>-z</code> with <code>center - eye</code> and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAt(Vector3f, Vector3f, Vector3f)}. * * @see #lookAt(float, float, float, float, float, float, float, float, float) * @see #setLookAlong(Vector3f, Vector3f) * * @param eye * the position of the camera * @param center * the point in space to look at * @param up * the direction of 'up' * @param dest * will hold the result * @return this */ public Matrix4f lookAt(Vector3f eye, Vector3f center, Vector3f up, Matrix4f dest) { return lookAt(eye.x, eye.y, eye.z, center.x, center.y, center.z, up.x, up.y, up.z, dest); } /** * Apply a "lookat" transformation to this matrix for a right-handed coordinate system, * that aligns <code>-z</code> with <code>center - eye</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAt(Vector3f, Vector3f, Vector3f)}. * * @see #lookAt(float, float, float, float, float, float, float, float, float) * @see #setLookAlong(Vector3f, Vector3f) * * @param eye * the position of the camera * @param center * the point in space to look at * @param up * the direction of 'up' * @return this */ public Matrix4f lookAt(Vector3f eye, Vector3f center, Vector3f up) { return lookAt(eye.x, eye.y, eye.z, center.x, center.y, center.z, up.x, up.y, up.z, this); } /** * Apply a "lookat" transformation to this matrix for a right-handed coordinate system, * that aligns <code>-z</code> with <code>center - eye</code> and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAt(float, float, float, float, float, float, float, float, float) setLookAt()}. * * @see #lookAt(Vector3f, Vector3f, Vector3f) * @see #setLookAt(float, float, float, float, float, float, float, float, float) * * @param eyeX * the x-coordinate of the eye/camera location * @param eyeY * the y-coordinate of the eye/camera location * @param eyeZ * the z-coordinate of the eye/camera location * @param centerX * the x-coordinate of the point to look at * @param centerY * the y-coordinate of the point to look at * @param centerZ * the z-coordinate of the point to look at * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @param dest * will hold the result * @return this */ public Matrix4f lookAt(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ, Matrix4f dest) { // Compute direction from position to lookAt float dirX, dirY, dirZ; dirX = centerX - eyeX; dirY = centerY - eyeY; dirZ = centerZ - eyeZ; // Normalize direction float dirLength = (float) Math.sqrt( (eyeX - centerX) * (eyeX - centerX) + (eyeY - centerY) * (eyeY - centerY) + (eyeZ - centerZ) * (eyeZ - centerZ)); dirX /= dirLength; dirY /= dirLength; dirZ /= dirLength; // right = direction x up float rightX, rightY, rightZ; rightX = dirY * upZ - dirZ * upY; rightY = dirZ * upX - dirX * upZ; rightZ = dirX * upY - dirY * upX; // normalize right float rightLength = (float) Math.sqrt(rightX * rightX + rightY * rightY + rightZ * rightZ); rightX /= rightLength; rightY /= rightLength; rightZ /= rightLength; // up = right x direction float upnX = rightY * dirZ - rightZ * dirY; float upnY = rightZ * dirX - rightX * dirZ; float upnZ = rightX * dirY - rightY * dirX; // calculate right matrix elements float rm00 = rightX; float rm01 = upnX; float rm02 = -dirX; float rm10 = rightY; float rm11 = upnY; float rm12 = -dirY; float rm20 = rightZ; float rm21 = upnZ; float rm22 = -dirZ; float rm30 = -rightX * eyeX - rightY * eyeY - rightZ * eyeZ; float rm31 = -upnX * eyeX - upnY * eyeY - upnZ * eyeZ; float rm32 = dirX * eyeX + dirY * eyeY + dirZ * eyeZ; // perform optimized matrix multiplication // compute last column first, because others do not depend on it dest.m30 = m00 * rm30 + m10 * rm31 + m20 * rm32 + m30; dest.m31 = m01 * rm30 + m11 * rm31 + m21 * rm32 + m31; dest.m32 = m02 * rm30 + m12 * rm31 + m22 * rm32 + m32; dest.m33 = m03 * rm30 + m13 * rm31 + m23 * rm32 + m33; // introduce temporaries for dependent results float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; // set the rest of the matrix elements dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; return this; } /** * Apply a "lookat" transformation to this matrix for a right-handed coordinate system, * that aligns <code>-z</code> with <code>center - eye</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, * then the new matrix will be <code>M * L</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * L * v</code>, * the lookat transformation will be applied first! * <p> * In order to set the matrix to a lookat transformation without post-multiplying it, * use {@link #setLookAt(float, float, float, float, float, float, float, float, float) setLookAt()}. * * @see #lookAt(Vector3f, Vector3f, Vector3f) * @see #setLookAt(float, float, float, float, float, float, float, float, float) * * @param eyeX * the x-coordinate of the eye/camera location * @param eyeY * the y-coordinate of the eye/camera location * @param eyeZ * the z-coordinate of the eye/camera location * @param centerX * the x-coordinate of the point to look at * @param centerY * the y-coordinate of the point to look at * @param centerZ * the z-coordinate of the point to look at * @param upX * the x-coordinate of the up vector * @param upY * the y-coordinate of the up vector * @param upZ * the z-coordinate of the up vector * @return this */ public Matrix4f lookAt(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { return lookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ, this); } /** * Apply a symmetric perspective projection frustum transformation to this matrix and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, * then the new matrix will be <code>M * P</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * P * v</code>, * the perspective projection will be applied first! * <p> * This method first computes the frustum corners using the specified parameters and then makes use of * {@link #frustum(float, float, float, float, float, float) frustum()} to finally apply the frustum * transformation. * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setPerspective(float, float, float, float) setPerspective}. * * @see #frustum(float, float, float, float, float, float) * @see #setPerspective(float, float, float, float) * * @param fovy * the vertical field of view in radians * @param aspect * the aspect ratio (i.e. width / height) * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @param dest * will hold the result * @return this */ public Matrix4f perspective(float fovy, float aspect, float zNear, float zFar, Matrix4f dest) { float h = (float) Math.tan(fovy * 0.5f) * zNear; float w = h * aspect; // calculate right matrix elements float rm00 = zNear / w; float rm11 = zNear / h; float rm22 = -(zFar + zNear) / (zFar - zNear); float rm32 = -2.0f * zFar * zNear / (zFar - zNear); // perform optimized matrix multiplication float nm20 = m20 * rm22 - m30; float nm21 = m21 * rm22 - m31; float nm22 = m22 * rm22 - m32; float nm23 = m23 * rm22 - m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m30 = m20 * rm32; dest.m31 = m21 * rm32; dest.m32 = m22 * rm32; dest.m33 = m23 * rm32; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; return this; } /** * Apply a symmetric perspective projection frustum transformation to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>P</code> the perspective projection matrix, * then the new matrix will be <code>M * P</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * P * v</code>, * the perspective projection will be applied first! * <p> * This method first computes the frustum corners using the specified parameters and then makes use of * {@link #frustum(float, float, float, float, float, float) frustum()} to finally apply the frustum * transformation. * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setPerspective(float, float, float, float) setPerspective}. * * @see #frustum(float, float, float, float, float, float) * @see #setPerspective(float, float, float, float) * * @param fovy * the vertical field of view in radians * @param aspect * the aspect ratio (i.e. width / height) * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @return this */ public Matrix4f perspective(float fovy, float aspect, float zNear, float zFar) { return perspective(fovy, aspect, zNear, zFar, this); } /** * Set this matrix to be a symmetric perspective projection frustum transformation. * <p> * This method first computes the frustum corners using the specified parameters and then makes use of * {@link #setFrustum(float, float, float, float, float, float) setFrustum()} to finally apply the frustum * transformation. * <p> * In order to apply the perspective projection transformation to an existing transformation, * use {@link #perspective(float, float, float, float) perspective()}. * * @see #setFrustum(float, float, float, float, float, float) * @see #perspective(float, float, float, float) * * @param fovy * the vertical field of view in radians * @param aspect * the aspect ratio (i.e. width / height) * @param zNear * near clipping plane distance * @param zFar * far clipping plane distance * @return this */ public Matrix4f setPerspective(float fovy, float aspect, float zNear, float zFar) { float h = (float) Math.tan(fovy * 0.5f) * zNear; float w = h * aspect; m00 = zNear / w; m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = zNear / h; m12 = 0.0f; m13 = 0.0f; m20 = 0.0f; m21 = 0.0f; m22 = -(zFar + zNear) / (zFar - zNear); m23 = -1.0f; m30 = 0.0f; m31 = 0.0f; m32 = -2.0f * zFar * zNear / (zFar - zNear); m33 = 0.0f; return this; } /** * Apply an arbitrary perspective projection frustum transformation to this matrix * and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>F</code> the frustum matrix, * then the new matrix will be <code>M * F</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * F * v</code>, * the frustum transformation will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setFrustum(float, float, float, float, float, float) setFrustum()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #setFrustum(float, float, float, float, float, float) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * the distance along the z-axis to the near clipping plane * @param zFar * the distance along the z-axis to the far clipping plane * @param dest * will hold the result * @return this */ public Matrix4f frustum(float left, float right, float bottom, float top, float zNear, float zFar, Matrix4f dest) { // calculate right matrix elements float rm00 = 2.0f * zNear / (right - left); float rm11 = 2.0f * zNear / (top - bottom); float rm20 = (right + left) / (right - left); float rm21 = (top + bottom) / (top - bottom); float rm22 = -(zFar + zNear) / (zFar - zNear); float rm32 = -2.0f * zFar * zNear / (zFar - zNear); // perform optimized matrix multiplication float nm20 = m00 * rm20 + m10 * rm21 + m20 * rm22 - m30; float nm21 = m01 * rm20 + m11 * rm21 + m21 * rm22 - m31; float nm22 = m02 * rm20 + m12 * rm21 + m22 * rm22 - m32; float nm23 = m03 * rm20 + m13 * rm21 + m23 * rm22 - m33; dest.m00 = m00 * rm00; dest.m01 = m01 * rm00; dest.m02 = m02 * rm00; dest.m03 = m03 * rm00; dest.m10 = m10 * rm11; dest.m11 = m11 * rm11; dest.m12 = m12 * rm11; dest.m13 = m13 * rm11; dest.m30 = m20 * rm32; dest.m31 = m21 * rm32; dest.m32 = m22 * rm32; dest.m33 = m23 * rm32; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return this; } /** * Apply an arbitrary perspective projection frustum transformation to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>F</code> the frustum matrix, * then the new matrix will be <code>M * F</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * F * v</code>, * the frustum transformation will be applied first! * <p> * In order to set the matrix to a perspective frustum transformation without post-multiplying, * use {@link #setFrustum(float, float, float, float, float, float) setFrustum()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #setFrustum(float, float, float, float, float, float) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * the distance along the z-axis to the near clipping plane * @param zFar * the distance along the z-axis to the far clipping plane * @return this */ public Matrix4f frustum(float left, float right, float bottom, float top, float zNear, float zFar) { return frustum(left, right, bottom, top, zNear, zFar, this); } /** * Set this matrix to be an arbitrary perspective projection frustum transformation. * <p> * In order to apply the perspective frustum transformation to an existing transformation, * use {@link #frustum(float, float, float, float, float, float) frustum()}. * <p> * Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective">http://www.songho.ca</a> * * @see #frustum(float, float, float, float, float, float) * * @param left * the distance along the x-axis to the left frustum edge * @param right * the distance along the x-axis to the right frustum edge * @param bottom * the distance along the y-axis to the bottom frustum edge * @param top * the distance along the y-axis to the top frustum edge * @param zNear * the distance along the z-axis to the near clipping plane * @param zFar * the distance along the z-axis to the far clipping plane * @return this */ public Matrix4f setFrustum(float left, float right, float bottom, float top, float zNear, float zFar) { m00 = 2.0f * zNear / (right - left); m01 = 0.0f; m02 = 0.0f; m03 = 0.0f; m10 = 0.0f; m11 = 2.0f * zNear / (top - bottom); m12 = 0.0f; m13 = 0.0f; m20 = (right + left) / (right - left); m21 = (top + bottom) / (top - bottom); m22 = -(zFar + zNear) / (zFar - zNear); m23 = -1.0f; m30 = 0.0f; m31 = 0.0f; m32 = -2.0f * zFar * zNear / (zFar - zNear); m33 = 0.0f; return this; } /** * Apply the rotation transformation of the given {@link Quaternionf} to this matrix and store * the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>Q</code> the rotation matrix obtained from the given quaternion, * then the new matrix will be <code>M * Q</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * Q * v</code>, * the quaternion rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(Quaternionf)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> * * @see #rotation(Quaternionf) * * @param quat * the {@link Quaternionf} * @param dest * will hold the result * @return this */ public Matrix4f rotate(Quaternionf quat, Matrix4f dest) { float q00 = 2.0f * quat.x * quat.x; float q11 = 2.0f * quat.y * quat.y; float q22 = 2.0f * quat.z * quat.z; float q01 = 2.0f * quat.x * quat.y; float q02 = 2.0f * quat.x * quat.z; float q03 = 2.0f * quat.x * quat.w; float q12 = 2.0f * quat.y * quat.z; float q13 = 2.0f * quat.y * quat.w; float q23 = 2.0f * quat.z * quat.w; float rm00 = 1.0f - q11 - q22; float rm01 = q01 + q23; float rm02 = q02 - q13; float rm10 = q01 - q23; float rm11 = 1.0f - q22 - q00; float rm12 = q12 + q03; float rm20 = q02 + q13; float rm21 = q12 - q03; float rm22 = 1.0f - q11 - q00; float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.m33 = m33; return this; } /** * Apply the rotation transformation of the given {@link Quaternionf} to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>Q</code> the rotation matrix obtained from the given quaternion, * then the new matrix will be <code>M * Q</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * Q * v</code>, * the quaternion rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(Quaternionf)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> * * @see #rotation(Quaternionf) * * @param quat * the {@link Quaternionf} * @return this */ public Matrix4f rotate(Quaternionf quat) { return rotate(quat, this); } /** * Apply a rotation transformation, rotating about the given {@link AxisAngle4f}, to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>A</code> the rotation matrix obtained from the given {@link AxisAngle4f}, * then the new matrix will be <code>M * A</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * A * v</code>, * the {@link AxisAngle4f} rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(AxisAngle4f)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(float, float, float, float) * @see #rotation(AxisAngle4f) * * @param axisAngle * the {@link AxisAngle4f} (needs to be {@link AxisAngle4f#normalize() normalized}) * @return this */ public Matrix4f rotate(AxisAngle4f axisAngle) { return rotate(axisAngle.angle, axisAngle.x, axisAngle.y, axisAngle.z); } /** * Apply a rotation transformation, rotating about the given {@link AxisAngle4f} and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>A</code> the rotation matrix obtained from the given {@link AxisAngle4f}, * then the new matrix will be <code>M * A</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * A * v</code>, * the {@link AxisAngle4f} rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(AxisAngle4f)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(float, float, float, float) * @see #rotation(AxisAngle4f) * * @param axisAngle * the {@link AxisAngle4f} (needs to be {@link AxisAngle4f#normalize() normalized}) * @param dest * will hold the result * @return this */ public Matrix4f rotate(AxisAngle4f axisAngle, Matrix4f dest) { return rotate(axisAngle.angle, axisAngle.x, axisAngle.y, axisAngle.z, dest); } /** * Apply a rotation transformation, rotating the given radians about the specified axis, to this matrix. * <p> * If <code>M</code> is <code>this</code> matrix and <code>A</code> the rotation matrix obtained from the given axis-angle, * then the new matrix will be <code>M * A</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * A * v</code>, * the axis-angle rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(float, Vector3f)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(float, float, float, float) * @see #rotation(float, Vector3f) * * @param angle * the angle in radians * @param axis * the rotation axis (needs to be {@link Vector3f#normalize() normalized}) * @return this */ public Matrix4f rotate(float angle, Vector3f axis) { return rotate(angle, axis.x, axis.y, axis.z); } /** * Apply a rotation transformation, rotating the given radians about the specified axis and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>A</code> the rotation matrix obtained from the given axis-angle, * then the new matrix will be <code>M * A</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * A * v</code>, * the axis-angle rotation will be applied first! * <p> * In order to set the matrix to a rotation transformation without post-multiplying, * use {@link #rotation(float, Vector3f)}. * <p> * Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle">http://en.wikipedia.org</a> * * @see #rotate(float, float, float, float) * @see #rotation(float, Vector3f) * * @param angle * the angle in radians * @param axis * the rotation axis (needs to be {@link Vector3f#normalize() normalized}) * @param dest * will hold the result * @return this */ public Matrix4f rotate(float angle, Vector3f axis, Matrix4f dest) { return rotate(angle, axis.x, axis.y, axis.z, dest); } /** * Unproject the given window coordinates <tt>(winX, winY, winZ)</tt> by <code>this</code> matrix using the specified viewport. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by the inverse of <code>this</code> matrix. * <p> * The depth range of <tt>winZ</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * As a necessary computation step for unprojecting, this method computes the inverse of <code>this</code> matrix and stores * it into the <code>inverseOut</code> parameter matrix. In order to avoid computing the matrix inverse with every * invocation, the inverse of <code>this</code> matrix can be built once outside and then the method {@link #unprojectInv(float, float, float, IntBuffer, Vector4f) unprojectInv()} * can be invoked on it. * * @see #unprojectInv(float, float, float, IntBuffer, Vector4f) * * @param winX * the x-coordinate in window coordinates (pixels) * @param winY * the y-coordinate in window coordinates (pixels) * @param winZ * the z-coordinate, which is the depth value in <tt>[0..1]</tt> * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param inverseOut * will hold the inverse of <code>this</code> after the method returns * @param dest * will hold the unprojected position * @return this */ public Matrix4f unproject(float winX, float winY, float winZ, IntBuffer viewport, Matrix4f inverseOut, Vector4f dest) { this.invert(inverseOut); inverseOut.unprojectInv(winX, winY, winZ, viewport, dest); return this; } /** * Unproject the given window coordinates <tt>(winX, winY, winZ)</tt> by <code>this</code> matrix using the specified viewport. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by the inverse of <code>this</code> matrix. * <p> * The depth range of <tt>winZ</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * As a necessary computation step for unprojecting, this method computes the inverse of <code>this</code> matrix and stores * it into the <code>inverseOut</code> parameter matrix. In order to avoid computing the matrix inverse with every * invocation, the inverse of <code>this</code> matrix can be built once outside and then the method {@link #unprojectInv(float, float, float, IntBuffer, Vector4f) unprojectInv()} * can be invoked on it. * * @see #unprojectInv(float, float, float, IntBuffer, Vector3f) * * @param winX * the x-coordinate in window coordinates (pixels) * @param winY * the y-coordinate in window coordinates (pixels) * @param winZ * the z-coordinate, which is the depth value in <tt>[0..1]</tt> * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param inverseOut * will hold the inverse of <code>this</code> after the method returns * @param dest * will hold the unprojected position * @return this */ public Matrix4f unproject(float winX, float winY, float winZ, IntBuffer viewport, Matrix4f inverseOut, Vector3f dest) { this.invert(inverseOut); inverseOut.unprojectInv(winX, winY, winZ, viewport, dest); return this; } /** * Unproject the given window coordinates <code>winCoords</code> by <code>this</code> matrix using the specified viewport. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by the inverse of <code>this</code> matrix. * <p> * The depth range of <tt>winCoords.z</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * As a necessary computation step for unprojecting, this method computes the inverse of <code>this</code> matrix and stores * it into the <code>inverseOut</code> parameter matrix. In order to avoid computing the matrix inverse with every * invocation, the inverse of <code>this</code> matrix can be built once outside and then the method {@link #unprojectInv(float, float, float, IntBuffer, Vector4f) unprojectInv()} * can be invoked on it. * * @see #unprojectInv(float, float, float, IntBuffer, Vector4f) * @see #unproject(float, float, float, IntBuffer, Matrix4f, Vector4f) * * @param winCoords * the window coordinates to unproject * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param inverseOut * will hold the inverse of <code>this</code> after the method returns * @param dest * will hold the unprojected position * @return this */ public Matrix4f unproject(Vector3f winCoords, IntBuffer viewport, Matrix4f inverseOut, Vector4f dest) { return unproject(winCoords.x, winCoords.y, winCoords.z, viewport, inverseOut, dest); } /** * Unproject the given window coordinates <code>winCoords</code> by <code>this</code> matrix using the specified viewport. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by the inverse of <code>this</code> matrix. * <p> * The depth range of <tt>winCoords.z</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * As a necessary computation step for unprojecting, this method computes the inverse of <code>this</code> matrix and stores * it into the <code>inverseOut</code> parameter matrix. In order to avoid computing the matrix inverse with every * invocation, the inverse of <code>this</code> matrix can be built once outside and then the method {@link #unprojectInv(float, float, float, IntBuffer, Vector3f) unprojectInv()} * can be invoked on it. * * @see #unprojectInv(float, float, float, IntBuffer, Vector3f) * @see #unproject(float, float, float, IntBuffer, Matrix4f, Vector3f) * * @param winCoords * the window coordinates to unproject * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param inverseOut * will hold the inverse of <code>this</code> after the method returns * @param dest * will hold the unprojected position * @return this */ public Matrix4f unproject(Vector3f winCoords, IntBuffer viewport, Matrix4f inverseOut, Vector3f dest) { return unproject(winCoords.x, winCoords.y, winCoords.z, viewport, inverseOut, dest); } /** * Unproject the given window coordinates <code>winCoords</code> by <code>this</code> matrix using the specified viewport. * <p> * This method differs from {@link #unproject(Vector3f, IntBuffer, Matrix4f, Vector4f) unproject()} * in that it assumes that <code>this</code> is already the inverse matrix of the original projection matrix. * It exists to avoid recomputing the matrix inverse with every invocation. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by <code>this</code> matrix. * <p> * The depth range of <tt>winCoords.z</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * * @see #unproject(Vector3f, IntBuffer, Matrix4f, Vector4f) * * @param winCoords * the window coordinates to unproject * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return this */ public Matrix4f unprojectInv(Vector3f winCoords, IntBuffer viewport, Vector4f dest) { return unprojectInv(winCoords.x, winCoords.y, winCoords.z, viewport, dest); } /** * Unproject the given window coordinates <tt>(winX, winY, winZ)</tt> by <code>this</code> matrix using the specified viewport. * <p> * This method differs from {@link #unproject(float, float, float, IntBuffer, Matrix4f, Vector4f) unproject()} * in that it assumes that <code>this</code> is already the inverse matrix of the original projection matrix. * It exists to avoid recomputing the matrix inverse with every invocation. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by <code>this</code> matrix. * <p> * The depth range of <tt>winZ</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * * @see #unproject(float, float, float, IntBuffer, Matrix4f, Vector4f) * * @param winX * the x-coordinate in window coordinates (pixels) * @param winY * the y-coordinate in window coordinates (pixels) * @param winZ * the z-coordinate, which is the depth value in <tt>[0..1]</tt> * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return this */ public Matrix4f unprojectInv(float winX, float winY, float winZ, IntBuffer viewport, Vector4f dest) { int pos = viewport.position(); float ndcX = (winX-viewport.get(pos))/viewport.get(pos+2)*2.0f-1.0f; float ndcY = (winY-viewport.get(pos+1))/viewport.get(pos+3)*2.0f-1.0f; float ndcZ = 2.0f*winZ-1.0f; dest.x = m00 * ndcX + m10 * ndcY + m20 * ndcZ + m30; dest.y = m01 * ndcX + m11 * ndcY + m21 * ndcZ + m31; dest.z = m02 * ndcX + m12 * ndcY + m22 * ndcZ + m32; dest.w = m03 * ndcX + m13 * ndcY + m23 * ndcZ + m33; dest.div(dest.w); return this; } /** * Unproject the given window coordinates <code>winCoords</code> by <code>this</code> matrix using the specified viewport. * <p> * This method differs from {@link #unproject(Vector3f, IntBuffer, Matrix4f, Vector3f) unproject()} * in that it assumes that <code>this</code> is already the inverse matrix of the original projection matrix. * It exists to avoid recomputing the matrix inverse with every invocation. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by <code>this</code> matrix. * <p> * The depth range of <tt>winCoords.z</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * * @see #unproject(Vector3f, IntBuffer, Matrix4f, Vector3f) * * @param winCoords * the window coordinates to unproject * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return this */ public Matrix4f unprojectInv(Vector3f winCoords, IntBuffer viewport, Vector3f dest) { return unprojectInv(winCoords.x, winCoords.y, winCoords.z, viewport, dest); } /** * Unproject the given window coordinates <tt>(winX, winY, winZ)</tt> by <code>this</code> matrix using the specified viewport. * <p> * This method differs from {@link #unproject(float, float, float, IntBuffer, Matrix4f, Vector3f) unproject()} * in that it assumes that <code>this</code> is already the inverse matrix of the original projection matrix. * It exists to avoid recomputing the matrix inverse with every invocation. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by <code>this</code> matrix. * <p> * The depth range of <tt>winZ</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * * @see #unproject(float, float, float, IntBuffer, Matrix4f, Vector3f) * * @param winX * the x-coordinate in window coordinates (pixels) * @param winY * the y-coordinate in window coordinates (pixels) * @param winZ * the z-coordinate, which is the depth value in <tt>[0..1]</tt> * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param dest * will hold the unprojected position * @return this */ public Matrix4f unprojectInv(float winX, float winY, float winZ, IntBuffer viewport, Vector3f dest) { int pos = viewport.position(); float ndcX = (winX-viewport.get(pos))/viewport.get(pos+2)*2.0f-1.0f; float ndcY = (winY-viewport.get(pos+1))/viewport.get(pos+3)*2.0f-1.0f; float ndcZ = 2.0f*winZ-1.0f; dest.x = m00 * ndcX + m10 * ndcY + m20 * ndcZ + m30; dest.y = m01 * ndcX + m11 * ndcY + m21 * ndcZ + m31; dest.z = m02 * ndcX + m12 * ndcY + m22 * ndcZ + m32; float w = m03 * ndcX + m13 * ndcY + m23 * ndcZ + m33; dest.div(w); return this; } /** * Unproject the given window coordinates <tt>(winX, winY, winZ)</tt> by the given <code>view</code> and <code>projection</code> matrices using the specified viewport. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by the inverse of <code>projection * view</code>. * <p> * The depth range of <tt>winZ</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * As a necessary computation step for unprojecting, this method computes the inverse of <code>projection * view</code> and stores * it into the <code>inverseOut</code> parameter matrix. In order to avoid computing the matrix inverse with every * invocation, the inverse of both matrices can be built once outside and then the method {@link #unprojectInv(float, float, float, IntBuffer, Vector4f) unprojectInv()} * can be invoked on it. * * @see #unprojectInv(float, float, float, IntBuffer, Vector4f) * * @param winX * the x-coordinate in window coordinates (pixels) * @param winY * the y-coordinate in window coordinates (pixels) * @param winZ * the z-coordinate, which is the depth value in <tt>[0..1]</tt> * @param projection * the projection matrix * @param view * the view matrix * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param inverseOut * will hold the inverse of <code>projection * view</code> after the method returns * @param dest * will hold the unprojected position */ public static void unproject(float winX, float winY, float winZ, Matrix4f projection, Matrix4f view, IntBuffer viewport, Matrix4f inverseOut, Vector4f dest) { inverseOut.set(projection).mul(view).invert().unprojectInv(winX, winY, winZ, viewport, dest); } /** * Unproject the given window coordinates <code>winCoords</code> by the given <code>view</code> and <code>projection</code> matrices using the specified viewport. * <p> * This method first converts the given window coordinates to normalized device coordinates in the range <tt>[-1..1]</tt> * and then transforms those NDC coordinates by the inverse of <code>projection * view</code>. * <p> * The depth range of <tt>winCoords.z</tt> is assumed to be <tt>[0..1]</tt>, which is also the OpenGL default. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * As a necessary computation step for unprojecting, this method computes the inverse of <code>projection * view</code> and stores * it into the <code>inverseOut</code> parameter matrix. In order to avoid computing the matrix inverse with every * invocation, the inverse of both matrices can be built once outside and then the method {@link #unprojectInv(float, float, float, IntBuffer, Vector4f) unprojectInv()} * can be invoked on it. * * @see #unprojectInv(float, float, float, IntBuffer, Vector4f) * * @param winCoords * the window coordinate to unproject * @param projection * the projection matrix * @param view * the view matrix * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param inverseOut * will hold the inverse of <code>projection * view</code> after the method returns * @param dest * will hold the unprojected position */ public static void unproject(Vector3f winCoords, Matrix4f projection, Matrix4f view, IntBuffer viewport, Matrix4f inverseOut, Vector4f dest) { unproject(winCoords.x, winCoords.y, winCoords.z, projection, view, viewport, inverseOut, dest); } /** * Project the given <tt>(x, y, z)</tt> position via <code>this</code> matrix using the specified viewport * and store the resulting window coordinates in <code>winCoordsDest</code>. * <p> * This method transforms the given coordinates by <code>this</code> matrix including perspective division to * obtain normalized device coordinates, and then translates these into window coordinates by using the * given <code>viewport</code> settings <tt>[x, y, width, height]</tt>. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * The depth range of the returned <code>winCoordsDest.z</code> will be <tt>[0..1]</tt>, which is also the OpenGL default. * * @param x * the x-coordinate of the position to project * @param y * the y-coordinate of the position to project * @param z * the z-coordinate of the position to project * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param winCoordsDest * will hold the projected window coordinates * @return this */ public Matrix4f project(float x, float y, float z, IntBuffer viewport, Vector4f winCoordsDest) { winCoordsDest.x = m00 * x + m10 * y + m20 * z + m30; winCoordsDest.y = m01 * x + m11 * y + m21 * z + m31; winCoordsDest.z = m02 * x + m12 * y + m22 * z + m32; winCoordsDest.w = m03 * x + m13 * y + m23 * z + m33; int pos = viewport.position(); winCoordsDest.div(winCoordsDest.w); winCoordsDest.x = (winCoordsDest.x*0.5f+0.5f) * viewport.get(pos+2) + viewport.get(pos); winCoordsDest.y = (winCoordsDest.y*0.5f+0.5f) * viewport.get(pos+3) + viewport.get(pos+1); winCoordsDest.z = (1.0f+winCoordsDest.z)*0.5f; return this; } /** * Project the given <tt>(x, y, z)</tt> position via <code>this</code> matrix using the specified viewport * and store the resulting window coordinates in <code>winCoordsDest</code>. * <p> * This method transforms the given coordinates by <code>this</code> matrix including perspective division to * obtain normalized device coordinates, and then translates these into window coordinates by using the * given <code>viewport</code> settings <tt>[x, y, width, height]</tt>. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * The depth range of the returned <code>winCoordsDest.z</code> will be <tt>[0..1]</tt>, which is also the OpenGL default. * * @param x * the x-coordinate of the position to project * @param y * the y-coordinate of the position to project * @param z * the z-coordinate of the position to project * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param winCoordsDest * will hold the projected window coordinates * @return this */ public Matrix4f project(float x, float y, float z, IntBuffer viewport, Vector3f winCoordsDest) { winCoordsDest.x = m00 * x + m10 * y + m20 * z + m30; winCoordsDest.y = m01 * x + m11 * y + m21 * z + m31; winCoordsDest.z = m02 * x + m12 * y + m22 * z + m32; float w = m03 * x + m13 * y + m23 * z + m33; int pos = viewport.position(); winCoordsDest.div(w); winCoordsDest.x = (winCoordsDest.x*0.5f+0.5f) * viewport.get(pos+2) + viewport.get(pos); winCoordsDest.y = (winCoordsDest.y*0.5f+0.5f) * viewport.get(pos+3) + viewport.get(pos+1); winCoordsDest.z = (1.0f+winCoordsDest.z)*0.5f; return this; } /** * Project the given <code>position</code> via <code>this</code> matrix using the specified viewport * and store the resulting window coordinates in <code>winCoordsDest</code>. * <p> * This method transforms the given coordinates by <code>this</code> matrix including perspective division to * obtain normalized device coordinates, and then translates these into window coordinates by using the * given <code>viewport</code> settings <tt>[x, y, width, height]</tt>. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * The depth range of the returned <code>winCoordsDest.z</code> will be <tt>[0..1]</tt>, which is also the OpenGL default. * * @see #project(float, float, float, IntBuffer, Vector4f) * * @param position * the position to project into window coordinates * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param winCoordsDest * will hold the projected window coordinates * @return this */ public Matrix4f project(Vector3f position, IntBuffer viewport, Vector4f winCoordsDest) { return project(position.x, position.y, position.z, viewport, winCoordsDest); } /** * Project the given <code>position</code> via <code>this</code> matrix using the specified viewport * and store the resulting window coordinates in <code>winCoordsDest</code>. * <p> * This method transforms the given coordinates by <code>this</code> matrix including perspective division to * obtain normalized device coordinates, and then translates these into window coordinates by using the * given <code>viewport</code> settings <tt>[x, y, width, height]</tt>. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * The depth range of the returned <code>winCoordsDest.z</code> will be <tt>[0..1]</tt>, which is also the OpenGL default. * * @see #project(float, float, float, IntBuffer, Vector4f) * * @param position * the position to project into window coordinates * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param winCoordsDest * will hold the projected window coordinates * @return this */ public Matrix4f project(Vector3f position, IntBuffer viewport, Vector3f winCoordsDest) { return project(position.x, position.y, position.z, viewport, winCoordsDest); } /** * Project the given <tt>(x, y, z)</tt> position via the given <code>view</code> and <code>projection</code> matrices using the specified viewport * and store the resulting window coordinates in <code>winCoordsDest</code>. * <p> * This method transforms the given coordinates by <code>projection * view</code> including perspective division to * obtain normalized device coordinates, and then translates these into window coordinates by using the * given <code>viewport</code> settings <tt>[x, y, width, height]</tt>. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * The depth range of the returned <code>winCoordsDest.z</code> will be <tt>[0..1]</tt>, which is also the OpenGL default. * * @param x * the x-coordinate of the position to project * @param y * the y-coordinate of the position to project * @param z * the z-coordinate of the position to project * @param projection * the projection matrix * @param view * the view matrix * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param winCoordsDest * will hold the projected window coordinates */ public static void project(float x, float y, float z, Matrix4f projection, Matrix4f view, IntBuffer viewport, Vector4f winCoordsDest) { winCoordsDest.set(x, y, z, 1.0f); view.transform(winCoordsDest); projection.transform(winCoordsDest); int pos = viewport.position(); winCoordsDest.div(winCoordsDest.w); winCoordsDest.x = (winCoordsDest.x*0.5f+0.5f) * viewport.get(pos+2) + viewport.get(pos); winCoordsDest.y = (winCoordsDest.y*0.5f+0.5f) * viewport.get(pos+3) + viewport.get(pos+1); winCoordsDest.z = (1.0f+winCoordsDest.z)*0.5f; } /** * Project the given <code>position</code> via the given <code>view</code> and <code>projection</code> matrices using the specified viewport * and store the resulting window coordinates in <code>winCoordsDest</code>. * <p> * This method transforms the given coordinates by <code>projection * view</code> including perspective division to * obtain normalized device coordinates, and then translates these into window coordinates by using the * given <code>viewport</code> settings <tt>[x, y, width, height]</tt>. * <p> * This method reads the four viewport parameters from the current IntBuffer's {@link Buffer#position() position} * and does not modify the buffer's position. * <p> * The depth range of the returned <code>winCoordsDest.z</code> will be <tt>[0..1]</tt>, which is also the OpenGL default. * * @see #project(float, float, float, Matrix4f, Matrix4f, IntBuffer, Vector4f) * * @param position * the position to project into window coordinates * @param projection * the projection matrix * @param view * the view matrix * @param viewport * the viewport described by <tt>[x, y, width, height]</tt> * @param winCoordsDest * will hold the projected window coordinates */ public static void project(Vector3f position, Matrix4f projection, Matrix4f view, IntBuffer viewport, Vector4f winCoordsDest) { project(position.x, position.y, position.z, projection, view, viewport, winCoordsDest); } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the equation <tt>x*a + y*b + z*c + d = 0</tt> and store the result in <code>dest</code>. * <p> * The vector <tt>(a, b, c)</tt> must be a unit vector. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb281733(v=vs.85).aspx">msdn.microsoft.com</a> * * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @param dest * will hold the result * @return this */ public Matrix4f reflect(float a, float b, float c, float d, Matrix4f dest) { float rm00 = 1.0f - 2.0f * a * a; float rm01 = -2.0f * a * b; float rm02 = -2.0f * a * c; float rm10 = -2.0f * a * b; float rm11 = 1.0f - 2.0f * b * b; float rm12 = -2.0f * b * c; float rm20 = -2.0f * a * c; float rm21 = -2.0f * b * c; float rm22 = 1.0f - 2.0f * c * c; float rm30 = -2.0f * a * d; float rm31 = -2.0f * b * d; float rm32 = -2.0f * c * d; // matrix multiplication dest.m30 = m00 * rm30 + m10 * rm31 + m20 * rm32 + m30; dest.m31 = m01 * rm30 + m11 * rm31 + m21 * rm32 + m31; dest.m32 = m02 * rm30 + m12 * rm31 + m22 * rm32 + m32; dest.m33 = m03 * rm30 + m13 * rm31 + m23 * rm32 + m33; float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12; dest.m20 = m00 * rm20 + m10 * rm21 + m20 * rm22; dest.m21 = m01 * rm20 + m11 * rm21 + m21 * rm22; dest.m22 = m02 * rm20 + m12 * rm21 + m22 * rm22; dest.m23 = m03 * rm20 + m13 * rm21 + m23 * rm22; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; return this; } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the equation <tt>x*a + y*b + z*c + d = 0</tt>. * <p> * The vector <tt>(a, b, c)</tt> must be a unit vector. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb281733(v=vs.85).aspx">msdn.microsoft.com</a> * * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @return this */ public Matrix4f reflect(float a, float b, float c, float d) { return reflect(a, b, c, d, this); } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the plane normal and a point on the plane. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param nx * the x-coordinate of the plane normal * @param ny * the y-coordinate of the plane normal * @param nz * the z-coordinate of the plane normal * @param px * the x-coordinate of a point on the plane * @param py * the y-coordinate of a point on the plane * @param pz * the z-coordinate of a point on the plane * @return this */ public Matrix4f reflect(float nx, float ny, float nz, float px, float py, float pz) { return reflect(nx, ny, nz, px, py, pz, this); } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the plane normal and a point on the plane, and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param nx * the x-coordinate of the plane normal * @param ny * the y-coordinate of the plane normal * @param nz * the z-coordinate of the plane normal * @param px * the x-coordinate of a point on the plane * @param py * the y-coordinate of a point on the plane * @param pz * the z-coordinate of a point on the plane * @param dest * will hold the result * @return this */ public Matrix4f reflect(float nx, float ny, float nz, float px, float py, float pz, Matrix4f dest) { float length = (float) Math.sqrt(nx * nx + ny * ny + nz * nz); float nnx = nx / length; float nny = ny / length; float nnz = nz / length; /* See: http://mathworld.wolfram.com/Plane.html */ return reflect(nnx, nny, nnz, -nnx * px - nny * py - nnz * pz, dest); } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the plane normal and a point on the plane. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param normal * the plane normal * @param point * a point on the plane * @return this */ public Matrix4f reflect(Vector3f normal, Vector3f point) { return reflect(normal.x, normal.y, normal.z, point.x, point.y, point.z); } /** * Apply a mirror/reflection transformation to this matrix that reflects about a plane * specified via the plane orientation and a point on the plane. * <p> * This method can be used to build a reflection transformation based on the orientation of a mirror object in the scene. * It is assumed that the default mirror plane's normal is <tt>(0, 0, 1)</tt>. So, if the given {@link Quaternionf} is * the identity (does not apply any additional rotation), the reflection plane will be <tt>z=0</tt>, offset by the given <code>point</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param orientation * the plane orientation * @param point * a point on the plane * @return this */ public Matrix4f reflect(Quaternionf orientation, Vector3f point) { return reflect(orientation, point, this); } /** * Apply a mirror/reflection transformation to this matrix that reflects about a plane * specified via the plane orientation and a point on the plane, and store the result in <code>dest</code>. * <p> * This method can be used to build a reflection transformation based on the orientation of a mirror object in the scene. * It is assumed that the default mirror plane's normal is <tt>(0, 0, 1)</tt>. So, if the given {@link Quaternionf} is * the identity (does not apply any additional rotation), the reflection plane will be <tt>z=0</tt>, offset by the given <code>point</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param orientation * the plane orientation * @param point * a point on the plane * @param dest * will hold the result * @return this */ public Matrix4f reflect(Quaternionf orientation, Vector3f point, Matrix4f dest) { double num1 = orientation.x * 2.0; double num2 = orientation.y * 2.0; double num3 = orientation.z * 2.0; float normalX = (float) (orientation.x * num3 + orientation.w * num2); float normalY = (float) (orientation.y * num3 - orientation.w * num1); float normalZ = (float) (1.0 - (orientation.x * num1 + orientation.y * num2)); return reflect(normalX, normalY, normalZ, point.x, point.y, point.z, dest); } /** * Apply a mirror/reflection transformation to this matrix that reflects about the given plane * specified via the plane normal and a point on the plane, and store the result in <code>dest</code>. * <p> * If <code>M</code> is <code>this</code> matrix and <code>R</code> the reflection matrix, * then the new matrix will be <code>M * R</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the * reflection will be applied first! * * @param normal * the plane normal * @param point * a point on the plane * @param dest * will hold the result * @return this */ public Matrix4f reflect(Vector3f normal, Vector3f point, Matrix4f dest) { return reflect(normal.x, normal.y, normal.z, point.x, point.y, point.z, dest); } /** * Set this matrix to a mirror/reflection transformation that reflects about the given plane * specified via the equation <tt>x*a + y*b + z*c + d = 0</tt>. * <p> * The vector <tt>(a, b, c)</tt> must be a unit vector. * <p> * Reference: <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb281733(v=vs.85).aspx">msdn.microsoft.com</a> * * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @return this */ public Matrix4f reflection(float a, float b, float c, float d) { m00 = 1.0f - 2.0f * a * a; m01 = -2.0f * a * b; m02 = -2.0f * a * c; m03 = 0.0f; m10 = -2.0f * a * b; m11 = 1.0f - 2.0f * b * b; m12 = -2.0f * b * c; m13 = 0.0f; m20 = -2.0f * a * c; m21 = -2.0f * b * c; m22 = 1.0f - 2.0f * c * c; m23 = 0.0f; m30 = -2.0f * a * d; m31 = -2.0f * b * d; m32 = -2.0f * c * d; m33 = 1.0f; return this; } /** * Set this matrix to a mirror/reflection transformation that reflects about the given plane * specified via the plane normal and a point on the plane. * * @param nx * the x-coordinate of the plane normal * @param ny * the y-coordinate of the plane normal * @param nz * the z-coordinate of the plane normal * @param px * the x-coordinate of a point on the plane * @param py * the y-coordinate of a point on the plane * @param pz * the z-coordinate of a point on the plane * @return this */ public Matrix4f reflection(float nx, float ny, float nz, float px, float py, float pz) { float length = (float) Math.sqrt(nx * nx + ny * ny + nz * nz); float nnx = nx / length; float nny = ny / length; float nnz = nz / length; /* See: http://mathworld.wolfram.com/Plane.html */ return reflection(nnx, nny, nnz, -nnx * px - nny * py - nnz * pz); } /** * Set this matrix to a mirror/reflection transformation that reflects about the given plane * specified via the plane normal and a point on the plane. * * @param normal * the plane normal * @param point * a point on the plane * @return this */ public Matrix4f reflection(Vector3f normal, Vector3f point) { return reflection(normal.x, normal.y, normal.z, point.x, point.y, point.z); } /** * Set this matrix to a mirror/reflection transformation that reflects about a plane * specified via the plane orientation and a point on the plane. * <p> * This method can be used to build a reflection transformation based on the orientation of a mirror object in the scene. * It is assumed that the default mirror plane's normal is <tt>(0, 0, 1)</tt>. So, if the given {@link Quaternionf} is * the identity (does not apply any additional rotation), the reflection plane will be <tt>z=0</tt>, offset by the given <code>point</code>. * * @param orientation * the plane orientation * @param point * a point on the plane * @return this */ public Matrix4f reflection(Quaternionf orientation, Vector3f point) { double num1 = orientation.x * 2.0; double num2 = orientation.y * 2.0; double num3 = orientation.z * 2.0; float normalX = (float) (orientation.x * num3 + orientation.w * num2); float normalY = (float) (orientation.y * num3 - orientation.w * num1); float normalZ = (float) (1.0 - (orientation.x * num1 + orientation.y * num2)); return reflection(normalX, normalY, normalZ, point.x, point.y, point.z); } /** * Get the row at the given <code>row</code> index, starting with <code>0</code>. * * @param row * the row index in <tt>[0..3]</tt> * @param dest * will hold the row components * @throws IndexOutOfBoundsException if <code>row</code> is not in <tt>[0..3]</tt> */ public void getRow(int row, Vector4f dest) throws IndexOutOfBoundsException { switch (row) { case 0: dest.x = m00; dest.y = m10; dest.z = m20; dest.w = m30; break; case 1: dest.x = m01; dest.y = m11; dest.z = m21; dest.w = m31; break; case 2: dest.x = m02; dest.y = m12; dest.z = m22; dest.w = m32; break; case 3: dest.x = m03; dest.y = m13; dest.z = m23; dest.w = m33; break; default: throw new IndexOutOfBoundsException(); } } /** * Get the column at the given <code>column</code> index, starting with <code>0</code>. * * @param column * the column index in <tt>[0..3]</tt> * @param dest * will hold the column components * @throws IndexOutOfBoundsException if <code>column</code> is not in <tt>[0..3]</tt> */ public void getColumn(int column, Vector4f dest) throws IndexOutOfBoundsException { switch (column) { case 0: dest.x = m00; dest.y = m01; dest.z = m02; dest.w = m03; break; case 1: dest.x = m10; dest.y = m11; dest.z = m12; dest.w = m13; break; case 2: dest.x = m20; dest.y = m21; dest.z = m22; dest.w = m23; break; case 3: dest.x = m30; dest.y = m31; dest.z = m32; dest.w = m32; break; default: throw new IndexOutOfBoundsException(); } } /** * Return the specified {@link Matrix4f}. * <p> * When using method chaining in a fluent interface style, this method can be used to switch * the <i>context object</i>, on which further method invocations operate, to be the given matrix. * * @param other * the {@link Matrix4f} to return * @return that matrix */ public Matrix4f with(Matrix4f other) { return other; } /** * Return the specified {@link Matrix4d}. * <p> * When using method chaining in a fluent interface style, this method can be used to switch * the <i>context object</i>, on which further method invocations operate, to be the given matrix. * * @param other * the {@link Matrix4d} to return * @return that matrix */ public Matrix4d with(Matrix4d other) { return other; } /** * Return the specified {@link Vector3f}. * <p> * When using method chaining in a fluent interface style, this method can be used to switch * the <i>context object</i>, on which further method invocations operate, to be the given vector. * * @param v * the {@link Vector3f} to return * @return that vector */ public Vector3f with(Vector3f v) { return v; } /** * Return the specified {@link Vector4f}. * <p> * When using method chaining in a fluent interface style, this method can be used to switch * the <i>context object</i>, on which further method invocations operate, to be the given vector. * * @param v * the {@link Vector4f} to return * @return that vector */ public Vector4f with(Vector4f v) { return v; } /** * Return the specified {@link Quaternionf}. * <p> * When using method chaining in a fluent interface style, this method can be used to switch * the <i>context object</i>, on which further method invocations operate, to be the given quaternion. * * @param q * the {@link Quaternionf} to return * @return that quaternion */ public Quaternionf with(Quaternionf q) { return q; } /** * Return the specified {@link Quaterniond}. * <p> * When using method chaining in a fluent interface style, this method can be used to switch * the <i>context object</i>, on which further method invocations operate, to be the given quaternion. * * @param q * the {@link Quaterniond} to return * @return that quaternion */ public Quaterniond with(Quaterniond q) { return q; } /** * Return the specified {@link AxisAngle4f}. * <p> * When using method chaining in a fluent interface style, this method can be used to switch * the <i>context object</i>, on which further method invocations operate, to be the given {@link AxisAngle4f}. * * @param a * the {@link AxisAngle4f} to return * @return that quaternion */ public AxisAngle4f with(AxisAngle4f a) { return a; } /** * Return the specified {@link Matrix3f}. * <p> * When using method chaining in a fluent interface style, this method can be used to switch * the <i>context object</i>, on which further method invocations operate, to be the given matrix. * * @param m * the {@link Matrix3f} to return * @return that matrix */ public Matrix3f with(Matrix3f m) { return m; } /** * Compute a normal matrix from the top-left 3x3 submatrix of <code>this</code> * and store it into the top-left 3x3 submatrix of <code>dest</code>. * All other values of <code>dest</code> will be set to {@link #identity() identity}. * <p> * The normal matrix of <tt>m</tt> is the transpose of the inverse of <tt>m</tt>. * In the special case of an orthonormal 3x3 matrix (one that maps any two perpendicular * unit vectors to another pair of perpendicular unit vectors) only the transpose is * computed. * * @param dest * will hold the result * @return this */ public Matrix4f normal(Matrix4f dest) { // see: http://mathworld.wolfram.com/OrthogonalMatrix.html float det = determinant3x3(); float diff = Math.abs(Math.abs(det) - 1.0f); if (diff < 1E-8f) { /* * The fast path, if only 1:1:1 scaling is being used. * In this case, the inverse is the transpose and we can * just return 'this'. */ dest.m00 = m00; dest.m01 = m01; dest.m02 = m02; dest.m03 = 0.0f; dest.m10 = m10; dest.m11 = m11; dest.m12 = m12; dest.m13 = 0.0f; dest.m20 = m20; dest.m21 = m21; dest.m22 = m22; dest.m23 = 0.0f; dest.m30 = 0.0f; dest.m31 = 0.0f; dest.m32 = 0.0f; dest.m33 = 1.0f; return this; } /* The general case */ float s = 1.0f / det; /* Invert and transpose in one go */ dest.set((m11 * m22 - m21 * m12) * s, -(m10 * m22 - m20 * m12) * s, (m10 * m21 - m20 * m11) * s, 0.0f, -(m01 * m22 - m21 * m02) * s, (m00 * m22 - m20 * m02) * s, -(m00 * m21 - m20 * m01) * s, 0.0f, (m01 * m12 - m11 * m02) * s, -(m00 * m12 - m10 * m02) * s, (m00 * m11 - m10 * m01) * s, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); return this; } /** * Compute a normal matrix from the top-left 3x3 submatrix of <code>this</code> * and store it into <code>dest</code>. * <p> * The normal matrix of <tt>m</tt> is the transpose of the inverse of <tt>m</tt>. * In the special case of an orthonormal 3x3 matrix (one that maps any two perpendicular * unit vectors to another pair of perpendicular unit vectors) only the transpose is * computed. * * @param dest * will hold the result * @return this */ public Matrix4f normal(Matrix3f dest) { // see: http://mathworld.wolfram.com/OrthogonalMatrix.html float det = determinant3x3(); float diff = Math.abs(Math.abs(det) - 1.0f); if (diff < 1E-8f) { /* * The fast path, if only 1:1:1 scaling is being used. * In this case, the inverse is the transpose and we can * just return 'this'. */ dest.m00 = m00; dest.m01 = m01; dest.m02 = m02; dest.m10 = m10; dest.m11 = m11; dest.m12 = m12; dest.m20 = m20; dest.m21 = m21; dest.m22 = m22; return this; } /* The general case */ float s = 1.0f / det; /* Invert and transpose in one go */ dest.m00 = (m11 * m22 - m21 * m12) * s; dest.m01 = -(m10 * m22 - m20 * m12) * s; dest.m02 = (m10 * m21 - m20 * m11) * s; dest.m10 = -(m01 * m22 - m21 * m02) * s; dest.m11 = (m00 * m22 - m20 * m02) * s; dest.m12 = -(m00 * m21 - m20 * m01) * s; dest.m20 = (m01 * m12 - m11 * m02) * s; dest.m21 = -(m00 * m12 - m10 * m02) * s; dest.m22 = (m00 * m11 - m10 * m01) * s; return this; } /** * Normalize the upper left 3x3 submatrix of this matrix. * <p> * The resulting matrix will map unit vectors to unit vectors, though a pair of orthogonal input unit * vectors need not be mapped to a pair of orthogonal output vectors if the original matrix was not orthogonal itself * (i.e. had <i>skewing</i>). * * @return this */ public Matrix4f normalize3x3() { return normalize3x3(this); } /** * Normalize the upper left 3x3 submatrix of this matrix and store the result in <code>dest</code>. * <p> * The resulting matrix will map unit vectors to unit vectors, though a pair of orthogonal input unit * vectors need not be mapped to a pair of orthogonal output vectors if the original matrix was not orthogonal itself * (i.e. had <i>skewing</i>). * * @param dest * will hold the result * @return this */ public Matrix4f normalize3x3(Matrix4f dest) { float xlen = (float) Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02); float ylen = (float) Math.sqrt(m10 * m10 + m11 * m11 + m12 * m12); float zlen = (float) Math.sqrt(m20 * m20 + m21 * m21 + m22 * m22); dest.m00 = m00 / xlen; dest.m01 = m01 / xlen; dest.m02 = m02 / xlen; dest.m10 = m10 / ylen; dest.m11 = m11 / ylen; dest.m12 = m12 / ylen; dest.m20 = m20 / zlen; dest.m21 = m21 / zlen; dest.m22 = m22 / zlen; return this; } /** * Normalize the upper left 3x3 submatrix of this matrix and store the result in <code>dest</code>. * <p> * The resulting matrix will map unit vectors to unit vectors, though a pair of orthogonal input unit * vectors need not be mapped to a pair of orthogonal output vectors if the original matrix was not orthogonal itself * (i.e. had <i>skewing</i>). * * @param dest * will hold the result * @return this */ public Matrix4f normalize3x3(Matrix3f dest) { float xlen = (float) Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02); float ylen = (float) Math.sqrt(m10 * m10 + m11 * m11 + m12 * m12); float zlen = (float) Math.sqrt(m20 * m20 + m21 * m21 + m22 * m22); dest.m00 = m00 / xlen; dest.m01 = m01 / xlen; dest.m02 = m02 / xlen; dest.m10 = m10 / ylen; dest.m11 = m11 / ylen; dest.m12 = m12 / ylen; dest.m20 = m20 / zlen; dest.m21 = m21 / zlen; dest.m22 = m22 / zlen; return this; } /** * Calculate a frustum plane of <code>this</code> matrix, which * can be a projection matrix or a combined modelview-projection matrix, and store the result * in the given <code>planeEquation</code>. * <p> * Generally, this method computes the frustum plane in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * The frustum plane will be given in the form of a general plane equation: * <tt>a*x + b*y + c*z + d = 0</tt>, where the given {@link Vector4f} components will * hold the <tt>(a, b, c, d)</tt> values of the equation. * <p> * The plane normal, which is <tt>(a, b, c)</tt>, is directed "inwards" of the frustum. * Any plane/point test using <tt>a*x + b*y + c*z + d</tt> therefore will yield a result greater than zero * if the point is within the frustum (i.e. at the <i>positive</i> side of the frustum plane). * <p> * Reference: <a href="http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @param plane * one of the six possible planes, given as numeric constants * {@link #PLANE_NX}, {@link #PLANE_PX}, * {@link #PLANE_NY}, {@link #PLANE_PY}, * {@link #PLANE_NZ} and {@link #PLANE_PZ} * @param planeEquation * will hold the computed plane equation. * The plane equation will be normalized, meaning that <tt>(a, b, c)</tt> will be a unit vector * @return this */ public Matrix4f frustumPlane(int plane, Vector4f planeEquation) { switch (plane) { case PLANE_NX: planeEquation.set(m03 + m00, m13 + m10, m23 + m20, m33 + m30).normalize3(); break; case PLANE_PX: planeEquation.set(m03 - m00, m13 - m10, m23 - m20, m33 - m30).normalize3(); break; case PLANE_NY: planeEquation.set(m03 + m01, m13 + m11, m23 + m21, m33 + m31).normalize3(); break; case PLANE_PY: planeEquation.set(m03 - m01, m13 - m11, m23 - m21, m33 - m31).normalize3(); break; case PLANE_NZ: planeEquation.set(m03 + m02, m13 + m12, m23 + m22, m33 + m32).normalize3(); break; case PLANE_PZ: planeEquation.set(m03 - m02, m13 - m12, m23 - m22, m33 - m32).normalize3(); break; default: throw new IllegalArgumentException("plane"); //$NON-NLS-1$ } return this; } /** * Compute the corner coordinates of the frustum defined by <code>this</code> matrix, which * can be a projection matrix or a combined modelview-projection matrix, and store the result * in the given <code>point</code>. * <p> * Generally, this method computes the frustum corners in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * Reference: <a href="http://geomalgorithms.com/a05-_intersect-1.html">http://geomalgorithms.com</a> * <p> * Reference: <a href="http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @param corner * one of the eight possible corners, given as numeric constants * {@link #CORNER_NXNYNZ}, {@link #CORNER_PXNYNZ}, {@link #CORNER_PXPYNZ}, {@link #CORNER_NXPYNZ}, * {@link #CORNER_PXNYPZ}, {@link #CORNER_NXNYPZ}, {@link #CORNER_NXPYPZ}, {@link #CORNER_PXPYPZ} * @param point * will hold the resulting corner point coordinates * @return this */ public Matrix4f frustumCorner(int corner, Vector3f point) { float d1, d2, d3; float n1x, n1y, n1z, n2x, n2y, n2z, n3x, n3y, n3z; switch (corner) { case CORNER_NXNYNZ: // left, bottom, near n1x = m03 + m00; n1y = m13 + m10; n1z = m23 + m20; d1 = m33 + m30; // left n2x = m03 + m01; n2y = m13 + m11; n2z = m23 + m21; d2 = m33 + m31; // bottom n3x = m03 + m02; n3y = m13 + m12; n3z = m23 + m22; d3 = m33 + m32; // near break; case CORNER_PXNYNZ: // right, bottom, near n1x = m03 - m00; n1y = m13 - m10; n1z = m23 - m20; d1 = m33 - m30; // right n2x = m03 + m01; n2y = m13 + m11; n2z = m23 + m21; d2 = m33 + m31; // bottom n3x = m03 + m02; n3y = m13 + m12; n3z = m23 + m22; d3 = m33 + m32; // near break; case CORNER_PXPYNZ: // right, top, near n1x = m03 - m00; n1y = m13 - m10; n1z = m23 - m20; d1 = m33 - m30; // right n2x = m03 - m01; n2y = m13 - m11; n2z = m23 - m21; d2 = m33 - m31; // top n3x = m03 + m02; n3y = m13 + m12; n3z = m23 + m22; d3 = m33 + m32; // near break; case CORNER_NXPYNZ: // left, top, near n1x = m03 + m00; n1y = m13 + m10; n1z = m23 + m20; d1 = m33 + m30; // left n2x = m03 - m01; n2y = m13 - m11; n2z = m23 - m21; d2 = m33 - m31; // top n3x = m03 + m02; n3y = m13 + m12; n3z = m23 + m22; d3 = m33 + m32; // near break; case CORNER_PXNYPZ: // right, bottom, far n1x = m03 - m00; n1y = m13 - m10; n1z = m23 - m20; d1 = m33 - m30; // right n2x = m03 + m01; n2y = m13 + m11; n2z = m23 + m21; d2 = m33 + m31; // bottom n3x = m03 - m02; n3y = m13 - m12; n3z = m23 - m22; d3 = m33 - m32; // far break; case CORNER_NXNYPZ: // left, bottom, far n1x = m03 + m00; n1y = m13 + m10; n1z = m23 + m20; d1 = m33 + m30; // left n2x = m03 + m01; n2y = m13 + m11; n2z = m23 + m21; d2 = m33 + m31; // bottom n3x = m03 - m02; n3y = m13 - m12; n3z = m23 - m22; d3 = m33 - m32; // far break; case CORNER_NXPYPZ: // left, top, far n1x = m03 + m00; n1y = m13 + m10; n1z = m23 + m20; d1 = m33 + m30; // left n2x = m03 - m01; n2y = m13 - m11; n2z = m23 - m21; d2 = m33 - m31; // top n3x = m03 - m02; n3y = m13 - m12; n3z = m23 - m22; d3 = m33 - m32; // far break; case CORNER_PXPYPZ: // right, top, far n1x = m03 - m00; n1y = m13 - m10; n1z = m23 - m20; d1 = m33 - m30; // right n2x = m03 - m01; n2y = m13 - m11; n2z = m23 - m21; d2 = m33 - m31; // top n3x = m03 - m02; n3y = m13 - m12; n3z = m23 - m22; d3 = m33 - m32; // far break; default: throw new IllegalArgumentException("corner"); //$NON-NLS-1$ } float c23x, c23y, c23z; c23x = n2y * n3z - n2z * n3y; c23y = n2z * n3x - n2x * n3z; c23z = n2x * n3y - n2y * n3x; float c31x, c31y, c31z; c31x = n3y * n1z - n3z * n1y; c31y = n3z * n1x - n3x * n1z; c31z = n3x * n1y - n3y * n1x; float c12x, c12y, c12z; c12x = n1y * n2z - n1z * n2y; c12y = n1z * n2x - n1x * n2z; c12z = n1x * n2y - n1y * n2x; float dot = n1x * c23x + n1y * c23y + n1z * c23z; point.x = (-c23x * d1 - c31x * d2 - c12x * d3) / dot; point.y = (-c23y * d1 - c31y * d2 - c12y * d3) / dot; point.z = (-c23z * d1 - c31z * d2 - c12z * d3) / dot; return this; } /** * Compute the eye/origin of the perspective frustum transformation defined by <code>this</code> matrix, * which can be a projection matrix or a combined modelview-projection matrix, and store the result * in the given <code>origin</code>. * <p> * Note that this method will only work using perspective projections obtained via one of the * perspective methods, such as {@link #perspective(float, float, float, float) perspective()} * or {@link #frustum(float, float, float, float, float, float) frustum()}. * <p> * Generally, this method computes the origin in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * Reference: <a href="http://geomalgorithms.com/a05-_intersect-1.html">http://geomalgorithms.com</a> * <p> * Reference: <a href="http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @param origin * will hold the origin of the coordinate system before applying <code>this</code> * perspective projection transformation * @return this */ public Matrix4f perspectiveOrigin(Vector3f origin) { /* * Simply compute the intersection point of the left, right and top frustum plane. */ float d1, d2, d3; float n1x, n1y, n1z, n2x, n2y, n2z, n3x, n3y, n3z; n1x = m03 + m00; n1y = m13 + m10; n1z = m23 + m20; d1 = m33 + m30; // left n2x = m03 - m00; n2y = m13 - m10; n2z = m23 - m20; d2 = m33 - m30; // right n3x = m03 - m01; n3y = m13 - m11; n3z = m23 - m21; d3 = m33 - m31; // top float c23x, c23y, c23z; c23x = n2y * n3z - n2z * n3y; c23y = n2z * n3x - n2x * n3z; c23z = n2x * n3y - n2y * n3x; float c31x, c31y, c31z; c31x = n3y * n1z - n3z * n1y; c31y = n3z * n1x - n3x * n1z; c31z = n3x * n1y - n3y * n1x; float c12x, c12y, c12z; c12x = n1y * n2z - n1z * n2y; c12y = n1z * n2x - n1x * n2z; c12z = n1x * n2y - n1y * n2x; float dot = n1x * c23x + n1y * c23y + n1z * c23z; origin.x = (-c23x * d1 - c31x * d2 - c12x * d3) / dot; origin.y = (-c23y * d1 - c31y * d2 - c12y * d3) / dot; origin.z = (-c23z * d1 - c31z * d2 - c12z * d3) / dot; return this; } /** * Return the vertical field-of-view angle in radians of this perspective transformation matrix. * <p> * Note that this method will only work using perspective projections obtained via one of the * perspective methods, such as {@link #perspective(float, float, float, float) perspective()} * or {@link #frustum(float, float, float, float, float, float) frustum()}. * <p> * For orthogonal transformations this method will return <tt>0.0</tt>. * <p> * Reference: <a href="http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @return the vertical field-of-view angle in radians */ public float perspectiveFov() { /* * Compute the angle between the bottom and top frustum plane normals. */ float n1x, n1y, n1z, n2x, n2y, n2z; n1x = m03 + m01; n1y = m13 + m11; n1z = m23 + m21; // bottom n2x = m01 - m03; n2y = m11 - m13; n2z = m21 - m23; // top float n1len = (float) Math.sqrt(n1x * n1x + n1y * n1y + n1z * n1z); float n2len = (float) Math.sqrt(n2x * n2x + n2y * n2y + n2z * n2z); return (float) Math.acos((n1x * n2x + n1y * n2y + n1z * n2z) / (n1len * n2len)); } /** * Determine whether the given point is within the viewing frustum * defined by <code>this</code> matrix. * <p> * This method computes the frustum planes in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * If multiple points are to be tested on the same frustum, create a {@link FrustumCuller} from this matrix instead. * * @see #frustumPlane(int, Vector4f) * @see #isPointInsideFrustum(float, float, float) * * @param point * the point to test * @return <code>true</code> if the given point is inside the clipping frustum; <code>false</code> otherwise */ public boolean isPointInsideFrustum(Vector3f point) { return isPointInsideFrustum(point.x, point.y, point.z); } /** * Determine whether the given point <tt>(x, y, z)</tt> is within the viewing frustum defined by <code>this</code> matrix. * <p> * This method computes the frustum planes in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * If multiple points are to be tested on the same frustum, create a {@link FrustumCuller} from this matrix instead. * <p> * Reference: <a href="http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @see #frustumPlane(int, Vector4f) * @see #isPointInsideFrustum(Vector3f) * * @param x * the x-coordinate of the point * @param y * the y-coordinate of the point * @param z * the z-coordinate of the point * @return <code>true</code> if the given point is inside the clipping frustum; <code>false</code> otherwise */ public boolean isPointInsideFrustum(float x, float y, float z) { return ((m03 + m00) * x + (m13 + m10) * y + (m23 + m20) * z + (m33 + m30) >= 0 && (m03 - m00) * x + (m13 - m10) * y + (m23 - m20) * z + (m33 - m30) >= 0 && (m03 + m01) * x + (m13 + m11) * y + (m23 + m21) * z + (m33 + m31) >= 0 && (m03 - m01) * x + (m13 - m11) * y + (m23 - m21) * z + (m33 - m31) >= 0 && (m03 + m02) * x + (m13 + m12) * y + (m23 + m22) * z + (m33 + m32) >= 0 && (m03 - m02) * x + (m13 - m12) * y + (m23 - m22) * z + (m33 - m32) >= 0); } /** * Determine whether the given sphere is partly or completely within the viewing frustum defined by <code>this</code> matrix. * <p> * This method computes the frustum planes in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * If multiple spheres are to be tested on the same frustum, create a {@link FrustumCuller} from this matrix instead. * * @see #frustumPlane(int, Vector4f) * @see #isSphereInsideFrustum(float, float, float, float) * * @param center * the sphere's center * @param radius * the sphere's radius * @return <code>true</code> if the given sphere is partly or completely inside the clipping frustum; * <code>false</code> otherwise */ public boolean isSphereInsideFrustum(Vector3f center, float radius) { return isSphereInsideFrustum(center.x, center.y, center.z, radius); } /** * Determine whether the given sphere is partly or completely within the viewing frustum defined by <code>this</code> matrix. * <p> * This method computes the frustum planes in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * The algorithm implemented by this method is conservative. This means that in certain circumstances a <i>false positive</i> * can occur, when the method returns <tt>true</tt> for spheres that are actually not visible. * See <a href="http://iquilezles.org/www/articles/frustumcorrect/frustumcorrect.htm">iquilezles.org</a> for an examination of this problem. * <p> * If multiple spheres are to be tested on the same frustum, create a {@link FrustumCuller} from this matrix instead. * <p> * Reference: <a href="http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @see #frustumPlane(int, Vector4f) * @see #isSphereInsideFrustum(Vector3f, float) * * @param x * the x-coordinate of the sphere's center * @param y * the y-coordinate of the sphere's center * @param z * the z-coordinate of the sphere's center * @param r * the sphere's radius * @return <code>true</code> if the given sphere is partly or completely inside the clipping frustum; * <code>false</code> otherwise */ public boolean isSphereInsideFrustum(float x, float y, float z, float r) { return ((m03 + m00) * x + (m13 + m10) * y + (m23 + m20) * z + (m33 + m30) >= -r * Math.sqrt((m03 + m00) * (m03 + m00) + (m13 + m10) * (m13 + m10) + (m23 + m20) * (m23 + m20)) && (m03 - m00) * x + (m13 - m10) * y + (m23 - m20) * z + (m33 - m30) >= -r * Math.sqrt((m03 - m00) * (m03 - m00) + (m13 - m10) * (m13 - m10) + (m23 - m20) * (m23 - m20)) && (m03 + m01) * x + (m13 + m11) * y + (m23 + m21) * z + (m33 + m31) >= -r * Math.sqrt((m03 + m01) * (m03 + m01) + (m13 + m11) * (m13 + m11) + (m23 + m21) * (m23 + m21)) && (m03 - m01) * x + (m13 - m11) * y + (m23 - m21) * z + (m33 - m31) >= -r * Math.sqrt((m03 - m01) * (m03 - m01) + (m13 - m11) * (m13 - m11) + (m23 - m21) * (m23 - m21)) && (m03 + m02) * x + (m13 + m12) * y + (m23 + m22) * z + (m33 + m32) >= -r * Math.sqrt((m03 + m02) * (m03 + m02) + (m13 + m12) * (m13 + m12) + (m23 + m22) * (m23 + m22)) && (m03 - m02) * x + (m13 - m12) * y + (m23 - m22) * z + (m33 - m32) >= -r * Math.sqrt((m03 - m02) * (m03 - m02) + (m13 - m12) * (m13 - m12) + (m23 - m22) * (m23 - m22))); } /** * Determine whether the given axis-aligned box is partly or completely within the viewing frustum defined by <code>this</code> matrix * and, if the box is not inside this frustum, return the index of the plane that culled it. * The box is specified via its <code>min</code> and <code>max</code> corner coordinates. * <p> * This method computes the frustum planes in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * The algorithm implemented by this method is conservative. This means that in certain circumstances a <i>false positive</i> * can occur, when the method returns <tt>true</tt> for boxes that are actually not visible. * See <a href="http://iquilezles.org/www/articles/frustumcorrect/frustumcorrect.htm">iquilezles.org</a> for an examination of this problem. * <p> * If multiple boxes are to be tested on the same frustum, create a {@link FrustumCuller} from this matrix instead. * * @see #frustumPlane(int, Vector4f) * @see #isAabInsideFrustum(float, float, float, float, float, float) * * @param min * the minimum corner coordinates of the axis-aligned box * @param max * the maximum corner coordinates of the axis-aligned box * @return the index of the first plane that culled the box, if the box does not intersect the frustum; * or <tt>-1</tt> if the box intersects the frustum. The plane index is one of * {@link #PLANE_NX}, {@link #PLANE_PX}, * {@link #PLANE_NY}, {@link #PLANE_PY}, * {@link #PLANE_NZ} and {@link #PLANE_PZ} */ public int isAabInsideFrustum(Vector3f min, Vector3f max) { return isAabInsideFrustum(min.x, min.y, min.z, max.x, max.y, max.z); } /** * Determine whether the given axis-aligned box is partly or completely within the viewing frustum defined by <code>this</code> matrix * and, if the box is not inside this frustum, return the index of the plane that culled it. * The box is specified via its min and max corner coordinates. * <p> * This method computes the frustum planes in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * The algorithm implemented by this method is conservative. This means that in certain circumstances a <i>false positive</i> * can occur, when the method returns <tt>true</tt> for boxes that are actually not visible. * See <a href="http://iquilezles.org/www/articles/frustumcorrect/frustumcorrect.htm">iquilezles.org</a> for an examination of this problem. * <p> * If multiple boxes are to be tested on the same frustum, create a {@link FrustumCuller} from this matrix instead. * <p> * Reference: <a href="http://www.cescg.org/CESCG-2002/DSykoraJJelinek/">Efficient View Frustum Culling</a> * <p> * Reference: <a href="http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @see #frustumPlane(int, Vector4f) * @see #isAabInsideFrustum(Vector3f, Vector3f) * * @param minX * the x-coordinate of the minimum corner * @param minY * the y-coordinate of the minimum corner * @param minZ * the z-coordinate of the minimum corner * @param maxX * the x-coordinate of the maximum corner * @param maxY * the y-coordinate of the maximum corner * @param maxZ * the z-coordinate of the maximum corner * @return the index of the first plane that culled the box, if the box does not intersect the frustum; * or <tt>-1</tt> if the box intersects the frustum. The plane index is one of * {@link #PLANE_NX}, {@link #PLANE_PX}, * {@link #PLANE_NY}, {@link #PLANE_PY}, * {@link #PLANE_NZ} and {@link #PLANE_PZ} */ public int isAabInsideFrustum(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { /* * This is an implementation of the "2.4 Basic intersection test" of the mentioned site. * It does not distinguish between partially inside and fully inside, though, so the test with the 'p' vertex is omitted. * * In addition to the algorithm in the paper, this method also returns the index of the first plane that culled the box * or -1 if the box intersects the frustum. */ int plane = 0; if ((m03 + m00) * (m03 + m00 < 0 ? minX : maxX) + (m13 + m10) * (m13 + m10 < 0 ? minY : maxY) + (m23 + m20) * (m23 + m20 < 0 ? minZ : maxZ) >= -m33 - m30 && ++plane != 0 && (m03 - m00) * (m03 - m00 < 0 ? minX : maxX) + (m13 - m10) * (m13 - m10 < 0 ? minY : maxY) + (m23 - m20) * (m23 - m20 < 0 ? minZ : maxZ) >= -m33 + m30 && ++plane != 0 && (m03 + m01) * (m03 + m01 < 0 ? minX : maxX) + (m13 + m11) * (m13 + m11 < 0 ? minY : maxY) + (m23 + m21) * (m23 + m21 < 0 ? minZ : maxZ) >= -m33 - m31 && ++plane != 0 && (m03 - m01) * (m03 - m01 < 0 ? minX : maxX) + (m13 - m11) * (m13 - m11 < 0 ? minY : maxY) + (m23 - m21) * (m23 - m21 < 0 ? minZ : maxZ) >= -m33 + m31 && ++plane != 0 && (m03 + m02) * (m03 + m02 < 0 ? minX : maxX) + (m13 + m12) * (m13 + m12 < 0 ? minY : maxY) + (m23 + m22) * (m23 + m22 < 0 ? minZ : maxZ) >= -m33 - m32 && ++plane != 0 && (m03 - m02) * (m03 - m02 < 0 ? minX : maxX) + (m13 - m12) * (m13 - m12 < 0 ? minY : maxY) + (m23 - m22) * (m23 - m22 < 0 ? minZ : maxZ) >= -m33 + m32) return -1; return plane; } /** * Determine whether the given axis-aligned box is partly or completely within the viewing frustum defined by <code>this</code> matrix * and, if the box is not inside this frustum, return the index of the plane that culled it. * The box is specified via its <code>min</code> and <code>max</code> corner coordinates. * <p> * This method differs from {@link #isAabInsideFrustum(Vector3f, Vector3f) isAabInsideFrustum()} in that * it allows to mask-off planes that should not be calculated. For example, in order to only test a box against the * left frustum plane, use a mask of {@link #PLANE_MASK_NX}. Or in order to test all planes <i>except</i> the left plane, use * a mask of <tt>(~0 ^ PLANE_MASK_NX)</tt>. * <p> * This method computes the frustum planes in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * The algorithm implemented by this method is conservative. This means that in certain circumstances a <i>false positive</i> * can occur, when the method returns <tt>true</tt> for boxes that are actually not visible. * See <a href="http://iquilezles.org/www/articles/frustumcorrect/frustumcorrect.htm">iquilezles.org</a> for an examination of this problem. * <p> * If multiple boxes are to be tested on the same frustum, create a {@link FrustumCuller} from this matrix instead. * * @see #frustumPlane(int, Vector4f) * @see #isAabInsideFrustumMasked(float, float, float, float, float, float, int) * * @param min * the minimum corner coordinates of the axis-aligned box * @param max * the maximum corner coordinates of the axis-aligned box * @param mask * contains as bitset all the planes that should be tested. This value can be any combination of * {@link #PLANE_MASK_NX}, {@link #PLANE_MASK_PY}, * {@link #PLANE_MASK_NY}, {@link #PLANE_MASK_PY}, * {@link #PLANE_MASK_NZ} and {@link #PLANE_MASK_PZ} * @return the index of the first plane that culled the box, if the box does not intersect the frustum; * or <tt>-1</tt> if the box intersects the frustum. The plane index is one of * {@link #PLANE_NX}, {@link #PLANE_PX}, * {@link #PLANE_NY}, {@link #PLANE_PY}, * {@link #PLANE_NZ} and {@link #PLANE_PZ} */ public int isAabInsideFrustumMasked(Vector3f min, Vector3f max, int mask) { return isAabInsideFrustumMasked(min.x, min.y, min.z, max.x, max.y, max.z, mask); } /** * Determine whether the given axis-aligned box is partly or completely within the viewing frustum defined by <code>this</code> matrix * and, if the box is not inside this frustum, return the index of the plane that culled it. * The box is specified via its min and max corner coordinates. * <p> * This method differs from {@link #isAabInsideFrustum(float, float, float, float, float, float) isAabInsideFrustum()} in that * it allows to mask-off planes that should not be calculated. For example, in order to only test a box against the * left frustum plane, use a mask of {@link #PLANE_MASK_NX}. Or in order to test all planes <i>except</i> the left plane, use * a mask of <tt>(~0 ^ PLANE_MASK_NX)</tt>. * <p> * This method computes the frustum planes in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * The algorithm implemented by this method is conservative. This means that in certain circumstances a <i>false positive</i> * can occur, when the method returns <tt>true</tt> for boxes that are actually not visible. * See <a href="http://iquilezles.org/www/articles/frustumcorrect/frustumcorrect.htm">iquilezles.org</a> for an examination of this problem. * <p> * If multiple boxes are to be tested on the same frustum, create a {@link FrustumCuller} from this matrix instead. * <p> * Reference: <a href="http://www.cescg.org/CESCG-2002/DSykoraJJelinek/">Efficient View Frustum Culling</a> * <p> * Reference: <a href="http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @see #frustumPlane(int, Vector4f) * @see #isAabInsideFrustumMasked(Vector3f, Vector3f, int) * * @param minX * the x-coordinate of the minimum corner * @param minY * the y-coordinate of the minimum corner * @param minZ * the z-coordinate of the minimum corner * @param maxX * the x-coordinate of the maximum corner * @param maxY * the y-coordinate of the maximum corner * @param maxZ * the z-coordinate of the maximum corner * @param mask * contains as bitset all the planes that should be tested. This value can be any combination of * {@link #PLANE_MASK_NX}, {@link #PLANE_MASK_PY}, * {@link #PLANE_MASK_NY}, {@link #PLANE_MASK_PY}, * {@link #PLANE_MASK_NZ} and {@link #PLANE_MASK_PZ} * @return the index of the first plane that culled the box, if the box does not intersect the frustum; * or <tt>-1</tt> if the box intersects the frustum. The plane index is one of * {@link #PLANE_NX}, {@link #PLANE_PX}, * {@link #PLANE_NY}, {@link #PLANE_PY}, * {@link #PLANE_NZ} and {@link #PLANE_PZ} */ public int isAabInsideFrustumMasked(float minX, float minY, float minZ, float maxX, float maxY, float maxZ, int mask) { /* * This is an implementation of the "2.5 Plane masking and coherency" of the mentioned site. * It does not distinguish between partially inside and fully inside, though, so the test with the 'p' vertex is omitted. * * In addition to the algorithm in the paper, this method also returns the index of the first plane that culled the box * or -1 if the box intersects the frustum. */ int plane = 0; if (((mask & PLANE_MASK_NX) == 0 || (m03 + m00) * (m03 + m00 < 0 ? minX : maxX) + (m13 + m10) * (m13 + m10 < 0 ? minY : maxY) + (m23 + m20) * (m23 + m20 < 0 ? minZ : maxZ) >= -m33 - m30) && ++plane != 0 && ((mask & PLANE_MASK_PX) == 0 || (m03 - m00) * (m03 - m00 < 0 ? minX : maxX) + (m13 - m10) * (m13 - m10 < 0 ? minY : maxY) + (m23 - m20) * (m23 - m20 < 0 ? minZ : maxZ) >= -m33 + m30) && ++plane != 0 && ((mask & PLANE_MASK_NY) == 0 || (m03 + m01) * (m03 + m01 < 0 ? minX : maxX) + (m13 + m11) * (m13 + m11 < 0 ? minY : maxY) + (m23 + m21) * (m23 + m21 < 0 ? minZ : maxZ) >= -m33 - m31) && ++plane != 0 && ((mask & PLANE_MASK_PY) == 0 || (m03 - m01) * (m03 - m01 < 0 ? minX : maxX) + (m13 - m11) * (m13 - m11 < 0 ? minY : maxY) + (m23 - m21) * (m23 - m21 < 0 ? minZ : maxZ) >= -m33 + m31) && ++plane != 0 && ((mask & PLANE_MASK_NZ) == 0 || (m03 + m02) * (m03 + m02 < 0 ? minX : maxX) + (m13 + m12) * (m13 + m12 < 0 ? minY : maxY) + (m23 + m22) * (m23 + m22 < 0 ? minZ : maxZ) >= -m33 - m32) && ++plane != 0 && ((mask & PLANE_MASK_PZ) == 0 || (m03 - m02) * (m03 - m02 < 0 ? minX : maxX) + (m13 - m12) * (m13 - m12 < 0 ? minY : maxY) + (m23 - m22) * (m23 - m22 < 0 ? minZ : maxZ) >= -m33 + m32)) return -1; return plane; } /** * Obtain the direction of a ray starting at the center of the coordinate system and going * through the near frustum plane. * <p> * This method computes the <code>dir</code> vector in the local frame of * any coordinate system that existed before <code>this</code> * transformation was applied to it in order to yield homogeneous clipping space. * <p> * The parameters <code>x</code> and <code>y</code> are used to interpolate the generated ray direction * from the bottom-left to the top-right frustum corners. * <p> * For optimal efficiency when building many ray directions over the whole frustum, * it is recommended to use this method only in order to compute the four corner rays at * <tt>(0, 0)</tt>, <tt>(1, 0)</tt>, <tt>(0, 1)</tt> and <tt>(1, 1)</tt> * and then bilinearly interpolating between them; or to use the {@link FrustumRayBuilder}. * <p> * Reference: <a href="http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf"> * Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix</a> * * @param x * the interpolation factor along the left-to-right frustum planes, within <tt>[0..1]</tt> * @param y * the interpolation factor along the bottom-to-top frustum planes, within <tt>[0..1]</tt> * @param dir * will hold the normalized ray direction in the local frame of the coordinate system before * transforming to homogeneous clipping space using <code>this</code> matrix * @return this */ public Matrix4f frustumRayDir(float x, float y, Vector3f dir) { /* * This method works by first obtaining the frustum plane normals, * then building the cross product to obtain the corner rays, * and finall bilinearly interpolating to obtain the desired direction. * The code below uses a condense form of doing all this making use * of some mathematical identities to simplify the overall expression. */ float a = m10 * m23, b = m13 * m21, c = m10 * m21, d = m11 * m23, e = m13 * m20, f = m11 * m20; float g = m03 * m20, h = m01 * m23, i = m01 * m20, j = m03 * m21, k = m00 * m23, l = m00 * m21; float m = m00 * m13, n = m03 * m11, o = m00 * m11, p = m01 * m13, q = m03 * m10, r = m01 * m10; float m1x, m1y, m1z; m1x = (d + e + f - a - b - c) * (1.0f - y) + (a - b - c + d - e + f) * y; m1y = (j + k + l - g - h - i) * (1.0f - y) + (g - h - i + j - k + l) * y; m1z = (p + q + r - m - n - o) * (1.0f - y) + (m - n - o + p - q + r) * y; float m2x, m2y, m2z; m2x = (b - c - d + e + f - a) * (1.0f - y) + (a + b - c - d - e + f) * y; m2y = (h - i - j + k + l - g) * (1.0f - y) + (g + h - i - j - k + l) * y; m2z = (n - o - p + q + r - m) * (1.0f - y) + (m + n - o - p - q + r) * y; dir.x = m1x * (1.0f - x) + m2x * x; dir.y = m1y * (1.0f - x) + m2y * x; dir.z = m1z * (1.0f - x) + m2z * x; dir.normalize(); return this; } /** * Obtain the direction of <tt>+Z</tt> before the orthogonal transformation represented by * <code>this</code> matrix is applied. * <p> * This method uses the rotation component of the top-left 3x3 submatrix to obtain the direction * that is transformed to <tt>+Z</tt> by <code>this</code> matrix. * <p> * Reference: <a href="http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/threeD/">http://www.euclideanspace.com</a> * * @param dir * will hold the direction of <tt>+Z</tt> * @return this */ public Matrix4f positiveZ(Vector3f dir) { dir.x = m10 * m21 - m11 * m20; dir.y = m20 * m01 - m21 * m00; dir.z = m00 * m11 - m01 * m10; dir.normalize(); return this; } /** * Obtain the direction of <tt>+X</tt> before the orthogonal transformation represented by * <code>this</code> matrix is applied. * <p> * This method uses the rotation component of the top-left 3x3 submatrix to obtain the direction * that is transformed to <tt>+X</tt> by <code>this</code> matrix. * <p> * Reference: <a href="http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/threeD/">http://www.euclideanspace.com</a> * * @param dir * will hold the direction of <tt>+X</tt> * @return this */ public Matrix4f positiveX(Vector3f dir) { dir.x = m11 * m22 - m12 * m21; dir.y = m02 * m21 - m01 * m22; dir.z = m01 * m12 - m02 * m11; dir.normalize(); return this; } /** * Obtain the direction of <tt>+Y</tt> before the orthogonal transformation represented by * <code>this</code> matrix is applied. * <p> * This method uses the rotation component of the top-left 3x3 submatrix to obtain the direction * that is transformed to <tt>+Y</tt> by <code>this</code> matrix. * <p> * Reference: <a href="http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/threeD/">http://www.euclideanspace.com</a> * * @param dir * will hold the direction of <tt>+Y</tt> * @return this */ public Matrix4f positiveY(Vector3f dir) { dir.x = m12 * m20 - m10 * m22; dir.y = m00 * m22 - m02 * m20; dir.z = m02 * m10 - m00 * m12; dir.normalize(); return this; } /** * Apply a projection transformation to this matrix that projects onto the plane specified via the general plane equation * <tt>x*a + y*b + z*c + d = 0</tt> as if casting a shadow from a given light position/direction <code>light</code>. * <p> * If the <code>light</code>'s w-component is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="ftp://ftp.sgi.com/opengl/contrib/blythe/advanced99/notes/node192.html">ftp.sgi.com</a> * * @param light * the light's vector * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @return this */ public Matrix4f shadow(Vector4f light, float a, float b, float c, float d) { return shadow(light.x, light.y, light.z, light.w, a, b, c, d, this); } /** * Apply a projection transformation to this matrix that projects onto the plane specified via the general plane equation * <tt>x*a + y*b + z*c + d = 0</tt> as if casting a shadow from a given light position/direction <code>light</code> * and store the result in <code>dest</code>. * <p> * If the <code>light</code>'s w-component is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="ftp://ftp.sgi.com/opengl/contrib/blythe/advanced99/notes/node192.html">ftp.sgi.com</a> * * @param light * the light's vector * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @param dest * will hold the result * @return this */ public Matrix4f shadow(Vector4f light, float a, float b, float c, float d, Matrix4f dest) { return shadow(light.x, light.y, light.z, light.w, a, b, c, d, dest); } /** * Apply a projection transformation to this matrix that projects onto the plane specified via the general plane equation * <tt>x*a + y*b + z*c + d = 0</tt> as if casting a shadow from a given light position/direction <tt>(lightX, lightY, lightZ, lightW)</tt>. * <p> * If <code>lightW</code> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="ftp://ftp.sgi.com/opengl/contrib/blythe/advanced99/notes/node192.html">ftp.sgi.com</a> * * @param lightX * the x-component of the light's vector * @param lightY * the y-component of the light's vector * @param lightZ * the z-component of the light's vector * @param lightW * the w-component of the light's vector * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @return this */ public Matrix4f shadow(float lightX, float lightY, float lightZ, float lightW, float a, float b, float c, float d) { return shadow(lightX, lightY, lightZ, lightW, a, b, c, d, this); } /** * Apply a projection transformation to this matrix that projects onto the plane specified via the general plane equation * <tt>x*a + y*b + z*c + d = 0</tt> as if casting a shadow from a given light position/direction <tt>(lightX, lightY, lightZ, lightW)</tt> * and store the result in <code>dest</code>. * <p> * If <code>lightW</code> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * <p> * Reference: <a href="ftp://ftp.sgi.com/opengl/contrib/blythe/advanced99/notes/node192.html">ftp.sgi.com</a> * * @param lightX * the x-component of the light's vector * @param lightY * the y-component of the light's vector * @param lightZ * the z-component of the light's vector * @param lightW * the w-component of the light's vector * @param a * the x factor in the plane equation * @param b * the y factor in the plane equation * @param c * the z factor in the plane equation * @param d * the constant in the plane equation * @param dest * will hold the result * @return this */ public Matrix4f shadow(float lightX, float lightY, float lightZ, float lightW, float a, float b, float c, float d, Matrix4f dest) { // normalize plane float planeLen = (float) Math.sqrt(a*a + b*b + c*c); float an = a / planeLen; float bn = b / planeLen; float cn = c / planeLen; float dn = d / planeLen; float dot = an * lightX + bn * lightY + cn * lightZ + dn * lightW; // compute right matrix elements float rm00 = dot - an * lightX; float rm01 = -an * lightY; float rm02 = -an * lightZ; float rm03 = -an * lightW; float rm10 = -bn * lightX; float rm11 = dot - bn * lightY; float rm12 = -bn * lightZ; float rm13 = -bn * lightW; float rm20 = -cn * lightX; float rm21 = -cn * lightY; float rm22 = dot - cn * lightZ; float rm23 = -cn * lightW; float rm30 = -dn * lightX; float rm31 = -dn * lightY; float rm32 = -dn * lightZ; float rm33 = dot - dn * lightW; // matrix multiplication float nm00 = m00 * rm00 + m10 * rm01 + m20 * rm02 + m30 * rm03; float nm01 = m01 * rm00 + m11 * rm01 + m21 * rm02 + m31 * rm03; float nm02 = m02 * rm00 + m12 * rm01 + m22 * rm02 + m32 * rm03; float nm03 = m03 * rm00 + m13 * rm01 + m23 * rm02 + m33 * rm03; float nm10 = m00 * rm10 + m10 * rm11 + m20 * rm12 + m30 * rm13; float nm11 = m01 * rm10 + m11 * rm11 + m21 * rm12 + m31 * rm13; float nm12 = m02 * rm10 + m12 * rm11 + m22 * rm12 + m32 * rm13; float nm13 = m03 * rm10 + m13 * rm11 + m23 * rm12 + m33 * rm13; float nm20 = m00 * rm20 + m10 * rm21 + m20 * rm22 + m30 * rm23; float nm21 = m01 * rm20 + m11 * rm21 + m21 * rm22 + m31 * rm23; float nm22 = m02 * rm20 + m12 * rm21 + m22 * rm22 + m32 * rm23; float nm23 = m03 * rm20 + m13 * rm21 + m23 * rm22 + m33 * rm23; dest.m30 = m00 * rm30 + m10 * rm31 + m20 * rm32 + m30 * rm33; dest.m31 = m01 * rm30 + m11 * rm31 + m21 * rm32 + m31 * rm33; dest.m32 = m02 * rm30 + m12 * rm31 + m22 * rm32 + m32 * rm33; dest.m33 = m03 * rm30 + m13 * rm31 + m23 * rm32 + m33 * rm33; dest.m00 = nm00; dest.m01 = nm01; dest.m02 = nm02; dest.m03 = nm03; dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m13 = nm13; dest.m20 = nm20; dest.m21 = nm21; dest.m22 = nm22; dest.m23 = nm23; return this; } /** * Apply a projection transformation to this matrix that projects onto the plane with the general plane equation * <tt>y = 0</tt> as if casting a shadow from a given light position/direction <tt>(lightX, lightY, lightZ, lightW)</tt> * and store the result in <code>dest</code>. * <p> * Before the shadow projection is applied, the plane is transformed via the specified <code>planeTransformation</code>. * <p> * If <code>lightW</code> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * * @param light * the light's vector * @param planeTransform * the transformation to transform the implied plane <tt>y = 0</tt> before applying the projection * @param dest * will hold the result * @return this */ public Matrix4f shadow(Vector4f light, Matrix4f planeTransform, Matrix4f dest) { // compute plane equation by transforming (y = 0) float a = planeTransform.m10; float b = planeTransform.m11; float c = planeTransform.m12; float d = -a * planeTransform.m30 - b * planeTransform.m31 - c * planeTransform.m32; return shadow(light.x, light.y, light.z, light.w, a, b, c, d, dest); } /** * Apply a projection transformation to this matrix that projects onto the plane with the general plane equation * <tt>y = 0</tt> as if casting a shadow from a given light position/direction <tt>(lightX, lightY, lightZ, lightW)</tt>. * <p> * Before the shadow projection is applied, the plane is transformed via the specified <code>planeTransformation</code>. * <p> * If <code>lightW</code> is <tt>0.0</tt> the light is being treated as a directional light; if it is <tt>1.0</tt> it is a point light. * <p> * If <code>M</code> is <code>this</code> matrix and <code>S</code> the shadow matrix, * then the new matrix will be <code>M * S</code>. So when transforming a * vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the * reflection will be applied first! * * @param light * the light's vector * @param planeTransform * the transformation to transform the implied plane <tt>y = 0</tt> before applying the projection * @return this */ public Matrix4f shadow(Vector4f light, Matrix4f planeTransform) { return shadow(light, planeTransform, this); } }
Fix JavaDocs
src/org/joml/Matrix4f.java
Fix JavaDocs
<ide><path>rc/org/joml/Matrix4f.java <ide> <ide> /** <ide> * Apply a projection transformation to this matrix that projects onto the plane with the general plane equation <del> * <tt>y = 0</tt> as if casting a shadow from a given light position/direction <tt>(lightX, lightY, lightZ, lightW)</tt> <add> * <tt>y = 0</tt> as if casting a shadow from a given light position/direction <code>light</code> <ide> * and store the result in <code>dest</code>. <ide> * <p> <ide> * Before the shadow projection is applied, the plane is transformed via the specified <code>planeTransformation</code>. <ide> <ide> /** <ide> * Apply a projection transformation to this matrix that projects onto the plane with the general plane equation <del> * <tt>y = 0</tt> as if casting a shadow from a given light position/direction <tt>(lightX, lightY, lightZ, lightW)</tt>. <add> * <tt>y = 0</tt> as if casting a shadow from a given light position/direction <code>light</code>. <ide> * <p> <ide> * Before the shadow projection is applied, the plane is transformed via the specified <code>planeTransformation</code>. <ide> * <p>
Java
apache-2.0
error: pathspec 'addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/CreationNewContact.java' did not match any file(s) known to git
2ed4d78759eabf21c1559c47fc91e3e60f41e98c
1
AlexGraf71/MyTestRepository,AlexGraf71/MyTestRepository
package ru.stqa.pft.addressbook; import org.testng.annotations.BeforeMethod; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import static org.testng.Assert.*; import java.util.concurrent.TimeUnit; import java.util.Date; import java.io.File; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.*; import static org.openqa.selenium.OutputType.*; public class CreationNewContact { FirefoxDriver wd; @BeforeMethod public void setUp() throws Exception { wd = new FirefoxDriver(); wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); } @Test public void CreationNewContact() { wd.get("http://localhost/addressbook/edit.php"); wd.findElement(By.name("user")).click(); wd.findElement(By.name("user")).clear(); wd.findElement(By.name("user")).sendKeys("admin"); wd.findElement(By.name("pass")).click(); wd.findElement(By.name("pass")).clear(); wd.findElement(By.name("pass")).sendKeys("secret"); wd.findElement(By.xpath("//form[@id='LoginForm']/input[3]")).click(); wd.findElement(By.linkText("add new")).click(); wd.findElement(By.name("firstname")).click(); wd.findElement(By.name("firstname")).clear(); wd.findElement(By.name("firstname")).sendKeys("Ivanov"); wd.findElement(By.name("middlename")).click(); wd.findElement(By.name("middlename")).clear(); wd.findElement(By.name("middlename")).sendKeys("I.I.I."); wd.findElement(By.name("lastname")).click(); wd.findElement(By.name("lastname")).clear(); wd.findElement(By.name("lastname")).sendKeys("Ivan"); wd.findElement(By.name("nickname")).click(); wd.findElement(By.name("nickname")).clear(); wd.findElement(By.name("nickname")).sendKeys("Vano"); wd.findElement(By.name("title")).click(); wd.findElement(By.name("title")).clear(); wd.findElement(By.name("title")).sendKeys("Frend"); wd.findElement(By.name("company")).click(); wd.findElement(By.name("company")).clear(); wd.findElement(By.name("company")).sendKeys("Smartech"); wd.findElement(By.name("address")).click(); wd.findElement(By.name("address")).clear(); wd.findElement(By.name("address")).sendKeys("Moskow"); wd.findElement(By.name("home")).click(); wd.findElement(By.name("home")).clear(); wd.findElement(By.name("home")).sendKeys("8999999999"); wd.findElement(By.name("mobile")).click(); wd.findElement(By.name("mobile")).clear(); wd.findElement(By.name("mobile")).sendKeys("8999999999"); wd.findElement(By.name("work")).click(); wd.findElement(By.name("work")).clear(); wd.findElement(By.name("work")).sendKeys("8777777777"); wd.findElement(By.name("fax")).click(); wd.findElement(By.name("fax")).clear(); wd.findElement(By.name("fax")).sendKeys("707070"); wd.findElement(By.name("email")).click(); wd.findElement(By.name("email")).clear(); wd.findElement(By.name("email")).sendKeys("[email protected]"); wd.findElement(By.xpath("//div[@id='content']/form/input[21]")).click(); } @AfterMethod public void tearDown() { wd.quit(); } public static boolean isAlertPresent(FirefoxDriver wd) { try { wd.switchTo().alert(); return true; } catch (NoAlertPresentException e) { return false; } } }
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/CreationNewContact.java
Тест на создание нового контакта
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/CreationNewContact.java
Тест на создание нового контакта
<ide><path>ddressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/CreationNewContact.java <add>package ru.stqa.pft.addressbook; <add>import org.testng.annotations.BeforeMethod; <add>import org.testng.annotations.AfterMethod; <add>import org.testng.annotations.Test; <add>import static org.testng.Assert.*; <add> <add>import java.util.concurrent.TimeUnit; <add>import java.util.Date; <add>import java.io.File; <add>import org.openqa.selenium.support.ui.Select; <add>import org.openqa.selenium.interactions.Actions; <add>import org.openqa.selenium.firefox.FirefoxDriver; <add>import org.openqa.selenium.*; <add>import static org.openqa.selenium.OutputType.*; <add> <add>public class CreationNewContact { <add> FirefoxDriver wd; <add> <add> @BeforeMethod <add> public void setUp() throws Exception { <add> wd = new FirefoxDriver(); <add> wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); <add> } <add> <add> @Test <add> public void CreationNewContact() { <add> wd.get("http://localhost/addressbook/edit.php"); <add> wd.findElement(By.name("user")).click(); <add> wd.findElement(By.name("user")).clear(); <add> wd.findElement(By.name("user")).sendKeys("admin"); <add> wd.findElement(By.name("pass")).click(); <add> wd.findElement(By.name("pass")).clear(); <add> wd.findElement(By.name("pass")).sendKeys("secret"); <add> wd.findElement(By.xpath("//form[@id='LoginForm']/input[3]")).click(); <add> wd.findElement(By.linkText("add new")).click(); <add> wd.findElement(By.name("firstname")).click(); <add> wd.findElement(By.name("firstname")).clear(); <add> wd.findElement(By.name("firstname")).sendKeys("Ivanov"); <add> wd.findElement(By.name("middlename")).click(); <add> wd.findElement(By.name("middlename")).clear(); <add> wd.findElement(By.name("middlename")).sendKeys("I.I.I."); <add> wd.findElement(By.name("lastname")).click(); <add> wd.findElement(By.name("lastname")).clear(); <add> wd.findElement(By.name("lastname")).sendKeys("Ivan"); <add> wd.findElement(By.name("nickname")).click(); <add> wd.findElement(By.name("nickname")).clear(); <add> wd.findElement(By.name("nickname")).sendKeys("Vano"); <add> wd.findElement(By.name("title")).click(); <add> wd.findElement(By.name("title")).clear(); <add> wd.findElement(By.name("title")).sendKeys("Frend"); <add> wd.findElement(By.name("company")).click(); <add> wd.findElement(By.name("company")).clear(); <add> wd.findElement(By.name("company")).sendKeys("Smartech"); <add> wd.findElement(By.name("address")).click(); <add> wd.findElement(By.name("address")).clear(); <add> wd.findElement(By.name("address")).sendKeys("Moskow"); <add> wd.findElement(By.name("home")).click(); <add> wd.findElement(By.name("home")).clear(); <add> wd.findElement(By.name("home")).sendKeys("8999999999"); <add> wd.findElement(By.name("mobile")).click(); <add> wd.findElement(By.name("mobile")).clear(); <add> wd.findElement(By.name("mobile")).sendKeys("8999999999"); <add> wd.findElement(By.name("work")).click(); <add> wd.findElement(By.name("work")).clear(); <add> wd.findElement(By.name("work")).sendKeys("8777777777"); <add> wd.findElement(By.name("fax")).click(); <add> wd.findElement(By.name("fax")).clear(); <add> wd.findElement(By.name("fax")).sendKeys("707070"); <add> wd.findElement(By.name("email")).click(); <add> wd.findElement(By.name("email")).clear(); <add> wd.findElement(By.name("email")).sendKeys("[email protected]"); <add> wd.findElement(By.xpath("//div[@id='content']/form/input[21]")).click(); <add> } <add> <add> @AfterMethod <add> public void tearDown() { <add> wd.quit(); <add> } <add> <add> public static boolean isAlertPresent(FirefoxDriver wd) { <add> try { <add> wd.switchTo().alert(); <add> return true; <add> } catch (NoAlertPresentException e) { <add> return false; <add> } <add> } <add>}
Java
agpl-3.0
fd49748cd5d6e1b61c84dabb167a834e5e636f03
0
ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,ua-eas/kfs,kkronenb/kfs,kuali/kfs,kkronenb/kfs,UniversityOfHawaii/kfs,UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,kuali/kfs,smith750/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,kkronenb/kfs,ua-eas/kfs,ua-eas/kfs,UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,bhutchinson/kfs,smith750/kfs,kuali/kfs,smith750/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,kuali/kfs,kkronenb/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,smith750/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,ua-eas/kfs,bhutchinson/kfs,UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,bhutchinson/kfs,UniversityOfHawaii/kfs,bhutchinson/kfs,kuali/kfs,ua-eas/kfs-devops-automation-fork
/* * Copyright 2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kfs.module.ar; /** * Business Object Property Constants for KFS-AR. */ public class ArPropertyConstants { // CustomerInvoiceDocument public static class CustomerInvoiceDocumentFields { public static final String DOCUMENT_NUMBER = "documentNumber"; public static final String PAYMENT_CHART_OF_ACCOUNTS_CODE = "paymentChartOfAccountsCode"; public static final String PAYMENT_FINANCIAL_OBJECT_CODE = "paymentFinancialObjectCode"; public static final String PAYMENT_FINANCIAL_SUB_OBJECT_CODE = "paymentFinancialSubObjectCode"; public static final String PAYMENT_ACCOUNT_NUMBER = "paymentAccountNumber"; public static final String PAYMENT_SUB_ACCOUNT_NUMBER = "paymentSubAccountNumber"; public static final String PAYMENT_PROJECT_CODE = "paymentProjectCode"; public static final String PAYMENT_CHART_OF_ACCOUNTS = "paymentChartOfAccounts"; public static final String PAYMENT_FINANCIAL_OBJECT = "paymentFinancialObject"; public static final String PAYMENT_FINANCIAL_SUB_OBJECT = "paymentFinancialSubObject"; public static final String PAYMENT_ACCOUNT = "paymentAccount"; public static final String PAYMENT_SUB_ACCOUNT = "paymentSubAccount"; public static final String PAYMENT_PROJECT = "paymentProject"; public static final String CUSTOMER_INVOICE_DETAILS = "accountingLines"; public static final String INVOICE_ITEM_CODE = "invoiceItemCode"; public static final String UNIT_OF_MEASURE_CODE = "itemUnitOfMeasureCode"; public static final String CUSTOMER = "customer"; public static final String CUSTOMER_NUMBER = "accountsReceivableDocumentHeader.customerNumber"; public static final String INVOICE_DUE_DATE = "invoiceDueDate"; public static final String BILLING_DATE = "billingDate"; public static final String SOURCE_TOTAL = "sourceTotal"; public static final String AGE = "age"; public static final String BILLED_BY_ORGANIZATION = "billedByOrganization"; public static final String BILLED_BY_ORGANIZATION_CODE = "billedByOrganizationCode"; public static final String BILL_BY_CHART_OF_ACCOUNT = "billByChartOfAccount"; public static final String BILL_BY_CHART_OF_ACCOUNT_CODE = "billByChartOfAccountCode"; public static final String INVOICE_ITEM_UNIT_PRICE = "invoiceItemUnitPrice"; public static final String INVOICE_ITEM_QUANTITY = "invoiceItemQuantity"; public static final String PROCESSING_CHART_OF_ACCOUNT_CODE = "accountsReceivableDocumentHeader.processingChartOfAccountCode"; public static final String SHIP_TO_ADDRESS_IDENTIFIER = "customerShipToAddressIdentifier"; public static final String BILL_TO_ADDRESS_IDENTIFIER = "customerBillToAddressIdentifier"; public static final String OPEN_AMOUNT = "openAmount"; } // InvoiceRecurrence public static final class InvoiceRecurrenceFields { public static final String RECURRING_INVOICE_NUMBER = "documentNumber"; public static final String INVOICE_RECURRENCE_BEGIN_DATE = "documentRecurrenceBeginDate"; public static final String INVOICE_RECURRENCE_END_DATE = "documentRecurrenceEndDate"; public static final String INVOICE_RECURRENCE_TOTAL_RECURRENCE_NUMBER = "documentTotalRecurrenceNumber"; } // OrganizationAccountingDefaults public static class OrganizationAccountingDefaultFields { public static final String LATE_CHARGE_OBJECT_CODE = "organizationLateChargeObjectCode"; public static final String INVOICE_CHART_OF_ACCOUNTS_CODE = "defaultInvoiceChartOfAccountsCode"; public static final String PAYMENT_CHART_OF_ACCOUNTS_CODE = "defaultPaymentChartOfAccountsCode"; public static final String PAYMENT_ACCOUNT_NUMBER = "defaultPaymentAccountNumber"; public static final String PAYMENT_FINANCIAL_OBJECT_CODE = "defaultPaymentFinancialObjectCode"; public static final String WRITEOFF_FINANCIAL_OBJECT_CODE = "writeoffFinancialObjectCode"; public static final String WRITEOFF_CHART_OF_ACCOUNTS_CODE = "writeoffChartOfAccountsCode"; public static final String WRITEOFF_ACCOUNT_NUMBER = "writeoffAccountNumber"; } // CustomerType public static class CustomerTypeFields { public static final String CUSTOMER_TYPE_DESC = "customerTypeDescription"; } // Customer public static class CustomerFields { public static final String CUSTOMER_TAB_ADDRESSES = "customerAddresses"; public static final String CUSTOMER_ADDRESS_TYPE_CODE = "customerAddressTypeCode"; public static final String CUSTOMER_ADDRESS_IDENTIFIER = "customerAddressIdentifier"; public static final String CUSTOMER_NUMBER = "customerNumber"; public static final String CUSTOMER_ADDRESS_STATE_CODE = "customerStateCode"; public static final String CUSTOMER_ADDRESS_ZIP_CODE = "customerZipCode"; public static final String CUSTOMER_ADDRESS_INTERNATIONAL_PROVINCE_NAME = "customerAddressInternationalProvinceName"; public static final String CUSTOMER_ADDRESS_INTERNATIONAL_MAIL_CODE = "customerInternationalMailCode"; public static final String CUSTOMER_SOCIAL_SECURITY_NUMBER = "customerSocialSecurityNumberIdentifier"; } // CustomerCreditMemoDocument public static class CustomerCreditMemoDocumentFields { public static final String CREDIT_MEMO_ITEM_QUANTITY = "creditMemoItemQuantity"; public static final String CREDIT_MEMO_ITEM_TOTAL_AMOUNT = "creditMemoItemTotalAmount"; public static final String CREDIT_MEMO_DOCUMENT_REF_INVOICE_NUMBER = "financialDocumentReferenceInvoiceNumber"; } // CashControlDocument public static class CashControlDocumentFields { public static final String FINANCIAL_DOCUMENT_LINE_AMOUNT = "financialDocumentLineAmount"; public static final String REFERENCE_FINANCIAL_DOC_NBR = "referenceFinancialDocumentNumber"; public static final String APPLICATION_DOC_STATUS = "status"; public static final String ORGANIZATION_DOC_NBR = "organizationDocumentNumber"; public static final String CUSTOMER_PAYMENT_MEDIUM_CODE = "customerPaymentMediumCode"; public static final String CUSTOMER_NUMBER = "customerNumber"; } // CustomerInvoiceWriteoffDocument public static class CustomerInvoiceWriteoffDocumentFields { public static final String CUSTOMER_INVOICE_DETAILS_FOR_WRITEOFF = "customerInvoiceDetailsForWriteoff"; } // CustomerAgingReport public static class CustomerAgingReportFields { public static final String REPORT_RUN_DATE = "reportRunDate"; public static final String REPORT_OPTION= "reportOption"; } // OrganizationOptions public static class OrganizationOptionsFields { public static final String PROCESSING_CHART_OF_ACCOUNTS_CODE = "processingChartOfAccountCode"; public static final String PROCESSING_ORGANIZATION_CODE = "processingOrganizationCode"; public static final String ORGANIZATION_CHECK_PAYABLE_TO_NAME = "organizationCheckPayableToName"; public static final String ORGANIZATION_REMIT_TO_ADDRESS_NAME = "organizationRemitToAddressName"; public static final String ORGANIZATION_REMIT_TO_LINE1_STREET_ADDRESS = "organizationRemitToLine1StreetAddress"; public static final String ORGANIZATION_REMIT_TO_LINE2_STREET_ADDRESS = "organizationRemitToLine2StreetAddress"; public static final String ORGANIZATION_REMIT_TO_CITY_NAME = "organizationRemitToCityName"; public static final String ORGANIZATION_REMIT_TO_STATE_CODE = "organizationRemitToStateCode"; public static final String ORGANIZATION_REMIT_TO_ZIP_CODE = "organizationRemitToZipCode"; public static final String ORGANIZATION_POSTAL_ZIP_CODE = "organizationPostalZipCode"; } // PaymentApplicationDocument public static class PaymentApplicationDocumentFields { public static final String AMOUNT_TO_BE_APPLIED = "amountToBeApplied"; } // CustomerInvoiceDocumentForm public static final String CUSTOMER_INVOICE_DOCUMENT_UNIT_OF_MEASURE_PROPERTY = "invoiceItemUnitOfMeasureCode"; public static final String UNIT_OF_MEASURE_PROPERTY = "itemUnitOfMeasureCode"; public static final String CUSTOMER_INVOICE_DOCUMENT_INVOICE_ITEM_CODE_PROPERTY = "invoiceItemCode"; }
work/src/org/kuali/kfs/module/ar/ArPropertyConstants.java
/* * Copyright 2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kfs.module.ar; /** * Business Object Property Constants for KFS-AR. */ public class ArPropertyConstants { // CustomerInvoiceDocument public static class CustomerInvoiceDocumentFields { public static final String DOCUMENT_NUMBER = "documentNumber"; public static final String PAYMENT_CHART_OF_ACCOUNTS_CODE = "paymentChartOfAccountsCode"; public static final String PAYMENT_FINANCIAL_OBJECT_CODE = "paymentFinancialObjectCode"; public static final String PAYMENT_FINANCIAL_SUB_OBJECT_CODE = "paymentFinancialSubObjectCode"; public static final String PAYMENT_ACCOUNT_NUMBER = "paymentAccountNumber"; public static final String PAYMENT_SUB_ACCOUNT_NUMBER = "paymentSubAccountNumber"; public static final String PAYMENT_PROJECT_CODE = "paymentProjectCode"; public static final String PAYMENT_CHART_OF_ACCOUNTS = "paymentChartOfAccounts"; public static final String PAYMENT_FINANCIAL_OBJECT = "paymentFinancialObject"; public static final String PAYMENT_FINANCIAL_SUB_OBJECT = "paymentFinancialSubObject"; public static final String PAYMENT_ACCOUNT = "paymentAccount"; public static final String PAYMENT_SUB_ACCOUNT = "paymentSubAccount"; public static final String PAYMENT_PROJECT = "paymentProject"; public static final String CUSTOMER_INVOICE_DETAILS = "accountingLines"; public static final String INVOICE_ITEM_CODE = "invoiceItemCode"; public static final String UNIT_OF_MEASURE_CODE = "itemUnitOfMeasureCode"; public static final String CUSTOMER = "customer"; public static final String CUSTOMER_NUMBER = "accountsReceivableDocumentHeader.customerNumber"; public static final String INVOICE_DUE_DATE = "invoiceDueDate"; public static final String BILLING_DATE = "billingDate"; public static final String SOURCE_TOTAL = "sourceTotal"; public static final String AGE = "age"; public static final String BILLED_BY_ORGANIZATION = "billedByOrganization"; public static final String BILLED_BY_ORGANIZATION_CODE = "billedByOrganizationCode"; public static final String BILL_BY_CHART_OF_ACCOUNT = "billByChartOfAccount"; public static final String BILL_BY_CHART_OF_ACCOUNT_CODE = "billByChartOfAccountCode"; public static final String INVOICE_ITEM_UNIT_PRICE = "invoiceItemUnitPrice"; public static final String INVOICE_ITEM_QUANTITY = "invoiceItemQuantity"; public static final String PROCESSING_CHART_OF_ACCOUNT_CODE = "accountsReceivableDocumentHeader.processingChartOfAccountCode"; public static final String SHIP_TO_ADDRESS_IDENTIFIER = "customerShipToAddressIdentifier"; public static final String BILL_TO_ADDRESS_IDENTIFIER = "customerBillToAddressIdentifier"; public static final String OPEN_AMOUNT = "openAmount"; } // InvoiceRecurrence public static final class InvoiceRecurrenceFields { public static final String RECURRING_INVOICE_NUMBER = "documentNumber"; public static final String INVOICE_RECURRENCE_BEGIN_DATE = "documentRecurrenceBeginDate"; public static final String INVOICE_RECURRENCE_END_DATE = "documentRecurrenceEndDate"; public static final String INVOICE_RECURRENCE_TOTAL_RECURRENCE_NUMBER = "documentTotalRecurrenceNumber"; } // OrganizationAccountingDefaults public static class OrganizationAccountingDefaultFields { public static final String LATE_CHARGE_OBJECT_CODE = "organizationLateChargeObjectCode"; public static final String INVOICE_CHART_OF_ACCOUNTS_CODE = "defaultInvoiceChartOfAccountsCode"; public static final String PAYMENT_CHART_OF_ACCOUNTS_CODE = "defaultPaymentChartOfAccountsCode"; public static final String PAYMENT_ACCOUNT_NUMBER = "defaultPaymentAccountNumber"; public static final String PAYMENT_FINANCIAL_OBJECT_CODE = "defaultPaymentFinancialObjectCode"; public static final String WRITEOFF_FINANCIAL_OBJECT_CODE = "writeoffFinancialObjectCode"; public static final String WRITEOFF_CHART_OF_ACCOUNTS_CODE = "writeoffChartOfAccountsCode"; public static final String WRITEOFF_ACCOUNT_NUMBER = "writeoffAccountNumber"; } // CustomerType public static class CustomerTypeFields { public static final String CUSTOMER_TYPE_DESC = "customerTypeDescription"; } // Customer public static class CustomerFields { public static final String CUSTOMER_TAB_ADDRESSES = "customerAddresses"; public static final String CUSTOMER_ADDRESS_TYPE_CODE = "customerAddressTypeCode"; public static final String CUSTOMER_ADDRESS_IDENTIFIER = "customerAddressIdentifier"; public static final String CUSTOMER_NUMBER = "customerNumber"; public static final String CUSTOMER_ADDRESS_STATE_CODE = "customerStateCode"; public static final String CUSTOMER_ADDRESS_ZIP_CODE = "customerZipCode"; public static final String CUSTOMER_ADDRESS_INTERNATIONAL_PROVINCE_NAME = "customerAddressInternationalProvinceName"; public static final String CUSTOMER_ADDRESS_INTERNATIONAL_MAIL_CODE = "customerInternationalMailCode"; public static final String CUSTOMER_SOCIAL_SECURITY_NUMBER = "customerSocialSecurityNumberIdentifier"; } // CustomerCreditMemoDocument public static class CustomerCreditMemoDocumentFields { public static final String CREDIT_MEMO_ITEM_QUANTITY = "creditMemoItemQuantity"; public static final String CREDIT_MEMO_ITEM_TOTAL_AMOUNT = "creditMemoItemTotalAmount"; public static final String CREDIT_MEMO_DOCUMENT_REF_INVOICE_NUMBER = "financialDocumentReferenceInvoiceNumber"; } // CashControlDocument public static class CashControlDocumentFields { public static final String FINANCIAL_DOCUMENT_LINE_AMOUNT = "financialDocumentLineAmount"; public static final String REFERENCE_FINANCIAL_DOC_NBR = "referenceFinancialDocumentNumber"; public static final String APPLICATION_DOC_STATUS = "status"; public static final String ORGANIZATION_DOC_NBR = "organizationDocumentNumber"; public static final String CUSTOMER_PAYMENT_MEDIUM_CODE = "customerPaymentMediumCode"; public static final String CUSTOMER_NUMBER = "customerNumber"; } // CustomerInvoiceWriteoffDocument public static class CustomerInvoiceWriteoffDocumentFields { public static final String CUSTOMER_INVOICE_DETAILS_FOR_WRITEOFF = "customerInvoiceDetailsForWriteoff"; } // CustomerAgingReport public static class CustomerAgingReportFields { public static final String REPORT_RUN_DATE = "reportRunDate"; public static final String REPORT_OPTION= "reportOption"; } // OrganizationOptions public static class OrganizationOptionsFields { public static final String PROCESSING_CHART_OF_ACCOUNTS_CODE = "processingChartOfAccountCode"; public static final String ORGANIZATION_CHECK_PAYABLE_TO_NAME = "organizationCheckPayableToName"; public static final String ORGANIZATION_REMIT_TO_ADDRESS_NAME = "organizationRemitToAddressName"; public static final String ORGANIZATION_REMIT_TO_LINE1_STREET_ADDRESS = "organizationRemitToLine1StreetAddress"; public static final String ORGANIZATION_REMIT_TO_LINE2_STREET_ADDRESS = "organizationRemitToLine2StreetAddress"; public static final String ORGANIZATION_REMIT_TO_CITY_NAME = "organizationRemitToCityName"; public static final String ORGANIZATION_REMIT_TO_STATE_CODE = "organizationRemitToStateCode"; public static final String ORGANIZATION_REMIT_TO_ZIP_CODE = "organizationRemitToZipCode"; public static final String ORGANIZATION_POSTAL_ZIP_CODE = "organizationPostalZipCode"; } // PaymentApplicationDocument public static class PaymentApplicationDocumentFields { public static final String AMOUNT_TO_BE_APPLIED = "amountToBeApplied"; } // CustomerInvoiceDocumentForm public static final String CUSTOMER_INVOICE_DOCUMENT_UNIT_OF_MEASURE_PROPERTY = "invoiceItemUnitOfMeasureCode"; public static final String UNIT_OF_MEASURE_PROPERTY = "itemUnitOfMeasureCode"; public static final String CUSTOMER_INVOICE_DOCUMENT_INVOICE_ITEM_CODE_PROPERTY = "invoiceItemCode"; }
Added constant for the OrganizationOptions processing org field.
work/src/org/kuali/kfs/module/ar/ArPropertyConstants.java
Added constant for the OrganizationOptions processing org field.
<ide><path>ork/src/org/kuali/kfs/module/ar/ArPropertyConstants.java <ide> // OrganizationOptions <ide> public static class OrganizationOptionsFields { <ide> public static final String PROCESSING_CHART_OF_ACCOUNTS_CODE = "processingChartOfAccountCode"; <add> public static final String PROCESSING_ORGANIZATION_CODE = "processingOrganizationCode"; <ide> public static final String ORGANIZATION_CHECK_PAYABLE_TO_NAME = "organizationCheckPayableToName"; <ide> public static final String ORGANIZATION_REMIT_TO_ADDRESS_NAME = "organizationRemitToAddressName"; <ide> public static final String ORGANIZATION_REMIT_TO_LINE1_STREET_ADDRESS = "organizationRemitToLine1StreetAddress";
Java
apache-2.0
dc0dcf5bc6d72254b87f0dd722bf4b9241de3c13
0
jphp-compiler/jphp,jphp-compiler/jphp,jphp-compiler/jphp,jphp-compiler/jphp
package org.develnext.jphp.debug; import org.develnext.jphp.debug.impl.DebugTick; import org.develnext.jphp.debug.impl.Debugger; import org.develnext.jphp.debug.impl.DebuggerException; import org.develnext.jphp.debug.impl.breakpoint.Breakpoint; import php.runtime.env.Environment; import php.runtime.env.TraceInfo; import php.runtime.env.handler.TickHandler; import php.runtime.memory.ArrayMemory; public class DebugTickHandler implements TickHandler { protected Debugger debugger; protected boolean init = false; public void setDebugger(Debugger debugger) { this.debugger = debugger; } protected void waitDebugger() { while (debugger == null || debugger.isWorking()) { try { Thread.sleep(30); } catch (InterruptedException e) { throw new DebuggerException(e); } } } @Override public void onTick(Environment env, TraceInfo trace, ArrayMemory locals) { waitDebugger(); if (!init) { init = true; debugger.registerBreak(null, env, trace, locals); return; } DebugTick oldTick = debugger.getRegisteredTick(); Debugger.Step waitStep = debugger.getWaitStep(); Breakpoint breakpoint = debugger.breakpointManager.findFor(env, trace); switch (waitStep) { case OVER: if (oldTick.getCallStack().getTop() >= env.getCallStackTop()) { debugger.registerBreak(breakpoint, env, trace, locals); } break; case OUT: if (oldTick.getCallStack().getTop() > env.getCallStackTop()) { debugger.registerBreak(breakpoint, env, trace, locals); } break; case INTO: debugger.registerBreak(breakpoint, env, trace, locals); break; case RUN: if (breakpoint != null) { debugger.registerBreak(breakpoint, env, trace, locals); } } waitDebugger(); } }
jphp-debugger/src/main/java/org/develnext/jphp/debug/DebugTickHandler.java
package org.develnext.jphp.debug; import org.develnext.jphp.debug.impl.DebugTick; import org.develnext.jphp.debug.impl.Debugger; import org.develnext.jphp.debug.impl.DebuggerException; import org.develnext.jphp.debug.impl.breakpoint.Breakpoint; import php.runtime.env.Environment; import php.runtime.env.TraceInfo; import php.runtime.env.handler.TickHandler; import php.runtime.memory.ArrayMemory; public class DebugTickHandler extends TickHandler { protected Debugger debugger; protected boolean init = false; public void setDebugger(Debugger debugger) { this.debugger = debugger; } protected void waitDebugger() { while (debugger == null || debugger.isWorking()) { try { Thread.sleep(30); } catch (InterruptedException e) { throw new DebuggerException(e); } } } @Override public void onTick(Environment env, TraceInfo trace, ArrayMemory locals) { waitDebugger(); if (!init) { init = true; debugger.registerBreak(null, env, trace, locals); return; } DebugTick oldTick = debugger.getRegisteredTick(); Debugger.Step waitStep = debugger.getWaitStep(); Breakpoint breakpoint = debugger.breakpointManager.findFor(env, trace); switch (waitStep) { case OVER: if (oldTick.getCallStack().getTop() >= env.getCallStackTop()) { debugger.registerBreak(breakpoint, env, trace, locals); } break; case OUT: if (oldTick.getCallStack().getTop() > env.getCallStackTop()) { debugger.registerBreak(breakpoint, env, trace, locals); } break; case INTO: debugger.registerBreak(breakpoint, env, trace, locals); break; case RUN: if (breakpoint != null) { debugger.registerBreak(breakpoint, env, trace, locals); } } waitDebugger(); } }
Change extends to implements in DebugTickHandler.
jphp-debugger/src/main/java/org/develnext/jphp/debug/DebugTickHandler.java
Change extends to implements in DebugTickHandler.
<ide><path>php-debugger/src/main/java/org/develnext/jphp/debug/DebugTickHandler.java <ide> import php.runtime.env.handler.TickHandler; <ide> import php.runtime.memory.ArrayMemory; <ide> <del>public class DebugTickHandler extends TickHandler { <add>public class DebugTickHandler implements TickHandler { <ide> protected Debugger debugger; <ide> protected boolean init = false; <ide>
Java
apache-2.0
7fdde200c2115a6b8019be122f0b6c3525850966
0
akrherz/Openfire,guusdk/Openfire,GregDThomas/Openfire,GregDThomas/Openfire,guusdk/Openfire,Gugli/Openfire,GregDThomas/Openfire,akrherz/Openfire,magnetsystems/message-openfire,guusdk/Openfire,magnetsystems/message-openfire,igniterealtime/Openfire,speedy01/Openfire,akrherz/Openfire,igniterealtime/Openfire,Gugli/Openfire,akrherz/Openfire,GregDThomas/Openfire,akrherz/Openfire,Gugli/Openfire,magnetsystems/message-openfire,magnetsystems/message-openfire,magnetsystems/message-openfire,igniterealtime/Openfire,speedy01/Openfire,speedy01/Openfire,Gugli/Openfire,speedy01/Openfire,igniterealtime/Openfire,Gugli/Openfire,guusdk/Openfire,GregDThomas/Openfire,igniterealtime/Openfire,speedy01/Openfire,guusdk/Openfire
/** * $Revision: $ * $Date: $ * * Copyright (C) 2007 Jive Software. All rights reserved. * * This software is published under the terms of the GNU Public License (GPL), * a copy of which is included in this distribution. */ package org.jivesoftware.openfire.muc.spi; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.QName; import org.jivesoftware.openfire.forms.DataForm; import org.jivesoftware.openfire.forms.FormField; import org.jivesoftware.openfire.forms.spi.XDataFormImpl; import org.jivesoftware.openfire.forms.spi.XFormFieldImpl; import org.jivesoftware.openfire.muc.MUCRoom; import org.jivesoftware.openfire.muc.MultiUserChatServer; import org.jivesoftware.openfire.resultsetmanager.ResultSet; import org.jivesoftware.openfire.resultsetmanager.ResultSetImpl; import org.jivesoftware.util.JiveGlobals; import org.xmpp.packet.IQ; import org.xmpp.packet.PacketError; import org.xmpp.packet.PacketError.Condition; import java.util.*; /** * This class adds jabber:iq:search combined with 'result set management' * functionality to the MUC service of Openfire. * * @author Guus der Kinderen - Nimbuzz B.V. <[email protected]> * @author Giancarlo Frison - Nimbuzz B.V. <[email protected]> */ public class IQMUCSearchHandler { /** * The MUC-server to extend with jabber:iq:search functionality. */ private final MultiUserChatServer mucServer; /** * Creates a new instance of the search provider. * * @param mucServer * The server for which to return search results. */ public IQMUCSearchHandler(MultiUserChatServer mucServer) { this.mucServer = mucServer; } /** * Utility method that returns a 'jabber:iq:search' child element filled * with a blank dataform. * * @return Element, named 'query', escaped by the 'jabber:iq:search' * namespace, filled with a blank dataform. */ private static Element getDataElement() { final XDataFormImpl searchForm = new XDataFormImpl(DataForm.TYPE_FORM); searchForm.setTitle("Chat Rooms Search"); searchForm.addInstruction("Instructions"); final FormField typeFF = new XFormFieldImpl("FORM_TYPE"); typeFF.setType(FormField.TYPE_HIDDEN); typeFF.addValue("jabber:iq:search"); searchForm.addField(typeFF); final FormField nameFF = new XFormFieldImpl("name"); nameFF.setType(FormField.TYPE_TEXT_SINGLE); nameFF.setLabel("Name"); nameFF.setRequired(false); searchForm.addField(nameFF); final FormField matchFF = new XFormFieldImpl("name_is_exact_match"); matchFF.setType(FormField.TYPE_BOOLEAN); matchFF.setLabel("Name must match exactly"); matchFF.setRequired(false); searchForm.addField(matchFF); final FormField subjectFF = new XFormFieldImpl("subject"); subjectFF.setType(FormField.TYPE_TEXT_SINGLE); subjectFF.setLabel("Subject"); subjectFF.setRequired(false); searchForm.addField(subjectFF); final FormField userAmountFF = new XFormFieldImpl("num_users"); userAmountFF.setType(FormField.TYPE_TEXT_SINGLE); userAmountFF.setLabel("Number of users"); userAmountFF.setRequired(false); searchForm.addField(userAmountFF); final FormField maxUsersFF = new XFormFieldImpl("num_max_users"); maxUsersFF.setType(FormField.TYPE_TEXT_SINGLE); maxUsersFF.setLabel("Max number allowed of users"); maxUsersFF.setRequired(false); searchForm.addField(maxUsersFF); final FormField includePasswordProtectedFF = new XFormFieldImpl( "include_password_protected"); includePasswordProtectedFF.setType(FormField.TYPE_BOOLEAN); includePasswordProtectedFF.setLabel("Include password protected rooms"); includePasswordProtectedFF.setRequired(false); searchForm.addField(includePasswordProtectedFF); final Element probeResult = DocumentHelper.createElement(QName.get( "query", "jabber:iq:search")); probeResult.add(searchForm.asXMLElement()); return probeResult; } /** * Constructs an answer on a IQ stanza that contains a search request. The * answer will be an IQ stanza of type 'result' or 'error'. * * @param iq * The IQ stanza that is the search request. * @return An answer to the provided request. */ public IQ handleIQ(IQ iq) { final IQ reply = IQ.createResultIQ(iq); final Element formElement = iq.getChildElement().element( QName.get("x", "jabber:x:data")); if (formElement == null) { reply.setChildElement(getDataElement()); return reply; } // parse params from request. final XDataFormImpl df = new XDataFormImpl(); df.parse(formElement); boolean name_is_exact_match = false; String subject = null; int numusers = -1; int numaxusers = -1; boolean includePasswordProtectedRooms = true; final Set<String> names = new HashSet<String>(); final Iterator<FormField> formFields = df.getFields(); while (formFields.hasNext()) { final FormField field = formFields.next(); if (field.getVariable().equals("name")) { names.add(getFirstValue(field)); } } final FormField matchFF = df.getField("name_is_exact_match"); if (matchFF != null) { final String b = getFirstValue(matchFF); if (b != null) { name_is_exact_match = b.equals("1") || b.equalsIgnoreCase("true") || b.equalsIgnoreCase("yes"); } } final FormField subjectFF = df.getField("subject"); if (subjectFF != null) { subject = getFirstValue(subjectFF); } try { final FormField userAmountFF = df.getField("num_users"); if (userAmountFF != null) { String value = getFirstValue(userAmountFF); if (value != null && !"".equals(value)) { numusers = Integer.parseInt(value); } } final FormField maxUsersFF = df.getField("num_max_users"); if (maxUsersFF != null) { String value = getFirstValue(maxUsersFF); if (value != null && !"".equals(value)) { numaxusers = Integer.parseInt(value); } } } catch (NumberFormatException e) { reply.setError(PacketError.Condition.bad_request); return reply; } final FormField includePasswordProtectedRoomsFF = df.getField("include_password_protected"); if (includePasswordProtectedRoomsFF != null) { final String b = getFirstValue(includePasswordProtectedRoomsFF); if (b != null) { if (b.equals("0") || b.equalsIgnoreCase("false") || b.equalsIgnoreCase("no")) { includePasswordProtectedRooms = false; } } } // search for chatrooms matching the request params. final List<MUCRoom> mucs = new ArrayList<MUCRoom>(); for (MUCRoom room : mucServer.getChatRooms()) { boolean find = false; if (names.size() > 0) { for (final String name : names) { if (name_is_exact_match) { if (name.equalsIgnoreCase(room.getNaturalLanguageName())) { find = true; break; } } else { if (room.getNaturalLanguageName().toLowerCase().indexOf( name.toLowerCase()) != -1) { find = true; break; } } } } if (subject != null && room.getSubject().toLowerCase().indexOf( subject.toLowerCase()) != -1) { find = true; } if (numusers > -1 && room.getParticipants().size() < numusers) { find = false; } if (numaxusers > -1 && room.getMaxUsers() < numaxusers) { find = false; } if (!includePasswordProtectedRooms && room.isPasswordProtected()) { find = false; } if (find && canBeIncludedInResult(room)) { mucs.add(room); } } final ResultSet<MUCRoom> searchResults = new ResultSetImpl<MUCRoom>( sortByUserAmount(mucs)); // See if the requesting entity would like to apply 'result set // management' final Element set = iq.getChildElement().element( QName.get("set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT)); final List<MUCRoom> mucrsm; // apply RSM only if the element exists, and the (total) results // set is not empty. final boolean applyRSM = set != null && !mucs.isEmpty(); if (applyRSM) { if (!ResultSet.isValidRSMRequest(set)) { reply.setError(Condition.bad_request); return reply; } try { mucrsm = searchResults.applyRSMDirectives(set); } catch (NullPointerException e) { final IQ itemNotFound = IQ.createResultIQ(iq); itemNotFound.setError(Condition.item_not_found); return itemNotFound; } } else { // if no rsm, all found rooms are part of the result. mucrsm = new ArrayList<MUCRoom>(searchResults); } ArrayList<XFormFieldImpl> fields = null; final Element res = DocumentHelper.createElement(QName.get("query", "jabber:iq:search")); final XDataFormImpl resultform = new XDataFormImpl(DataForm.TYPE_RESULT); boolean atLeastoneResult = false; for (MUCRoom room : mucrsm) { fields = new ArrayList<XFormFieldImpl>(); XFormFieldImpl innerfield = new XFormFieldImpl("name"); innerfield.setType(FormField.TYPE_TEXT_SINGLE); innerfield.addValue(room.getNaturalLanguageName()); fields.add(innerfield); innerfield = new XFormFieldImpl("subject"); innerfield.setType(FormField.TYPE_TEXT_SINGLE); innerfield.addValue(room.getSubject()); fields.add(innerfield); innerfield = new XFormFieldImpl("num_users"); innerfield.setType(FormField.TYPE_TEXT_SINGLE); innerfield.addValue(String.valueOf(room.getOccupantsCount())); fields.add(innerfield); innerfield = new XFormFieldImpl("num_max_users"); innerfield.setType(FormField.TYPE_TEXT_SINGLE); innerfield.addValue(String.valueOf(room.getMaxUsers())); fields.add(innerfield); innerfield = new XFormFieldImpl("is_password_protected"); innerfield.setType(FormField.TYPE_BOOLEAN); innerfield.addValue(Boolean.toString(room.isPasswordProtected())); fields.add(innerfield); innerfield = new XFormFieldImpl("is_member_only"); innerfield.setType(FormField.TYPE_BOOLEAN); innerfield.addValue(Boolean.toString(room.isMembersOnly())); fields.add(innerfield); innerfield = new XFormFieldImpl("jid"); innerfield.setType(FormField.TYPE_TEXT_SINGLE); innerfield.addValue(room.getRole().getRoleAddress().toString()); fields.add(innerfield); resultform.addItemFields(fields); atLeastoneResult = true; } if (atLeastoneResult) { final FormField rffName = new XFormFieldImpl("name"); rffName.setLabel("Name"); resultform.addReportedField(rffName); final FormField rffSubject = new XFormFieldImpl("subject"); rffSubject.setLabel("Subject"); resultform.addReportedField(rffSubject); final FormField rffNumUsers = new XFormFieldImpl("num_users"); rffNumUsers.setLabel("Number of users"); resultform.addReportedField(rffNumUsers); final FormField rffNumMaxUsers = new XFormFieldImpl("num_max_users"); rffNumMaxUsers.setLabel("Max number allowed of users"); resultform.addReportedField(rffNumMaxUsers); final FormField rffPasswordProtected = new XFormFieldImpl( "is_password_protected"); rffPasswordProtected.setLabel("Is a password protected room."); resultform.addReportedField(rffPasswordProtected); final FormField rffJID = new XFormFieldImpl("jid"); rffJID.setLabel("JID"); resultform.addReportedField(rffJID); FormField innerfield = new XFormFieldImpl("is_member_only"); innerfield.setType(FormField.TYPE_TEXT_SINGLE); innerfield.setLabel("Is a member only room."); resultform.addReportedField(innerfield); res.add(resultform.asXMLElement()); } if (applyRSM) { res.add(searchResults.generateSetElementFromResults(mucrsm)); } reply.setChildElement(res); return reply; } /** * Sorts the provided list in such a way that the MUC with the most users * will be the first one in the list. * * @param mucs * The unordered list that will be sorted. */ private static List<MUCRoom> sortByUserAmount(List<MUCRoom> mucs) { Collections.sort(mucs, new Comparator<MUCRoom>() { public int compare(MUCRoom o1, MUCRoom o2) { return o2.getOccupantsCount() - o1.getOccupantsCount(); } }); return mucs; } /** * Checks if the room may be included in search results. This is almost * identical to {@link MultiUserChatServerImpl#canDiscoverRoom(MUCRoom room)}, * but that method is private and cannot be re-used here. * * @param room * The room to check * @return ''true'' if the room may be included in search results, ''false'' * otherwise. */ private static boolean canBeIncludedInResult(MUCRoom room) { // Check if locked rooms may be discovered final boolean discoverLocked = JiveGlobals.getBooleanProperty("xmpp.muc.discover.locked", true); if (!discoverLocked && room.isLocked()) { return false; } return room.isPublicRoom(); } /** * Returns the first value from the FormField, or 'null' if no value has * been set. * * @param formField * The field from which to return the first value. * @return String based value, or 'null' if the FormField has no values. */ public static String getFirstValue(FormField formField) { if (formField == null) { throw new IllegalArgumentException( "The argument 'formField' cannot be null."); } Iterator<String> it = formField.getValues(); if (!it.hasNext()) { return null; } return it.next(); } }
src/java/org/jivesoftware/openfire/muc/spi/IQMUCSearchHandler.java
/** * $Revision: $ * $Date: $ * * Copyright (C) 2007 Jive Software. All rights reserved. * * This software is published under the terms of the GNU Public License (GPL), * a copy of which is included in this distribution. */ package org.jivesoftware.openfire.muc.spi; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.QName; import org.jivesoftware.openfire.forms.DataForm; import org.jivesoftware.openfire.forms.FormField; import org.jivesoftware.openfire.forms.spi.XDataFormImpl; import org.jivesoftware.openfire.forms.spi.XFormFieldImpl; import org.jivesoftware.openfire.muc.MUCRoom; import org.jivesoftware.openfire.muc.MultiUserChatServer; import org.jivesoftware.openfire.resultsetmanager.ResultSet; import org.jivesoftware.openfire.resultsetmanager.ResultSetImpl; import org.jivesoftware.util.JiveGlobals; import org.xmpp.packet.IQ; import org.xmpp.packet.PacketError; import org.xmpp.packet.PacketError.Condition; import java.util.*; /** * This class adds jabber:iq:search combined with 'result set management' * functionality to the MUC service of Openfire. * * @author Guus der Kinderen - Nimbuzz B.V. <[email protected]> * @author Giancarlo Frison - Nimbuzz B.V. <[email protected]> */ public class IQMUCSearchHandler { /** * The MUC-server to extend with jabber:iq:search functionality. */ private final MultiUserChatServer mucServer; /** * Creates a new instance of the search provider. * * @param mucServer * The server for which to return search results. */ public IQMUCSearchHandler(MultiUserChatServer mucServer) { this.mucServer = mucServer; } /** * Utility method that returns a 'jabber:iq:search' child element filled * with a blank dataform. * * @return Element, named 'query', escaped by the 'jabber:iq:search' * namespace, filled with a blank dataform. */ private static Element getDataElement() { final XDataFormImpl searchForm = new XDataFormImpl(DataForm.TYPE_FORM); searchForm.setTitle("Chat Rooms Search"); searchForm.addInstruction("Instructions"); final FormField typeFF = new XFormFieldImpl("FORM_TYPE"); typeFF.setType(FormField.TYPE_HIDDEN); typeFF.addValue("jabber:iq:search"); searchForm.addField(typeFF); final FormField nameFF = new XFormFieldImpl("name"); nameFF.setType(FormField.TYPE_TEXT_SINGLE); nameFF.setLabel("Name"); nameFF.setRequired(false); searchForm.addField(nameFF); final FormField matchFF = new XFormFieldImpl("name_is_exact_match"); matchFF.setType(FormField.TYPE_BOOLEAN); matchFF.setLabel("Name must match exactly"); matchFF.setRequired(false); searchForm.addField(matchFF); final FormField subjectFF = new XFormFieldImpl("subject"); subjectFF.setType(FormField.TYPE_TEXT_SINGLE); subjectFF.setLabel("Subject"); subjectFF.setRequired(false); searchForm.addField(subjectFF); final FormField userAmountFF = new XFormFieldImpl("num_users"); userAmountFF.setType(FormField.TYPE_TEXT_SINGLE); userAmountFF.setLabel("Number of users"); userAmountFF.setRequired(false); searchForm.addField(userAmountFF); final FormField maxUsersFF = new XFormFieldImpl("num_max_users"); maxUsersFF.setType(FormField.TYPE_TEXT_SINGLE); maxUsersFF.setLabel("Max number allowed of users"); maxUsersFF.setRequired(false); searchForm.addField(maxUsersFF); final FormField includePasswordProtectedFF = new XFormFieldImpl( "include_password_protected"); includePasswordProtectedFF.setType(FormField.TYPE_BOOLEAN); includePasswordProtectedFF.setLabel("Include password protected rooms"); includePasswordProtectedFF.setRequired(false); searchForm.addField(includePasswordProtectedFF); final Element probeResult = DocumentHelper.createElement(QName.get( "query", "jabber:iq:search")); probeResult.add(searchForm.asXMLElement()); return probeResult; } /** * Constructs an answer on a IQ stanza that contains a search request. The * answer will be an IQ stanza of type 'result' or 'error'. * * @param iq * The IQ stanza that is the search request. * @return An answer to the provided request. */ public IQ handleIQ(IQ iq) { final IQ reply = IQ.createResultIQ(iq); final Element formElement = iq.getChildElement().element( QName.get("x", "jabber:x:data")); if (formElement == null) { reply.setChildElement(getDataElement()); return reply; } // parse params from request. final XDataFormImpl df = new XDataFormImpl(); df.parse(formElement); boolean name_is_exact_match = false; String subject = null; int numusers = -1; int numaxusers = -1; boolean includePasswordProtectedRooms = true; final Set<String> names = new HashSet<String>(); final Iterator<FormField> formFields = df.getFields(); while (formFields.hasNext()) { final FormField field = formFields.next(); if (field.getVariable().equals("name")) { names.add(getFirstValue(field)); } } final FormField matchFF = df.getField("name_is_exact_match"); if (matchFF != null) { final String b = getFirstValue(matchFF); if (b != null) { name_is_exact_match = b.equals("1") || b.equalsIgnoreCase("true") || b.equalsIgnoreCase("yes"); } } final FormField subjectFF = df.getField("subject"); if (subjectFF != null) { subject = getFirstValue(subjectFF); } try { final FormField userAmountFF = df.getField("num_users"); if (userAmountFF != null) { String value = getFirstValue(userAmountFF); if (value != null && !"".equals(value)) { numusers = Integer.parseInt(value); } } final FormField maxUsersFF = df.getField("num_max_users"); if (maxUsersFF != null) { String value = getFirstValue(maxUsersFF); if (value != null && !"".equals(value)) { numaxusers = Integer.parseInt(value); } } } catch (NumberFormatException e) { reply.setError(PacketError.Condition.bad_request); return reply; } final FormField includePasswordProtectedRoomsFF = df.getField("include_password_protected"); if (includePasswordProtectedRoomsFF != null) { final String b = getFirstValue(includePasswordProtectedRoomsFF); if (b != null) { if (b.equals("0") || b.equalsIgnoreCase("false") || b.equalsIgnoreCase("no")) { includePasswordProtectedRooms = false; } } } // search for chatrooms matching the request params. final List<MUCRoom> mucs = new ArrayList<MUCRoom>(); for (MUCRoom room : mucServer.getChatRooms()) { boolean find = false; if (names.size() > 0) { for (final String name : names) { if (name_is_exact_match) { if (name.equalsIgnoreCase(room.getNaturalLanguageName())) { find = true; break; } } else { if (room.getNaturalLanguageName().toLowerCase().indexOf( name.toLowerCase()) != -1) { find = true; break; } } } } if (subject != null && room.getSubject().toLowerCase().indexOf( subject.toLowerCase()) != -1) { find = true; } if (numusers > -1 && room.getParticipants().size() < numusers) { find = false; } if (numaxusers > -1 && room.getMaxUsers() < numaxusers) { find = false; } if (!includePasswordProtectedRooms && room.isPasswordProtected()) { find = false; } if (find && canBeIncludedInResult(room)) { mucs.add(room); } } final ResultSet<MUCRoom> searchResults = new ResultSetImpl<MUCRoom>( sortByUserAmount(mucs)); // See if the requesting entity would like to apply 'result set // management' final Element set = iq.getChildElement().element( QName.get("set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT)); final List<MUCRoom> mucrsm; // apply RSM only if the element exists, and the (total) results // set is not empty. final boolean applyRSM = set != null && !mucs.isEmpty(); if (applyRSM) { if (!ResultSet.isValidRSMRequest(set)) { reply.setError(Condition.bad_request); return reply; } try { mucrsm = searchResults.applyRSMDirectives(set); } catch (NullPointerException e) { final IQ itemNotFound = IQ.createResultIQ(iq); itemNotFound.setError(Condition.item_not_found); return itemNotFound; } } else { // if no rsm, all found rooms are part of the result. mucrsm = new ArrayList<MUCRoom>(searchResults); } ArrayList<XFormFieldImpl> fields = null; final Element res = DocumentHelper.createElement(QName.get("query", "jabber:iq:search")); final XDataFormImpl resultform = new XDataFormImpl(DataForm.TYPE_RESULT); boolean atLeastoneResult = false; for (MUCRoom room : mucrsm) { fields = new ArrayList<XFormFieldImpl>(); XFormFieldImpl innerfield = new XFormFieldImpl("name"); innerfield.setType(FormField.TYPE_TEXT_SINGLE); innerfield.addValue(room.getNaturalLanguageName()); fields.add(innerfield); innerfield = new XFormFieldImpl("subject"); innerfield.setType(FormField.TYPE_TEXT_SINGLE); innerfield.addValue(room.getSubject()); fields.add(innerfield); innerfield = new XFormFieldImpl("num_users"); innerfield.setType(FormField.TYPE_TEXT_SINGLE); innerfield.addValue(String.valueOf(room.getOccupantsCount())); fields.add(innerfield); innerfield = new XFormFieldImpl("num_max_users"); innerfield.setType(FormField.TYPE_TEXT_SINGLE); innerfield.addValue(String.valueOf(room.getMaxUsers())); fields.add(innerfield); innerfield = new XFormFieldImpl("is_password_protected"); innerfield.setType(FormField.TYPE_BOOLEAN); innerfield.addValue(Boolean.toString(room.isPasswordProtected())); fields.add(innerfield); innerfield = new XFormFieldImpl("is_member_only"); innerfield.setType(FormField.TYPE_BOOLEAN); innerfield.addValue(Boolean.toString(room.isMembersOnly())); fields.add(innerfield); resultform.addItemFields(fields); atLeastoneResult = true; } if (atLeastoneResult) { final FormField rffName = new XFormFieldImpl("name"); rffName.setLabel("Name"); resultform.addReportedField(rffName); final FormField rffSubject = new XFormFieldImpl("subject"); rffSubject.setLabel("Subject"); resultform.addReportedField(rffSubject); final FormField rffNumUsers = new XFormFieldImpl("num_users"); rffNumUsers.setLabel("Number of users"); resultform.addReportedField(rffNumUsers); final FormField rffNumMaxUsers = new XFormFieldImpl("num_max_users"); rffNumMaxUsers.setLabel("Max number allowed of users"); resultform.addReportedField(rffNumMaxUsers); final FormField rffPasswordProtected = new XFormFieldImpl( "is_password_protected"); rffPasswordProtected.setLabel("Is a password protected room."); resultform.addReportedField(rffPasswordProtected); FormField innerfield = new XFormFieldImpl("is_member_only"); innerfield.setType(FormField.TYPE_TEXT_SINGLE); innerfield.setLabel("Is a member only room."); resultform.addReportedField(innerfield); res.add(resultform.asXMLElement()); } if (applyRSM) { res.add(searchResults.generateSetElementFromResults(mucrsm)); } reply.setChildElement(res); return reply; } /** * Sorts the provided list in such a way that the MUC with the most users * will be the first one in the list. * * @param mucs * The unordered list that will be sorted. */ private static List<MUCRoom> sortByUserAmount(List<MUCRoom> mucs) { Collections.sort(mucs, new Comparator<MUCRoom>() { public int compare(MUCRoom o1, MUCRoom o2) { return o2.getOccupantsCount() - o1.getOccupantsCount(); } }); return mucs; } /** * Checks if the room may be included in search results. This is almost * identical to {@link MultiUserChatServerImpl#canDiscoverRoom(MUCRoom room)}, * but that method is private and cannot be re-used here. * * @param room * The room to check * @return ''true'' if the room may be included in search results, ''false'' * otherwise. */ private static boolean canBeIncludedInResult(MUCRoom room) { // Check if locked rooms may be discovered final boolean discoverLocked = JiveGlobals.getBooleanProperty("xmpp.muc.discover.locked", true); if (!discoverLocked && room.isLocked()) { return false; } return room.isPublicRoom(); } /** * Returns the first value from the FormField, or 'null' if no value has * been set. * * @param formField * The field from which to return the first value. * @return String based value, or 'null' if the FormField has no values. */ public static String getFirstValue(FormField formField) { if (formField == null) { throw new IllegalArgumentException( "The argument 'formField' cannot be null."); } Iterator<String> it = formField.getValues(); if (!it.hasNext()) { return null; } return it.next(); } }
Add a 'jid' field to the MUC search results git-svn-id: 2e83ce7f183c9abd424edb3952fab2cdab7acd7f@9819 b35dd754-fafc-0310-a699-88a17e54d16e
src/java/org/jivesoftware/openfire/muc/spi/IQMUCSearchHandler.java
Add a 'jid' field to the MUC search results
<ide><path>rc/java/org/jivesoftware/openfire/muc/spi/IQMUCSearchHandler.java <ide> innerfield.setType(FormField.TYPE_BOOLEAN); <ide> innerfield.addValue(Boolean.toString(room.isMembersOnly())); <ide> fields.add(innerfield); <del> <del> resultform.addItemFields(fields); <add> innerfield = new XFormFieldImpl("jid"); <add> innerfield.setType(FormField.TYPE_TEXT_SINGLE); <add> innerfield.addValue(room.getRole().getRoleAddress().toString()); <add> fields.add(innerfield); <add> resultform.addItemFields(fields); <ide> atLeastoneResult = true; <ide> } <ide> if (atLeastoneResult) <ide> "is_password_protected"); <ide> rffPasswordProtected.setLabel("Is a password protected room."); <ide> resultform.addReportedField(rffPasswordProtected); <del> <del> FormField innerfield = new XFormFieldImpl("is_member_only"); <add> <add> final FormField rffJID = new XFormFieldImpl("jid"); <add> rffJID.setLabel("JID"); <add> resultform.addReportedField(rffJID); <add> <add> FormField innerfield = new XFormFieldImpl("is_member_only"); <ide> innerfield.setType(FormField.TYPE_TEXT_SINGLE); <ide> innerfield.setLabel("Is a member only room."); <ide> resultform.addReportedField(innerfield);
Java
mit
a93748aef3744434085fac0dcb4dfae33291da92
0
yarl/pattypan
/* * The MIT License * * Copyright 2016 Pawel Marynowski. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package pattypan; import edu.stanford.ejalbert.BrowserLauncher; import edu.stanford.ejalbert.exception.BrowserLaunchingInitializingException; import edu.stanford.ejalbert.exception.UnsupportedOperatingSystemException; import java.awt.Desktop; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.MissingResourceException; import java.util.Objects; import java.util.ResourceBundle; import java.util.Set; import java.util.logging.Level; import java.util.stream.Collectors; import javafx.geometry.HPos; import javafx.scene.layout.ColumnConstraints; public final class Util { private Util() {} public static int WINDOW_WIDTH = 750; public static int WINDOW_HEIGHT = 550; static ResourceBundle bundle = ResourceBundle.getBundle("pattypan/text/messages"); public static String text(String key) { try { String val = bundle.getString(key); return new String(val.getBytes("ISO-8859-1"), "UTF-8"); } catch (final MissingResourceException ex) { return ""; } catch (UnsupportedEncodingException ex) { return ""; } } public static String text(String key, Object... vars) { String text = text(key); return String.format(text, vars); } /** * Open URL in browser * * @source http://stackoverflow.com/a/28807079 * @param url website URL */ public static void openUrl(String url) { String os = System.getProperty("os.name").toLowerCase(); try { if (os.contains("win")) { Desktop.getDesktop().browse(new URI(url)); } else if (os.contains("mac")) { Runtime rt = Runtime.getRuntime(); rt.exec("open " + url); } else { new BrowserLauncher().openURLinBrowser(url); } } catch (BrowserLaunchingInitializingException | UnsupportedOperatingSystemException ex) { Session.LOGGER.log(Level.WARNING, null, ex); } catch (URISyntaxException | IOException ex) { Session.LOGGER.log(Level.WARNING, null, ex); } } public static void openDirectory(Path path) { try { Desktop.getDesktop().open(new File(path.toString())); } catch (IllegalArgumentException | IOException ex) { Session.LOGGER.log(Level.WARNING, null, ex); } } /* row and column utils */ public static ColumnConstraints newColumn(int value) { return newColumn(value, "%", HPos.CENTER); } public static ColumnConstraints newColumn(int value, String unit) { return newColumn(value, unit, HPos.CENTER); } public static ColumnConstraints newColumn(int value, String unit, HPos position) { ColumnConstraints col = new ColumnConstraints(); if (unit.equals("%")) { col.setPercentWidth(value); } if (unit.equals("px")) { col.setMaxWidth(value); col.setMinWidth(value); } if (position != null) { col.setHalignment(position); } return col; } /* file utils */ private final static ArrayList<String> allowedFileExtension = new ArrayList<>( Arrays.asList("djvu", "flac", "gif", "jpg", "jpeg", "mid", "mkv", "oga", "ogg","ogv", "opus", "pdf", "png", "svg", "tiff", "tif", "wav", "webm", "webp", "xcf", "mp3", "stl") ); // https://commons.wikimedia.org/wiki/MediaWiki:Filename-prefix-blacklist private final static ArrayList<String> filenamePrefixBlacklist = new ArrayList<>( Arrays.asList("CIMG", "DSC_", "DSCF", "DSCN", "DUW", "GEDC", "IMG", "JD", "MGP", "PICT", "Imagen", "FOTO", "DSC", "SANY", "SAM") ); public static boolean stringHasValidFileExtension(String string) { return allowedFileExtension.parallelStream().anyMatch(string::endsWith); } public static boolean isPossibleBadFilename(String name) { return filenamePrefixBlacklist.parallelStream().anyMatch(name::startsWith); } public static String getNameFromFilename(String filename) { int pos = filename.lastIndexOf("."); if (pos > 0) { filename = filename.substring(0, pos); } return filename; } public static String getExtFromFilename(String filename) { String extension = ""; int i = filename.lastIndexOf('.'); if (i >= 0) { extension = filename.substring(i + 1).toLowerCase(); } return extension; } public static File[] getFilesAllowedToUpload(File directory, boolean includeSubdirectories) { ArrayList<File> files = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory.toPath())) { for (Path path : stream) { if (path.toFile().isDirectory() && includeSubdirectories) { File[] dirFiles = getFilesAllowedToUpload(path.toFile(), includeSubdirectories); ArrayList<File> dirFilesList = new ArrayList<>(Arrays.asList(dirFiles)); files.addAll(dirFilesList); } else if (isFileAllowedToUpload(path.toFile().getName())) { files.add(path.toFile()); } } } catch (IOException e) { } return files.stream().toArray(File[]::new); } public static File[] getFilesAllowedToUpload(File directory, String ext) { File[] files = directory.listFiles((File dir, String name) -> name.toLowerCase().endsWith(ext)); Arrays.sort(files); return files; } public static Map<String, Integer> getFilesByExtention(File[] files) { Map<String, Integer> map = new HashMap<>(); for (File file : files) { String ext = getExtFromFilename(file.getName()); if (map.containsKey(ext)) { int count = map.get(ext); map.replace(ext, ++count); } else { map.put(ext, 1); } } return map; } // @TODO: remove fancy chars public static String getNormalizedName(String name) { return name.trim().replaceAll(" +", " "); } public static boolean isFileAllowedToUpload(String name) { return allowedFileExtension.indexOf(getExtFromFilename(name)) > -1; } // @source: https://howtodoinjava.com/java/io/how-to-generate-sha-or-md5-file-checksum-hash-in-java/ public static String getFileChecksum(MessageDigest digest, File file) throws IOException { //Get file input stream for reading the file content FileInputStream fis = new FileInputStream(file); //Create byte array to read data in chunks byte[] byteArray = new byte[1024]; int bytesCount = 0; //Read file data and update in message digest while ((bytesCount = fis.read(byteArray)) != -1) { digest.update(byteArray, 0, bytesCount); }; //close the stream; We don't need it now. fis.close(); //Get the hash's bytes byte[] bytes = digest.digest(); //This bytes[] has bytes in decimal format; //Convert it to hexadecimal format StringBuilder sb = new StringBuilder(); for(int i=0; i< bytes.length ;i++) { sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); } //return complete hash return sb.toString(); } public static String readUrl(String urlString) throws Exception { BufferedReader reader = null; try { URL url = new URL(urlString); reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuilder buffer = new StringBuilder(); int read; char[] chars = new char[1024]; while ((read = reader.read(chars)) != -1) { buffer.append(chars, 0, read); } return buffer.toString(); } finally { if (reader != null) { reader.close(); } } } public static boolean validUrl(String path) { try { URL url = new URL(path); url.toURI(); return true; } catch(Exception e) { return false; } } /** * Compares two version strings. * * Use this instead of String.compareTo() for a non-lexicographical comparison * that works for version strings. e.g. "1.10".compareTo("1.6"). * * @note It does not work if "1.10" is supposed to be equal to "1.10.0". * * @param str1 a string of ordinal numbers separated by decimal points. * @param str2 a string of ordinal numbers separated by decimal points. * @return The result is a negative integer if str1 is _numerically_ less than * str2. The result is a positive integer if str1 is _numerically_ greater * than str2. The result is zero if the strings are _numerically_ equal. * @source http://stackoverflow.com/a/6702029/1418878 */ public static Integer versionCompare(String str1, String str2) { String[] vals1 = str1.split("\\."); String[] vals2 = str2.split("\\."); int i = 0; // set index to first non-equal ordinal or length of shortest version string while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) { i++; } // compare first non-equal ordinal number if (i < vals1.length && i < vals2.length) { int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i])); return Integer.signum(diff); } // the strings are equal or one string is a substring of the other // e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4" else { return Integer.signum(vals1.length - vals2.length); } } /** * Returns keys by value * * @param map map with data * @param value searched value * @return list of keys that has searched value * @source http://stackoverflow.com/a/2904266/1418878 */ public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) { return map.entrySet() .stream() .filter(entry -> Objects.equals(entry.getValue(), value)) .map(Map.Entry::getKey) .collect(Collectors.toSet()); } /** * Gets directory for local application files * * @source http://stackoverflow.com/a/16660314/1418878 * @return path to local Pattypan directory */ public static String getApplicationDirectory() { String dir; String OS = (System.getProperty("os.name")).toUpperCase(); if (OS.contains("WIN")) { dir = System.getenv("AppData") + "/Pattypan"; } else if (OS.contains("NUX")) { dir = System.getProperty("user.home") + "/.pattypan"; } else { dir = System.getProperty("user.home"); dir += "/Library/Application Support/Pattypan"; } return dir; } }
src/pattypan/Util.java
/* * The MIT License * * Copyright 2016 Pawel Marynowski. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package pattypan; import edu.stanford.ejalbert.BrowserLauncher; import edu.stanford.ejalbert.exception.BrowserLaunchingInitializingException; import edu.stanford.ejalbert.exception.UnsupportedOperatingSystemException; import java.awt.Desktop; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.MissingResourceException; import java.util.Objects; import java.util.ResourceBundle; import java.util.Set; import java.util.logging.Level; import java.util.stream.Collectors; import javafx.geometry.HPos; import javafx.scene.layout.ColumnConstraints; public final class Util { private Util() {} public static int WINDOW_WIDTH = 750; public static int WINDOW_HEIGHT = 550; static ResourceBundle bundle = ResourceBundle.getBundle("pattypan/text/messages"); public static String text(String key) { try { String val = bundle.getString(key); return new String(val.getBytes("ISO-8859-1"), "UTF-8"); } catch (final MissingResourceException ex) { return ""; } catch (UnsupportedEncodingException ex) { return ""; } } public static String text(String key, Object... vars) { String text = text(key); return String.format(text, vars); } /** * Open URL in browser * * @source http://stackoverflow.com/a/28807079 * @param url website URL */ public static void openUrl(String url) { String os = System.getProperty("os.name").toLowerCase(); try { if (os.contains("win")) { Desktop.getDesktop().browse(new URI(url)); } else if (os.contains("mac")) { Runtime rt = Runtime.getRuntime(); rt.exec("open " + url); } else { new BrowserLauncher().openURLinBrowser(url); } } catch (BrowserLaunchingInitializingException | UnsupportedOperatingSystemException ex) { Session.LOGGER.log(Level.WARNING, null, ex); } catch (URISyntaxException | IOException ex) { Session.LOGGER.log(Level.WARNING, null, ex); } } public static void openDirectory(Path path) { try { Desktop.getDesktop().open(new File(path.toString())); } catch (IllegalArgumentException | IOException ex) { Session.LOGGER.log(Level.WARNING, null, ex); } } /* row and column utils */ public static ColumnConstraints newColumn(int value) { return newColumn(value, "%", HPos.CENTER); } public static ColumnConstraints newColumn(int value, String unit) { return newColumn(value, unit, HPos.CENTER); } public static ColumnConstraints newColumn(int value, String unit, HPos position) { ColumnConstraints col = new ColumnConstraints(); if (unit.equals("%")) { col.setPercentWidth(value); } if (unit.equals("px")) { col.setMaxWidth(value); col.setMinWidth(value); } if (position != null) { col.setHalignment(position); } return col; } /* file utils */ private final static ArrayList<String> allowedFileExtension = new ArrayList<>( Arrays.asList("djvu", "flac", "gif", "jpg", "jpeg", "mid", "mkv", "oga", "ogg","ogv", "opus", "pdf", "png", "svg", "tiff", "tif", "wav", "webm", "webp", "xcf", "mp3", "stl") ); // https://commons.wikimedia.org/wiki/MediaWiki:Filename-prefix-blacklist private final static ArrayList<String> filenamePrefixBlacklist = new ArrayList<>( Arrays.asList("CIMG", "DSC_", "DSCF", "DSCN", "DUW", "GEDC", "IMG", "JD", "MGP", "PICT", "Imagen", "FOTO", "DSC", "SANY", "SAM") ); public static boolean stringHasValidFileExtension(String string) { return allowedFileExtension.parallelStream().anyMatch(string::endsWith); } public static boolean isPossibleBadFilename(String name) { return filenamePrefixBlacklist.parallelStream().anyMatch(name::startsWith); } public static String getNameFromFilename(String filename) { int pos = filename.lastIndexOf("."); if (pos > 0) { filename = filename.substring(0, pos); } return filename; } public static String getExtFromFilename(String filename) { String extension = ""; int i = filename.lastIndexOf('.'); if (i >= 0) { extension = filename.substring(i + 1).toLowerCase(); } return extension; } public static File[] getFilesAllowedToUpload(File directory, boolean includeSubdirectories) { ArrayList<File> files = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory.toPath())) { for (Path path : stream) { if (path.toFile().isDirectory() && includeSubdirectories) { File[] dirFiles = getFilesAllowedToUpload(path.toFile(), includeSubdirectories); ArrayList<File> dirFilesList = new ArrayList<>(Arrays.asList(dirFiles)); files.addAll(dirFilesList); } else if (isFileAllowedToUpload(path.toFile().getName())) { files.add(path.toFile()); } } } catch (IOException e) { } return files.stream().toArray(File[]::new); } public static File[] getFilesAllowedToUpload(File directory, String ext) { return directory.listFiles((File dir, String name) -> name.toLowerCase().endsWith(ext) ); } public static Map<String, Integer> getFilesByExtention(File[] files) { Map<String, Integer> map = new HashMap<>(); for (File file : files) { String ext = getExtFromFilename(file.getName()); if (map.containsKey(ext)) { int count = map.get(ext); map.replace(ext, ++count); } else { map.put(ext, 1); } } return map; } // @TODO: remove fancy chars public static String getNormalizedName(String name) { return name.trim().replaceAll(" +", " "); } public static boolean isFileAllowedToUpload(String name) { return allowedFileExtension.indexOf(getExtFromFilename(name)) > -1; } // @source: https://howtodoinjava.com/java/io/how-to-generate-sha-or-md5-file-checksum-hash-in-java/ public static String getFileChecksum(MessageDigest digest, File file) throws IOException { //Get file input stream for reading the file content FileInputStream fis = new FileInputStream(file); //Create byte array to read data in chunks byte[] byteArray = new byte[1024]; int bytesCount = 0; //Read file data and update in message digest while ((bytesCount = fis.read(byteArray)) != -1) { digest.update(byteArray, 0, bytesCount); }; //close the stream; We don't need it now. fis.close(); //Get the hash's bytes byte[] bytes = digest.digest(); //This bytes[] has bytes in decimal format; //Convert it to hexadecimal format StringBuilder sb = new StringBuilder(); for(int i=0; i< bytes.length ;i++) { sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); } //return complete hash return sb.toString(); } public static String readUrl(String urlString) throws Exception { BufferedReader reader = null; try { URL url = new URL(urlString); reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuilder buffer = new StringBuilder(); int read; char[] chars = new char[1024]; while ((read = reader.read(chars)) != -1) { buffer.append(chars, 0, read); } return buffer.toString(); } finally { if (reader != null) { reader.close(); } } } public static boolean validUrl(String path) { try { URL url = new URL(path); url.toURI(); return true; } catch(Exception e) { return false; } } /** * Compares two version strings. * * Use this instead of String.compareTo() for a non-lexicographical comparison * that works for version strings. e.g. "1.10".compareTo("1.6"). * * @note It does not work if "1.10" is supposed to be equal to "1.10.0". * * @param str1 a string of ordinal numbers separated by decimal points. * @param str2 a string of ordinal numbers separated by decimal points. * @return The result is a negative integer if str1 is _numerically_ less than * str2. The result is a positive integer if str1 is _numerically_ greater * than str2. The result is zero if the strings are _numerically_ equal. * @source http://stackoverflow.com/a/6702029/1418878 */ public static Integer versionCompare(String str1, String str2) { String[] vals1 = str1.split("\\."); String[] vals2 = str2.split("\\."); int i = 0; // set index to first non-equal ordinal or length of shortest version string while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) { i++; } // compare first non-equal ordinal number if (i < vals1.length && i < vals2.length) { int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i])); return Integer.signum(diff); } // the strings are equal or one string is a substring of the other // e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4" else { return Integer.signum(vals1.length - vals2.length); } } /** * Returns keys by value * * @param map map with data * @param value searched value * @return list of keys that has searched value * @source http://stackoverflow.com/a/2904266/1418878 */ public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) { return map.entrySet() .stream() .filter(entry -> Objects.equals(entry.getValue(), value)) .map(Map.Entry::getKey) .collect(Collectors.toSet()); } /** * Gets directory for local application files * * @source http://stackoverflow.com/a/16660314/1418878 * @return path to local Pattypan directory */ public static String getApplicationDirectory() { String dir; String OS = (System.getProperty("os.name")).toUpperCase(); if (OS.contains("WIN")) { dir = System.getenv("AppData") + "/Pattypan"; } else if (OS.contains("NUX")) { dir = System.getProperty("user.home") + "/.pattypan"; } else { dir = System.getProperty("user.home"); dir += "/Library/Application Support/Pattypan"; } return dir; } }
sort files upon spreadsheet creation #109
src/pattypan/Util.java
sort files upon spreadsheet creation #109
<ide><path>rc/pattypan/Util.java <ide> } <ide> <ide> public static File[] getFilesAllowedToUpload(File directory, String ext) { <del> return directory.listFiles((File dir, String name) <del> -> name.toLowerCase().endsWith(ext) <del> ); <add> File[] files = directory.listFiles((File dir, String name) -> name.toLowerCase().endsWith(ext)); <add> Arrays.sort(files); <add> return files; <add> <ide> } <ide> <ide> public static Map<String, Integer> getFilesByExtention(File[] files) {
Java
mit
99b0d4cd026bc794121d79d283ac6547f53a9d99
0
BrujosDeJava/jrpg-2017a-dominio
package dominio; /** La clase "Hechicero" hereda de la clase Casta, con esta clase se podran crear y administrar personajes "hechiceros" con sus atributos y metodos. */ public class Hechicero extends Casta { public Hechicero(double prob_crit, double evasion, double daño_crit) { super(prob_crit, evasion, daño_crit); this.nombreCasta = "Hechicero"; } public Hechicero() { super(); this.nombreCasta = "Hechicero"; habilidadesCasta = new String[3]; habilidadesCasta[0] = "Bola de Fuego"; habilidadesCasta[1] = "Curar Aliado"; habilidadesCasta[2] = "Robar Energia y Salud"; } // Bola de Fuego /** "habilidad 1 es un metodo de ataque, se debe tener una energia mayor a 10 para poder ejecutarlo*/ public boolean habilidad1(Personaje caster, Peleable atacado) { if (caster.getEnergia() > 10) { caster.setEnergia(caster.getEnergia() - 10); if (atacado.serAtacado((int) (caster.calcularPuntosDeMagia() * 1.5)) > 0) return true; } return false; } // Curar Aliado /** Con este metodo "habilidad2" el personaje "hechicero" tiene la capacidad de curar a un aliado, para poder hacerlo su energia *debe ser mayor a 10. */ public boolean habilidad2(Personaje caster, Peleable aliado) { if (caster.getEnergia() > 10) { caster.setEnergia(caster.getEnergia() - 10); if (aliado instanceof Personaje) { ((Personaje) aliado).serCurado(caster.calcularPuntosDeMagia()); return true; } } return false; } // Robar Energia y Salud public boolean habilidad3(Personaje caster, Peleable atacado) { if (caster.getEnergia() > 10) { caster.setEnergia(caster.getEnergia() - 10); if (atacado instanceof Personaje) { int energia_robada = ((Personaje) atacado).serDesernegizado(caster.calcularPuntosDeMagia()); int salud_robada = ((Personaje) atacado).serRobadoSalud(caster.calcularPuntosDeMagia() / 2); caster.serEnergizado(energia_robada); caster.serCurado(salud_robada); return true; } } return false; } }
src/main/java/dominio/Hechicero.java
package dominio; /** La clase "Hechicero" hereda de la clase Casta, con esta clase se podran crear personajes "hechiceros" con sus atributos y metodos. */ public class Hechicero extends Casta { public Hechicero(double prob_crit, double evasion, double daño_crit) { super(prob_crit, evasion, daño_crit); this.nombreCasta = "Hechicero"; } public Hechicero() { super(); this.nombreCasta = "Hechicero"; habilidadesCasta = new String[3]; habilidadesCasta[0] = "Bola de Fuego"; habilidadesCasta[1] = "Curar Aliado"; habilidadesCasta[2] = "Robar Energia y Salud"; } // Bola de Fuego public boolean habilidad1(Personaje caster, Peleable atacado) { if (caster.getEnergia() > 10) { caster.setEnergia(caster.getEnergia() - 10); if (atacado.serAtacado((int) (caster.calcularPuntosDeMagia() * 1.5)) > 0) return true; } return false; } // Curar Aliado public boolean habilidad2(Personaje caster, Peleable aliado) { if (caster.getEnergia() > 10) { caster.setEnergia(caster.getEnergia() - 10); if (aliado instanceof Personaje) { ((Personaje) aliado).serCurado(caster.calcularPuntosDeMagia()); return true; } } return false; } // Robar Energia y Salud public boolean habilidad3(Personaje caster, Peleable atacado) { if (caster.getEnergia() > 10) { caster.setEnergia(caster.getEnergia() - 10); if (atacado instanceof Personaje) { int energia_robada = ((Personaje) atacado).serDesernegizado(caster.calcularPuntosDeMagia()); int salud_robada = ((Personaje) atacado).serRobadoSalud(caster.calcularPuntosDeMagia() / 2); caster.serEnergizado(energia_robada); caster.serCurado(salud_robada); return true; } } return false; } }
Update Hechicero.java
src/main/java/dominio/Hechicero.java
Update Hechicero.java
<ide><path>rc/main/java/dominio/Hechicero.java <ide> package dominio; <ide> <ide> /** <del> La clase "Hechicero" hereda de la clase Casta, con esta clase se podran crear personajes "hechiceros" con sus atributos y metodos. <add> La clase "Hechicero" hereda de la clase Casta, con esta clase se podran crear y administrar personajes "hechiceros" con sus atributos y metodos. <ide> */ <ide> <ide> <ide> } <ide> <ide> // Bola de Fuego <del> <add>/** "habilidad 1 es un metodo de ataque, se debe tener una energia mayor a 10 para poder ejecutarlo*/ <ide> public boolean habilidad1(Personaje caster, Peleable atacado) { <ide> if (caster.getEnergia() > 10) { <ide> caster.setEnergia(caster.getEnergia() - 10); <ide> } <ide> <ide> // Curar Aliado <add> /** <add> Con este metodo "habilidad2" el personaje "hechicero" tiene la capacidad de curar a un aliado, para poder hacerlo su energia <add> *debe ser mayor a 10. <add>*/ <ide> public boolean habilidad2(Personaje caster, Peleable aliado) { <ide> if (caster.getEnergia() > 10) { <ide> caster.setEnergia(caster.getEnergia() - 10);
Java
apache-2.0
d04f8367e7f37c27d7d1597dd52aa6b410259dc4
0
wso2-extensions/identity-inbound-auth-oauth,wso2-extensions/identity-inbound-auth-oauth
/* * Copyright (c) 2013, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.oauth2.util; import com.nimbusds.jose.Algorithm; import com.nimbusds.jose.EncryptionMethod; import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JWEAlgorithm; import com.nimbusds.jose.JWEEncrypter; import com.nimbusds.jose.JWEHeader; import com.nimbusds.jose.JWEObject; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.JWSHeader; import com.nimbusds.jose.JWSSigner; import com.nimbusds.jose.JWSVerifier; import com.nimbusds.jose.Payload; import com.nimbusds.jose.crypto.RSAEncrypter; import com.nimbusds.jose.crypto.RSASSASigner; import com.nimbusds.jose.crypto.RSASSAVerifier; import com.nimbusds.jose.jwk.JWK; import com.nimbusds.jose.jwk.JWKMatcher; import com.nimbusds.jose.jwk.JWKSelector; import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.KeyUse; import com.nimbusds.jose.jwk.RSAKey; import com.nimbusds.jose.util.Base64URL; import com.nimbusds.jwt.EncryptedJWT; import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.JWTParser; import com.nimbusds.jwt.SignedJWT; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.apache.axiom.om.OMElement; import org.apache.axiom.util.base64.Base64Utils; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.Charsets; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.client.utils.URIBuilder; import org.apache.oltu.oauth2.common.exception.OAuthRuntimeException; import org.apache.oltu.oauth2.common.exception.OAuthSystemException; import org.json.JSONException; import org.json.JSONObject; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.core.util.KeyStoreManager; import org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException; import org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; import org.wso2.carbon.identity.application.authentication.framework.store.UserSessionStore; import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants; import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils; import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; import org.wso2.carbon.identity.application.common.model.ClaimMapping; import org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig; import org.wso2.carbon.identity.application.common.model.IdentityProvider; import org.wso2.carbon.identity.application.common.model.ServiceProvider; import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants; import org.wso2.carbon.identity.application.common.util.IdentityApplicationManagementUtil; import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; import org.wso2.carbon.identity.base.IdentityConstants; import org.wso2.carbon.identity.base.IdentityException; import org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils; import org.wso2.carbon.identity.core.ServiceURLBuilder; import org.wso2.carbon.identity.core.URLBuilderException; import org.wso2.carbon.identity.core.util.IdentityConfigParser; import org.wso2.carbon.identity.core.util.IdentityCoreConstants; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.oauth.IdentityOAuthAdminException; import org.wso2.carbon.identity.oauth.cache.AppInfoCache; import org.wso2.carbon.identity.oauth.cache.CacheEntry; import org.wso2.carbon.identity.oauth.cache.OAuthCache; import org.wso2.carbon.identity.oauth.cache.OAuthCacheKey; import org.wso2.carbon.identity.oauth.common.OAuthConstants; import org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException; import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; import org.wso2.carbon.identity.oauth.dao.OAuthAppDAO; import org.wso2.carbon.identity.oauth.dao.OAuthAppDO; import org.wso2.carbon.identity.oauth.dao.OAuthConsumerDAO; import org.wso2.carbon.identity.oauth.dto.ScopeDTO; import org.wso2.carbon.identity.oauth.event.OAuthEventInterceptor; import org.wso2.carbon.identity.oauth.internal.OAuthComponentServiceHolder; import org.wso2.carbon.identity.oauth.tokenprocessor.PlainTextPersistenceProcessor; import org.wso2.carbon.identity.oauth.tokenprocessor.TokenPersistenceProcessor; import org.wso2.carbon.identity.oauth.user.UserInfoEndpointException; import org.wso2.carbon.identity.oauth2.IdentityOAuth2ClientException; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; import org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeException; import org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeServerException; import org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext; import org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext; import org.wso2.carbon.identity.oauth2.bean.Scope; import org.wso2.carbon.identity.oauth2.bean.ScopeBinding; import org.wso2.carbon.identity.oauth2.config.SpOAuth2ExpiryTimeConfiguration; import org.wso2.carbon.identity.oauth2.dao.OAuthTokenPersistenceFactory; import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO; import org.wso2.carbon.identity.oauth2.dto.OAuth2IntrospectionResponseDTO; import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO; import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO; import org.wso2.carbon.identity.oauth2.dto.OAuthRevocationRequestDTO; import org.wso2.carbon.identity.oauth2.internal.OAuth2ServiceComponentHolder; import org.wso2.carbon.identity.oauth2.model.AccessTokenDO; import org.wso2.carbon.identity.oauth2.model.ClientCredentialDO; import org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer; import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; import org.wso2.carbon.identity.oauth2.token.OauthTokenIssuer; import org.wso2.carbon.identity.oauth2.token.bindings.TokenBinder; import org.wso2.carbon.identity.oauth2.token.bindings.TokenBinding; import org.wso2.carbon.identity.oauth2.token.handlers.grant.AuthorizationGrantHandler; import org.wso2.carbon.identity.openidconnect.model.Constants; import org.wso2.carbon.identity.openidconnect.model.RequestedClaim; import org.wso2.carbon.identity.organization.management.service.exception.OrganizationManagementServerException; import org.wso2.carbon.idp.mgt.IdentityProviderManagementException; import org.wso2.carbon.idp.mgt.IdentityProviderManager; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.user.api.RealmConfiguration; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.UserCoreConstants; import org.wso2.carbon.user.core.UserStoreManager; import org.wso2.carbon.user.core.common.AbstractUserStoreManager; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.util.UserCoreUtil; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.Key; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.sql.Timestamp; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.xml.namespace.QName; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth10AEndpoints.OAUTH_AUTHZ_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth10AEndpoints.OAUTH_REQUEST_TOKEN_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth10AEndpoints.OAUTH_TOKEN_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.DEVICE_AUTHZ_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OAUTH2_AUTHZ_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OAUTH2_CONSENT_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OAUTH2_DCR_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OAUTH2_DISCOVERY_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OAUTH2_ERROR_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OAUTH2_INTROSPECT_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OAUTH2_JWKS_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OAUTH2_REVOKE_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OAUTH2_TOKEN_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OAUTH2_USER_INFO_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OIDC_CONSENT_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OIDC_WEB_FINGER_EP_URL; import static org.wso2.carbon.identity.oauth2.Oauth2ScopeConstants.PERMISSIONS_BINDING_TYPE; import static org.wso2.carbon.identity.oauth2.device.constants.Constants.DEVICE_SUCCESS_ENDPOINT_PATH; /** * Utility methods for OAuth 2.0 implementation */ public class OAuth2Util { public static final String REMOTE_ACCESS_TOKEN = "REMOTE_ACCESS_TOKEN"; public static final String JWT_ACCESS_TOKEN = "JWT_ACCESS_TOKEN"; public static final String ACCESS_TOKEN_DO = "AccessTokenDo"; public static final String OAUTH2_VALIDATION_MESSAGE_CONTEXT = "OAuth2TokenValidationMessageContext"; public static final String CONFIG_ELEM_OAUTH = "OAuth"; public static final String OPENID_CONNECT = "OpenIDConnect"; public static final String ENABLE_OPENID_CONNECT_AUDIENCES = "EnableAudiences"; public static final String OPENID_CONNECT_AUDIENCE = "audience"; public static final String OPENID_SCOPE = "openid"; /* * Maintain a separate parameter "OPENID_CONNECT_AUDIENCE_IDENTITY_CONFIG" to get the audience from the identity.xml * when user didn't add any audience in the UI while creating service provider. */ public static final String OPENID_CONNECT_AUDIENCE_IDENTITY_CONFIG = "Audience"; private static final String OPENID_CONNECT_AUDIENCES = "Audiences"; private static final String DOT_SEPARATER = "."; private static final String IDP_ENTITY_ID = "IdPEntityId"; private static final String OIDC_ROLE_CLAIM_URI = "roles"; public static final String DEFAULT_TOKEN_TYPE = "Default"; /* * OPTIONAL. A JSON string containing a space-separated list of scopes associated with this token, in the format * described in Section 3.3 of OAuth 2.0 */ public static final String SCOPE = "scope"; /* * OPTIONAL. Client identifier for the OAuth 2.0 client that requested this token. */ public static final String CLIENT_ID = "client_id"; /* * OPTIONAL. Human-readable identifier for the resource owner who authorized this token. */ public static final String USERNAME = "username"; /* * OPTIONAL. Type of the token as defined in Section 5.1 of OAuth 2.0 */ public static final String TOKEN_TYPE = "token_type"; /* * OPTIONAL. Integer time-stamp, measured in the number of seconds since January 1 1970 UTC, indicating when this * token is not to be used before, as defined in JWT */ public static final String NBF = "nbf"; /* * OPTIONAL. Service-specific string identifier or list of string identifiers representing the intended audience for * this token, as defined in JWT */ public static final String AUD = "aud"; /* * OPTIONAL. String representing the issuer of this token, as defined in JWT */ public static final String ISS = "iss"; /* * OPTIONAL. String identifier for the token, as defined in JWT */ public static final String JTI = "jti"; /* * OPTIONAL. Subject of the token, as defined in JWT [RFC7519]. Usually a machine-readable identifier of the * resource owner who authorized this token. */ public static final String SUB = "sub"; /* * OPTIONAL. Integer time-stamp, measured in the number of seconds since January 1 1970 UTC, indicating when this * token will expire, as defined in JWT */ public static final String EXP = "exp"; /* * OPTIONAL. Integer time-stamp, measured in the number of seconds since January 1 1970 UTC, indicating when this * token was originally issued, as defined in JWT */ public static final String IAT = "iat"; /*** * Constant for user access token expiry time. */ public static final String USER_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS = "userAccessTokenExpireTime"; /*** * Constant for refresh token expiry time. */ public static final String REFRESH_TOKEN_EXP_TIME_IN_MILLISECONDS = "refreshTokenExpireTime"; /*** * Constant for application access token expiry time. */ public static final String APPLICATION_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS = "applicationAccessTokenExpireTime"; /** * FIdp Role Based authentication application config. */ public static final String FIDP_ROLE_BASED_AUTHZ_APP_CONFIG = "FIdPRoleBasedAuthzApplications.AppName"; private static final String INBOUND_AUTH2_TYPE = "oauth2"; private static final Log log = LogFactory.getLog(OAuth2Util.class); private static final Log diagnosticLog = LogFactory.getLog("diagnostics"); private static final String INTERNAL_LOGIN_SCOPE = "internal_login"; public static final String JWT = "JWT"; private static long timestampSkew = OAuthServerConfiguration.getInstance().getTimeStampSkewInSeconds() * 1000; private static ThreadLocal<Integer> clientTenantId = new ThreadLocal<>(); private static ThreadLocal<OAuthTokenReqMessageContext> tokenRequestContext = new ThreadLocal<>(); private static ThreadLocal<OAuthAuthzReqMessageContext> authzRequestContext = new ThreadLocal<>(); //Precompile PKCE Regex pattern for performance improvement private static Pattern pkceCodeVerifierPattern = Pattern.compile("[\\w\\-\\._~]+"); // System flag to allow the weak keys (key length less than 2048) to be used for the signing. private static final String ALLOW_WEAK_RSA_SIGNER_KEY = "allow_weak_rsa_signer_key"; private static Map<Integer, Certificate> publicCerts = new ConcurrentHashMap<Integer, Certificate>(); private static Map<Integer, Key> privateKeys = new ConcurrentHashMap<Integer, Key>(); // Supported Signature Algorithms private static final String NONE = "NONE"; private static final String SHA256_WITH_RSA = "SHA256withRSA"; private static final String SHA384_WITH_RSA = "SHA384withRSA"; private static final String SHA512_WITH_RSA = "SHA512withRSA"; private static final String SHA256_WITH_HMAC = "SHA256withHMAC"; private static final String SHA384_WITH_HMAC = "SHA384withHMAC"; private static final String SHA512_WITH_HMAC = "SHA512withHMAC"; private static final String SHA256_WITH_EC = "SHA256withEC"; private static final String SHA384_WITH_EC = "SHA384withEC"; private static final String SHA512_WITH_EC = "SHA512withEC"; private static final String SHA256_WITH_PS = "SHA256withPS"; private static final String PS256 = "PS256"; private static final String SHA256 = "SHA-256"; private static final String SHA384 = "SHA-384"; private static final String SHA512 = "SHA-512"; // Supported Client Authentication Methods private static final String CLIENT_SECRET_BASIC = "client_secret_basic"; private static final String CLIENT_SECRET_POST = "client_secret_post"; private static final String PRIVATE_KEY_JWT = "private_key_jwt"; // Supported Response Modes. private static final String QUERY_RESPONSE_MODE = "query"; private static final String FRAGMENT_RESPONSE_MODE = "fragment"; private static final String FORM_POST_RESPONSE_MODE = "form_post"; public static final String ACCESS_TOKEN_IS_NOT_ACTIVE_ERROR_MESSAGE = "Invalid Access Token. Access token is " + "not ACTIVE."; public static final String IS_CARBON_ROLE_VALIDATION_ENABLED_FOR_LEVEL_ONE_ORGS = "OrganizationManagement.LevelOneOrganizationConfigs.EnableCarbonRoleBasedValidation"; private OAuth2Util() { } /** * @return */ public static OAuthAuthzReqMessageContext getAuthzRequestContext() { if (log.isDebugEnabled()) { log.debug("Retreived OAuthAuthzReqMessageContext from threadlocal"); } return authzRequestContext.get(); } /** * @param context */ public static void setAuthzRequestContext(OAuthAuthzReqMessageContext context) { authzRequestContext.set(context); if (log.isDebugEnabled()) { log.debug("Added OAuthAuthzReqMessageContext to threadlocal"); } } /** * */ public static void clearAuthzRequestContext() { authzRequestContext.remove(); if (log.isDebugEnabled()) { log.debug("Cleared OAuthAuthzReqMessageContext"); } } /** * @return */ public static OAuthTokenReqMessageContext getTokenRequestContext() { if (log.isDebugEnabled()) { log.debug("Retreived OAuthTokenReqMessageContext from threadlocal"); } return tokenRequestContext.get(); } /** * @param context */ public static void setTokenRequestContext(OAuthTokenReqMessageContext context) { tokenRequestContext.set(context); if (log.isDebugEnabled()) { log.debug("Added OAuthTokenReqMessageContext to threadlocal"); } } /** * */ public static void clearTokenRequestContext() { tokenRequestContext.remove(); if (log.isDebugEnabled()) { log.debug("Cleared OAuthTokenReqMessageContext"); } } /** * @return */ public static int getClientTenatId() { if (clientTenantId.get() == null) { return -1; } return clientTenantId.get(); } /** * @param tenantId */ public static void setClientTenatId(int tenantId) { Integer id = tenantId; clientTenantId.set(id); } /** * */ public static void clearClientTenantId() { clientTenantId.remove(); } /** * Build a comma separated list of scopes passed as a String set by OLTU. * * @param scopes set of scopes * @return Comma separated list of scopes */ public static String buildScopeString(String[] scopes) { if (scopes != null) { Arrays.sort(scopes); return StringUtils.join(scopes, " "); } return null; } /** * @param scopeStr * @return */ public static String[] buildScopeArray(String scopeStr) { if (StringUtils.isNotBlank(scopeStr)) { scopeStr = scopeStr.trim(); return scopeStr.split("\\s"); } return new String[0]; } /** * Authenticate the OAuth Consumer * * @param clientId Consumer Key/Id * @param clientSecretProvided Consumer Secret issued during the time of registration * @return true, if the authentication is successful, false otherwise. * @throws IdentityOAuthAdminException Error when looking up the credentials from the database */ public static boolean authenticateClient(String clientId, String clientSecretProvided) throws IdentityOAuthAdminException, IdentityOAuth2Exception, InvalidOAuthClientException { OAuthAppDO appDO = OAuth2Util.getAppInformationByClientId(clientId); if (appDO == null) { if (log.isDebugEnabled()) { log.debug("Cannot find a valid application with the provided client_id: " + clientId); } return false; } // Cache miss boolean isHashDisabled = isHashDisabled(); String appClientSecret = appDO.getOauthConsumerSecret(); if (isHashDisabled) { if (!StringUtils.equals(appClientSecret, clientSecretProvided)) { if (log.isDebugEnabled()) { log.debug("Provided the Client ID : " + clientId + " and Client Secret do not match with the issued credentials."); } return false; } } else { TokenPersistenceProcessor persistenceProcessor = getPersistenceProcessor(); // We convert the provided client_secret to the processed form stored in the DB. String processedProvidedClientSecret = persistenceProcessor.getProcessedClientSecret(clientSecretProvided); if (!StringUtils.equals(appClientSecret, processedProvidedClientSecret)) { if (log.isDebugEnabled()) { log.debug("Provided the Client ID : " + clientId + " and Client Secret do not match with the issued credentials."); } return false; } } if (log.isDebugEnabled()) { log.debug("Successfully authenticated the client with client id : " + clientId); } return true; } public static TokenPersistenceProcessor getPersistenceProcessor() { TokenPersistenceProcessor persistenceProcessor; try { persistenceProcessor = OAuthServerConfiguration.getInstance().getPersistenceProcessor(); } catch (IdentityOAuth2Exception e) { String msg = "Error retrieving TokenPersistenceProcessor configured in OAuth.TokenPersistenceProcessor " + "in identity.xml. Defaulting to PlainTextPersistenceProcessor."; log.warn(msg); if (log.isDebugEnabled()) { log.debug(msg, e); } persistenceProcessor = new PlainTextPersistenceProcessor(); } return persistenceProcessor; } /** * Check whether hashing oauth keys (consumer secret, access token, refresh token and authorization code) * configuration is disabled or not in identity.xml file. * * @return Whether hash feature is disabled or not. */ public static boolean isHashDisabled() { boolean isHashEnabled = OAuthServerConfiguration.getInstance().isClientSecretHashEnabled(); return !isHashEnabled; } /** * Check whether hashing oauth keys (consumer secret, access token, refresh token and authorization code) * configuration is enabled or not in identity.xml file. * * @return Whether hash feature is enable or not. */ public static boolean isHashEnabled() { boolean isHashEnabled = OAuthServerConfiguration.getInstance().isClientSecretHashEnabled(); return isHashEnabled; } /** * @param clientId Consumer Key/Id * @param clientSecretProvided Consumer Secret issued during the time of registration * @return Username of the user which own client id and client secret if authentication is * successful. Empty string otherwise. * @throws IdentityOAuthAdminException Error when looking up the credentials from the database * @deprecated Authenticate the OAuth consumer and return the username of user which own the provided client id * and client secret. */ @Deprecated public static String getAuthenticatedUsername(String clientId, String clientSecretProvided) throws IdentityOAuthAdminException, IdentityOAuth2Exception, InvalidOAuthClientException { boolean cacheHit = false; String username = null; boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(username); if (OAuth2Util.authenticateClient(clientId, clientSecretProvided)) { CacheEntry cacheResult = OAuthCache.getInstance().getValueFromCache(new OAuthCacheKey(clientId + ":" + username)); if (cacheResult != null && cacheResult instanceof ClientCredentialDO) { // Ugh. This is fugly. Have to have a generic way of caching a key:value pair username = ((ClientCredentialDO) cacheResult).getClientSecret(); cacheHit = true; if (log.isDebugEnabled()) { log.debug("Username was available in the cache : " + username); } } if (username == null) { // Cache miss OAuthConsumerDAO oAuthConsumerDAO = new OAuthConsumerDAO(); username = oAuthConsumerDAO.getAuthenticatedUsername(clientId, clientSecretProvided); if (log.isDebugEnabled()) { log.debug("Username fetch from the database"); } } if (username != null && !cacheHit) { /* Using the same ClientCredentialDO to host username. Semantically wrong since ClientCredentialDo accept a client secret and we're storing a username in the secret variable. Do we have to make our own cache key and cache entry class every time we need to put something to it? Ideal solution is to have a generalized way of caching a key:value pair */ if (isUsernameCaseSensitive) { OAuthCache.getInstance() .addToCache(new OAuthCacheKey(clientId + ":" + username), new ClientCredentialDO(username)); } else { OAuthCache.getInstance().addToCache(new OAuthCacheKey(clientId + ":" + username.toLowerCase()), new ClientCredentialDO(username)); } if (log.isDebugEnabled()) { log.debug("Caching username : " + username); } } } return username; } /** * Build the cache key string when storing Authz Code info in cache * * @param clientId Client Id representing the client * @param authzCode Authorization Code issued to the client * @return concatenated <code>String</code> of clientId:authzCode */ public static String buildCacheKeyStringForAuthzCode(String clientId, String authzCode) { return clientId + ":" + authzCode; } /** * Build the cache key string when storing token info in cache * * @param clientId * @param scope * @param authorizedUser * @return * @deprecated To make the cache key completely unique the authenticated IDP should also be introduced. * Use {@link #buildCacheKeyStringForTokenWithUserId(String, String, String, String, String)} instead. */ @Deprecated public static String buildCacheKeyStringForToken(String clientId, String scope, String authorizedUser) { AuthenticatedUser authenticatedUser = OAuth2Util.getUserFromUserName(authorizedUser); try { return clientId + ":" + authenticatedUser.getUserId() + ":" + scope; } catch (UserIdNotFoundException e) { if (log.isDebugEnabled()) { log.debug("Cache could not be built for user: " + authorizedUser, e); } } return null; } /** * Build the cache key string when storing token info in cache. * * @param clientId ClientId of the App. * @param scope Scopes used. * @param authorizedUser Authorised user. * @param authenticatedIDP Authenticated IdP. * @return Cache key string combining the input parameters. * @deprecated use {@link #buildCacheKeyStringForTokenWithUserId(String, String, String, String, String)} instead. */ @Deprecated public static String buildCacheKeyStringForToken(String clientId, String scope, String authorizedUser, String authenticatedIDP) { AuthenticatedUser authenticatedUser = OAuth2Util.getUserFromUserName(authorizedUser); try { return clientId + ":" + authenticatedUser.getUserId() + ":" + scope + ":" + authenticatedIDP; } catch (UserIdNotFoundException e) { log.error("Cache could not be built for user: " + authorizedUser, e); } return null; } /** * Build the cache key string when storing token info in cache. * Use {@link #buildCacheKeyStringForTokenWithUserId(String, String, String, String, String)} instead. * * @param clientId ClientId of the App. * @param scope Scopes used. * @param authorizedUser Authorised user. * @param authenticatedIDP Authenticated IdP. * @param tokenBindingReference Token binding reference. * @return Cache key string combining the input parameters. */ @Deprecated public static String buildCacheKeyStringForToken(String clientId, String scope, String authorizedUser, String authenticatedIDP, String tokenBindingReference) { AuthenticatedUser authenticatedUser = OAuth2Util.getUserFromUserName(authorizedUser); try { return clientId + ":" + authenticatedUser.getUserId() + ":" + scope + ":" + authenticatedIDP + ":" + tokenBindingReference; } catch (UserIdNotFoundException e) { log.error("Cache could not be built for user: " + authorizedUser, e); } return null; } /** * Build the cache key string when storing token info in cache. * * @param clientId ClientId of the App. * @param scope Scopes used. * @param authorizedUserId Authorised user. * @param authenticatedIDP Authenticated IdP. * @param tokenBindingReference Token binding reference. * @return Cache key string combining the input parameters. */ public static String buildCacheKeyStringForTokenWithUserId(String clientId, String scope, String authorizedUserId, String authenticatedIDP, String tokenBindingReference) { String oauthCacheKey = clientId + ":" + authorizedUserId + ":" + scope + ":" + authenticatedIDP + ":" + tokenBindingReference; if (log.isDebugEnabled()) { log.debug(String.format("Building cache key: %s to access OAuthCache.", oauthCacheKey)); } return oauthCacheKey; } /** * Build the cache key string when storing token info in cache. * * @param clientId ClientId of the App. * @param scope Scopes used. * @param authorizedUserId Authorised user. * @param authenticatedIDP Authenticated IdP. * @return Cache key string combining the input parameters. */ public static String buildCacheKeyStringForTokenWithUserId(String clientId, String scope, String authorizedUserId, String authenticatedIDP) { return clientId + ":" + authorizedUserId + ":" + scope + ":" + authenticatedIDP; } @SuppressFBWarnings("WEAK_MESSAGE_DIGEST_MD5") public static String getTokenBindingReference(String tokenBindingValue) { if (StringUtils.isBlank(tokenBindingValue)) { return null; } return DigestUtils.md5Hex(tokenBindingValue); } public static AccessTokenDO validateAccessTokenDO(AccessTokenDO accessTokenDO) { long validityPeriodMillis = accessTokenDO.getValidityPeriodInMillis(); long issuedTime = accessTokenDO.getIssuedTime().getTime(); //check the validity of cached OAuth2AccessToken Response long accessTokenValidityMillis = getTimeToExpire(issuedTime, validityPeriodMillis); if (accessTokenValidityMillis > 1000) { long refreshValidityPeriodMillis = OAuthServerConfiguration.getInstance() .getRefreshTokenValidityPeriodInSeconds() * 1000; long refreshTokenValidityMillis = getTimeToExpire(issuedTime, refreshValidityPeriodMillis); if (refreshTokenValidityMillis > 1000) { //Set new validity period to response object accessTokenDO.setValidityPeriodInMillis(accessTokenValidityMillis); accessTokenDO.setRefreshTokenValidityPeriodInMillis(refreshTokenValidityMillis); //Set issued time period to response object accessTokenDO.setIssuedTime(new Timestamp(issuedTime)); return accessTokenDO; } } //returns null if cached OAuth2AccessToken response object is expired return null; } public static boolean checkAccessTokenPartitioningEnabled() { return OAuthServerConfiguration.getInstance().isAccessTokenPartitioningEnabled(); } public static boolean checkUserNameAssertionEnabled() { return OAuthServerConfiguration.getInstance().isUserNameAssertionEnabled(); } public static String getAccessTokenPartitioningDomains() { return OAuthServerConfiguration.getInstance().getAccessTokenPartitioningDomains(); } public static Map<String, String> getAvailableUserStoreDomainMappings() throws IdentityOAuth2Exception { // TreeMap is used to ignore the case sensitivity of key. Because when user logged in, the case of the // username is ignored. Map<String, String> userStoreDomainMap = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); String domainsStr = getAccessTokenPartitioningDomains(); if (domainsStr != null) { String[] userStoreDomainsArr = domainsStr.split(","); for (String userStoreDomains : userStoreDomainsArr) { String[] mapping = userStoreDomains.trim().split(":"); //A:foo.com , B:bar.com if (mapping.length < 2) { throw new IdentityOAuth2Exception("Domain mapping has not defined correctly"); } userStoreDomainMap.put(mapping[1].trim(), mapping[0].trim()); //key=domain & value=mapping } } return userStoreDomainMap; } /** * Returns the mapped user store if a mapping is defined for this user store in AccessTokenPartitioningDomains * element in identity.xml, or the original userstore domain if the mapping is not available. * * @param userStoreDomain * @return * @throws IdentityOAuth2Exception */ public static String getMappedUserStoreDomain(String userStoreDomain) throws IdentityOAuth2Exception { String mappedUserStoreDomain = userStoreDomain; Map<String, String> availableDomainMappings = OAuth2Util.getAvailableUserStoreDomainMappings(); if (userStoreDomain != null && availableDomainMappings.containsKey(userStoreDomain)) { mappedUserStoreDomain = availableDomainMappings.get(userStoreDomain); } return mappedUserStoreDomain; } /** * Returns the updated table name using user store domain if a mapping is defined for this users store in * AccessTokenPartitioningDomains element in identity.xml, * or the original table name if the mapping is not available. * <p> * Updated table name derived by appending a underscore and mapped user store domain name to the origin table name. * * @param userStoreDomain * @return * @throws IdentityOAuth2Exception */ public static String getPartitionedTableByUserStore(String tableName, String userStoreDomain) throws IdentityOAuth2Exception { if (StringUtils.isNotBlank(tableName) && StringUtils.isNotBlank(userStoreDomain) && !IdentityUtil.getPrimaryDomainName().equalsIgnoreCase(userStoreDomain)) { String mappedUserStoreDomain = OAuth2Util.getMappedUserStoreDomain(userStoreDomain); tableName = tableName + "_" + mappedUserStoreDomain; } return tableName; } /** * Returns the updated sql using user store domain if access token partitioning enabled & username assertion enabled * or the original sql otherwise. * <p> * Updated sql derived by replacing original table names IDN_OAUTH2_ACCESS_TOKEN & IDN_OAUTH2_ACCESS_TOKEN_SCOPE * with the updated table names which derived using {@code getPartitionedTableByUserStore()} method. * * @param sql * @param userStoreDomain * @return * @throws IdentityOAuth2Exception */ public static String getTokenPartitionedSqlByUserStore(String sql, String userStoreDomain) throws IdentityOAuth2Exception { String partitionedSql = sql; if (OAuth2Util.checkAccessTokenPartitioningEnabled() && OAuth2Util.checkUserNameAssertionEnabled()) { String partitionedAccessTokenTable = OAuth2Util.getPartitionedTableByUserStore(OAuthConstants. ACCESS_TOKEN_STORE_TABLE, userStoreDomain); String accessTokenScopeTable = "IDN_OAUTH2_ACCESS_TOKEN_SCOPE"; String partitionedAccessTokenScopeTable = OAuth2Util.getPartitionedTableByUserStore(accessTokenScopeTable, userStoreDomain); if (log.isDebugEnabled()) { log.debug("PartitionedAccessTokenTable: " + partitionedAccessTokenTable + " & PartitionedAccessTokenScopeTable: " + partitionedAccessTokenScopeTable + " for user store domain: " + userStoreDomain); } String wordBoundaryRegex = "\\b"; partitionedSql = sql.replaceAll(wordBoundaryRegex + OAuthConstants.ACCESS_TOKEN_STORE_TABLE + wordBoundaryRegex, partitionedAccessTokenTable); partitionedSql = partitionedSql.replaceAll(wordBoundaryRegex + accessTokenScopeTable + wordBoundaryRegex, partitionedAccessTokenScopeTable); if (log.isDebugEnabled()) { log.debug("Original SQL: " + sql); log.debug("Partitioned SQL: " + partitionedSql); } } return partitionedSql; } /** * Returns the updated sql using username. * <p> * If the username contains the domain separator, updated sql derived using * {@code getTokenPartitionedSqlByUserStore()} method. Returns the original sql otherwise. * * @param sql * @param username * @return * @throws IdentityOAuth2Exception */ public static String getTokenPartitionedSqlByUserId(String sql, String username) throws IdentityOAuth2Exception { String partitionedSql = sql; if (OAuth2Util.checkAccessTokenPartitioningEnabled() && OAuth2Util.checkUserNameAssertionEnabled()) { if (log.isDebugEnabled()) { log.debug("Calculating partitioned sql for username: " + username); } String userStore = null; if (username != null) { String[] strArr = username.split(UserCoreConstants.DOMAIN_SEPARATOR); if (strArr != null && strArr.length > 1) { userStore = strArr[0]; } } partitionedSql = OAuth2Util.getTokenPartitionedSqlByUserStore(sql, userStore); } return partitionedSql; } /** * Returns the updated sql using token. * <p> * If the token contains the username appended, updated sql derived using * {@code getTokenPartitionedSqlByUserId()} method. Returns the original sql otherwise. * * @param sql * @param token * @return * @throws IdentityOAuth2Exception */ public static String getTokenPartitionedSqlByToken(String sql, String token) throws IdentityOAuth2Exception { String partitionedSql = sql; if (OAuth2Util.checkAccessTokenPartitioningEnabled() && OAuth2Util.checkUserNameAssertionEnabled()) { if (log.isDebugEnabled()) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Calculating partitioned sql for token: " + token); } else { // Avoid logging token since its a sensitive information. log.debug("Calculating partitioned sql for token"); } } String userId = OAuth2Util.getUserIdFromAccessToken(token); //i.e: 'foo.com/admin' or 'admin' partitionedSql = OAuth2Util.getTokenPartitionedSqlByUserId(sql, userId); } return partitionedSql; } public static String getUserStoreDomainFromUserId(String userId) throws IdentityOAuth2Exception { String userStoreDomain = null; if (userId != null) { String[] strArr = userId.split(UserCoreConstants.DOMAIN_SEPARATOR); if (strArr != null && strArr.length > 1) { userStoreDomain = getMappedUserStoreDomain(strArr[0]); } } return userStoreDomain; } public static String getUserStoreDomainFromAccessToken(String apiKey) throws IdentityOAuth2Exception { String userStoreDomain = null; String userId; String decodedKey = new String(Base64.decodeBase64(apiKey.getBytes(Charsets.UTF_8)), Charsets.UTF_8); String[] tmpArr = decodedKey.split(":"); if (tmpArr != null) { userId = tmpArr[1]; if (userId != null) { userStoreDomain = getUserStoreDomainFromUserId(userId); } } return userStoreDomain; } @Deprecated public static String getAccessTokenStoreTableFromUserId(String userId) throws IdentityOAuth2Exception { String accessTokenStoreTable = OAuthConstants.ACCESS_TOKEN_STORE_TABLE; String userStore; if (userId != null) { String[] strArr = userId.split(UserCoreConstants.DOMAIN_SEPARATOR); if (strArr.length > 1) { userStore = strArr[0]; accessTokenStoreTable = OAuth2Util.getPartitionedTableByUserStore(OAuthConstants.ACCESS_TOKEN_STORE_TABLE, userStore); } } return accessTokenStoreTable; } @Deprecated public static String getAccessTokenStoreTableFromAccessToken(String apiKey) throws IdentityOAuth2Exception { String userId = getUserIdFromAccessToken(apiKey); //i.e: 'foo.com/admin' or 'admin' return OAuth2Util.getAccessTokenStoreTableFromUserId(userId); } public static String getUserIdFromAccessToken(String apiKey) { String userId = null; String decodedKey = new String(Base64.decodeBase64(apiKey.getBytes(Charsets.UTF_8)), Charsets.UTF_8); String[] tmpArr = decodedKey.split(":"); if (tmpArr != null && tmpArr.length > 1) { userId = tmpArr[1]; } return userId; } /** * Get token expire time in milliseconds. * * @param accessTokenDO Access token data object. * @return expire time in milliseconds. * @deprecated Instead use {@link #getTokenExpireTimeMillis(AccessTokenDO, boolean)}. */ @Deprecated public static long getTokenExpireTimeMillis(AccessTokenDO accessTokenDO) { return getTokenExpireTimeMillis(accessTokenDO, true); } /** * Get token expire time in milliseconds. * * @param accessTokenDO Access token data object. * @param considerSkew Consider time stamp skew when calculating expire time. * @return expire time in milliseconds. */ public static long getTokenExpireTimeMillis(AccessTokenDO accessTokenDO, boolean considerSkew) { if (accessTokenDO == null) { throw new IllegalArgumentException("accessTokenDO is " + "\'NULL\'"); } long accessTokenValidity = getAccessTokenExpireMillis(accessTokenDO, considerSkew); long refreshTokenValidity = getRefreshTokenExpireTimeMillis(accessTokenDO); if (accessTokenValidity > 1000 && (refreshTokenValidity > 1000 || refreshTokenValidity < 0)) { return accessTokenValidity; } return 0; } public static long getRefreshTokenExpireTimeMillis(AccessTokenDO accessTokenDO) { if (accessTokenDO == null) { throw new IllegalArgumentException("accessTokenDO is " + "\'NULL\'"); } long refreshTokenValidityPeriodMillis = accessTokenDO.getRefreshTokenValidityPeriodInMillis(); if (refreshTokenValidityPeriodMillis < 0) { if (log.isDebugEnabled()) { log.debug("Refresh Token has infinite lifetime"); } return -1; } long refreshTokenIssuedTime = accessTokenDO.getRefreshTokenIssuedTime().getTime(); long refreshTokenValidity = getTimeToExpire(refreshTokenIssuedTime, refreshTokenValidityPeriodMillis); if (refreshTokenValidity > 1000) { return refreshTokenValidity; } return 0; } /** * Get access token expire time in milliseconds. * * @param accessTokenDO Access token data object. * @return expire time in milliseconds. * @deprecated {@link #getAccessTokenExpireMillis(AccessTokenDO, boolean)}. */ @Deprecated public static long getAccessTokenExpireMillis(AccessTokenDO accessTokenDO) { return getAccessTokenExpireMillis(accessTokenDO, true); } /** * Get access token expire time in milliseconds. * * @param accessTokenDO Access token data object. * @param considerSkew Consider time stamp skew when calculating expire time. * @return expire time in milliseconds. */ public static long getAccessTokenExpireMillis(AccessTokenDO accessTokenDO, boolean considerSkew) { if (accessTokenDO == null) { throw new IllegalArgumentException("accessTokenDO is " + "\'NULL\'"); } long validityPeriodMillis = accessTokenDO.getValidityPeriodInMillis(); if (validityPeriodMillis < 0) { if (log.isDebugEnabled()) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Access Token(hashed) : " + DigestUtils.sha256Hex(accessTokenDO.getAccessToken()) + " has infinite lifetime"); } else { log.debug("Access Token has infinite lifetime"); } } return -1; } long issuedTime = accessTokenDO.getIssuedTime().getTime(); long validityMillis = getTimeToExpire(issuedTime, validityPeriodMillis, considerSkew); if (validityMillis > 1000) { return validityMillis; } else { return 0; } } @Deprecated public static long calculateValidityInMillis(long issuedTimeInMillis, long validityPeriodMillis) { return getTimeToExpire(issuedTimeInMillis, validityPeriodMillis); } /** * Util method to calculate the validity period after applying skew corrections. * * @param issuedTimeInMillis * @param validityPeriodMillis * @return skew corrected validity period in milliseconds * @deprecated use {@link #getTimeToExpire(long, long, boolean)}. */ @Deprecated public static long getTimeToExpire(long issuedTimeInMillis, long validityPeriodMillis) { return getTimeToExpire(issuedTimeInMillis, validityPeriodMillis, true); } /** * Util method to calculate the validity period. * * @param issuedTimeInMillis Issued time in milliseconds. * @param validityPeriodMillis Validity period in milliseconds. * @param considerSkew Consider timestamp skew when calculating exipry time. * @return skew corrected validity period in milliseconds. */ public static long getTimeToExpire(long issuedTimeInMillis, long validityPeriodMillis, boolean considerSkew) { if (considerSkew) { return issuedTimeInMillis + validityPeriodMillis - (System.currentTimeMillis() - timestampSkew); } return issuedTimeInMillis + validityPeriodMillis - (System.currentTimeMillis()); } public static int getTenantId(String tenantDomain) throws IdentityOAuth2Exception { RealmService realmService = OAuthComponentServiceHolder.getInstance().getRealmService(); try { return realmService.getTenantManager().getTenantId(tenantDomain); } catch (UserStoreException e) { String error = "Error in obtaining tenant ID from tenant domain : " + tenantDomain; throw new IdentityOAuth2Exception(error, e); } } public static String getTenantDomain(int tenantId) throws IdentityOAuth2Exception { RealmService realmService = OAuthComponentServiceHolder.getInstance().getRealmService(); try { return realmService.getTenantManager().getDomain(tenantId); } catch (UserStoreException e) { String error = "Error in obtaining tenant domain from tenant ID : " + tenantId; throw new IdentityOAuth2Exception(error, e); } } public static int getTenantIdFromUserName(String username) throws IdentityOAuth2Exception { String domainName = MultitenantUtils.getTenantDomain(username); return getTenantId(domainName); } @SuppressFBWarnings("WEAK_MESSAGE_DIGEST_MD5") public static String hashScopes(String[] scope) { return DigestUtils.md5Hex(OAuth2Util.buildScopeString(scope)); } @SuppressFBWarnings("WEAK_MESSAGE_DIGEST_MD5") public static String hashScopes(String scope) { if (scope != null) { //first converted to an array to sort the scopes return DigestUtils.md5Hex(OAuth2Util.buildScopeString(buildScopeArray(scope))); } else { return null; } } public static AuthenticatedUser getUserFromUserName(String username) throws IllegalArgumentException { if (StringUtils.isNotBlank(username)) { String tenantDomain = MultitenantUtils.getTenantDomain(username); String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username); String tenantAwareUsernameWithNoUserDomain = UserCoreUtil.removeDomainFromName(tenantAwareUsername); String userStoreDomain = IdentityUtil.extractDomainFromName(username).toUpperCase(); AuthenticatedUser user = new AuthenticatedUser(); user.setUserName(tenantAwareUsernameWithNoUserDomain); user.setTenantDomain(tenantDomain); user.setUserStoreDomain(userStoreDomain); return user; } throw new IllegalArgumentException("Cannot create user from empty user name"); } public static String getIDTokenIssuer() { String issuer = OAuthServerConfiguration.getInstance().getOpenIDConnectIDTokenIssuerIdentifier(); if (StringUtils.isBlank(issuer)) { issuer = OAuthURL.getOAuth2TokenEPUrl(); } return issuer; } /** * OAuth URL related utility functions. */ public static class OAuthURL { public static String getOAuth1RequestTokenUrl() { String oauth1RequestTokenUrl = OAuthServerConfiguration.getInstance().getOAuth1RequestTokenUrl(); if (StringUtils.isBlank(oauth1RequestTokenUrl)) { oauth1RequestTokenUrl = IdentityUtil.getServerURL(OAUTH_REQUEST_TOKEN_EP_URL, true, true); } return oauth1RequestTokenUrl; } public static String getOAuth1AuthorizeUrl() { String oauth1AuthorizeUrl = OAuthServerConfiguration.getInstance().getOAuth1AuthorizeUrl(); if (StringUtils.isBlank(oauth1AuthorizeUrl)) { oauth1AuthorizeUrl = IdentityUtil.getServerURL(OAUTH_AUTHZ_EP_URL, true, true); } return oauth1AuthorizeUrl; } public static String getOAuth1AccessTokenUrl() { String oauth1AccessTokenUrl = OAuthServerConfiguration.getInstance().getOAuth1AccessTokenUrl(); if (StringUtils.isBlank(oauth1AccessTokenUrl)) { oauth1AccessTokenUrl = IdentityUtil.getServerURL(OAUTH_TOKEN_EP_URL, true, true); } return oauth1AccessTokenUrl; } public static String getOAuth2AuthzEPUrl() { return buildUrl(OAUTH2_AUTHZ_EP_URL, OAuthServerConfiguration.getInstance()::getOAuth2AuthzEPUrl); } public static String getOAuth2TokenEPUrl() { return buildUrl(OAUTH2_TOKEN_EP_URL, OAuthServerConfiguration.getInstance()::getOAuth2TokenEPUrl); } /** * This method is used to get the resolved URL for the OAuth2 Registration Endpoint. * * @param tenantDomain Tenant Domain. * @return String of the resolved URL for the Registration endpoint. * @throws URISyntaxException URI Syntax Exception. */ public static String getOAuth2DCREPUrl(String tenantDomain) throws URISyntaxException { String oauth2TokenEPUrl = buildUrl(OAUTH2_DCR_EP_URL, OAuthServerConfiguration.getInstance()::getOAuth2DCREPUrl); if (!IdentityTenantUtil.isTenantQualifiedUrlsEnabled() && isNotSuperTenant(tenantDomain)) { //Append tenant domain to path when the tenant-qualified url mode is disabled. oauth2TokenEPUrl = appendTenantDomainAsPathParamInLegacyMode(oauth2TokenEPUrl, tenantDomain); } return oauth2TokenEPUrl; } /** * This method is used to get the resolved URL for the JWKS Page. * * @param tenantDomain Tenant Domain. * @return String of the resolved URL for the JWKS page. * @throws URISyntaxException URI Syntax Exception. */ public static String getOAuth2JWKSPageUrl(String tenantDomain) throws URISyntaxException { String auth2JWKSPageUrl = buildUrl(OAUTH2_JWKS_EP_URL, OAuthServerConfiguration.getInstance()::getOAuth2JWKSPageUrl); if (!IdentityTenantUtil.isTenantQualifiedUrlsEnabled() && isNotSuperTenant(tenantDomain)) { //Append tenant domain to path when the tenant-qualified url mode is disabled. auth2JWKSPageUrl = appendTenantDomainAsPathParamInLegacyMode(auth2JWKSPageUrl, tenantDomain); } return auth2JWKSPageUrl; } public static String getOidcWebFingerEPUrl() { return buildUrl(OIDC_WEB_FINGER_EP_URL, OAuthServerConfiguration.getInstance()::getOidcWebFingerEPUrl); } public static String getOidcDiscoveryEPUrl(String tenantDomain) throws URISyntaxException { String oidcDiscoveryEPUrl = buildUrl(OAUTH2_DISCOVERY_EP_URL, OAuthServerConfiguration.getInstance()::getOidcDiscoveryUrl); if (!IdentityTenantUtil.isTenantQualifiedUrlsEnabled() && isNotSuperTenant(tenantDomain)) { //Append tenant domain to path when the tenant-qualified url mode is disabled. oidcDiscoveryEPUrl = appendTenantDomainAsPathParamInLegacyMode(oidcDiscoveryEPUrl, tenantDomain); } return oidcDiscoveryEPUrl; } public static String getOAuth2UserInfoEPUrl() { return buildUrl(OAUTH2_USER_INFO_EP_URL, OAuthServerConfiguration.getInstance()::getOauth2UserInfoEPUrl); } /** * Get oauth2 revocation endpoint URL. * * @return Revocation Endpoint URL. */ public static String getOAuth2RevocationEPUrl() { return buildUrl(OAUTH2_REVOKE_EP_URL, OAuthServerConfiguration.getInstance()::getOauth2RevocationEPUrl); } /** * Get oauth2 introspection endpoint URL. * * @return Introspection Endpoint URL. */ public static String getOAuth2IntrospectionEPUrl() { return buildUrl(OAUTH2_INTROSPECT_EP_URL, OAuthServerConfiguration.getInstance()::getOauth2IntrospectionEPUrl); } /** * This method is used to get the resolved URL for the OAuth2 introspection endpoint. * * @param tenantDomain Tenant Domain. * @return String of the resolved URL for the introspection endpoint. * @throws URISyntaxException URI Syntax Exception. */ public static String getOAuth2IntrospectionEPUrl(String tenantDomain) throws URISyntaxException { String getOAuth2IntrospectionEPUrl = buildUrl(OAUTH2_INTROSPECT_EP_URL, OAuthServerConfiguration.getInstance()::getOauth2IntrospectionEPUrl); if (!IdentityTenantUtil.isTenantQualifiedUrlsEnabled() && isNotSuperTenant(tenantDomain)) { // Append tenant domain to path when the tenant-qualified url mode is disabled. getOAuth2IntrospectionEPUrl = appendTenantDomainAsPathParamInLegacyMode(getOAuth2IntrospectionEPUrl, tenantDomain); } return getOAuth2IntrospectionEPUrl; } public static String getOIDCConsentPageUrl() { return buildUrl(OIDC_CONSENT_EP_URL, OAuthServerConfiguration.getInstance()::getOIDCConsentPageUrl); } public static String getOAuth2ConsentPageUrl() { return buildUrl(OAUTH2_CONSENT_EP_URL, OAuthServerConfiguration.getInstance()::getOauth2ConsentPageUrl); } public static String getOAuth2ErrorPageUrl() { return buildUrl(OAUTH2_ERROR_EP_URL, OAuthServerConfiguration.getInstance()::getOauth2ErrorPageUrl); } private static String appendTenantDomainAsPathParamInLegacyMode(String url, String tenantDomain) throws URISyntaxException { URI uri = new URI(url); URI uriModified = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), ("/t/" + tenantDomain + uri.getPath()), uri.getQuery(), uri.getFragment()); return uriModified.toString(); } public static String getDeviceAuthzEPUrl() { return buildUrl(DEVICE_AUTHZ_EP_URL, OAuthServerConfiguration.getInstance()::getDeviceAuthzEPUrl); } } /** * This method is used to generate the device flow authentication completed page URI. * * @param appName Service provider name. * @param tenantDomain Tenant domain. * @return Redirection URI */ public static String getDeviceFlowCompletionPageURI(String appName, String tenantDomain) throws IdentityOAuth2Exception { try { String pageURI = ServiceURLBuilder.create().addPath(DEVICE_SUCCESS_ENDPOINT_PATH) .build().getAbsolutePublicURL(); URIBuilder uriBuilder = new URIBuilder(pageURI); uriBuilder.addParameter(org.wso2.carbon.identity.oauth2.device.constants.Constants.APP_NAME, appName); if (!IdentityTenantUtil.isTenantQualifiedUrlsEnabled() && isNotSuperTenant(tenantDomain)) { // Append tenant domain to path when the tenant-qualified url mode is disabled. uriBuilder.addParameter(FrameworkUtils.TENANT_DOMAIN, tenantDomain); } return uriBuilder.build().toString(); } catch (URISyntaxException | URLBuilderException e) { throw new IdentityOAuth2Exception("Error occurred when getting the device flow authentication completed" + " page URI.", e); } } /** * Builds a URL with a given context in both the tenant-qualified url supported mode and the legacy mode. * Returns the absolute URL build from the default context in the tenant-qualified url supported mode. Gives * precedence to the file configurations in the legacy mode and returns the absolute url build from file * configuration context. * * @param defaultContext Default URL context. * @param getValueFromFileBasedConfig File-based Configuration. * @return Absolute URL. */ private static String buildUrl(String defaultContext, Supplier<String> getValueFromFileBasedConfig) { String oauth2EndpointURLInFile = null; if (getValueFromFileBasedConfig != null) { oauth2EndpointURLInFile = getValueFromFileBasedConfig.get(); } return buildServiceUrl(defaultContext, oauth2EndpointURLInFile); } /** * Returns the public service url given the default context and the url picked from the configuration based on * the 'tenant_context.enable_tenant_qualified_urls' mode set in deployment.toml. * * @param defaultContext default url context path * @param oauth2EndpointURLInFile url picked from the file configuration * @return absolute public url of the service if 'enable_tenant_qualified_urls' is 'true', else returns the url * from the file config */ public static String buildServiceUrl(String defaultContext, String oauth2EndpointURLInFile) { if (IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) { try { return ServiceURLBuilder.create().addPath(defaultContext).build().getAbsolutePublicURL(); } catch (URLBuilderException e) { throw new OAuthRuntimeException("Error while building url for context: " + defaultContext); } } else if (StringUtils.isNotBlank(oauth2EndpointURLInFile)) { // Use the value configured in the file. return oauth2EndpointURLInFile; } // Use the default context. try { return ServiceURLBuilder.create().addPath(defaultContext).build().getAbsolutePublicURL(); } catch (URLBuilderException e) { throw new OAuthRuntimeException("Error while building url for context: " + defaultContext); } } private static boolean isNotSuperTenant(String tenantDomain) { return (StringUtils.isNotBlank(tenantDomain) && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)); } public static boolean isOIDCAuthzRequest(Set<String> scope) { return scope.contains(OAuthConstants.Scope.OPENID); } public static boolean isOIDCAuthzRequest(String[] scope) { for (String openidscope : scope) { if (openidscope.equals(OAuthConstants.Scope.OPENID)) { return true; } } return false; } /** * Verifies if the PKCE code verifier is upto specification as per RFC 7636 * * @param codeVerifier PKCE Code Verifier sent with the token request * @return */ public static boolean validatePKCECodeVerifier(String codeVerifier) { Matcher pkceCodeVerifierMatcher = pkceCodeVerifierPattern.matcher(codeVerifier); if (!pkceCodeVerifierMatcher.matches() || (codeVerifier.length() < 43 || codeVerifier.length() > 128)) { return false; } return true; } /** * Verifies if the codeChallenge is upto specification as per RFC 7636 * * @param codeChallenge * @param codeChallengeMethod * @return */ public static boolean validatePKCECodeChallenge(String codeChallenge, String codeChallengeMethod) { if (codeChallengeMethod == null || OAuthConstants.OAUTH_PKCE_PLAIN_CHALLENGE.equals(codeChallengeMethod)) { return validatePKCECodeVerifier(codeChallenge); } else if (OAuthConstants.OAUTH_PKCE_S256_CHALLENGE.equals(codeChallengeMethod)) { // SHA256 code challenge is 256 bits that is 256 / 6 ~= 43 // See https://tools.ietf.org/html/rfc7636#section-3 if (codeChallenge != null && codeChallenge.trim().length() == 43) { return true; } } //provided code challenge method is wrong return false; } @Deprecated public static boolean doPKCEValidation(String referenceCodeChallenge, String codeVerifier, String challengeMethod, OAuthAppDO oAuthAppDO) throws IdentityOAuth2Exception { return validatePKCE(referenceCodeChallenge, codeVerifier, challengeMethod, oAuthAppDO); } public static boolean validatePKCE(String referenceCodeChallenge, String verificationCode, String challengeMethod, OAuthAppDO oAuthApp) throws IdentityOAuth2Exception { if (oAuthApp != null && oAuthApp.isPkceMandatory() || referenceCodeChallenge != null) { Map<String, Object> params = null; if (LoggerUtils.isDiagnosticLogsEnabled()) { params = new HashMap<>(); params.put("clientId", oAuthApp.getOauthConsumerKey()); params.put("verificationCode", verificationCode); params.put("codeChallenge", referenceCodeChallenge); params.put("challengeMethod", challengeMethod); } //As per RFC 7636 Fallback to 'plain' if no code_challenge_method parameter is sent if (challengeMethod == null || challengeMethod.trim().length() == 0) { challengeMethod = "plain"; } //if app with no PKCE code verifier arrives if ((verificationCode == null || verificationCode.trim().length() == 0)) { //if pkce is mandatory, throw error if (oAuthApp.isPkceMandatory()) { if (LoggerUtils.isDiagnosticLogsEnabled()) { LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "No PKCE code verifier found. PKCE is mandatory for the application.", "validate-pkce", null); } throw new IdentityOAuth2Exception("No PKCE code verifier found.PKCE is mandatory for this " + "oAuth 2.0 application."); } else { //PKCE is optional, see if the authz code was requested with a PKCE challenge if (referenceCodeChallenge == null || referenceCodeChallenge.trim().length() == 0) { //since no PKCE challenge was provided if (LoggerUtils.isDiagnosticLogsEnabled()) { LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "PKCE challenge is not provided.", "validate-pkce", null); } return true; } else { if (LoggerUtils.isDiagnosticLogsEnabled()) { LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Empty PKCE code_verifier sent. This authorization code requires a PKCE " + "verification to obtain an access token.", "validate-pkce", null); } throw new IdentityOAuth2Exception("Empty PKCE code_verifier sent. This authorization code " + "requires a PKCE verification to obtain an access token."); } } } //verify that the code verifier is upto spec as per RFC 7636 if (!validatePKCECodeVerifier(verificationCode)) { if (LoggerUtils.isDiagnosticLogsEnabled()) { LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Code verifier used is not up to RFC 7636 specifications.", "validate-pkce", null); } throw new IdentityOAuth2Exception("Code verifier used is not up to RFC 7636 specifications."); } if (OAuthConstants.OAUTH_PKCE_PLAIN_CHALLENGE.equals(challengeMethod)) { //if the current application explicitly doesn't support plain, throw exception if (!oAuthApp.isPkceSupportPlain()) { if (LoggerUtils.isDiagnosticLogsEnabled()) { LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "This application does not allow 'plain' transformation algorithm.", "validate-pkce", null); } throw new IdentityOAuth2Exception( "This application does not allow 'plain' transformation algorithm."); } if (!referenceCodeChallenge.equals(verificationCode)) { if (LoggerUtils.isDiagnosticLogsEnabled()) { LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Reference code challenge does not match with verification code.", "validate-pkce", null); } return false; } } else if (OAuthConstants.OAUTH_PKCE_S256_CHALLENGE.equals(challengeMethod)) { try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte[] hash = messageDigest.digest(verificationCode.getBytes(StandardCharsets.US_ASCII)); //Trim the base64 string to remove trailing CR LF characters. String referencePKCECodeChallenge = new String(Base64.encodeBase64URLSafe(hash), StandardCharsets.UTF_8).trim(); if (!referencePKCECodeChallenge.equals(referenceCodeChallenge)) { if (LoggerUtils.isDiagnosticLogsEnabled()) { LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Reference code challenge does not match with verification code.", "validate-pkce", null); } return false; } } catch (NoSuchAlgorithmException e) { if (log.isDebugEnabled()) { log.debug("Failed to create SHA256 Message Digest."); } if (LoggerUtils.isDiagnosticLogsEnabled()) { LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "System error occurred.", "validate-pkce", null); } return false; } } else { //Invalid OAuth2 token response if (LoggerUtils.isDiagnosticLogsEnabled()) { LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Invalid PKCE Code Challenge Method.", "validate-pkce", null); } throw new IdentityOAuth2Exception("Invalid OAuth2 Token Response. Invalid PKCE Code Challenge Method '" + challengeMethod + "'"); } } //pkce validation successful LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.SUCCESS, "PKCE validation is successful for the token request.", "validate-pkce", null); return true; } @Deprecated public static boolean isPKCESupportEnabled() { return OAuth2ServiceComponentHolder.isPkceEnabled(); } /** * To check whether the given response type is for Implicit flow. * * @param responseType response type * @return true if the response type is for Implicit flow */ public static boolean isImplicitResponseType(String responseType) { return (StringUtils.isNotBlank(responseType) && (OAuthConstants.ID_TOKEN).equals(responseType) || (OAuthConstants.TOKEN).equals(responseType) || (OAuthConstants.IDTOKEN_TOKEN).equals(responseType)); } /** * To check whether the given response type is for Hybrid flow. * * @param responseType response type * @return true if the response type is for Hybrid flow. */ public static boolean isHybridResponseType(String responseType) { return (StringUtils.isNotBlank(responseType) && (OAuthConstants.CODE_TOKEN).equals(responseType) || (OAuthConstants.CODE_IDTOKEN).equals(responseType) || (OAuthConstants.CODE_IDTOKEN_TOKEN).equals (responseType)); } /** * To populate the database in the very first server startup. * * @param tenantId tenant id */ public static void initiateOIDCScopes(int tenantId) { List<ScopeDTO> scopeClaimsList = OAuth2ServiceComponentHolder.getInstance().getOIDCScopesClaims(); try { OAuthTokenPersistenceFactory.getInstance().getScopeClaimMappingDAO().initScopeClaimMapping(tenantId, scopeClaimsList); } catch (IdentityOAuth2ClientException e) { if (log.isDebugEnabled()) { log.debug(e.getMessage(), e); } } catch (IdentityOAuth2Exception e) { log.error(e.getMessage(), e); } } public static List<String> getOIDCScopes(String tenantDomain) { List<String> scopes = new ArrayList<>(); try { int tenantId = OAuthComponentServiceHolder.getInstance().getRealmService().getTenantManager() .getTenantId(tenantDomain); // Get the scopes from the cache or the db List<ScopeDTO> scopesDTOList = OAuthTokenPersistenceFactory.getInstance().getScopeClaimMappingDAO(). getScopes(tenantId); if (CollectionUtils.isNotEmpty(scopesDTOList)) { for (ScopeDTO scope : scopesDTOList) { scopes.add(scope.getName()); } } } catch (UserStoreException | IdentityOAuth2Exception e) { log.error("Error while retrieving OIDC scopes.", e); } return scopes; } public static AccessTokenDO getAccessTokenDOfromTokenIdentifier(String accessTokenIdentifier) throws IdentityOAuth2Exception { return getAccessTokenDOFromTokenIdentifier(accessTokenIdentifier, false); } public static AccessTokenDO getAccessTokenDOFromTokenIdentifier(String accessTokenIdentifier, boolean includeExpired) throws IdentityOAuth2Exception { boolean cacheHit = false; AccessTokenDO accessTokenDO = null; // As the server implementation knows about the PersistenceProcessor Processed Access Token, // we are converting before adding to the cache. String processedToken = getPersistenceProcessor().getProcessedAccessTokenIdentifier(accessTokenIdentifier); // check the cache, if caching is enabled. OAuthCacheKey cacheKey = new OAuthCacheKey(accessTokenIdentifier); CacheEntry result = OAuthCache.getInstance().getValueFromCache(cacheKey); // cache hit, do the type check. if (result != null && result instanceof AccessTokenDO) { accessTokenDO = (AccessTokenDO) result; cacheHit = true; if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Hit OAuthCache for accessTokenIdentifier: " + accessTokenIdentifier); } else { if (log.isDebugEnabled()) { log.debug("Hit OAuthCache with accessTokenIdentifier"); } } } // cache miss, load the access token info from the database. if (accessTokenDO == null) { accessTokenDO = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO() .getAccessToken(accessTokenIdentifier, includeExpired); } else { if (log.isDebugEnabled()) { log.debug("Retrieved active access token from OAuthCache for token Identifier: " + accessTokenDO.getTokenId()); } } if (accessTokenDO == null) { // this means the token is not active so we can't proceed further throw new IllegalArgumentException(ACCESS_TOKEN_IS_NOT_ACTIVE_ERROR_MESSAGE); } // Add the token back to the cache in the case of a cache miss but don't add to cache when OAuth2 token // hashing feature enabled inorder to reduce the complexity. if (!cacheHit & OAuth2Util.isHashDisabled()) { OAuthCache.getInstance().addToCache(cacheKey, accessTokenDO); if (log.isDebugEnabled()) { log.debug("Access Token Info object was added back to the cache."); } } return accessTokenDO; } public static String getClientIdForAccessToken(String accessTokenIdentifier) throws IdentityOAuth2Exception { AccessTokenDO accessTokenDO = getAccessTokenDOfromTokenIdentifier(accessTokenIdentifier); return accessTokenDO.getConsumerKey(); } /*** * Read the configuration file at server start up. * @param tenantId * @deprecated due to UI implementation. */ @Deprecated public static void initTokenExpiryTimesOfSps(int tenantId) { try { Registry registry = OAuth2ServiceComponentHolder.getRegistryService().getConfigSystemRegistry(tenantId); if (!registry.resourceExists(OAuthConstants.TOKEN_EXPIRE_TIME_RESOURCE_PATH)) { Resource resource = registry.newResource(); registry.put(OAuthConstants.TOKEN_EXPIRE_TIME_RESOURCE_PATH, resource); } } catch (RegistryException e) { log.error("Error while creating registry collection for :" + OAuthConstants.TOKEN_EXPIRE_TIME_RESOURCE_PATH, e); } } /*** * Return the SP-token Expiry time configuration object when consumer key is given. * @param consumerKey * @param tenantId * @return A SpOAuth2ExpiryTimeConfiguration Object * @deprecated due to UI implementation */ @Deprecated public static SpOAuth2ExpiryTimeConfiguration getSpTokenExpiryTimeConfig(String consumerKey, int tenantId) { SpOAuth2ExpiryTimeConfiguration spTokenTimeObject = new SpOAuth2ExpiryTimeConfiguration(); try { if (log.isDebugEnabled()) { log.debug("SP wise token expiry time feature is applied for tenant id : " + tenantId + "and consumer key : " + consumerKey); } IdentityTenantUtil.initializeRegistry(tenantId, getTenantDomain(tenantId)); Registry registry = IdentityTenantUtil.getConfigRegistry(tenantId); if (registry.resourceExists(OAuthConstants.TOKEN_EXPIRE_TIME_RESOURCE_PATH)) { Resource resource = registry.get(OAuthConstants.TOKEN_EXPIRE_TIME_RESOURCE_PATH); String jsonString = "{}"; Object consumerKeyObject = resource.getProperties().get(consumerKey); if (consumerKeyObject instanceof List) { if (!((List) consumerKeyObject).isEmpty()) { jsonString = ((List) consumerKeyObject).get(0).toString(); } } JSONObject spTimeObject = new JSONObject(jsonString); if (spTimeObject.length() > 0) { if (spTimeObject.has(USER_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS) && !spTimeObject.isNull(USER_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS)) { try { spTokenTimeObject.setUserAccessTokenExpiryTime(Long.parseLong(spTimeObject .get(USER_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS).toString())); if (log.isDebugEnabled()) { log.debug("The user access token expiry time :" + spTimeObject .get(USER_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS).toString() + " for application id : " + consumerKey); } } catch (NumberFormatException e) { String errorMsg = String.format( "Invalid value provided as user access token expiry time for consumer " + "key %s, tenant id : %d. Given value: %s, Expected a long value", consumerKey, tenantId, spTimeObject.get(USER_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS).toString()); log.error(errorMsg, e); } } else { spTokenTimeObject.setUserAccessTokenExpiryTime(OAuthServerConfiguration.getInstance() .getUserAccessTokenValidityPeriodInSeconds() * 1000); } if (spTimeObject.has(APPLICATION_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS) && !spTimeObject.isNull(APPLICATION_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS)) { try { spTokenTimeObject.setApplicationAccessTokenExpiryTime(Long.parseLong(spTimeObject .get(APPLICATION_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS).toString())); if (log.isDebugEnabled()) { log.debug("The application access token expiry time :" + spTimeObject .get(APPLICATION_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS).toString() + " for application id : " + consumerKey); } } catch (NumberFormatException e) { String errorMsg = String.format( "Invalid value provided as application access token expiry time for consumer " + "key %s, tenant id : %d. Given value: %s, Expected a long value ", consumerKey, tenantId, spTimeObject.get(APPLICATION_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS).toString()); log.error(errorMsg, e); } } else { spTokenTimeObject.setApplicationAccessTokenExpiryTime(OAuthServerConfiguration.getInstance() .getApplicationAccessTokenValidityPeriodInSeconds() * 1000); } if (spTimeObject.has(REFRESH_TOKEN_EXP_TIME_IN_MILLISECONDS) && !spTimeObject.isNull(REFRESH_TOKEN_EXP_TIME_IN_MILLISECONDS)) { try { spTokenTimeObject.setRefreshTokenExpiryTime(Long.parseLong(spTimeObject .get(REFRESH_TOKEN_EXP_TIME_IN_MILLISECONDS).toString())); if (log.isDebugEnabled()) { log.debug("The refresh token expiry time :" + spTimeObject .get(REFRESH_TOKEN_EXP_TIME_IN_MILLISECONDS).toString() + " for application id : " + consumerKey); } } catch (NumberFormatException e) { String errorMsg = String.format( "Invalid value provided as refresh token expiry time for consumer key %s, tenant " + "id : %d. Given value: %s, Expected a long value", consumerKey, tenantId, spTimeObject.get(REFRESH_TOKEN_EXP_TIME_IN_MILLISECONDS).toString()); log.error(errorMsg, e); } } else { spTokenTimeObject.setRefreshTokenExpiryTime(OAuthServerConfiguration.getInstance() .getRefreshTokenValidityPeriodInSeconds() * 1000); } } } } catch (RegistryException e) { log.error("Error while getting data from the registry.", e); } catch (IdentityException e) { log.error("Error while getting the tenant domain from tenant id : " + tenantId, e); } return spTokenTimeObject; } /** * Retrieve audience configured for the particular service provider. * * @param clientId * @param oAuthAppDO * @return */ public static List<String> getOIDCAudience(String clientId, OAuthAppDO oAuthAppDO) { List<String> oidcAudiences = getDefinedCustomOIDCAudiences(oAuthAppDO); // Need to add client_id as an audience value according to the spec. if (!oidcAudiences.contains(clientId)) { oidcAudiences.add(0, clientId); } else { Collections.swap(oidcAudiences, oidcAudiences.indexOf(clientId), 0); } return oidcAudiences; } private static List<String> getDefinedCustomOIDCAudiences(OAuthAppDO oAuthAppDO) { List<String> audiences = new ArrayList<>(); // Priority should be given to service provider specific audiences over globally configured ones. if (OAuth2ServiceComponentHolder.isAudienceEnabled()) { audiences = getAudienceListFromOAuthAppDO(oAuthAppDO); if (CollectionUtils.isNotEmpty(audiences)) { if (log.isDebugEnabled()) { log.debug("OIDC Audiences " + audiences + " had been retrieved for the client_id: " + oAuthAppDO.getOauthConsumerKey()); } return audiences; } } IdentityConfigParser configParser = IdentityConfigParser.getInstance(); OMElement oauthElem = configParser.getConfigElement(CONFIG_ELEM_OAUTH); if (oauthElem == null) { log.warn("Error in OAuth Configuration: <OAuth> configuration element is not available in identity.xml."); return audiences; } OMElement oidcConfig = oauthElem.getFirstChildWithName(new QName(IdentityCoreConstants. IDENTITY_DEFAULT_NAMESPACE, OPENID_CONNECT)); if (oidcConfig == null) { log.warn("Error in OAuth Configuration: <OpenIDConnect> element is not available in identity.xml."); return audiences; } OMElement audienceConfig = oidcConfig.getFirstChildWithName(new QName(IdentityCoreConstants. IDENTITY_DEFAULT_NAMESPACE, OPENID_CONNECT_AUDIENCES)); if (audienceConfig == null) { return audiences; } Iterator iterator = audienceConfig.getChildrenWithName(new QName(IdentityCoreConstants. IDENTITY_DEFAULT_NAMESPACE, OPENID_CONNECT_AUDIENCE_IDENTITY_CONFIG)); while (iterator.hasNext()) { OMElement supportedAudience = (OMElement) iterator.next(); String supportedAudienceName; if (supportedAudience != null) { supportedAudienceName = IdentityUtil.fillURLPlaceholders(supportedAudience.getText()); if (StringUtils.isNotBlank(supportedAudienceName)) { audiences.add(supportedAudienceName); } } } return audiences; } private static List<String> getAudienceListFromOAuthAppDO(OAuthAppDO oAuthAppDO) { if (oAuthAppDO.getAudiences() == null) { return new ArrayList<>(); } else { return new ArrayList<>(Arrays.asList(oAuthAppDO.getAudiences())); } } /** * Returns oauth token issuer registered in the service provider app * * @param clientId client id of the oauth app * @return oauth token issuer * @throws IdentityOAuth2Exception * @throws InvalidOAuthClientException */ public static OauthTokenIssuer getOAuthTokenIssuerForOAuthApp(String clientId) throws IdentityOAuth2Exception, InvalidOAuthClientException { OAuthAppDO appDO; try { appDO = getAppInformationByClientId(clientId); } catch (IdentityOAuth2Exception e) { throw new IdentityOAuth2Exception("Error while retrieving app information for clientId: " + clientId, e); } return getOAuthTokenIssuerForOAuthApp(appDO); } /** * Returns oauth token issuer registered in the service provider app. * * @param appDO oauth app data object * @return oauth token issuer * @throws IdentityOAuth2Exception * @throws InvalidOAuthClientException */ public static OauthTokenIssuer getOAuthTokenIssuerForOAuthApp(OAuthAppDO appDO) throws IdentityOAuth2Exception { OauthTokenIssuer oauthIdentityTokenGenerator; if (appDO.getTokenType() != null) { oauthIdentityTokenGenerator = OAuthServerConfiguration.getInstance() .addAndReturnTokenIssuerInstance(appDO.getTokenType()); if (oauthIdentityTokenGenerator == null) { //get server level configured token issuer oauthIdentityTokenGenerator = OAuthServerConfiguration.getInstance().getIdentityOauthTokenIssuer(); } } else { oauthIdentityTokenGenerator = OAuthServerConfiguration.getInstance().getIdentityOauthTokenIssuer(); if (log.isDebugEnabled()) { log.debug("Token type is not set for service provider app with client Id: " + appDO.getOauthConsumerKey() + ". Hence the default Identity OAuth token issuer will be used. " + "No custom token generator is set."); } } return oauthIdentityTokenGenerator; } /** * Get Oauth application information * * @param clientId * @return Oauth app information * @throws IdentityOAuth2Exception * @throws InvalidOAuthClientException */ public static OAuthAppDO getAppInformationByClientId(String clientId) throws IdentityOAuth2Exception, InvalidOAuthClientException { OAuthAppDO oAuthAppDO = AppInfoCache.getInstance().getValueFromCache(clientId); if (oAuthAppDO != null) { return oAuthAppDO; } else { oAuthAppDO = new OAuthAppDAO().getAppInformation(clientId); if (oAuthAppDO != null) { AppInfoCache.getInstance().addToCache(clientId, oAuthAppDO); } return oAuthAppDO; } } /** * Get the tenant domain of an oauth application * * @param oAuthAppDO * @return */ public static String getTenantDomainOfOauthApp(OAuthAppDO oAuthAppDO) { String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; if (oAuthAppDO != null && oAuthAppDO.getUser() != null) { tenantDomain = oAuthAppDO.getUser().getTenantDomain(); } return tenantDomain; } /** * This is used to get the tenant domain of an application by clientId. * * @param clientId Consumer key of Application * @return Tenant Domain * @throws IdentityOAuth2Exception * @throws InvalidOAuthClientException */ public static String getTenantDomainOfOauthApp(String clientId) throws IdentityOAuth2Exception, InvalidOAuthClientException { OAuthAppDO oAuthAppDO = getAppInformationByClientId(clientId); return getTenantDomainOfOauthApp(oAuthAppDO); } /** * Get the client secret of the application. * * @param consumerKey Consumer Key provided by the user. * @return Consumer Secret. * @throws IdentityOAuth2Exception Error when loading the application. * @throws InvalidOAuthClientException Error when loading the application. */ public static String getClientSecret(String consumerKey) throws IdentityOAuth2Exception, InvalidOAuthClientException { OAuthAppDO oAuthAppDO = getAppInformationByClientId(consumerKey); if (oAuthAppDO == null) { throw new InvalidOAuthClientException("Unable to retrieve app information for consumer key: " + consumerKey); } return oAuthAppDO.getOauthConsumerSecret(); } /** * This method map signature algorithm define in identity.xml to nimbus * signature algorithm * * @param signatureAlgorithm name of the signature algorithm * @return mapped JWSAlgorithm name * @throws IdentityOAuth2Exception */ @Deprecated public static String mapSignatureAlgorithm(String signatureAlgorithm) throws IdentityOAuth2Exception { return mapSignatureAlgorithmForJWSAlgorithm(signatureAlgorithm).getName(); } /** * This method maps the encryption algorithm name defined in identity.xml to a respective * nimbus encryption algorithm. * * @param encryptionAlgorithm name of the encryption algorithm * @return mapped JWEAlgorithm * @throws IdentityOAuth2Exception */ public static JWEAlgorithm mapEncryptionAlgorithmForJWEAlgorithm(String encryptionAlgorithm) throws IdentityOAuth2Exception { // Parse method in JWEAlgorithm is used to get a JWEAlgorithm object from the algorithm name. JWEAlgorithm jweAlgorithm = JWEAlgorithm.parse(encryptionAlgorithm); // Parse method returns a new JWEAlgorithm with requirement set to null if unknown algorithm name is passed. if (jweAlgorithm.getRequirement() != null) { return jweAlgorithm; } else { throw new IdentityOAuth2Exception("Unsupported Encryption Algorithm: " + encryptionAlgorithm); } } /** * This method maps the encryption method name defined in identity.xml to a respective nimbus * encryption method. * * @param encryptionMethod name of the encryption method * @return mapped EncryptionMethod * @throws IdentityOAuth2Exception */ public static EncryptionMethod mapEncryptionMethodForJWEAlgorithm(String encryptionMethod) throws IdentityOAuth2Exception { // Parse method in EncryptionMethod is used to get a EncryptionMethod object from the method name. EncryptionMethod method = EncryptionMethod.parse(encryptionMethod); // Parse method returns a new EncryptionMethod with requirement set to null if unknown method name is passed. if (method.getRequirement() != null) { return method; } else { log.error("Unsupported Encryption Method in identity.xml"); throw new IdentityOAuth2Exception("Unsupported Encryption Method: " + encryptionMethod); } } /** * This method map signature algorithm define in identity.xml to nimbus * signature algorithm * * @param signatureAlgorithm name of the signature algorithm * @return mapped JWSAlgorithm * @throws IdentityOAuth2Exception */ public static JWSAlgorithm mapSignatureAlgorithmForJWSAlgorithm(String signatureAlgorithm) throws IdentityOAuth2Exception { if (NONE.equalsIgnoreCase(signatureAlgorithm)) { return new JWSAlgorithm(JWSAlgorithm.NONE.getName()); } else if (SHA256_WITH_RSA.equals(signatureAlgorithm)) { return JWSAlgorithm.RS256; } else if (SHA384_WITH_RSA.equals(signatureAlgorithm)) { return JWSAlgorithm.RS384; } else if (SHA512_WITH_RSA.equals(signatureAlgorithm)) { return JWSAlgorithm.RS512; } else if (SHA256_WITH_HMAC.equals(signatureAlgorithm)) { return JWSAlgorithm.HS256; } else if (SHA384_WITH_HMAC.equals(signatureAlgorithm)) { return JWSAlgorithm.HS384; } else if (SHA512_WITH_HMAC.equals(signatureAlgorithm)) { return JWSAlgorithm.HS512; } else if (SHA256_WITH_EC.equals(signatureAlgorithm)) { return JWSAlgorithm.ES256; } else if (SHA384_WITH_EC.equals(signatureAlgorithm)) { return JWSAlgorithm.ES384; } else if (SHA512_WITH_EC.equals(signatureAlgorithm)) { return JWSAlgorithm.ES512; } else if (SHA256_WITH_PS.equals(signatureAlgorithm) || PS256.equals(signatureAlgorithm)) { return JWSAlgorithm.PS256; } else { log.error("Unsupported Signature Algorithm in identity.xml"); throw new IdentityOAuth2Exception("Unsupported Signature Algorithm in identity.xml"); } } /** * Check if audiences are enabled by reading configuration file at server startup. * * @return */ public static boolean checkAudienceEnabled() { boolean isAudienceEnabled = false; IdentityConfigParser configParser = IdentityConfigParser.getInstance(); OMElement oauthElem = configParser.getConfigElement(CONFIG_ELEM_OAUTH); if (oauthElem == null) { log.warn("Error in OAuth Configuration. OAuth element is not available."); return isAudienceEnabled; } OMElement configOpenIDConnect = oauthElem .getFirstChildWithName(new QName(IdentityCoreConstants.IDENTITY_DEFAULT_NAMESPACE, OPENID_CONNECT)); if (configOpenIDConnect == null) { log.warn("Error in OAuth Configuration. OpenID element is not available."); return isAudienceEnabled; } OMElement configAudience = configOpenIDConnect.getFirstChildWithName( new QName(IdentityCoreConstants.IDENTITY_DEFAULT_NAMESPACE, ENABLE_OPENID_CONNECT_AUDIENCES)); if (configAudience != null) { String configAudienceValue = configAudience.getText(); if (StringUtils.isNotBlank(configAudienceValue)) { isAudienceEnabled = Boolean.parseBoolean(configAudienceValue); } } return isAudienceEnabled; } /** * Generate the unique user domain value in the format of "FEDERATED:idp_name". * * @param authenticatedIDP : Name of the IDP, which authenticated the user. * @return */ public static String getFederatedUserDomain(String authenticatedIDP) { if (IdentityUtil.isNotBlank(authenticatedIDP)) { return OAuthConstants.UserType.FEDERATED_USER_DOMAIN_PREFIX + OAuthConstants.UserType.FEDERATED_USER_DOMAIN_SEPARATOR + authenticatedIDP; } else { return OAuthConstants.UserType.FEDERATED_USER_DOMAIN_PREFIX; } } /** * Validate Id token signature * * @param idToken Id token * @return validation state */ public static boolean validateIdToken(String idToken) { boolean isJWTSignedWithSPKey = OAuthServerConfiguration.getInstance().isJWTSignedWithSPKey(); String tenantDomain; try { String clientId = SignedJWT.parse(idToken).getJWTClaimsSet().getAudience().get(0); if (isJWTSignedWithSPKey) { OAuthAppDO oAuthAppDO = OAuth2Util.getAppInformationByClientId(clientId); tenantDomain = OAuth2Util.getTenantDomainOfOauthApp(oAuthAppDO); } else { //It is not sending tenant domain with the subject in id_token by default, So to work this as //expected, need to enable the option "Use tenant domain in local subject identifier" in SP config tenantDomain = MultitenantUtils.getTenantDomain(SignedJWT.parse(idToken).getJWTClaimsSet().getSubject()); } if (StringUtils.isEmpty(tenantDomain)) { return false; } int tenantId = IdentityTenantUtil.getTenantId(tenantDomain); RSAPublicKey publicKey; KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId); if (!tenantDomain.equals(org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { String ksName = tenantDomain.trim().replace(".", "-"); String jksName = ksName + ".jks"; publicKey = (RSAPublicKey) keyStoreManager.getKeyStore(jksName).getCertificate(tenantDomain) .getPublicKey(); } else { publicKey = (RSAPublicKey) keyStoreManager.getDefaultPublicKey(); } SignedJWT signedJWT = SignedJWT.parse(idToken); JWSVerifier verifier = new RSASSAVerifier(publicKey); return signedJWT.verify(verifier); } catch (JOSEException | ParseException e) { if (log.isDebugEnabled()) { log.debug("Error occurred while validating id token signature."); } return false; } catch (Exception e) { log.error("Error occurred while validating id token signature."); return false; } } /** * This method maps signature algorithm define in identity.xml to digest algorithms to generate the at_hash * * @param signatureAlgorithm * @return the mapped digest algorithm * @throws IdentityOAuth2Exception */ public static String mapDigestAlgorithm(Algorithm signatureAlgorithm) throws IdentityOAuth2Exception { if (JWSAlgorithm.RS256.equals(signatureAlgorithm) || JWSAlgorithm.HS256.equals(signatureAlgorithm) || JWSAlgorithm.ES256.equals(signatureAlgorithm) || JWSAlgorithm.PS256.equals(signatureAlgorithm)) { return SHA256; } else if (JWSAlgorithm.RS384.equals(signatureAlgorithm) || JWSAlgorithm.HS384.equals(signatureAlgorithm) || JWSAlgorithm.ES384.equals(signatureAlgorithm)) { return SHA384; } else if (JWSAlgorithm.RS512.equals(signatureAlgorithm) || JWSAlgorithm.HS512.equals(signatureAlgorithm) || JWSAlgorithm.ES512.equals(signatureAlgorithm)) { return SHA512; } else { throw new RuntimeException("Provided signature algorithm: " + signatureAlgorithm + " is not supported"); } } /** * This is the generic Encryption function which calls algorithm specific encryption function * depending on the algorithm name. * * @param jwtClaimsSet contains JWT body * @param encryptionAlgorithm JWT encryption algorithm * @param spTenantDomain Service provider tenant domain * @param clientId ID of the client * @return encrypted JWT token * @throws IdentityOAuth2Exception * @deprecated replaced by * {@link #encryptJWT(JWTClaimsSet, JWSAlgorithm, String, JWEAlgorithm, EncryptionMethod, String, String)} */ @Deprecated public static JWT encryptJWT(JWTClaimsSet jwtClaimsSet, JWEAlgorithm encryptionAlgorithm, EncryptionMethod encryptionMethod, String spTenantDomain, String clientId) throws IdentityOAuth2Exception { if (isRSAAlgorithm(encryptionAlgorithm)) { return encryptWithRSA(jwtClaimsSet, encryptionAlgorithm, encryptionMethod, spTenantDomain, clientId); } else { throw new RuntimeException("Provided encryption algorithm: " + encryptionAlgorithm + " is not supported"); } } /** * This is the generic Encryption function which calls algorithm specific encryption function * depending on the algorithm name. * * @param jwtClaimsSet JwtClaimsSet to encrypt * @param signatureAlgorithm Signature algorithm * @param signingTenantDomain Tenant Domain for signing * @param encryptionAlgorithm JWT encryption algorithm * @param spTenantDomain Service provider tenant domain * @param clientId ID of the client * @return encrypted JWT token * @throws IdentityOAuth2Exception */ public static JWT encryptJWT(JWTClaimsSet jwtClaimsSet, JWSAlgorithm signatureAlgorithm, String signingTenantDomain, JWEAlgorithm encryptionAlgorithm, EncryptionMethod encryptionMethod, String spTenantDomain, String clientId) throws IdentityOAuth2Exception { if (isRSAAlgorithm(encryptionAlgorithm)) { if (log.isDebugEnabled()) { log.debug(String.format("Signing JWT before encryption using the algorithm: %s ." , signatureAlgorithm)); } SignedJWT signedJwt = (SignedJWT) OAuth2Util.signJWT(jwtClaimsSet, signatureAlgorithm, signingTenantDomain); return encryptWithRSA(signedJwt, encryptionAlgorithm, encryptionMethod, spTenantDomain, clientId); } else { throw new RuntimeException("Provided encryption algorithm: " + encryptionAlgorithm + " is not supported"); } } /** * Encrypt JWT id token using RSA algorithm. * * @param jwtClaimsSet contains JWT body * @param encryptionAlgorithm JWT signing algorithm * @param spTenantDomain Service provider tenant domain * @param clientId ID of the client * @return encrypted JWT token * @throws IdentityOAuth2Exception * @deprecated replaced by {@link #encryptWithRSA(SignedJWT, JWEAlgorithm, EncryptionMethod, String, String)} */ @Deprecated private static JWT encryptWithRSA(JWTClaimsSet jwtClaimsSet, JWEAlgorithm encryptionAlgorithm, EncryptionMethod encryptionMethod, String spTenantDomain, String clientId) throws IdentityOAuth2Exception { if (StringUtils.isBlank(spTenantDomain)) { spTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; if (log.isDebugEnabled()) { log.debug("Assigned super tenant domain as signing domain when encrypting id token for " + "client_id: " + clientId); } } String jwksUri = getSPJwksUrl(clientId, spTenantDomain); Certificate publicCert; String thumbPrint; if (StringUtils.isBlank(jwksUri)) { if (log.isDebugEnabled()) { log.debug(String.format("Jwks uri is not configured for the service provider associated with " + "client_id: %s. Checking for x509 certificate", clientId)); } publicCert = getX509CertOfOAuthApp(clientId, spTenantDomain); thumbPrint = getThumbPrint(publicCert); } else { if (log.isDebugEnabled()) { log.debug(String.format("Fetching public keys for the client %s from jwks uri %s", clientId, jwksUri)); } publicCert = getPublicCertFromJWKS(jwksUri); thumbPrint = getJwkThumbPrint(publicCert); } Key publicKey = publicCert.getPublicKey(); return encryptWithPublicKey(publicKey, jwtClaimsSet, encryptionAlgorithm, encryptionMethod, spTenantDomain, clientId, thumbPrint); } /** * Encrypt JWT id token using RSA algorithm. * * @param signedJwt contains signed JWT body * @param encryptionAlgorithm JWT signing algorithm * @param spTenantDomain Service provider tenant domain * @param clientId ID of the client * @return encrypted JWT token * @throws IdentityOAuth2Exception */ private static JWT encryptWithRSA(SignedJWT signedJwt, JWEAlgorithm encryptionAlgorithm, EncryptionMethod encryptionMethod, String spTenantDomain, String clientId) throws IdentityOAuth2Exception { try { if (StringUtils.isBlank(spTenantDomain)) { spTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; if (log.isDebugEnabled()) { log.debug(String.format("Assigned super tenant domain as signing domain when encrypting id token " + "for client_id: %s .", clientId)); } } String jwksUri = getSPJwksUrl(clientId, spTenantDomain); if (StringUtils.isBlank(jwksUri)) { if (log.isDebugEnabled()) { log.debug(String.format("Jwks uri is not configured for the service provider associated with " + "client_id: %s , Checking for x509 certificate.", clientId)); } return encryptUsingSPX509Certificate(signedJwt, encryptionAlgorithm, encryptionMethod, spTenantDomain, clientId); } else { if (log.isDebugEnabled()) { log.debug(String.format("Jwks uri is configured for the service provider associated with" + " client %s from jwks uri %s .", clientId, jwksUri)); } return encryptUsingJwksPublicKey(signedJwt, encryptionAlgorithm, encryptionMethod, spTenantDomain, clientId, jwksUri); } } catch (JOSEException | ParseException e) { throw new IdentityOAuth2Exception("Error occurred while encrypting JWT for the client_id: " + clientId + " with the tenant domain: " + spTenantDomain, e); } } /** * Encrypt jwt using service provider's configured X509 certificate * * @param signedJwt contains signed JWT body * @param encryptionAlgorithm JWT signing algorithm * @param encryptionMethod Encryption method * @param spTenantDomain Service provider tenant domain * @param clientId ID of the client * @return * @throws IdentityOAuth2Exception */ private static JWT encryptUsingSPX509Certificate(SignedJWT signedJwt, JWEAlgorithm encryptionAlgorithm, EncryptionMethod encryptionMethod, String spTenantDomain, String clientId) throws IdentityOAuth2Exception { Certificate publicCert = getX509CertOfOAuthApp(clientId, spTenantDomain); if (publicCert == null) { throw new IdentityOAuth2Exception("Error while retrieving X509 cert from oauth app with " + "client_id: " + clientId + " of tenantDomain: " + spTenantDomain); } Key publicKey = publicCert.getPublicKey(); if (publicKey == null) { throw new IdentityOAuth2Exception("Error while retrieving public key from X509 cert of oauth app with " + "client_id: " + clientId + " of tenantDomain: " + spTenantDomain); } String kid = getThumbPrint(publicCert); return encryptWithPublicKey(publicKey, signedJwt, encryptionAlgorithm, encryptionMethod, spTenantDomain, clientId, kid); } /** * Encrypt jwt using publickey fetched from jwks * * @param signedJwt contains signed JWT body * @param encryptionAlgorithm JWT signing algorithm * @param encryptionMethod Encryption method * @param spTenantDomain Service provider tenant domain * @param clientId ID of the client * @param jwksUri jwks url * @return * @throws IdentityOAuth2Exception * @throws JOSEException * @throws ParseException */ private static JWT encryptUsingJwksPublicKey(SignedJWT signedJwt, JWEAlgorithm encryptionAlgorithm, EncryptionMethod encryptionMethod, String spTenantDomain, String clientId, String jwksUri) throws IdentityOAuth2Exception, JOSEException, ParseException { JWK encryptionJwk = getEncryptionJWKFromJWKS(jwksUri, encryptionAlgorithm); Key publicKey = RSAKey.parse(encryptionJwk.toJSONString()).toRSAPublicKey(); String kid = getKidValueFromJwk(encryptionJwk); return encryptWithPublicKey(publicKey, signedJwt, encryptionAlgorithm, encryptionMethod, spTenantDomain, clientId, kid); } /** * Get kid value from the jwk * * @param encryptionJwk Encryption jwk * @return */ private static String getKidValueFromJwk(JWK encryptionJwk) { String kid; Certificate publicCert; if (encryptionJwk.getKeyID() != null) { if (log.isDebugEnabled()) { log.debug(String.format("Kid value is available in jwk %s .", encryptionJwk.getKeyID())); } kid = encryptionJwk.getKeyID(); } else { if (log.isDebugEnabled()) { log.debug("Kid value is not available in jwk, attempting to set x5c thumbprint as kid."); } try { publicCert = getPublicCertFromJWK(encryptionJwk); kid = getJwkThumbPrint(publicCert); } catch (IdentityOAuth2Exception e) { log.error("Failed to set x5c thumbprint as kid value.", e); kid = null; } } return kid; } /** * Get encryption jwk from JWKS list when JWKS Uri is given. * * @param jwksUri - JWKS Uri * @param encryptionAlgorithm encryption algorithm * @return - encryption JWK from the jwks url * @throws IdentityOAuth2Exception - IdentityOAuth2Exception */ private static JWK getEncryptionJWKFromJWKS(String jwksUri, JWEAlgorithm encryptionAlgorithm) throws IdentityOAuth2Exception { if (log.isDebugEnabled()) { log.debug(String.format("Attempting to retrieve encryption jwk from the Jwks uri: %s , algorithm : %s", jwksUri, encryptionAlgorithm)); } try { JWKSet publicKeys = JWKSet.load(new URL(jwksUri)); // Get the first key, use as enc and alg from the list JWKMatcher keyMatcherWithAlgAndEncryptionUse = new JWKMatcher.Builder().algorithm(encryptionAlgorithm).keyUse(KeyUse.ENCRYPTION).build(); List<JWK> jwkList = new JWKSelector(keyMatcherWithAlgAndEncryptionUse).select(publicKeys); if (jwkList.isEmpty()) { // If empty, then get the first key, use as enc from the list JWKMatcher keyMatcherWithEncryptionUse = new JWKMatcher.Builder().keyUse(KeyUse.ENCRYPTION).build(); jwkList = new JWKSelector(keyMatcherWithEncryptionUse).select(publicKeys); if (jwkList.isEmpty()) { // failover defaults to ->, then get the first key, use as sig from the list JWKMatcher keyMatcherWithSignatureUse = new JWKMatcher.Builder().keyUse(KeyUse.SIGNATURE).build(); jwkList = new JWKSelector(keyMatcherWithSignatureUse).select(publicKeys); } } if (jwkList.isEmpty()) { throw new IdentityOAuth2Exception(String.format("Failed to retrieve valid jwk from " + "jwks uri: %s, algorithm : %s ", jwksUri, encryptionAlgorithm)); } else { return jwkList.get(0); } } catch (ParseException | IOException e) { throw new IdentityOAuth2Exception(String.format("Failed to retrieve jwk from jwks uri: %s, algorithm : %s", jwksUri, encryptionAlgorithm), e); } } /** * Get public certificate from JWK * * @param jwk * @return * @throws IdentityOAuth2Exception */ private static X509Certificate getPublicCertFromJWK(JWK jwk) throws IdentityOAuth2Exception { if (log.isDebugEnabled()) { log.debug(String.format("Attempting to retrieve public certificate from the Jwk kid: %s ." , jwk.getKeyID())); } X509Certificate certificate; if (jwk != null && jwk.getParsedX509CertChain() != null) { certificate = jwk.getParsedX509CertChain().get(0); if (log.isDebugEnabled()) { log.debug(String.format("Retrieved the public signing certificate successfully from the " + "jwk : %s .", jwk)); } return certificate; } throw new IdentityOAuth2Exception("Failed to retrieve public certificate from jwk due to null."); } /** * Encrypt the JWT token with with given public key. * * @param publicKey public key used to encrypt * @param jwtClaimsSet contains JWT body * @param encryptionAlgorithm JWT signing algorithm * @param spTenantDomain Service provider tenant domain * @param clientId ID of the client * @param thumbPrint value used as 'kid' * @return encrypted JWT token * @throws IdentityOAuth2Exception * @deprecated replaced by * {@link #encryptWithPublicKey(Key, SignedJWT, JWEAlgorithm, EncryptionMethod, String, String, String)} */ @Deprecated private static JWT encryptWithPublicKey(Key publicKey, JWTClaimsSet jwtClaimsSet, JWEAlgorithm encryptionAlgorithm, EncryptionMethod encryptionMethod, String spTenantDomain, String clientId, String thumbPrint) throws IdentityOAuth2Exception { JWEHeader.Builder headerBuilder = new JWEHeader.Builder(encryptionAlgorithm, encryptionMethod); try { headerBuilder.keyID(thumbPrint); JWEHeader header = headerBuilder.build(); EncryptedJWT encryptedJWT = new EncryptedJWT(header, jwtClaimsSet); if (log.isDebugEnabled()) { log.debug("Encrypting JWT using the algorithm: " + encryptionAlgorithm + ", method: " + encryptionMethod + ", tenant: " + spTenantDomain + " & header: " + header.toString()); } JWEEncrypter encrypter = new RSAEncrypter((RSAPublicKey) publicKey); encryptedJWT.encrypt(encrypter); return encryptedJWT; } catch (JOSEException e) { throw new IdentityOAuth2Exception("Error occurred while encrypting JWT for the client_id: " + clientId + " with the tenant domain: " + spTenantDomain, e); } } /** * Encrypt the JWT token with with given public key. * * @param publicKey public key used to encrypt * @param signedJwt contains signed JWT body * @param encryptionAlgorithm JWT signing algorithm * @param spTenantDomain Service provider tenant domain * @param clientId ID of the client * @param kid value used as 'kid' * @return encrypted JWT token * @throws IdentityOAuth2Exception */ private static JWT encryptWithPublicKey(Key publicKey, SignedJWT signedJwt, JWEAlgorithm encryptionAlgorithm, EncryptionMethod encryptionMethod, String spTenantDomain, String clientId, String kid) throws IdentityOAuth2Exception { JWEHeader.Builder headerBuilder = new JWEHeader.Builder(encryptionAlgorithm, encryptionMethod); try { if (StringUtils.isNotBlank(kid)) { headerBuilder.keyID(kid); } headerBuilder.contentType(JWT); // Required to indicate nested JWT. JWEHeader header = headerBuilder.build(); JWEObject jweObject = new JWEObject(header, new Payload(signedJwt)); // Encrypt with the recipient's public key. jweObject.encrypt(new RSAEncrypter((RSAPublicKey) publicKey)); EncryptedJWT encryptedJWT = EncryptedJWT.parse(jweObject.serialize()); if (log.isDebugEnabled()) { log.debug("Encrypting JWT using the algorithm: " + encryptionAlgorithm + ", method: " + encryptionMethod + ", tenant: " + spTenantDomain + " & header: " + header.toString()); } return encryptedJWT; } catch (JOSEException | ParseException e) { throw new IdentityOAuth2Exception("Error occurred while encrypting JWT for the client_id: " + clientId + " with the tenant domain: " + spTenantDomain, e); } } /** * Create JWSSigner using the server level configurations and return. * * @param privateKey RSA Private key. * @return JWSSigner */ public static JWSSigner createJWSSigner(RSAPrivateKey privateKey) { boolean allowWeakKey = Boolean.parseBoolean(System.getProperty(ALLOW_WEAK_RSA_SIGNER_KEY)); if (allowWeakKey && log.isDebugEnabled()) { log.debug("System flag 'allow_weak_rsa_signer_key' is enabled. So weak keys (key length less than 2048) " + " will be allowed for signing."); } return new RSASSASigner(privateKey, allowWeakKey); } /** * Generic Signing function * * @param jwtClaimsSet contains JWT body * @param signatureAlgorithm JWT signing algorithm * @param tenantDomain tenant domain * @return signed JWT token * @throws IdentityOAuth2Exception */ public static JWT signJWT(JWTClaimsSet jwtClaimsSet, JWSAlgorithm signatureAlgorithm, String tenantDomain) throws IdentityOAuth2Exception { if (JWSAlgorithm.RS256.equals(signatureAlgorithm) || JWSAlgorithm.RS384.equals(signatureAlgorithm) || JWSAlgorithm.RS512.equals(signatureAlgorithm) || JWSAlgorithm.PS256.equals(signatureAlgorithm)) { return signJWTWithRSA(jwtClaimsSet, signatureAlgorithm, tenantDomain); } else if (JWSAlgorithm.HS256.equals(signatureAlgorithm) || JWSAlgorithm.HS384.equals(signatureAlgorithm) || JWSAlgorithm.HS512.equals(signatureAlgorithm)) { // return signWithHMAC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done throw new RuntimeException("Provided signature algorithm: " + signatureAlgorithm + " is not supported"); } else { // return signWithEC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done throw new RuntimeException("Provided signature algorithm: " + signatureAlgorithm + " is not supported"); } } /** * sign JWT token from RSA algorithm * * @param jwtClaimsSet contains JWT body * @param signatureAlgorithm JWT signing algorithm * @param tenantDomain tenant domain * @return signed JWT token * @throws IdentityOAuth2Exception */ //TODO: Can make this private after removing deprecated "signJWTWithRSA" methods in DefaultIDTokenBuilder public static JWT signJWTWithRSA(JWTClaimsSet jwtClaimsSet, JWSAlgorithm signatureAlgorithm, String tenantDomain) throws IdentityOAuth2Exception { try { if (StringUtils.isBlank(tenantDomain)) { tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; if (log.isDebugEnabled()) { log.debug("Assign super tenant domain as signing domain."); } } if (log.isDebugEnabled()) { log.debug("Signing JWT using the algorithm: " + signatureAlgorithm + " & key of the tenant: " + tenantDomain); } int tenantId = IdentityTenantUtil.getTenantId(tenantDomain); Key privateKey = getPrivateKey(tenantDomain, tenantId); JWSSigner signer = OAuth2Util.createJWSSigner((RSAPrivateKey) privateKey); JWSHeader.Builder headerBuilder = new JWSHeader.Builder((JWSAlgorithm) signatureAlgorithm); headerBuilder.keyID(getKID(getCertificate(tenantDomain, tenantId), signatureAlgorithm, tenantDomain)); headerBuilder.x509CertThumbprint(new Base64URL(getThumbPrint(tenantDomain, tenantId))); SignedJWT signedJWT = new SignedJWT(headerBuilder.build(), jwtClaimsSet); signedJWT.sign(signer); return signedJWT; } catch (JOSEException e) { throw new IdentityOAuth2Exception("Error occurred while signing JWT", e); } } public static Key getPrivateKey(String tenantDomain, int tenantId) throws IdentityOAuth2Exception { Key privateKey; if (!(privateKeys.containsKey(tenantId))) { try { IdentityTenantUtil.initializeRegistry(tenantId, tenantDomain); } catch (IdentityException e) { throw new IdentityOAuth2Exception("Error occurred while loading registry for tenant " + tenantDomain, e); } // get tenant's key store manager KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId); if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { // derive key store name String ksName = tenantDomain.trim().replace(".", "-"); String jksName = ksName + ".jks"; // obtain private key privateKey = tenantKSM.getPrivateKey(jksName, tenantDomain); } else { try { privateKey = tenantKSM.getDefaultPrivateKey(); } catch (Exception e) { throw new IdentityOAuth2Exception("Error while obtaining private key for super tenant", e); } } //privateKey will not be null always privateKeys.put(tenantId, privateKey); } else { //privateKey will not be null because containsKey() true says given key is exist and ConcurrentHashMap // does not allow to store null values privateKey = privateKeys.get(tenantId); } return privateKey; } /** * Helper method to add algo into to JWT_HEADER to signature verification. * * @param certThumbprint * @param signatureAlgorithm * @return * */ public static String getKID(String certThumbprint, JWSAlgorithm signatureAlgorithm) { return certThumbprint + "_" + signatureAlgorithm.toString(); } /** * Method to obtain 'kid' value for the signing key to be included the JWT header. * * @param certificate Signing Certificate. * @param signatureAlgorithm relevant signature algorithm. * @return KID value as a String. */ public static String getKID(Certificate certificate, JWSAlgorithm signatureAlgorithm, String tenantDomain) throws IdentityOAuth2Exception { return OAuth2ServiceComponentHolder.getKeyIDProvider().getKeyId(certificate, signatureAlgorithm, tenantDomain); } /** * Helper method to add public certificate to JWT_HEADER to signature verification. * * @param tenantDomain * @param tenantId * @throws IdentityOAuth2Exception */ public static String getThumbPrint(String tenantDomain, int tenantId) throws IdentityOAuth2Exception { try { Certificate certificate = getCertificate(tenantDomain, tenantId); // TODO: maintain a hashmap with tenants' pubkey thumbprints after first initialization return getThumbPrint(certificate); } catch (Exception e) { String error = "Error in obtaining certificate for tenant " + tenantDomain; throw new IdentityOAuth2Exception(error, e); } } /** * Helper method to add public certificate to JWT_HEADER to signature verification. * This creates thumbPrints directly from given certificates * * @param certificate * @param alias * @return * @throws IdentityOAuth2Exception */ public static String getThumbPrint(Certificate certificate, String alias) throws IdentityOAuth2Exception { return getThumbPrint(certificate); } /** * Method to obtain certificate thumbprint. * * @param certificate java.security.cert type certificate. * @return Certificate thumbprint as a String. * @throws IdentityOAuth2Exception When failed to obtain the thumbprint. */ public static String getThumbPrint(Certificate certificate) throws IdentityOAuth2Exception { try { MessageDigest digestValue = MessageDigest.getInstance("SHA-256"); byte[] der = certificate.getEncoded(); digestValue.update(der); byte[] digestInBytes = digestValue.digest(); String publicCertThumbprint = hexify(digestInBytes); String thumbprint = new String(new Base64(0, null, true). encode(publicCertThumbprint.getBytes(Charsets.UTF_8)), Charsets.UTF_8); if (log.isDebugEnabled()) { log.debug(String.format("Thumbprint value: %s calculated for Certificate: %s using algorithm: %s", thumbprint, certificate, digestValue.getAlgorithm())); } return thumbprint; } catch (CertificateEncodingException e) { String error = "Error occurred while encoding thumbPrint from certificate."; throw new IdentityOAuth2Exception(error, e); } catch (NoSuchAlgorithmException e) { String error = "Error in obtaining SHA-256 thumbprint from certificate."; throw new IdentityOAuth2Exception(error, e); } } private static boolean isRSAAlgorithm(JWEAlgorithm algorithm) { return (JWEAlgorithm.RSA_OAEP.equals(algorithm) || JWEAlgorithm.RSA1_5.equals(algorithm) || JWEAlgorithm.RSA_OAEP_256.equals(algorithm)); } /** * Method to obatin Default Signing certificate for the tenant. * * @param tenantDomain Tenant Domain as a String. * @param tenantId Tenan ID as an integer. * @return Default Signing Certificate of the tenant domain. * @throws IdentityOAuth2Exception When failed to obtain the certificate for the requested tenant. */ public static Certificate getCertificate(String tenantDomain, int tenantId) throws IdentityOAuth2Exception { Certificate publicCert = null; if (!(publicCerts.containsKey(tenantId))) { if (log.isDebugEnabled()) { log.debug(String.format("Obtaining certificate for the tenant %s", tenantDomain)); } try { IdentityTenantUtil.initializeRegistry(tenantId, tenantDomain); } catch (IdentityException e) { throw new IdentityOAuth2Exception("Error occurred while loading registry for tenant " + tenantDomain, e); } // get tenant's key store manager KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId); KeyStore keyStore = null; if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { // derive key store name String ksName = tenantDomain.trim().replace(".", "-"); String jksName = ksName + ".jks"; if (log.isDebugEnabled()) { log.debug(String.format("Loading default tenant certificate for tenant : %s from the KeyStore" + " %s", tenantDomain, ksName)); } try { keyStore = tenantKSM.getKeyStore(jksName); publicCert = keyStore.getCertificate(tenantDomain); } catch (KeyStoreException e) { throw new IdentityOAuth2Exception("Error occurred while loading public certificate for tenant: " + tenantDomain, e); } catch (Exception e) { throw new IdentityOAuth2Exception("Error occurred while loading Keystore for tenant: " + tenantDomain, e); } } else { try { publicCert = tenantKSM.getDefaultPrimaryCertificate(); } catch (Exception e) { throw new IdentityOAuth2Exception("Error occurred while loading default public " + "certificate for tenant: " + tenantDomain, e); } } if (publicCert != null) { publicCerts.put(tenantId, publicCert); } } else { publicCert = publicCerts.get(tenantId); } return publicCert; } /** * Helper method to hexify a byte array. * TODO:need to verify the logic * * @param bytes * @return hexadecimal representation */ private static String hexify(byte bytes[]) { char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', +'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; StringBuilder buf = new StringBuilder(bytes.length * 2); for (int i = 0; i < bytes.length; ++i) { buf.append(hexDigits[(bytes[i] & 0xf0) >> 4]); buf.append(hexDigits[bytes[i] & 0x0f]); } return buf.toString(); } /** * Returns essential claims according to claim type: id_token/userinfo . * * @param essentialClaims * @param claimType * @return essential claims list */ public static List<String> getEssentialClaims(String essentialClaims, String claimType) { JSONObject jsonObjectClaims = new JSONObject(essentialClaims); List<String> essentialClaimsList = new ArrayList<>(); if (jsonObjectClaims.toString().contains(claimType)) { JSONObject newJSON = jsonObjectClaims.getJSONObject(claimType); if (newJSON != null) { Iterator<?> keys = newJSON.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (!newJSON.isNull(key)) { String value = newJSON.get(key).toString(); JSONObject jsonObjectValues = new JSONObject(value); Iterator<?> claimKeyValues = jsonObjectValues.keys(); while (claimKeyValues.hasNext()) { String claimKey = (String) claimKeyValues.next(); String claimValue = jsonObjectValues.get(claimKey).toString(); if (Boolean.parseBoolean(claimValue) && claimKey.equals(OAuthConstants.OAuth20Params.ESSENTIAL)) { essentialClaimsList.add(key); } } } } } } return essentialClaimsList; } /** * Returns the domain name convert to upper case if the domain is not not empty, else return primary domain name. * * @param userStoreDomain * @return */ public static String getSanitizedUserStoreDomain(String userStoreDomain) { if (StringUtils.isNotBlank(userStoreDomain)) { userStoreDomain = userStoreDomain.toUpperCase(); } else { userStoreDomain = IdentityUtil.getPrimaryDomainName(); } return userStoreDomain; } /** * Returns the mapped user store domain representation federated users according to the MapFederatedUsersToLocal * configuration in the identity.xml file. * * @param authenticatedUser * @return * @throws IdentityOAuth2Exception */ public static String getUserStoreForFederatedUser(AuthenticatedUser authenticatedUser) throws IdentityOAuth2Exception { if (authenticatedUser == null) { throw new IllegalArgumentException("Authenticated user cannot be null"); } String userStoreDomain = OAuth2Util.getUserStoreDomainFromUserId(authenticatedUser.toString()); if (!OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal() && authenticatedUser. isFederatedUser()) { if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) { // When the IDP_ID column is available it was decided to set the // domain name for federated users to 'FEDERATED'. // This is a system reserved word and users stores cannot be created with this name. userStoreDomain = FrameworkConstants.FEDERATED_IDP_NAME; } else { userStoreDomain = OAuth2Util.getFederatedUserDomain(authenticatedUser.getFederatedIdPName()); } } return userStoreDomain; } /** * Returns Base64 encoded token which have username appended. * * @param authenticatedUser * @param token * @return */ public static String addUsernameToToken(AuthenticatedUser authenticatedUser, String token) { if (authenticatedUser == null) { throw new IllegalArgumentException("Authenticated user cannot be null"); } if (StringUtils.isBlank(token)) { throw new IllegalArgumentException("Token cannot be blank"); } String usernameForToken = authenticatedUser.toString(); if (!OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal() && authenticatedUser.isFederatedUser()) { usernameForToken = OAuth2Util.getFederatedUserDomain(authenticatedUser.getFederatedIdPName()); usernameForToken = usernameForToken + UserCoreConstants.DOMAIN_SEPARATOR + authenticatedUser. getAuthenticatedSubjectIdentifier(); } //use ':' for token & userStoreDomain separation String tokenStrToEncode = token + ":" + usernameForToken; return Base64Utils.encode(tokenStrToEncode.getBytes(Charsets.UTF_8)); } /** * Validates the json provided. * * @param redirectURL redirect url * @return true if a valid json */ public static boolean isValidJson(String redirectURL) { try { new JSONObject(redirectURL); } catch (JSONException ex) { return false; } return true; } /** * This method returns essential:true claims list from the request parameter of OIDC authorization request * * @param claimRequestor claimrequestor is either id_token or userinfo * @param requestedClaimsFromRequestParam claims defined in the value of the request parameter * @return the claim list which have attribute vale essentail :true */ public static List<String> essentialClaimsFromRequestParam(String claimRequestor, Map<String, List<RequestedClaim>> requestedClaimsFromRequestParam) { List<String> essentialClaimsfromRequestParam = new ArrayList<>(); List<RequestedClaim> claimsforClaimRequestor = requestedClaimsFromRequestParam.get(claimRequestor); if (CollectionUtils.isNotEmpty(claimsforClaimRequestor)) { for (RequestedClaim claimforClaimRequestor : claimsforClaimRequestor) { String claim = claimforClaimRequestor.getName(); if (claimforClaimRequestor.isEssential()) { essentialClaimsfromRequestParam.add(claim); } } } return essentialClaimsfromRequestParam; } /* Get authorized user from the {@link AccessTokenDO}. When getting authorized user we also make sure flag to * determine whether the user is federated or not is set. * * @param accessTokenDO accessTokenDO * @return user */ public static AuthenticatedUser getAuthenticatedUser(AccessTokenDO accessTokenDO) { AuthenticatedUser authenticatedUser = null; if (accessTokenDO != null) { authenticatedUser = accessTokenDO.getAuthzUser(); } if (authenticatedUser != null) { authenticatedUser.setFederatedUser(isFederatedUser(authenticatedUser)); } return authenticatedUser; } /** * Determine whether the user represented by {@link AuthenticatedUser} object is a federated user. * * @param authenticatedUser * @return true if user is federated, false otherwise. */ public static boolean isFederatedUser(AuthenticatedUser authenticatedUser) { String userStoreDomain = authenticatedUser.getUserStoreDomain(); // We consider a user federated if the flag for federated user is set or the user store domain contain the // federated user store domain prefix. boolean isExplicitlyFederatedUser = StringUtils.startsWith(userStoreDomain, OAuthConstants.UserType.FEDERATED_USER_DOMAIN_PREFIX) || authenticatedUser.isFederatedUser(); // Flag to make sure federated user is not mapped to local users. boolean isFederatedUserNotMappedToLocalUser = !OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal(); return isExplicitlyFederatedUser && isFederatedUserNotMappedToLocalUser; } /** * Returns the service provider associated with the OAuth clientId. * * @param clientId OAuth2/OIDC Client Identifier * @param tenantDomain * @return * @throws IdentityOAuth2Exception */ public static ServiceProvider getServiceProvider(String clientId, String tenantDomain) throws IdentityOAuth2Exception { ApplicationManagementService applicationMgtService = OAuth2ServiceComponentHolder.getApplicationMgtService(); try { // Get the Service Provider. return applicationMgtService.getServiceProviderByClientId( clientId, IdentityApplicationConstants.OAuth2.NAME, tenantDomain); } catch (IdentityApplicationManagementException e) { throw new IdentityOAuth2Exception("Error while obtaining the service provider for client_id: " + clientId + " of tenantDomain: " + tenantDomain, e); } } /** * Returns the service provider associated with the OAuth clientId. * * @param clientId OAuth2/OIDC Client Identifier * @return * @throws IdentityOAuth2Exception */ public static ServiceProvider getServiceProvider(String clientId) throws IdentityOAuth2Exception { ApplicationManagementService applicationMgtService = OAuth2ServiceComponentHolder.getApplicationMgtService(); String tenantDomain = null; try { tenantDomain = getTenantDomainOfOauthApp(clientId); // Get the Service Provider. return applicationMgtService.getServiceProviderByClientId( clientId, IdentityApplicationConstants.OAuth2.NAME, tenantDomain); } catch (IdentityApplicationManagementException e) { throw new IdentityOAuth2Exception("Error while obtaining the service provider for client_id: " + clientId + " of tenantDomain: " + tenantDomain, e); } catch (InvalidOAuthClientException e) { throw new IdentityOAuth2ClientException("Could not find an existing app for clientId: " + clientId, e); } } /** * Returns the public certificate of the service provider associated with the OAuth consumer app as * an X509 @{@link Certificate} object. * * @param clientId OAuth2/OIDC Client Identifier * @param tenantDomain * @return * @throws IdentityOAuth2Exception */ public static Certificate getX509CertOfOAuthApp(String clientId, String tenantDomain) throws IdentityOAuth2Exception { try { ServiceProvider serviceProvider = OAuth2Util.getServiceProvider(clientId, tenantDomain); // Get the certificate content. String certificateContent = serviceProvider.getCertificateContent(); if (StringUtils.isNotBlank(certificateContent)) { // Build the Certificate object from cert content. return IdentityUtil.convertPEMEncodedContentToCertificate(certificateContent); } else { throw new IdentityOAuth2Exception("Public certificate not configured for Service Provider with " + "client_id: " + clientId + " of tenantDomain: " + tenantDomain); } } catch (CertificateException e) { throw new IdentityOAuth2Exception("Error while building X509 cert of oauth app with client_id: " + clientId + " of tenantDomain: " + tenantDomain, e); } } /** * Return true if the token identifier is a parsable JWT. * * @param tokenIdentifier String JWT token identifier. * @return true for a JWT token. */ public static boolean isParsableJWT(String tokenIdentifier) { if (StringUtils.isBlank(tokenIdentifier)) { return false; } try { JWTParser.parse(tokenIdentifier); return true; } catch (ParseException e) { if (log.isDebugEnabled()) { log.debug("Provided token identifier is not a parsable JWT.", e); } return false; } } /** * Return true if the token identifier is JWT. * * @param tokenIdentifier String JWT token identifier. * @return true for a JWT token. */ public static boolean isJWT(String tokenIdentifier) { // JWT token contains 3 base64 encoded components separated by periods. return StringUtils.countMatches(tokenIdentifier, DOT_SEPARATER) == 2; } /** * Return true if the JWT id token is encrypted. * * @param idToken String JWT ID token. * @return Boolean state of encryption. */ public static boolean isIDTokenEncrypted(String idToken) { // Encrypted ID token contains 5 base64 encoded components separated by periods. return StringUtils.countMatches(idToken, DOT_SEPARATER) == 4; } /** * @deprecated We cannot determine the token issuer this way. Have a look at the * {@link #findAccessToken(String, boolean)} method. */ @Deprecated public static OauthTokenIssuer getTokenIssuer(String accessToken) throws IdentityOAuth2Exception { OauthTokenIssuer oauthTokenIssuer = null; String consumerKey = null; if (isJWT(accessToken) || isIDTokenEncrypted(accessToken)) { oauthTokenIssuer = new JWTTokenIssuer(); } else { try { consumerKey = OAuth2Util.getClientIdForAccessToken(accessToken); if (consumerKey != null) { oauthTokenIssuer = OAuth2Util.getOAuthTokenIssuerForOAuthApp(consumerKey); } } catch (IllegalArgumentException e) { if (log.isDebugEnabled()) { log.debug("Consumer key is not found for token identifier: " + accessToken, e); } } catch (InvalidOAuthClientException e) { throw new IdentityOAuth2Exception( "Error while retrieving oauth issuer for the app with clientId: " + consumerKey, e); } } return oauthTokenIssuer; } /** * Publish event on token generation error. * * @param exception Exception occurred. * @param params Additional parameters. */ public static void triggerOnTokenExceptionListeners(Throwable exception, Map<String, Object> params) { try { OAuthEventInterceptor oAuthEventInterceptorProxy = OAuthComponentServiceHolder.getInstance().getOAuthEventInterceptorProxy(); if (oAuthEventInterceptorProxy != null) { try { oAuthEventInterceptorProxy.onTokenIssueException(exception, params); } catch (IdentityOAuth2Exception e) { log.error("Error while invoking OAuthEventInterceptor for onTokenIssueException", e); } } } catch (Throwable e) { // Catching a throwable as we do no need to interrupt the code flow since these are logging purposes. if (log.isDebugEnabled()) { log.debug("Error occurred while executing oAuthEventInterceptorProxy for onTokenIssueException.", e); } } } /** * Extract information related to the token introspection and publish the event on introspection error. * * @param */ public static void triggerOnIntrospectionExceptionListeners(OAuth2TokenValidationRequestDTO introspectionRequest, OAuth2IntrospectionResponseDTO introspectionResponse) { Map<String, Object> params = new HashMap<>(); params.put("error", introspectionResponse.getError()); try { OAuthEventInterceptor oAuthEventInterceptorProxy = OAuthComponentServiceHolder.getInstance() .getOAuthEventInterceptorProxy(); if (oAuthEventInterceptorProxy != null) { try { oAuthEventInterceptorProxy.onTokenValidationException(introspectionRequest, params); } catch (IdentityOAuth2Exception e) { log.error("Error while invoking OAuthEventInterceptor for onTokenValidationException", e); } } } catch (Throwable e) { // Catching a throwable as we do no need to interrupt the code flow since these are logging purposes. if (log.isDebugEnabled()) { log.debug("Error occurred while executing oAuthEventInterceptorProxy for onTokenValidationException.", e); } } } /** * Get the supported oauth grant types * * @return list of grant types */ public static List<String> getSupportedGrantTypes() { Map<String, AuthorizationGrantHandler> supportedGrantTypesMap = OAuthServerConfiguration.getInstance() .getSupportedGrantTypes(); List<String> supportedGrantTypes = new ArrayList<>(); if (supportedGrantTypesMap != null && !supportedGrantTypesMap.isEmpty()) { supportedGrantTypes = supportedGrantTypesMap.keySet().stream().collect(Collectors.toList()); } return supportedGrantTypes; } /** * Get the supported client authentication methods * * @return list of client authentication methods */ public static List<String> getSupportedClientAuthenticationMethods() { List<String> clientAuthenticationMethods = new ArrayList<>(); clientAuthenticationMethods.add(CLIENT_SECRET_BASIC); clientAuthenticationMethods.add(CLIENT_SECRET_POST); return clientAuthenticationMethods; } /** * Get the supported code challenge methods. * * @return list of code challenge methods. */ public static List<String> getSupportedCodeChallengeMethods() { List<String> codeChallengeMethods = new ArrayList<>(); codeChallengeMethods.add(OAuthConstants.OAUTH_PKCE_S256_CHALLENGE); codeChallengeMethods.add(OAuthConstants.OAUTH_PKCE_PLAIN_CHALLENGE); return codeChallengeMethods; } /** * Get the supported response modes. * * @return list of response modes supported. */ public static List<String> getSupportedResponseModes() { List<String> responseModes = new ArrayList<>(); responseModes.add(QUERY_RESPONSE_MODE); responseModes.add(FRAGMENT_RESPONSE_MODE); responseModes.add(FORM_POST_RESPONSE_MODE); return responseModes; } /** * Get the supported request object signing algorithms * * @return list of algorithms */ public static List<String> getRequestObjectSigningAlgValuesSupported() { List<String> requestObjectSigningAlgValues = new ArrayList<>(); requestObjectSigningAlgValues.add(JWSAlgorithm.RS256.getName()); requestObjectSigningAlgValues.add(JWSAlgorithm.RS384.getName()); requestObjectSigningAlgValues.add(JWSAlgorithm.RS512.getName()); requestObjectSigningAlgValues.add(JWSAlgorithm.PS256.getName()); requestObjectSigningAlgValues.add(JWSAlgorithm.NONE.getName()); return requestObjectSigningAlgValues; } /** * Check whether the request object parameter is supported * * @return true if supported */ public static boolean isRequestParameterSupported() { return Boolean.TRUE; } /** * Check whether the claims parameter is supported * * @return true if supported */ public static boolean isClaimsParameterSupported() { return Boolean.TRUE; } /** * Returns the federated IdP resolved from the given domain. * For a federated user the user store domain is in the format of FEDERATED:{federated-idp-name} * * @param userStoreDomain user store domain to be resolved from * @return federated IdP name if user store domain is of format FEDERATED:{federated-idp-name}. Else returns null. */ public static String getFederatedIdPFromDomain(String userStoreDomain) { if (StringUtils.startsWith(userStoreDomain, OAuthConstants.UserType.FEDERATED_USER_DOMAIN_PREFIX)) { String[] tokens = userStoreDomain.split(OAuthConstants.UserType.FEDERATED_USER_DOMAIN_SEPARATOR); if (tokens.length == 2) { return tokens[1]; } } return null; } /** * Creates an instance on AuthenticatedUser{@link AuthenticatedUser} for the given parameters. * If given user store domain is of format FEDERATED:{federated-idp-name}, the authenticated user instance will * be flagged as a federated user. * * @param username username of the user * @param userStoreDomain user store domain * @param tenantDomain tenent domain * @return an instance of AuthenticatedUser{@link AuthenticatedUser} * @deprecated use {@link #createAuthenticatedUser(String, String, String, String)} instead. */ @Deprecated public static AuthenticatedUser createAuthenticatedUser(String username, String userStoreDomain, String tenantDomain) { AuthenticatedUser authenticatedUser = new AuthenticatedUser(); authenticatedUser.setUserName(username); authenticatedUser.setTenantDomain(tenantDomain); if (StringUtils.startsWith(userStoreDomain, OAuthConstants.UserType.FEDERATED_USER_DOMAIN_PREFIX) && !OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal()) { if (log.isDebugEnabled()) { log.debug("Federated prefix found in domain: " + userStoreDomain + " for user: " + username + " in tenant domain: " + tenantDomain + ". Flag user as a federated user."); } authenticatedUser.setFederatedUser(true); authenticatedUser.setFederatedIdPName(OAuth2Util.getFederatedIdPFromDomain(userStoreDomain)); } else { authenticatedUser.setUserStoreDomain(userStoreDomain); } return authenticatedUser; } /** * Creates an instance of AuthenticatedUser{@link AuthenticatedUser} for the given parameters. * * @param username username of the user * @param userStoreDomain user store domain * @param tenantDomain tenent domain * @param idpName idp name * @return an instance of AuthenticatedUser{@link AuthenticatedUser} */ public static AuthenticatedUser createAuthenticatedUser(String username, String userStoreDomain, String tenantDomain, String idpName) { AuthenticatedUser authenticatedUser = new AuthenticatedUser(); authenticatedUser.setUserName(username); authenticatedUser.setTenantDomain(tenantDomain); /* When the IDP_ID column is available it was decided to set the domain name for federated users to 'FEDERATED'. This is a system reserved word and user stores cannot be created with this name. For jwt bearer grant and saml bearer grant types, assertion issuing idp is set as the authenticated idp, but this may not always be the idp user is in; i.e, for an assertion issued by IS, idp name will be 'LOCAL', yet the user could have been authenticated with some external idp. Therefore, we cannot stop setting 'FEDERATED' as the user store domain for federated users.*/ if (StringUtils.startsWith(userStoreDomain, OAuthConstants.UserType.FEDERATED_USER_DOMAIN_PREFIX) && !OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal()) { authenticatedUser.setFederatedUser(true); if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) { authenticatedUser.setFederatedIdPName(idpName); } else { authenticatedUser.setFederatedIdPName(OAuth2Util.getFederatedIdPFromDomain(userStoreDomain)); } authenticatedUser.setUserId(getUserIdOfFederatedUser(username, tenantDomain, idpName)); if (log.isDebugEnabled()) { log.debug("Federated prefix found in domain: " + userStoreDomain + " for user: " + username + " in tenant domain: " + tenantDomain + ". Flag user as a federated user. " + authenticatedUser.getFederatedIdPName() + " is set as the authenticated idp."); } } else { authenticatedUser.setUserStoreDomain(userStoreDomain); authenticatedUser.setFederatedIdPName(idpName); } return authenticatedUser; } /** * Get the user if of the federated user from the user session store. * * @param username Username. * @param tenantDomain Tenant domain. * @param idpName IDP name. * @return User id associated with the given federated user. */ private static String getUserIdOfFederatedUser(String username, String tenantDomain, String idpName) { String userId = null; int tenantId = IdentityTenantUtil.getTenantId(tenantDomain); try { int idpId = UserSessionStore.getInstance().getIdPId(idpName, tenantId); userId = UserSessionStore.getInstance().getFederatedUserId(username, tenantId, idpId); } catch (UserSessionException e) { // In here we better not log the user id. log.error("Error occurred while resolving the user id from the username for the federated user", e); } return userId; } public static String getIdTokenIssuer(String tenantDomain) throws IdentityOAuth2Exception { if (IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) { try { return ServiceURLBuilder.create().addPath(OAUTH2_TOKEN_EP_URL).build().getAbsolutePublicURL(); } catch (URLBuilderException e) { String errorMsg = String.format("Error while building the absolute url of the context: '%s', for the" + " tenant domain: '%s'", OAUTH2_TOKEN_EP_URL, tenantDomain); throw new IdentityOAuth2Exception(errorMsg, e); } } else { return getIssuerLocation(tenantDomain); } } /** * Used to get the issuer url for a given tenant. * * @param tenantDomain Tenant domain. * @return Token issuer url. * @throws IdentityOAuth2Exception IdentityOAuth2Exception. */ public static String getIssuerLocation(String tenantDomain) throws IdentityOAuth2Exception { /* * IMPORTANT: * This method should only honor the given tenant. * Do not add any auto tenant resolving logic. */ if (IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) { try { startTenantFlow(tenantDomain); return ServiceURLBuilder.create().addPath(OAUTH2_TOKEN_EP_URL).build().getAbsolutePublicURL(); } catch (URLBuilderException e) { String errorMsg = String.format("Error while building the absolute url of the context: '%s', for the" + " tenant domain: '%s'", OAUTH2_TOKEN_EP_URL, tenantDomain); throw new IdentityOAuth2Exception(errorMsg, e); } finally { endTenantFlow(); } } else { return getResidentIdpEntityId(tenantDomain); } } /** * Retrieve entity id of the resident identity provider. * * @param tenantDomain tenant domain. * @return idp entity id. * @throws IdentityOAuth2Exception when failed to retrieve the idp entity id. */ public static String getResidentIdpEntityId(String tenantDomain) throws IdentityOAuth2Exception { IdentityProvider identityProvider = getResidentIdp(tenantDomain); FederatedAuthenticatorConfig[] fedAuthnConfigs = identityProvider.getFederatedAuthenticatorConfigs(); // Get OIDC authenticator FederatedAuthenticatorConfig oidcAuthenticatorConfig = IdentityApplicationManagementUtil.getFederatedAuthenticator(fedAuthnConfigs, IdentityApplicationConstants.Authenticator.OIDC.NAME); return IdentityApplicationManagementUtil.getProperty(oidcAuthenticatorConfig.getProperties(), IDP_ENTITY_ID).getValue(); } private static IdentityProvider getResidentIdp(String tenantDomain) throws IdentityOAuth2Exception { try { return IdentityProviderManager.getInstance().getResidentIdP(tenantDomain); } catch (IdentityProviderManagementException e) { String errorMsg = String.format("Error while getting Resident Identity Provider of '%s' tenant.", tenantDomain); throw new IdentityOAuth2Exception(errorMsg, e); } } /** * Used to build an OAuth revocation request DTO. * * @param oAuthClientAuthnContext OAuth client authentication context. * @param accessToken Access token to be revoked. * @return Returns a OAuth revocation request DTO. */ public static OAuthRevocationRequestDTO buildOAuthRevocationRequest(OAuthClientAuthnContext oAuthClientAuthnContext, String accessToken) { OAuthRevocationRequestDTO revocationRequestDTO = new OAuthRevocationRequestDTO(); revocationRequestDTO.setToken(accessToken); revocationRequestDTO.setOauthClientAuthnContext(oAuthClientAuthnContext); revocationRequestDTO.setConsumerKey(oAuthClientAuthnContext.getClientId()); return revocationRequestDTO; } /** * Find access tokenDO from token identifier by chaining through all available token issuers. * * @param tokenIdentifier access token data object from the validation request. * @return AccessTokenDO * @throws IdentityOAuth2Exception */ public static AccessTokenDO findAccessToken(String tokenIdentifier, boolean includeExpired) throws IdentityOAuth2Exception { AccessTokenDO accessTokenDO; // Get a copy of the list of token issuers . Map<String, OauthTokenIssuer> allOAuthTokenIssuerMap = new HashMap<>( OAuthServerConfiguration.getInstance().getOauthTokenIssuerMap()); // Differentiate default token issuers and other issuers for better performance. Map<String, OauthTokenIssuer> defaultOAuthTokenIssuerMap = new HashMap<>(); extractDefaultOauthTokenIssuers(allOAuthTokenIssuerMap, defaultOAuthTokenIssuerMap); // First try default token issuers. accessTokenDO = getAccessTokenDOFromMatchingTokenIssuer(tokenIdentifier, defaultOAuthTokenIssuerMap, includeExpired); if (accessTokenDO != null) { return accessTokenDO; } // Loop through other issuer and try to get the hash. accessTokenDO = getAccessTokenDOFromMatchingTokenIssuer(tokenIdentifier, allOAuthTokenIssuerMap, includeExpired); // If the lookup is only for tokens in 'ACTIVE' state, APIs calling this method expect an // IllegalArgumentException to be thrown to identify inactive/invalid tokens. if (accessTokenDO == null && !includeExpired) { throw new IllegalArgumentException("Invalid Access Token. ACTIVE access token is not found."); } return accessTokenDO; } /** * Loop through provided token issuer list and tries to get the access token DO. * * @param tokenIdentifier Provided token identifier. * @param tokenIssuerMap List of token issuers. * @return Obtained matching access token DO if possible. * @throws IdentityOAuth2Exception */ private static AccessTokenDO getAccessTokenDOFromMatchingTokenIssuer(String tokenIdentifier, Map<String, OauthTokenIssuer> tokenIssuerMap, boolean includeExpired) throws IdentityOAuth2Exception { AccessTokenDO accessTokenDO; if (tokenIssuerMap != null) { for (Map.Entry<String, OauthTokenIssuer> oauthTokenIssuerEntry: tokenIssuerMap.entrySet()) { try { OauthTokenIssuer oauthTokenIssuer = oauthTokenIssuerEntry.getValue(); String tokenAlias = oauthTokenIssuer.getAccessTokenHash(tokenIdentifier); if (oauthTokenIssuer.usePersistedAccessTokenAlias()) { accessTokenDO = OAuth2Util.getAccessTokenDOFromTokenIdentifier(tokenAlias, includeExpired); } else { accessTokenDO = OAuth2Util.getAccessTokenDOFromTokenIdentifier(tokenIdentifier, includeExpired); } if (accessTokenDO != null) { return accessTokenDO; } } catch (OAuthSystemException e) { if (log.isDebugEnabled()) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Token issuer: " + oauthTokenIssuerEntry.getKey() + " was tried and" + " failed to parse the received token: " + tokenIdentifier); } else { log.debug("Token issuer: " + oauthTokenIssuerEntry.getKey() + " was tried and" + " failed to parse the received token."); } } } catch (IllegalArgumentException e) { if (log.isDebugEnabled()) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Token issuer: " + oauthTokenIssuerEntry.getKey() + " was tried and" + " failed to get the token from database: " + tokenIdentifier); } else { log.debug("Token issuer: " + oauthTokenIssuerEntry.getKey() + " was tried and" + " failed to get the token from database."); } } } } } return null; } /** * Differentiate default token issuers from all available token issuers map. * * @param allOAuthTokenIssuerMap Map of all available token issuers. * @param defaultOAuthTokenIssuerMap default token issuers */ private static void extractDefaultOauthTokenIssuers(Map<String, OauthTokenIssuer> allOAuthTokenIssuerMap, Map<String, OauthTokenIssuer> defaultOAuthTokenIssuerMap) { // TODO: 4/9/19 Implement logic to read default issuer from config. // TODO: 4/9/19 add sorting mechanism to use JWT issuer first. defaultOAuthTokenIssuerMap.put(OAuthServerConfiguration.JWT_TOKEN_TYPE, allOAuthTokenIssuerMap.get(OAuthServerConfiguration.JWT_TOKEN_TYPE)); allOAuthTokenIssuerMap.remove(OAuthServerConfiguration.JWT_TOKEN_TYPE); defaultOAuthTokenIssuerMap.put(OAuthServerConfiguration.DEFAULT_TOKEN_TYPE, allOAuthTokenIssuerMap.get(OAuthServerConfiguration.DEFAULT_TOKEN_TYPE)); allOAuthTokenIssuerMap.remove(OAuthServerConfiguration.DEFAULT_TOKEN_TYPE); } /** * Return access token identifier from OAuth2TokenValidationResponseDTO. This method validated the token against * the cache and the DB. * * @param tokenResponse OAuth2TokenValidationResponseDTO object. * @return extracted access token identifier. * @throws UserInfoEndpointException */ public static String getAccessTokenIdentifier(OAuth2TokenValidationResponseDTO tokenResponse) throws UserInfoEndpointException { if (tokenResponse.getAuthorizationContextToken().getTokenString() != null) { AccessTokenDO accessTokenDO = null; try { accessTokenDO = OAuth2Util.findAccessToken( tokenResponse.getAuthorizationContextToken().getTokenString(), false); } catch (IdentityOAuth2Exception e) { throw new UserInfoEndpointException("Error occurred while obtaining access token.", e); } if (accessTokenDO != null) { return accessTokenDO.getAccessToken(); } } return null; } /** * There are cases where we store an 'alias' of the token returned to the client as the token inside IS. * For example, in the case of JWT access tokens we store the 'jti' claim in the database instead of the * actual JWT. Therefore we need to cache an AccessTokenDO with the stored token identifier. * * @param newTokenBean token DO to be added to the cache. */ public static void addTokenDOtoCache(AccessTokenDO newTokenBean) throws IdentityOAuth2Exception { OauthTokenIssuer tokenIssuer = null; try { tokenIssuer = OAuth2Util.getOAuthTokenIssuerForOAuthApp(newTokenBean.getConsumerKey()); String tokenAlias = tokenIssuer.getAccessTokenHash(newTokenBean.getAccessToken()); OAuthCacheKey accessTokenCacheKey = new OAuthCacheKey(tokenAlias); AccessTokenDO tokenDO = AccessTokenDO.clone(newTokenBean); tokenDO.setAccessToken(tokenAlias); OAuthCache.getInstance().addToCache(accessTokenCacheKey, tokenDO); if (log.isDebugEnabled()) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Access token DO was added to OAuthCache with cache key: " + accessTokenCacheKey.getCacheKeyString()); } else { log.debug("Access token DO was added to OAuthCache"); } } } catch (OAuthSystemException e) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { throw new IdentityOAuth2Exception("Error while getting the token alias from token issuer: " + tokenIssuer.toString() + " for the token: " + newTokenBean.getAccessToken(), e); } else { throw new IdentityOAuth2Exception("Error while getting the token alias from token issuer: " + tokenIssuer.toString(), e); } } catch (InvalidOAuthClientException e) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { throw new IdentityOAuth2Exception("Error while getting the token issuer for the token: " + newTokenBean.getAccessToken(), e); } else { throw new IdentityOAuth2Exception("Error while getting the token issuer", e); } } } /** * Used to get the authenticated IDP name from a user. * * @param user Authenticated User. * @return Returns the authenticated IDP name. */ public static String getAuthenticatedIDP(AuthenticatedUser user) { String authenticatedIDP; if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) { if (!OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal() && user.isFederatedUser()) { authenticatedIDP = user.getFederatedIdPName(); if (log.isDebugEnabled()) { log.debug("IDP_ID column is available. User is federated and not mapped to local users. " + "Authenticated IDP is set to:" + authenticatedIDP + " for user:" + user.getLoggableUserId()); } } else { authenticatedIDP = FrameworkConstants.LOCAL_IDP_NAME; if (log.isDebugEnabled()) { log.debug("IDP_ID column is available. Authenticated IDP is set to:" + authenticatedIDP + " for user:" + user.getLoggableUserId()); } } } else { authenticatedIDP = user.getFederatedIdPName(); if (log.isDebugEnabled()) { log.debug("IDP_ID column is not available. Authenticated IDP is set to:" + authenticatedIDP + " for user:" + user.getLoggableUserId()); } } return authenticatedIDP; } /** * Used to get the user store domain name from a user. * * @param user Authenticated User. * @return Returns the sanitized user store domain. */ public static String getUserStoreDomain(AuthenticatedUser user) { String userDomain; if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled() && !OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal() && user.isFederatedUser()) { if (log.isDebugEnabled()) { log.debug("IDP_ID column is available. User is federated and not mapped to local users."); } // When the IDP_ID column is available it was decided to set the // domain name for federated users to 'FEDERATED'. // This is a system reserved word and users stores cannot be created with this name. userDomain = FrameworkConstants.FEDERATED_IDP_NAME; } else if (!OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal() && user.isFederatedUser()) { if (log.isDebugEnabled()) { log.debug("IDP_ID column is not available. User is federated and not mapped to local users."); } userDomain = OAuth2Util.getFederatedUserDomain(user.getFederatedIdPName()); } else { userDomain = user.getUserStoreDomain(); if (log.isDebugEnabled()) { if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) { log.debug("IDP_ID column is available. User is not federated or mapped to local users."); } else { log.debug("IDP_ID column is not available. User is not federated or mapped to local users."); } } } String sanitizedUserDomain = OAuth2Util.getSanitizedUserStoreDomain(userDomain); if (log.isDebugEnabled()) { log.debug("User domain is set to:" + sanitizedUserDomain + " for user:" + user.getLoggableUserId()); } return sanitizedUserDomain; } /** * Check if the IDP_ID column is available in the relevant tables. * * @return True if IDP_ID column is available in all the relevant table. */ public static boolean checkIDPIdColumnAvailable() { boolean isIdpIdAvailableInAuthzCodeTable; boolean isIdpIdAvailableInTokenTable; boolean isIdpIdAvailableInTokenAuditTable; String columnIdpId = "IDP_ID"; isIdpIdAvailableInAuthzCodeTable = FrameworkUtils .isTableColumnExists("IDN_OAUTH2_AUTHORIZATION_CODE", columnIdpId); isIdpIdAvailableInTokenTable = FrameworkUtils .isTableColumnExists("IDN_OAUTH2_ACCESS_TOKEN", columnIdpId); if (OAuthServerConfiguration.getInstance().useRetainOldAccessTokens()) { isIdpIdAvailableInTokenAuditTable = FrameworkUtils .isTableColumnExists("IDN_OAUTH2_ACCESS_TOKEN_AUDIT", columnIdpId); } else { isIdpIdAvailableInTokenAuditTable = true; if (log.isDebugEnabled()) { log.debug("Retaining old access tokens in IDN_OAUTH2_ACCESS_TOKEN_AUDIT is disabled, therefore " + "ignoring the availability of IDP_ID column in IDN_OAUTH2_ACCESS_TOKEN_AUDIT table."); } } return isIdpIdAvailableInAuthzCodeTable && isIdpIdAvailableInTokenTable && isIdpIdAvailableInTokenAuditTable; } /** * Check whether the CONSENTED_TOKEN column is available in IDN_OAUTH2_ACCESS_TOKEN table. * * @return True if the column is available. */ public static boolean checkConsentedTokenColumnAvailable() { return FrameworkUtils.isTableColumnExists("IDN_OAUTH2_ACCESS_TOKEN", "CONSENTED_TOKEN"); } /** * This can be used to load the oauth scope permissions bindings in oauth-scope-bindings.xml file. */ public static void initiateOAuthScopePermissionsBindings(int tenantId) { if (Oauth2ScopeUtils.isSystemLevelInternalSystemScopeManagementEnabled()) { if (log.isDebugEnabled()) { log.debug("OAuth internal scopes permission binding initialization is skipped as the scopes " + "are managed globally."); } return; } try { //Check login scope is available. If exists, assumes all scopes are loaded using the file. if (!hasScopesAlreadyAdded(tenantId)) { List<Scope> scopes = OAuth2ServiceComponentHolder.getInstance().getOauthScopeBinding(); for (Scope scope : scopes) { OAuthTokenPersistenceFactory.getInstance().getOAuthScopeDAO().addScope(scope, tenantId); } if (log.isDebugEnabled()) { log.debug("OAuth scopes are loaded for the tenant : " + tenantId); } } else { if (log.isDebugEnabled()) { log.debug("OAuth scopes are already loaded"); } } } catch (IdentityOAuth2ScopeException e) { log.error("Error while registering OAuth scopes with permissions bindings", e); } } private static boolean hasScopesAlreadyAdded(int tenantId) throws IdentityOAuth2ScopeServerException { Scope loginScope = OAuthTokenPersistenceFactory.getInstance().getOAuthScopeDAO().getScopeByName( INTERNAL_LOGIN_SCOPE, tenantId); if (loginScope == null) { return false; } else { List<ScopeBinding> scopeBindings = loginScope.getScopeBindings(); for (ScopeBinding scopeBinding : scopeBindings) { if (PERMISSIONS_BINDING_TYPE.equalsIgnoreCase(scopeBinding.getBindingType())) { return true; } } } return false; } /** * Check whether required token binding available in the request. * * @param tokenBinding token binding. * @param request http request. * @return true if binding is valid. */ public static boolean isValidTokenBinding(TokenBinding tokenBinding, HttpServletRequest request) { if (request == null || tokenBinding == null || StringUtils.isBlank(tokenBinding.getBindingReference()) || StringUtils.isBlank(tokenBinding.getBindingType())) { return true; } Optional<TokenBinder> tokenBinderOptional = OAuth2ServiceComponentHolder.getInstance() .getTokenBinder(tokenBinding.getBindingType()); if (!tokenBinderOptional.isPresent()) { log.warn("Token binder with type: " + tokenBinding.getBindingType() + " is not available."); return false; } return tokenBinderOptional.get().isValidTokenBinding(request, tokenBinding); } /** * Get public certificate from JWKS when kid and JWKS Uri is given. * * @param jwksUri - JWKS Uri * @return - X509Certificate * @throws IdentityOAuth2Exception - IdentityOAuth2Exception * @deprecated replaced with {@link #getEncryptionJWKFromJWKS(String, JWEAlgorithm)} */ @Deprecated private static X509Certificate getPublicCertFromJWKS(String jwksUri) throws IdentityOAuth2Exception { if (log.isDebugEnabled()) { log.debug(String.format("Attempting to retrieve public certificate from the Jwks uri: %s.", jwksUri)); } try { JWKSet publicKeys = JWKSet.load(new URL(jwksUri)); JWK jwk = null; X509Certificate certificate; //Get the first signing JWK from the list List<JWK> jwkList = publicKeys.getKeys(); for (JWK currentJwk : jwkList) { if (KeyUse.SIGNATURE == currentJwk.getKeyUse()) { jwk = currentJwk; break; } } if (jwk != null) { certificate = jwk.getParsedX509CertChain().get(0); if (log.isDebugEnabled()) { log.debug(String.format("Retrieved the public signing certificate successfully from the " + "jwks uri: %s", jwksUri)); } return certificate; } else { throw new IdentityOAuth2Exception(String.format("Failed to retrieve public certificate from " + "jwks uri: %s", jwksUri)); } } catch (ParseException | IOException e) { throw new IdentityOAuth2Exception(String.format("Failed to retrieve public certificate from " + "jwks uri: %s", jwksUri), e); } } /** * Get Jwks uri of SP when clientId and spTenantDomain is provided. * * @param clientId - ClientId * @param spTenantDomain - Tenant domain * @return Jwks Url * @throws IdentityOAuth2Exception */ public static String getSPJwksUrl(String clientId, String spTenantDomain) throws IdentityOAuth2Exception { ServiceProvider serviceProvider = OAuth2Util.getServiceProvider(clientId, spTenantDomain); String jwksUri = serviceProvider.getJwksUri(); if (StringUtils.isNotBlank(jwksUri)) { if (log.isDebugEnabled()) { log.debug(String.format("Retrieved jwks uri: %s for the service provider associated with client_id: %s", jwksUri, clientId)); } } return jwksUri; } /** * Method to extract the SHA-1 JWK thumbprint from certificates. * * @param certificate x509 certificate * @return String thumbprint * @throws IdentityOAuth2Exception When failed to extract thumbprint */ public static String getJwkThumbPrint(Certificate certificate) throws IdentityOAuth2Exception { if (log.isDebugEnabled()) { log.debug(String.format("Calculating SHA-1 JWK thumb-print for certificate: %s", certificate.toString())); } try { CertificateFactory cf = CertificateFactory.getInstance(Constants.X509); ByteArrayInputStream bais = new ByteArrayInputStream(certificate.getEncoded()); X509Certificate x509 = (X509Certificate) cf.generateCertificate(bais); Base64URL jwkThumbprint = RSAKey.parse(x509).computeThumbprint(Constants.SHA1); String thumbprintString = jwkThumbprint.toString(); if (log.isDebugEnabled()) { log.debug(String.format("Calculated SHA-1 JWK thumbprint %s from the certificate", thumbprintString)); } return thumbprintString; } catch (CertificateException | JOSEException e) { throw new IdentityOAuth2Exception("Error occurred while generating SHA-1 JWK thumbprint", e); } } /** * Validates whether the tenant domain set in context matches with the app's tenant domain in tenant qualified * URL mode. * * @param tenantDomainOfApp Tenant domain of the app. * @throws InvalidOAuthClientException */ public static void validateRequestTenantDomain(String tenantDomainOfApp) throws InvalidOAuthClientException { if (IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) { // In tenant qualified URL mode we would always have the tenant domain in the context. String tenantDomainFromContext = IdentityTenantUtil.getTenantDomainFromContext(); if (!StringUtils.equals(tenantDomainFromContext, tenantDomainOfApp)) { // This means the tenant domain sent in the request and app's tenant domain do not match. if (log.isDebugEnabled()) { log.debug("A valid client with the given client_id cannot be found in " + "tenantDomain: " + tenantDomainFromContext); } throw new InvalidOAuthClientException("no.valid.client.in.tenant"); } } } /** * Validates whether the tenant domain set in context matches with the app's tenant domain in tenant qualified * URL mode. * * @param tenantDomainOfApp Tenant domain of the app. * @param tokenReqDTO Access token request DTO object that contains request parameters. * @throws InvalidOAuthClientException */ public static void validateRequestTenantDomain(String tenantDomainOfApp, OAuth2AccessTokenReqDTO tokenReqDTO) throws InvalidOAuthClientException { if (IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) { Optional<String> contextTenantDomainFromTokenReqDTO = getContextTenantDomainFromTokenReqDTO(tokenReqDTO); String tenantDomainFromContext; if (contextTenantDomainFromTokenReqDTO.isPresent()) { tenantDomainFromContext = contextTenantDomainFromTokenReqDTO.get(); // In tenant qualified URL mode we would always have the tenant domain in the context. if (!StringUtils.equals(tenantDomainFromContext, tenantDomainOfApp)) { // This means the tenant domain sent in the request and app's tenant domain do not match. throw new InvalidOAuthClientException("A valid client with the given client_id cannot be found in " + "tenantDomain: " + tenantDomainFromContext); } } else { validateRequestTenantDomain(tenantDomainOfApp); } } } private static Optional<String> getContextTenantDomainFromTokenReqDTO(OAuth2AccessTokenReqDTO tokenReqDTO) { if (tokenReqDTO == null || tokenReqDTO.getParameters() == null) { return Optional.empty(); } String tenantDomainFromContext = tokenReqDTO.getParameters().get(OAuthConstants.TENANT_DOMAIN_FROM_CONTEXT); if (StringUtils.isNotBlank(tenantDomainFromContext)) { return Optional.of(tenantDomainFromContext); } return Optional.empty(); } private static void startTenantFlow(String tenantDomain) { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(IdentityTenantUtil.getTenantId(tenantDomain)); } private static void endTenantFlow() { PrivilegedCarbonContext.endTenantFlow(); } /** * Determines if the scope is specified in the allowed scopes list. * * @param allowedScopesList Allowed scopes list * @param scope The scope key to check. * @return - 'true' if the scope is allowed. 'false' if not. */ public static boolean isAllowedScope(List<String> allowedScopesList, String scope) { for (String scopeTobeSkipped : allowedScopesList) { if (scope.matches(scopeTobeSkipped)) { if (log.isDebugEnabled()) { log.debug(scope + " is found in the allowed list of scopes."); } return true; } } return false; } /** * Util method to get Identity Provider by name and tenant domain. * * @param identityProviderName Identity provider * @param tenantDomain Tenant domain * @return Identity Provider * @throws IdentityOAuth2Exception If were unable to get Identity provider. */ public static IdentityProvider getIdentityProvider(String identityProviderName, String tenantDomain) throws IdentityOAuth2Exception { try { if (OAuth2ServiceComponentHolder.getInstance().getIdpManager() != null) { return OAuth2ServiceComponentHolder.getInstance().getIdpManager().getIdPByName(identityProviderName, tenantDomain); } else { String errorMsg = String.format("Unable to retrieve Idp manager. Error while " + "getting '%s' Identity Provider of '%s' tenant.", identityProviderName, tenantDomain); throw new IdentityOAuth2Exception(errorMsg); } } catch (IdentityProviderManagementException e) { String errorMsg = String.format("Error while getting '%s' Identity Provider of '%s' tenant.", identityProviderName, tenantDomain); throw new IdentityOAuth2Exception(errorMsg, e); } } /** * Get Internal/everyone role for corresponding user using realm configuration. * * @param user Authenticated user * @return Internal/everyone role * @throws IdentityOAuth2Exception IdentityOAuth2Exception */ public static String getInternalEveryoneRole(AuthenticatedUser user) throws IdentityOAuth2Exception { try { RealmConfiguration realmConfiguration; RealmService realmService = OAuthComponentServiceHolder.getInstance().getRealmService(); int tenantId = getTenantId(user.getTenantDomain()); if (realmService != null && tenantId != org.wso2.carbon.base.MultitenantConstants.INVALID_TENANT_ID) { UserStoreManager userStoreManager; userStoreManager = (UserStoreManager) realmService.getTenantUserRealm(tenantId).getUserStoreManager(); if (userStoreManager != null) { realmConfiguration = userStoreManager.getRealmConfiguration(); return realmConfiguration.getEveryOneRoleName(); } } return null; } catch (UserStoreException e) { String errorMsg = "Error while getting Realm configuration of tenant " + user.getTenantDomain(); throw new IdentityOAuth2Exception(errorMsg, e); } } /** * Get a filtered set of scopes after dropping unregistered scopes. * * @param requestedScopesArr Array of requested scopes. * @param tenantDomain Tenant domain. * @return Filtered set of scopes after dropping unregistered scopes. * @throws IdentityOAuth2Exception IdentityOAuth2Exception */ public static String[] dropUnregisteredScopes(String[] requestedScopesArr, String tenantDomain) throws IdentityOAuth2Exception { if (ArrayUtils.isEmpty(requestedScopesArr)) { if (log.isDebugEnabled()) { log.debug("Scope string is empty. No scopes to check for unregistered scopes."); } return requestedScopesArr; } try { int tenantId = IdentityTenantUtil.getTenantId(tenantDomain); String requestedScopes = StringUtils.join(requestedScopesArr, " "); Set<Scope> registeredScopeSet = OAuthTokenPersistenceFactory.getInstance().getOAuthScopeDAO() .getRequestedScopesOnly(tenantId, true, requestedScopes); List<String> filteredScopes = new ArrayList<>(); registeredScopeSet.forEach(scope -> filteredScopes.add(scope.getName())); if (log.isDebugEnabled()) { log.debug(String.format("Dropping unregistered scopes. Requested scopes: %s | Filtered result: %s", requestedScopes, StringUtils.join(filteredScopes, " "))); } return filteredScopes.toArray(new String[0]); } catch (IdentityOAuth2ScopeServerException e) { throw new IdentityOAuth2Exception("Error occurred while retrieving registered scopes.", e); } } public static String resolveUsernameFromUserId(String tenantDomain, String userId) throws UserStoreException { RealmService realmService = OAuthComponentServiceHolder.getInstance().getRealmService(); int tenantId = realmService.getTenantManager().getTenantId(tenantDomain); AbstractUserStoreManager userStoreManager = (AbstractUserStoreManager) realmService.getTenantUserRealm(tenantId).getUserStoreManager(); return userStoreManager.getUserNameFromUserID(userId); } /** * Resolve tenant domain from the httpServlet request. * * @param request HttpServlet Request. * @return Tenant Domain. */ public static String resolveTenantDomain(HttpServletRequest request) { if (!IdentityTenantUtil.isTenantedSessionsEnabled()) { return MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; } if (request != null) { String tenantDomainFromReq = request.getParameter(FrameworkConstants.RequestParams.LOGIN_TENANT_DOMAIN); if (StringUtils.isNotBlank(tenantDomainFromReq)) { return tenantDomainFromReq; } } return IdentityTenantUtil.getTenantDomainFromContext(); } /** * Get user role list from federated user attributes. * * @param userAttributes User attribute. * @return User role-list. */ public static List<String> getRolesFromFederatedUserAttributes(Map<ClaimMapping, String> userAttributes) { Optional<ClaimMapping> roleClaimMapping = Optional.ofNullable(userAttributes).get().entrySet().stream() .map(entry -> entry.getKey()) .filter(claim -> StringUtils.equals(OIDC_ROLE_CLAIM_URI, claim.getRemoteClaim().getClaimUri())) .findFirst(); if (roleClaimMapping.isPresent()) { return Arrays.asList(userAttributes.get(roleClaimMapping.get()) .split(Pattern.quote(FrameworkUtils.getMultiAttributeSeparator()))); } return Collections.emptyList(); } /** * Check federated role based authorization enabled or not. * * @param requestMsgCtx Token request message context. * @return Role based authz flow enabled or not. * @throws IdentityOAuth2Exception IdentityOAuth2Exception. */ public static boolean isFederatedRoleBasedAuthzEnabled(OAuthTokenReqMessageContext requestMsgCtx) throws IdentityOAuth2Exception { String clientId = requestMsgCtx.getOauth2AccessTokenReqDTO().getClientId(); return isFederatedRoleBasedAuthzEnabled(clientId); } /** * Check federated role based authorization enabled or not. * * @param oauthAuthzMsgCtx OAuth authorization request message context. * @return Role based authz flow enabled or not. * @throws IdentityOAuth2Exception IdentityOAuth2Exception. */ public static boolean isFederatedRoleBasedAuthzEnabled(OAuthAuthzReqMessageContext oauthAuthzMsgCtx) throws IdentityOAuth2Exception { String clientId = oauthAuthzMsgCtx.getAuthorizationReqDTO().getConsumerKey(); return isFederatedRoleBasedAuthzEnabled(clientId); } /** * Check federated role based authorization enabled or not. * * @param clientId Application's client ID. * @return Role based authz flow enabled or not. * @throws IdentityOAuth2Exception IdentityOAuth2Exception. */ public static boolean isFederatedRoleBasedAuthzEnabled(String clientId) throws IdentityOAuth2Exception { List<String> federatedRoleBasedAuthzApps = IdentityUtil.getPropertyAsList(FIDP_ROLE_BASED_AUTHZ_APP_CONFIG); boolean isFederatedRoleBasedAuthzEnabled = false; if (!federatedRoleBasedAuthzApps.isEmpty()) { OAuthAppDO app = null; try { app = getAppInformationByClientId(clientId); } catch (InvalidOAuthClientException e) { if (log.isDebugEnabled()) { log.debug("Error while retrieving the Application Information for client id: " + clientId, e); } throw new IdentityOAuth2Exception(e.getMessage(), e); } String appTenantDomain = getTenantDomainOfOauthApp(app); if (StringUtils.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, appTenantDomain) && federatedRoleBasedAuthzApps.contains(app.getApplicationName())) { isFederatedRoleBasedAuthzEnabled = true; } } return isFederatedRoleBasedAuthzEnabled; } /** * Is carbon role based validation enabled for first level organizations in the deployment. * * @return True if carbon role based validation enabled for first level organizations. */ public static boolean isCarbonRoleValidationEnabledForLevelOneOrgs() { return Boolean.parseBoolean(IdentityUtil.getProperty(IS_CARBON_ROLE_VALIDATION_ENABLED_FOR_LEVEL_ONE_ORGS)); } /** * Return whether organization role based validation is used. * * @param organizationId Organization id. * @return False if the organization is a first level organization in the deployment and * IS_CARBON_ROLE_VALIDATION_ENABLED_FOR_LEVEL_ONE_ORGS config is enabled. Other true. */ public static boolean useOrganizationRolesForValidation(String organizationId) { if (!isCarbonRoleValidationEnabledForLevelOneOrgs()) { return true; } try { // Return false if the organization is in depth 1. return OAuth2ServiceComponentHolder.getOrganizationManagementService() .getOrganizationDepthInHierarchy(organizationId) == 1; } catch (OrganizationManagementServerException e) { log.error("Error while checking the depth of the given organization."); } return true; } }
components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/util/OAuth2Util.java
/* * Copyright (c) 2013, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.oauth2.util; import com.nimbusds.jose.Algorithm; import com.nimbusds.jose.EncryptionMethod; import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JWEAlgorithm; import com.nimbusds.jose.JWEEncrypter; import com.nimbusds.jose.JWEHeader; import com.nimbusds.jose.JWEObject; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.JWSHeader; import com.nimbusds.jose.JWSSigner; import com.nimbusds.jose.JWSVerifier; import com.nimbusds.jose.Payload; import com.nimbusds.jose.crypto.RSAEncrypter; import com.nimbusds.jose.crypto.RSASSASigner; import com.nimbusds.jose.crypto.RSASSAVerifier; import com.nimbusds.jose.jwk.JWK; import com.nimbusds.jose.jwk.JWKMatcher; import com.nimbusds.jose.jwk.JWKSelector; import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.KeyUse; import com.nimbusds.jose.jwk.RSAKey; import com.nimbusds.jose.util.Base64URL; import com.nimbusds.jwt.EncryptedJWT; import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.JWTParser; import com.nimbusds.jwt.SignedJWT; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.apache.axiom.om.OMElement; import org.apache.axiom.util.base64.Base64Utils; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.Charsets; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.client.utils.URIBuilder; import org.apache.oltu.oauth2.common.exception.OAuthRuntimeException; import org.apache.oltu.oauth2.common.exception.OAuthSystemException; import org.json.JSONException; import org.json.JSONObject; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.core.util.KeyStoreManager; import org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException; import org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; import org.wso2.carbon.identity.application.authentication.framework.store.UserSessionStore; import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants; import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils; import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; import org.wso2.carbon.identity.application.common.model.ClaimMapping; import org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig; import org.wso2.carbon.identity.application.common.model.IdentityProvider; import org.wso2.carbon.identity.application.common.model.ServiceProvider; import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants; import org.wso2.carbon.identity.application.common.util.IdentityApplicationManagementUtil; import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; import org.wso2.carbon.identity.base.IdentityConstants; import org.wso2.carbon.identity.base.IdentityException; import org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils; import org.wso2.carbon.identity.core.ServiceURLBuilder; import org.wso2.carbon.identity.core.URLBuilderException; import org.wso2.carbon.identity.core.util.IdentityConfigParser; import org.wso2.carbon.identity.core.util.IdentityCoreConstants; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.oauth.IdentityOAuthAdminException; import org.wso2.carbon.identity.oauth.cache.AppInfoCache; import org.wso2.carbon.identity.oauth.cache.CacheEntry; import org.wso2.carbon.identity.oauth.cache.OAuthCache; import org.wso2.carbon.identity.oauth.cache.OAuthCacheKey; import org.wso2.carbon.identity.oauth.common.OAuthConstants; import org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException; import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; import org.wso2.carbon.identity.oauth.dao.OAuthAppDAO; import org.wso2.carbon.identity.oauth.dao.OAuthAppDO; import org.wso2.carbon.identity.oauth.dao.OAuthConsumerDAO; import org.wso2.carbon.identity.oauth.dto.ScopeDTO; import org.wso2.carbon.identity.oauth.event.OAuthEventInterceptor; import org.wso2.carbon.identity.oauth.internal.OAuthComponentServiceHolder; import org.wso2.carbon.identity.oauth.tokenprocessor.PlainTextPersistenceProcessor; import org.wso2.carbon.identity.oauth.tokenprocessor.TokenPersistenceProcessor; import org.wso2.carbon.identity.oauth.user.UserInfoEndpointException; import org.wso2.carbon.identity.oauth2.IdentityOAuth2ClientException; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; import org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeException; import org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeServerException; import org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext; import org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext; import org.wso2.carbon.identity.oauth2.bean.Scope; import org.wso2.carbon.identity.oauth2.bean.ScopeBinding; import org.wso2.carbon.identity.oauth2.config.SpOAuth2ExpiryTimeConfiguration; import org.wso2.carbon.identity.oauth2.dao.OAuthTokenPersistenceFactory; import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO; import org.wso2.carbon.identity.oauth2.dto.OAuth2IntrospectionResponseDTO; import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO; import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO; import org.wso2.carbon.identity.oauth2.dto.OAuthRevocationRequestDTO; import org.wso2.carbon.identity.oauth2.internal.OAuth2ServiceComponentHolder; import org.wso2.carbon.identity.oauth2.model.AccessTokenDO; import org.wso2.carbon.identity.oauth2.model.ClientCredentialDO; import org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer; import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; import org.wso2.carbon.identity.oauth2.token.OauthTokenIssuer; import org.wso2.carbon.identity.oauth2.token.bindings.TokenBinder; import org.wso2.carbon.identity.oauth2.token.bindings.TokenBinding; import org.wso2.carbon.identity.oauth2.token.handlers.grant.AuthorizationGrantHandler; import org.wso2.carbon.identity.openidconnect.model.Constants; import org.wso2.carbon.identity.openidconnect.model.RequestedClaim; import org.wso2.carbon.identity.organization.management.service.exception.OrganizationManagementServerException; import org.wso2.carbon.idp.mgt.IdentityProviderManagementException; import org.wso2.carbon.idp.mgt.IdentityProviderManager; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.user.api.RealmConfiguration; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.UserCoreConstants; import org.wso2.carbon.user.core.UserStoreManager; import org.wso2.carbon.user.core.common.AbstractUserStoreManager; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.util.UserCoreUtil; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.Key; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.sql.Timestamp; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.xml.namespace.QName; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth10AEndpoints.OAUTH_AUTHZ_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth10AEndpoints.OAUTH_REQUEST_TOKEN_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth10AEndpoints.OAUTH_TOKEN_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.DEVICE_AUTHZ_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OAUTH2_AUTHZ_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OAUTH2_CONSENT_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OAUTH2_DCR_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OAUTH2_DISCOVERY_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OAUTH2_ERROR_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OAUTH2_INTROSPECT_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OAUTH2_JWKS_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OAUTH2_REVOKE_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OAUTH2_TOKEN_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OAUTH2_USER_INFO_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OIDC_CONSENT_EP_URL; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Endpoints.OIDC_WEB_FINGER_EP_URL; import static org.wso2.carbon.identity.oauth2.Oauth2ScopeConstants.PERMISSIONS_BINDING_TYPE; import static org.wso2.carbon.identity.oauth2.device.constants.Constants.DEVICE_SUCCESS_ENDPOINT_PATH; /** * Utility methods for OAuth 2.0 implementation */ public class OAuth2Util { public static final String REMOTE_ACCESS_TOKEN = "REMOTE_ACCESS_TOKEN"; public static final String JWT_ACCESS_TOKEN = "JWT_ACCESS_TOKEN"; public static final String ACCESS_TOKEN_DO = "AccessTokenDo"; public static final String OAUTH2_VALIDATION_MESSAGE_CONTEXT = "OAuth2TokenValidationMessageContext"; public static final String CONFIG_ELEM_OAUTH = "OAuth"; public static final String OPENID_CONNECT = "OpenIDConnect"; public static final String ENABLE_OPENID_CONNECT_AUDIENCES = "EnableAudiences"; public static final String OPENID_CONNECT_AUDIENCE = "audience"; public static final String OPENID_SCOPE = "openid"; /* * Maintain a separate parameter "OPENID_CONNECT_AUDIENCE_IDENTITY_CONFIG" to get the audience from the identity.xml * when user didn't add any audience in the UI while creating service provider. */ public static final String OPENID_CONNECT_AUDIENCE_IDENTITY_CONFIG = "Audience"; private static final String OPENID_CONNECT_AUDIENCES = "Audiences"; private static final String DOT_SEPARATER = "."; private static final String IDP_ENTITY_ID = "IdPEntityId"; private static final String OIDC_ROLE_CLAIM_URI = "roles"; public static final String DEFAULT_TOKEN_TYPE = "Default"; /* * OPTIONAL. A JSON string containing a space-separated list of scopes associated with this token, in the format * described in Section 3.3 of OAuth 2.0 */ public static final String SCOPE = "scope"; /* * OPTIONAL. Client identifier for the OAuth 2.0 client that requested this token. */ public static final String CLIENT_ID = "client_id"; /* * OPTIONAL. Human-readable identifier for the resource owner who authorized this token. */ public static final String USERNAME = "username"; /* * OPTIONAL. Type of the token as defined in Section 5.1 of OAuth 2.0 */ public static final String TOKEN_TYPE = "token_type"; /* * OPTIONAL. Integer time-stamp, measured in the number of seconds since January 1 1970 UTC, indicating when this * token is not to be used before, as defined in JWT */ public static final String NBF = "nbf"; /* * OPTIONAL. Service-specific string identifier or list of string identifiers representing the intended audience for * this token, as defined in JWT */ public static final String AUD = "aud"; /* * OPTIONAL. String representing the issuer of this token, as defined in JWT */ public static final String ISS = "iss"; /* * OPTIONAL. String identifier for the token, as defined in JWT */ public static final String JTI = "jti"; /* * OPTIONAL. Subject of the token, as defined in JWT [RFC7519]. Usually a machine-readable identifier of the * resource owner who authorized this token. */ public static final String SUB = "sub"; /* * OPTIONAL. Integer time-stamp, measured in the number of seconds since January 1 1970 UTC, indicating when this * token will expire, as defined in JWT */ public static final String EXP = "exp"; /* * OPTIONAL. Integer time-stamp, measured in the number of seconds since January 1 1970 UTC, indicating when this * token was originally issued, as defined in JWT */ public static final String IAT = "iat"; /*** * Constant for user access token expiry time. */ public static final String USER_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS = "userAccessTokenExpireTime"; /*** * Constant for refresh token expiry time. */ public static final String REFRESH_TOKEN_EXP_TIME_IN_MILLISECONDS = "refreshTokenExpireTime"; /*** * Constant for application access token expiry time. */ public static final String APPLICATION_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS = "applicationAccessTokenExpireTime"; /** * FIdp Role Based authentication application config. */ public static final String FIDP_ROLE_BASED_AUTHZ_APP_CONFIG = "FIdPRoleBasedAuthzApplications.AppName"; private static final String INBOUND_AUTH2_TYPE = "oauth2"; private static final Log log = LogFactory.getLog(OAuth2Util.class); private static final Log diagnosticLog = LogFactory.getLog("diagnostics"); private static final String INTERNAL_LOGIN_SCOPE = "internal_login"; public static final String JWT = "JWT"; private static long timestampSkew = OAuthServerConfiguration.getInstance().getTimeStampSkewInSeconds() * 1000; private static ThreadLocal<Integer> clientTenantId = new ThreadLocal<>(); private static ThreadLocal<OAuthTokenReqMessageContext> tokenRequestContext = new ThreadLocal<>(); private static ThreadLocal<OAuthAuthzReqMessageContext> authzRequestContext = new ThreadLocal<>(); //Precompile PKCE Regex pattern for performance improvement private static Pattern pkceCodeVerifierPattern = Pattern.compile("[\\w\\-\\._~]+"); // System flag to allow the weak keys (key length less than 2048) to be used for the signing. private static final String ALLOW_WEAK_RSA_SIGNER_KEY = "allow_weak_rsa_signer_key"; private static Map<Integer, Certificate> publicCerts = new ConcurrentHashMap<Integer, Certificate>(); private static Map<Integer, Key> privateKeys = new ConcurrentHashMap<Integer, Key>(); // Supported Signature Algorithms private static final String NONE = "NONE"; private static final String SHA256_WITH_RSA = "SHA256withRSA"; private static final String SHA384_WITH_RSA = "SHA384withRSA"; private static final String SHA512_WITH_RSA = "SHA512withRSA"; private static final String SHA256_WITH_HMAC = "SHA256withHMAC"; private static final String SHA384_WITH_HMAC = "SHA384withHMAC"; private static final String SHA512_WITH_HMAC = "SHA512withHMAC"; private static final String SHA256_WITH_EC = "SHA256withEC"; private static final String SHA384_WITH_EC = "SHA384withEC"; private static final String SHA512_WITH_EC = "SHA512withEC"; private static final String SHA256_WITH_PS = "SHA256withPS"; private static final String PS256 = "PS256"; private static final String SHA256 = "SHA-256"; private static final String SHA384 = "SHA-384"; private static final String SHA512 = "SHA-512"; // Supported Client Authentication Methods private static final String CLIENT_SECRET_BASIC = "client_secret_basic"; private static final String CLIENT_SECRET_POST = "client_secret_post"; private static final String PRIVATE_KEY_JWT = "private_key_jwt"; // Supported Response Modes. private static final String QUERY_RESPONSE_MODE = "query"; private static final String FRAGMENT_RESPONSE_MODE = "fragment"; private static final String FORM_POST_RESPONSE_MODE = "form_post"; public static final String ACCESS_TOKEN_IS_NOT_ACTIVE_ERROR_MESSAGE = "Invalid Access Token. Access token is " + "not ACTIVE."; public static final String IS_CARBON_ROLE_VALIDATION_ENABLED_FOR_LEVEL_ONE_ORGS = "OrganizationManagement.LevelOneOrganizationConfigs.EnableCarbonRoleBasedValidation"; private OAuth2Util() { } /** * @return */ public static OAuthAuthzReqMessageContext getAuthzRequestContext() { if (log.isDebugEnabled()) { log.debug("Retreived OAuthAuthzReqMessageContext from threadlocal"); } return authzRequestContext.get(); } /** * @param context */ public static void setAuthzRequestContext(OAuthAuthzReqMessageContext context) { authzRequestContext.set(context); if (log.isDebugEnabled()) { log.debug("Added OAuthAuthzReqMessageContext to threadlocal"); } } /** * */ public static void clearAuthzRequestContext() { authzRequestContext.remove(); if (log.isDebugEnabled()) { log.debug("Cleared OAuthAuthzReqMessageContext"); } } /** * @return */ public static OAuthTokenReqMessageContext getTokenRequestContext() { if (log.isDebugEnabled()) { log.debug("Retreived OAuthTokenReqMessageContext from threadlocal"); } return tokenRequestContext.get(); } /** * @param context */ public static void setTokenRequestContext(OAuthTokenReqMessageContext context) { tokenRequestContext.set(context); if (log.isDebugEnabled()) { log.debug("Added OAuthTokenReqMessageContext to threadlocal"); } } /** * */ public static void clearTokenRequestContext() { tokenRequestContext.remove(); if (log.isDebugEnabled()) { log.debug("Cleared OAuthTokenReqMessageContext"); } } /** * @return */ public static int getClientTenatId() { if (clientTenantId.get() == null) { return -1; } return clientTenantId.get(); } /** * @param tenantId */ public static void setClientTenatId(int tenantId) { Integer id = tenantId; clientTenantId.set(id); } /** * */ public static void clearClientTenantId() { clientTenantId.remove(); } /** * Build a comma separated list of scopes passed as a String set by OLTU. * * @param scopes set of scopes * @return Comma separated list of scopes */ public static String buildScopeString(String[] scopes) { if (scopes != null) { Arrays.sort(scopes); return StringUtils.join(scopes, " "); } return null; } /** * @param scopeStr * @return */ public static String[] buildScopeArray(String scopeStr) { if (StringUtils.isNotBlank(scopeStr)) { scopeStr = scopeStr.trim(); return scopeStr.split("\\s"); } return new String[0]; } /** * Authenticate the OAuth Consumer * * @param clientId Consumer Key/Id * @param clientSecretProvided Consumer Secret issued during the time of registration * @return true, if the authentication is successful, false otherwise. * @throws IdentityOAuthAdminException Error when looking up the credentials from the database */ public static boolean authenticateClient(String clientId, String clientSecretProvided) throws IdentityOAuthAdminException, IdentityOAuth2Exception, InvalidOAuthClientException { OAuthAppDO appDO = OAuth2Util.getAppInformationByClientId(clientId); if (appDO == null) { if (log.isDebugEnabled()) { log.debug("Cannot find a valid application with the provided client_id: " + clientId); } return false; } // Cache miss boolean isHashDisabled = isHashDisabled(); String appClientSecret = appDO.getOauthConsumerSecret(); if (isHashDisabled) { if (!StringUtils.equals(appClientSecret, clientSecretProvided)) { if (log.isDebugEnabled()) { log.debug("Provided the Client ID : " + clientId + " and Client Secret do not match with the issued credentials."); } return false; } } else { TokenPersistenceProcessor persistenceProcessor = getPersistenceProcessor(); // We convert the provided client_secret to the processed form stored in the DB. String processedProvidedClientSecret = persistenceProcessor.getProcessedClientSecret(clientSecretProvided); if (!StringUtils.equals(appClientSecret, processedProvidedClientSecret)) { if (log.isDebugEnabled()) { log.debug("Provided the Client ID : " + clientId + " and Client Secret do not match with the issued credentials."); } return false; } } if (log.isDebugEnabled()) { log.debug("Successfully authenticated the client with client id : " + clientId); } return true; } public static TokenPersistenceProcessor getPersistenceProcessor() { TokenPersistenceProcessor persistenceProcessor; try { persistenceProcessor = OAuthServerConfiguration.getInstance().getPersistenceProcessor(); } catch (IdentityOAuth2Exception e) { String msg = "Error retrieving TokenPersistenceProcessor configured in OAuth.TokenPersistenceProcessor " + "in identity.xml. Defaulting to PlainTextPersistenceProcessor."; log.warn(msg); if (log.isDebugEnabled()) { log.debug(msg, e); } persistenceProcessor = new PlainTextPersistenceProcessor(); } return persistenceProcessor; } /** * Check whether hashing oauth keys (consumer secret, access token, refresh token and authorization code) * configuration is disabled or not in identity.xml file. * * @return Whether hash feature is disabled or not. */ public static boolean isHashDisabled() { boolean isHashEnabled = OAuthServerConfiguration.getInstance().isClientSecretHashEnabled(); return !isHashEnabled; } /** * Check whether hashing oauth keys (consumer secret, access token, refresh token and authorization code) * configuration is enabled or not in identity.xml file. * * @return Whether hash feature is enable or not. */ public static boolean isHashEnabled() { boolean isHashEnabled = OAuthServerConfiguration.getInstance().isClientSecretHashEnabled(); return isHashEnabled; } /** * @param clientId Consumer Key/Id * @param clientSecretProvided Consumer Secret issued during the time of registration * @return Username of the user which own client id and client secret if authentication is * successful. Empty string otherwise. * @throws IdentityOAuthAdminException Error when looking up the credentials from the database * @deprecated Authenticate the OAuth consumer and return the username of user which own the provided client id * and client secret. */ @Deprecated public static String getAuthenticatedUsername(String clientId, String clientSecretProvided) throws IdentityOAuthAdminException, IdentityOAuth2Exception, InvalidOAuthClientException { boolean cacheHit = false; String username = null; boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(username); if (OAuth2Util.authenticateClient(clientId, clientSecretProvided)) { CacheEntry cacheResult = OAuthCache.getInstance().getValueFromCache(new OAuthCacheKey(clientId + ":" + username)); if (cacheResult != null && cacheResult instanceof ClientCredentialDO) { // Ugh. This is fugly. Have to have a generic way of caching a key:value pair username = ((ClientCredentialDO) cacheResult).getClientSecret(); cacheHit = true; if (log.isDebugEnabled()) { log.debug("Username was available in the cache : " + username); } } if (username == null) { // Cache miss OAuthConsumerDAO oAuthConsumerDAO = new OAuthConsumerDAO(); username = oAuthConsumerDAO.getAuthenticatedUsername(clientId, clientSecretProvided); if (log.isDebugEnabled()) { log.debug("Username fetch from the database"); } } if (username != null && !cacheHit) { /* Using the same ClientCredentialDO to host username. Semantically wrong since ClientCredentialDo accept a client secret and we're storing a username in the secret variable. Do we have to make our own cache key and cache entry class every time we need to put something to it? Ideal solution is to have a generalized way of caching a key:value pair */ if (isUsernameCaseSensitive) { OAuthCache.getInstance() .addToCache(new OAuthCacheKey(clientId + ":" + username), new ClientCredentialDO(username)); } else { OAuthCache.getInstance().addToCache(new OAuthCacheKey(clientId + ":" + username.toLowerCase()), new ClientCredentialDO(username)); } if (log.isDebugEnabled()) { log.debug("Caching username : " + username); } } } return username; } /** * Build the cache key string when storing Authz Code info in cache * * @param clientId Client Id representing the client * @param authzCode Authorization Code issued to the client * @return concatenated <code>String</code> of clientId:authzCode */ public static String buildCacheKeyStringForAuthzCode(String clientId, String authzCode) { return clientId + ":" + authzCode; } /** * Build the cache key string when storing token info in cache * * @param clientId * @param scope * @param authorizedUser * @return * @deprecated To make the cache key completely unique the authenticated IDP should also be introduced. * Use {@link #buildCacheKeyStringForTokenWithUserId(String, String, String, String, String)} instead. */ @Deprecated public static String buildCacheKeyStringForToken(String clientId, String scope, String authorizedUser) { AuthenticatedUser authenticatedUser = OAuth2Util.getUserFromUserName(authorizedUser); try { return clientId + ":" + authenticatedUser.getUserId() + ":" + scope; } catch (UserIdNotFoundException e) { if (log.isDebugEnabled()) { log.debug("Cache could not be built for user: " + authorizedUser, e); } } return null; } /** * Build the cache key string when storing token info in cache. * * @param clientId ClientId of the App. * @param scope Scopes used. * @param authorizedUser Authorised user. * @param authenticatedIDP Authenticated IdP. * @return Cache key string combining the input parameters. * @deprecated use {@link #buildCacheKeyStringForTokenWithUserId(String, String, String, String, String)} instead. */ @Deprecated public static String buildCacheKeyStringForToken(String clientId, String scope, String authorizedUser, String authenticatedIDP) { AuthenticatedUser authenticatedUser = OAuth2Util.getUserFromUserName(authorizedUser); try { return clientId + ":" + authenticatedUser.getUserId() + ":" + scope + ":" + authenticatedIDP; } catch (UserIdNotFoundException e) { log.error("Cache could not be built for user: " + authorizedUser, e); } return null; } /** * Build the cache key string when storing token info in cache. * Use {@link #buildCacheKeyStringForTokenWithUserId(String, String, String, String, String)} instead. * * @param clientId ClientId of the App. * @param scope Scopes used. * @param authorizedUser Authorised user. * @param authenticatedIDP Authenticated IdP. * @param tokenBindingReference Token binding reference. * @return Cache key string combining the input parameters. */ @Deprecated public static String buildCacheKeyStringForToken(String clientId, String scope, String authorizedUser, String authenticatedIDP, String tokenBindingReference) { AuthenticatedUser authenticatedUser = OAuth2Util.getUserFromUserName(authorizedUser); try { return clientId + ":" + authenticatedUser.getUserId() + ":" + scope + ":" + authenticatedIDP + ":" + tokenBindingReference; } catch (UserIdNotFoundException e) { log.error("Cache could not be built for user: " + authorizedUser, e); } return null; } /** * Build the cache key string when storing token info in cache. * * @param clientId ClientId of the App. * @param scope Scopes used. * @param authorizedUserId Authorised user. * @param authenticatedIDP Authenticated IdP. * @param tokenBindingReference Token binding reference. * @return Cache key string combining the input parameters. */ public static String buildCacheKeyStringForTokenWithUserId(String clientId, String scope, String authorizedUserId, String authenticatedIDP, String tokenBindingReference) { String oauthCacheKey = clientId + ":" + authorizedUserId + ":" + scope + ":" + authenticatedIDP + ":" + tokenBindingReference; if (log.isDebugEnabled()) { log.debug(String.format("Building cache key: %s to access OAuthCache.", oauthCacheKey)); } return oauthCacheKey; } /** * Build the cache key string when storing token info in cache. * * @param clientId ClientId of the App. * @param scope Scopes used. * @param authorizedUserId Authorised user. * @param authenticatedIDP Authenticated IdP. * @return Cache key string combining the input parameters. */ public static String buildCacheKeyStringForTokenWithUserId(String clientId, String scope, String authorizedUserId, String authenticatedIDP) { return clientId + ":" + authorizedUserId + ":" + scope + ":" + authenticatedIDP; } @SuppressFBWarnings("WEAK_MESSAGE_DIGEST_MD5") public static String getTokenBindingReference(String tokenBindingValue) { if (StringUtils.isBlank(tokenBindingValue)) { return null; } return DigestUtils.md5Hex(tokenBindingValue); } public static AccessTokenDO validateAccessTokenDO(AccessTokenDO accessTokenDO) { long validityPeriodMillis = accessTokenDO.getValidityPeriodInMillis(); long issuedTime = accessTokenDO.getIssuedTime().getTime(); //check the validity of cached OAuth2AccessToken Response long accessTokenValidityMillis = getTimeToExpire(issuedTime, validityPeriodMillis); if (accessTokenValidityMillis > 1000) { long refreshValidityPeriodMillis = OAuthServerConfiguration.getInstance() .getRefreshTokenValidityPeriodInSeconds() * 1000; long refreshTokenValidityMillis = getTimeToExpire(issuedTime, refreshValidityPeriodMillis); if (refreshTokenValidityMillis > 1000) { //Set new validity period to response object accessTokenDO.setValidityPeriodInMillis(accessTokenValidityMillis); accessTokenDO.setRefreshTokenValidityPeriodInMillis(refreshTokenValidityMillis); //Set issued time period to response object accessTokenDO.setIssuedTime(new Timestamp(issuedTime)); return accessTokenDO; } } //returns null if cached OAuth2AccessToken response object is expired return null; } public static boolean checkAccessTokenPartitioningEnabled() { return OAuthServerConfiguration.getInstance().isAccessTokenPartitioningEnabled(); } public static boolean checkUserNameAssertionEnabled() { return OAuthServerConfiguration.getInstance().isUserNameAssertionEnabled(); } public static String getAccessTokenPartitioningDomains() { return OAuthServerConfiguration.getInstance().getAccessTokenPartitioningDomains(); } public static Map<String, String> getAvailableUserStoreDomainMappings() throws IdentityOAuth2Exception { // TreeMap is used to ignore the case sensitivity of key. Because when user logged in, the case of the // username is ignored. Map<String, String> userStoreDomainMap = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); String domainsStr = getAccessTokenPartitioningDomains(); if (domainsStr != null) { String[] userStoreDomainsArr = domainsStr.split(","); for (String userStoreDomains : userStoreDomainsArr) { String[] mapping = userStoreDomains.trim().split(":"); //A:foo.com , B:bar.com if (mapping.length < 2) { throw new IdentityOAuth2Exception("Domain mapping has not defined correctly"); } userStoreDomainMap.put(mapping[1].trim(), mapping[0].trim()); //key=domain & value=mapping } } return userStoreDomainMap; } /** * Returns the mapped user store if a mapping is defined for this user store in AccessTokenPartitioningDomains * element in identity.xml, or the original userstore domain if the mapping is not available. * * @param userStoreDomain * @return * @throws IdentityOAuth2Exception */ public static String getMappedUserStoreDomain(String userStoreDomain) throws IdentityOAuth2Exception { String mappedUserStoreDomain = userStoreDomain; Map<String, String> availableDomainMappings = OAuth2Util.getAvailableUserStoreDomainMappings(); if (userStoreDomain != null && availableDomainMappings.containsKey(userStoreDomain)) { mappedUserStoreDomain = availableDomainMappings.get(userStoreDomain); } return mappedUserStoreDomain; } /** * Returns the updated table name using user store domain if a mapping is defined for this users store in * AccessTokenPartitioningDomains element in identity.xml, * or the original table name if the mapping is not available. * <p> * Updated table name derived by appending a underscore and mapped user store domain name to the origin table name. * * @param userStoreDomain * @return * @throws IdentityOAuth2Exception */ public static String getPartitionedTableByUserStore(String tableName, String userStoreDomain) throws IdentityOAuth2Exception { if (StringUtils.isNotBlank(tableName) && StringUtils.isNotBlank(userStoreDomain) && !IdentityUtil.getPrimaryDomainName().equalsIgnoreCase(userStoreDomain)) { String mappedUserStoreDomain = OAuth2Util.getMappedUserStoreDomain(userStoreDomain); tableName = tableName + "_" + mappedUserStoreDomain; } return tableName; } /** * Returns the updated sql using user store domain if access token partitioning enabled & username assertion enabled * or the original sql otherwise. * <p> * Updated sql derived by replacing original table names IDN_OAUTH2_ACCESS_TOKEN & IDN_OAUTH2_ACCESS_TOKEN_SCOPE * with the updated table names which derived using {@code getPartitionedTableByUserStore()} method. * * @param sql * @param userStoreDomain * @return * @throws IdentityOAuth2Exception */ public static String getTokenPartitionedSqlByUserStore(String sql, String userStoreDomain) throws IdentityOAuth2Exception { String partitionedSql = sql; if (OAuth2Util.checkAccessTokenPartitioningEnabled() && OAuth2Util.checkUserNameAssertionEnabled()) { String partitionedAccessTokenTable = OAuth2Util.getPartitionedTableByUserStore(OAuthConstants. ACCESS_TOKEN_STORE_TABLE, userStoreDomain); String accessTokenScopeTable = "IDN_OAUTH2_ACCESS_TOKEN_SCOPE"; String partitionedAccessTokenScopeTable = OAuth2Util.getPartitionedTableByUserStore(accessTokenScopeTable, userStoreDomain); if (log.isDebugEnabled()) { log.debug("PartitionedAccessTokenTable: " + partitionedAccessTokenTable + " & PartitionedAccessTokenScopeTable: " + partitionedAccessTokenScopeTable + " for user store domain: " + userStoreDomain); } String wordBoundaryRegex = "\\b"; partitionedSql = sql.replaceAll(wordBoundaryRegex + OAuthConstants.ACCESS_TOKEN_STORE_TABLE + wordBoundaryRegex, partitionedAccessTokenTable); partitionedSql = partitionedSql.replaceAll(wordBoundaryRegex + accessTokenScopeTable + wordBoundaryRegex, partitionedAccessTokenScopeTable); if (log.isDebugEnabled()) { log.debug("Original SQL: " + sql); log.debug("Partitioned SQL: " + partitionedSql); } } return partitionedSql; } /** * Returns the updated sql using username. * <p> * If the username contains the domain separator, updated sql derived using * {@code getTokenPartitionedSqlByUserStore()} method. Returns the original sql otherwise. * * @param sql * @param username * @return * @throws IdentityOAuth2Exception */ public static String getTokenPartitionedSqlByUserId(String sql, String username) throws IdentityOAuth2Exception { String partitionedSql = sql; if (OAuth2Util.checkAccessTokenPartitioningEnabled() && OAuth2Util.checkUserNameAssertionEnabled()) { if (log.isDebugEnabled()) { log.debug("Calculating partitioned sql for username: " + username); } String userStore = null; if (username != null) { String[] strArr = username.split(UserCoreConstants.DOMAIN_SEPARATOR); if (strArr != null && strArr.length > 1) { userStore = strArr[0]; } } partitionedSql = OAuth2Util.getTokenPartitionedSqlByUserStore(sql, userStore); } return partitionedSql; } /** * Returns the updated sql using token. * <p> * If the token contains the username appended, updated sql derived using * {@code getTokenPartitionedSqlByUserId()} method. Returns the original sql otherwise. * * @param sql * @param token * @return * @throws IdentityOAuth2Exception */ public static String getTokenPartitionedSqlByToken(String sql, String token) throws IdentityOAuth2Exception { String partitionedSql = sql; if (OAuth2Util.checkAccessTokenPartitioningEnabled() && OAuth2Util.checkUserNameAssertionEnabled()) { if (log.isDebugEnabled()) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Calculating partitioned sql for token: " + token); } else { // Avoid logging token since its a sensitive information. log.debug("Calculating partitioned sql for token"); } } String userId = OAuth2Util.getUserIdFromAccessToken(token); //i.e: 'foo.com/admin' or 'admin' partitionedSql = OAuth2Util.getTokenPartitionedSqlByUserId(sql, userId); } return partitionedSql; } public static String getUserStoreDomainFromUserId(String userId) throws IdentityOAuth2Exception { String userStoreDomain = null; if (userId != null) { String[] strArr = userId.split(UserCoreConstants.DOMAIN_SEPARATOR); if (strArr != null && strArr.length > 1) { userStoreDomain = getMappedUserStoreDomain(strArr[0]); } } return userStoreDomain; } public static String getUserStoreDomainFromAccessToken(String apiKey) throws IdentityOAuth2Exception { String userStoreDomain = null; String userId; String decodedKey = new String(Base64.decodeBase64(apiKey.getBytes(Charsets.UTF_8)), Charsets.UTF_8); String[] tmpArr = decodedKey.split(":"); if (tmpArr != null) { userId = tmpArr[1]; if (userId != null) { userStoreDomain = getUserStoreDomainFromUserId(userId); } } return userStoreDomain; } @Deprecated public static String getAccessTokenStoreTableFromUserId(String userId) throws IdentityOAuth2Exception { String accessTokenStoreTable = OAuthConstants.ACCESS_TOKEN_STORE_TABLE; String userStore; if (userId != null) { String[] strArr = userId.split(UserCoreConstants.DOMAIN_SEPARATOR); if (strArr.length > 1) { userStore = strArr[0]; accessTokenStoreTable = OAuth2Util.getPartitionedTableByUserStore(OAuthConstants.ACCESS_TOKEN_STORE_TABLE, userStore); } } return accessTokenStoreTable; } @Deprecated public static String getAccessTokenStoreTableFromAccessToken(String apiKey) throws IdentityOAuth2Exception { String userId = getUserIdFromAccessToken(apiKey); //i.e: 'foo.com/admin' or 'admin' return OAuth2Util.getAccessTokenStoreTableFromUserId(userId); } public static String getUserIdFromAccessToken(String apiKey) { String userId = null; String decodedKey = new String(Base64.decodeBase64(apiKey.getBytes(Charsets.UTF_8)), Charsets.UTF_8); String[] tmpArr = decodedKey.split(":"); if (tmpArr != null && tmpArr.length > 1) { userId = tmpArr[1]; } return userId; } /** * Get token expire time in milliseconds. * * @param accessTokenDO Access token data object. * @return expire time in milliseconds. * @deprecated Instead use {@link #getTokenExpireTimeMillis(AccessTokenDO, boolean)}. */ @Deprecated public static long getTokenExpireTimeMillis(AccessTokenDO accessTokenDO) { return getTokenExpireTimeMillis(accessTokenDO, true); } /** * Get token expire time in milliseconds. * * @param accessTokenDO Access token data object. * @param considerSkew Consider time stamp skew when calculating expire time. * @return expire time in milliseconds. */ public static long getTokenExpireTimeMillis(AccessTokenDO accessTokenDO, boolean considerSkew) { if (accessTokenDO == null) { throw new IllegalArgumentException("accessTokenDO is " + "\'NULL\'"); } long accessTokenValidity = getAccessTokenExpireMillis(accessTokenDO, considerSkew); long refreshTokenValidity = getRefreshTokenExpireTimeMillis(accessTokenDO); if (accessTokenValidity > 1000 && (refreshTokenValidity > 1000 || refreshTokenValidity < 0)) { return accessTokenValidity; } return 0; } public static long getRefreshTokenExpireTimeMillis(AccessTokenDO accessTokenDO) { if (accessTokenDO == null) { throw new IllegalArgumentException("accessTokenDO is " + "\'NULL\'"); } long refreshTokenValidityPeriodMillis = accessTokenDO.getRefreshTokenValidityPeriodInMillis(); if (refreshTokenValidityPeriodMillis < 0) { if (log.isDebugEnabled()) { log.debug("Refresh Token has infinite lifetime"); } return -1; } long refreshTokenIssuedTime = accessTokenDO.getRefreshTokenIssuedTime().getTime(); long refreshTokenValidity = getTimeToExpire(refreshTokenIssuedTime, refreshTokenValidityPeriodMillis); if (refreshTokenValidity > 1000) { return refreshTokenValidity; } return 0; } /** * Get access token expire time in milliseconds. * * @param accessTokenDO Access token data object. * @return expire time in milliseconds. * @deprecated {@link #getAccessTokenExpireMillis(AccessTokenDO, boolean)}. */ @Deprecated public static long getAccessTokenExpireMillis(AccessTokenDO accessTokenDO) { return getAccessTokenExpireMillis(accessTokenDO, true); } /** * Get access token expire time in milliseconds. * * @param accessTokenDO Access token data object. * @param considerSkew Consider time stamp skew when calculating expire time. * @return expire time in milliseconds. */ public static long getAccessTokenExpireMillis(AccessTokenDO accessTokenDO, boolean considerSkew) { if (accessTokenDO == null) { throw new IllegalArgumentException("accessTokenDO is " + "\'NULL\'"); } long validityPeriodMillis = accessTokenDO.getValidityPeriodInMillis(); if (validityPeriodMillis < 0) { if (log.isDebugEnabled()) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Access Token(hashed) : " + DigestUtils.sha256Hex(accessTokenDO.getAccessToken()) + " has infinite lifetime"); } else { log.debug("Access Token has infinite lifetime"); } } return -1; } long issuedTime = accessTokenDO.getIssuedTime().getTime(); long validityMillis = getTimeToExpire(issuedTime, validityPeriodMillis, considerSkew); if (validityMillis > 1000) { return validityMillis; } else { return 0; } } @Deprecated public static long calculateValidityInMillis(long issuedTimeInMillis, long validityPeriodMillis) { return getTimeToExpire(issuedTimeInMillis, validityPeriodMillis); } /** * Util method to calculate the validity period after applying skew corrections. * * @param issuedTimeInMillis * @param validityPeriodMillis * @return skew corrected validity period in milliseconds * @deprecated use {@link #getTimeToExpire(long, long, boolean)}. */ @Deprecated public static long getTimeToExpire(long issuedTimeInMillis, long validityPeriodMillis) { return getTimeToExpire(issuedTimeInMillis, validityPeriodMillis, true); } /** * Util method to calculate the validity period. * * @param issuedTimeInMillis Issued time in milliseconds. * @param validityPeriodMillis Validity period in milliseconds. * @param considerSkew Consider timestamp skew when calculating exipry time. * @return skew corrected validity period in milliseconds. */ public static long getTimeToExpire(long issuedTimeInMillis, long validityPeriodMillis, boolean considerSkew) { if (considerSkew) { return issuedTimeInMillis + validityPeriodMillis - (System.currentTimeMillis() - timestampSkew); } return issuedTimeInMillis + validityPeriodMillis - (System.currentTimeMillis()); } public static int getTenantId(String tenantDomain) throws IdentityOAuth2Exception { RealmService realmService = OAuthComponentServiceHolder.getInstance().getRealmService(); try { return realmService.getTenantManager().getTenantId(tenantDomain); } catch (UserStoreException e) { String error = "Error in obtaining tenant ID from tenant domain : " + tenantDomain; throw new IdentityOAuth2Exception(error, e); } } public static String getTenantDomain(int tenantId) throws IdentityOAuth2Exception { RealmService realmService = OAuthComponentServiceHolder.getInstance().getRealmService(); try { return realmService.getTenantManager().getDomain(tenantId); } catch (UserStoreException e) { String error = "Error in obtaining tenant domain from tenant ID : " + tenantId; throw new IdentityOAuth2Exception(error, e); } } public static int getTenantIdFromUserName(String username) throws IdentityOAuth2Exception { String domainName = MultitenantUtils.getTenantDomain(username); return getTenantId(domainName); } @SuppressFBWarnings("WEAK_MESSAGE_DIGEST_MD5") public static String hashScopes(String[] scope) { return DigestUtils.md5Hex(OAuth2Util.buildScopeString(scope)); } @SuppressFBWarnings("WEAK_MESSAGE_DIGEST_MD5") public static String hashScopes(String scope) { if (scope != null) { //first converted to an array to sort the scopes return DigestUtils.md5Hex(OAuth2Util.buildScopeString(buildScopeArray(scope))); } else { return null; } } public static AuthenticatedUser getUserFromUserName(String username) throws IllegalArgumentException { if (StringUtils.isNotBlank(username)) { String tenantDomain = MultitenantUtils.getTenantDomain(username); String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username); String tenantAwareUsernameWithNoUserDomain = UserCoreUtil.removeDomainFromName(tenantAwareUsername); String userStoreDomain = IdentityUtil.extractDomainFromName(username).toUpperCase(); AuthenticatedUser user = new AuthenticatedUser(); user.setUserName(tenantAwareUsernameWithNoUserDomain); user.setTenantDomain(tenantDomain); user.setUserStoreDomain(userStoreDomain); return user; } throw new IllegalArgumentException("Cannot create user from empty user name"); } public static String getIDTokenIssuer() { String issuer = OAuthServerConfiguration.getInstance().getOpenIDConnectIDTokenIssuerIdentifier(); if (StringUtils.isBlank(issuer)) { issuer = OAuthURL.getOAuth2TokenEPUrl(); } return issuer; } /** * OAuth URL related utility functions. */ public static class OAuthURL { public static String getOAuth1RequestTokenUrl() { String oauth1RequestTokenUrl = OAuthServerConfiguration.getInstance().getOAuth1RequestTokenUrl(); if (StringUtils.isBlank(oauth1RequestTokenUrl)) { oauth1RequestTokenUrl = IdentityUtil.getServerURL(OAUTH_REQUEST_TOKEN_EP_URL, true, true); } return oauth1RequestTokenUrl; } public static String getOAuth1AuthorizeUrl() { String oauth1AuthorizeUrl = OAuthServerConfiguration.getInstance().getOAuth1AuthorizeUrl(); if (StringUtils.isBlank(oauth1AuthorizeUrl)) { oauth1AuthorizeUrl = IdentityUtil.getServerURL(OAUTH_AUTHZ_EP_URL, true, true); } return oauth1AuthorizeUrl; } public static String getOAuth1AccessTokenUrl() { String oauth1AccessTokenUrl = OAuthServerConfiguration.getInstance().getOAuth1AccessTokenUrl(); if (StringUtils.isBlank(oauth1AccessTokenUrl)) { oauth1AccessTokenUrl = IdentityUtil.getServerURL(OAUTH_TOKEN_EP_URL, true, true); } return oauth1AccessTokenUrl; } public static String getOAuth2AuthzEPUrl() { return buildUrl(OAUTH2_AUTHZ_EP_URL, OAuthServerConfiguration.getInstance()::getOAuth2AuthzEPUrl); } public static String getOAuth2TokenEPUrl() { return buildUrl(OAUTH2_TOKEN_EP_URL, OAuthServerConfiguration.getInstance()::getOAuth2TokenEPUrl); } /** * This method is used to get the resolved URL for the OAuth2 Registration Endpoint. * * @param tenantDomain Tenant Domain. * @return String of the resolved URL for the Registration endpoint. * @throws URISyntaxException URI Syntax Exception. */ public static String getOAuth2DCREPUrl(String tenantDomain) throws URISyntaxException { String oauth2TokenEPUrl = buildUrl(OAUTH2_DCR_EP_URL, OAuthServerConfiguration.getInstance()::getOAuth2DCREPUrl); if (!IdentityTenantUtil.isTenantQualifiedUrlsEnabled() && isNotSuperTenant(tenantDomain)) { //Append tenant domain to path when the tenant-qualified url mode is disabled. oauth2TokenEPUrl = appendTenantDomainAsPathParamInLegacyMode(oauth2TokenEPUrl, tenantDomain); } return oauth2TokenEPUrl; } /** * This method is used to get the resolved URL for the JWKS Page. * * @param tenantDomain Tenant Domain. * @return String of the resolved URL for the JWKS page. * @throws URISyntaxException URI Syntax Exception. */ public static String getOAuth2JWKSPageUrl(String tenantDomain) throws URISyntaxException { String auth2JWKSPageUrl = buildUrl(OAUTH2_JWKS_EP_URL, OAuthServerConfiguration.getInstance()::getOAuth2JWKSPageUrl); if (!IdentityTenantUtil.isTenantQualifiedUrlsEnabled() && isNotSuperTenant(tenantDomain)) { //Append tenant domain to path when the tenant-qualified url mode is disabled. auth2JWKSPageUrl = appendTenantDomainAsPathParamInLegacyMode(auth2JWKSPageUrl, tenantDomain); } return auth2JWKSPageUrl; } public static String getOidcWebFingerEPUrl() { return buildUrl(OIDC_WEB_FINGER_EP_URL, OAuthServerConfiguration.getInstance()::getOidcWebFingerEPUrl); } public static String getOidcDiscoveryEPUrl(String tenantDomain) throws URISyntaxException { String oidcDiscoveryEPUrl = buildUrl(OAUTH2_DISCOVERY_EP_URL, OAuthServerConfiguration.getInstance()::getOidcDiscoveryUrl); if (!IdentityTenantUtil.isTenantQualifiedUrlsEnabled() && isNotSuperTenant(tenantDomain)) { //Append tenant domain to path when the tenant-qualified url mode is disabled. oidcDiscoveryEPUrl = appendTenantDomainAsPathParamInLegacyMode(oidcDiscoveryEPUrl, tenantDomain); } return oidcDiscoveryEPUrl; } public static String getOAuth2UserInfoEPUrl() { return buildUrl(OAUTH2_USER_INFO_EP_URL, OAuthServerConfiguration.getInstance()::getOauth2UserInfoEPUrl); } /** * Get oauth2 revocation endpoint URL. * * @return Revocation Endpoint URL. */ public static String getOAuth2RevocationEPUrl() { return buildUrl(OAUTH2_REVOKE_EP_URL, OAuthServerConfiguration.getInstance()::getOauth2RevocationEPUrl); } /** * Get oauth2 introspection endpoint URL. * * @return Introspection Endpoint URL. */ public static String getOAuth2IntrospectionEPUrl() { return buildUrl(OAUTH2_INTROSPECT_EP_URL, OAuthServerConfiguration.getInstance()::getOauth2IntrospectionEPUrl); } /** * This method is used to get the resolved URL for the OAuth2 introspection endpoint. * * @param tenantDomain Tenant Domain. * @return String of the resolved URL for the introspection endpoint. * @throws URISyntaxException URI Syntax Exception. */ public static String getOAuth2IntrospectionEPUrl(String tenantDomain) throws URISyntaxException { String getOAuth2IntrospectionEPUrl = buildUrl(OAUTH2_INTROSPECT_EP_URL, OAuthServerConfiguration.getInstance()::getOauth2IntrospectionEPUrl); if (!IdentityTenantUtil.isTenantQualifiedUrlsEnabled() && isNotSuperTenant(tenantDomain)) { // Append tenant domain to path when the tenant-qualified url mode is disabled. getOAuth2IntrospectionEPUrl = appendTenantDomainAsPathParamInLegacyMode(getOAuth2IntrospectionEPUrl, tenantDomain); } return getOAuth2IntrospectionEPUrl; } public static String getOIDCConsentPageUrl() { return buildUrl(OIDC_CONSENT_EP_URL, OAuthServerConfiguration.getInstance()::getOIDCConsentPageUrl); } public static String getOAuth2ConsentPageUrl() { return buildUrl(OAUTH2_CONSENT_EP_URL, OAuthServerConfiguration.getInstance()::getOauth2ConsentPageUrl); } public static String getOAuth2ErrorPageUrl() { return buildUrl(OAUTH2_ERROR_EP_URL, OAuthServerConfiguration.getInstance()::getOauth2ErrorPageUrl); } private static String appendTenantDomainAsPathParamInLegacyMode(String url, String tenantDomain) throws URISyntaxException { URI uri = new URI(url); URI uriModified = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), ("/t/" + tenantDomain + uri.getPath()), uri.getQuery(), uri.getFragment()); return uriModified.toString(); } public static String getDeviceAuthzEPUrl() { return buildUrl(DEVICE_AUTHZ_EP_URL, OAuthServerConfiguration.getInstance()::getDeviceAuthzEPUrl); } } /** * This method is used to generate the device flow authentication completed page URI. * * @param appName Service provider name. * @param tenantDomain Tenant domain. * @return Redirection URI */ public static String getDeviceFlowCompletionPageURI(String appName, String tenantDomain) throws IdentityOAuth2Exception { try { String pageURI = ServiceURLBuilder.create().addPath(DEVICE_SUCCESS_ENDPOINT_PATH) .build().getAbsolutePublicURL(); URIBuilder uriBuilder = new URIBuilder(pageURI); uriBuilder.addParameter(org.wso2.carbon.identity.oauth2.device.constants.Constants.APP_NAME, appName); if (!IdentityTenantUtil.isTenantQualifiedUrlsEnabled() && isNotSuperTenant(tenantDomain)) { // Append tenant domain to path when the tenant-qualified url mode is disabled. uriBuilder.addParameter(FrameworkUtils.TENANT_DOMAIN, tenantDomain); } return uriBuilder.build().toString(); } catch (URISyntaxException | URLBuilderException e) { throw new IdentityOAuth2Exception("Error occurred when getting the device flow authentication completed" + " page URI.", e); } } /** * Builds a URL with a given context in both the tenant-qualified url supported mode and the legacy mode. * Returns the absolute URL build from the default context in the tenant-qualified url supported mode. Gives * precedence to the file configurations in the legacy mode and returns the absolute url build from file * configuration context. * * @param defaultContext Default URL context. * @param getValueFromFileBasedConfig File-based Configuration. * @return Absolute URL. */ private static String buildUrl(String defaultContext, Supplier<String> getValueFromFileBasedConfig) { String oauth2EndpointURLInFile = null; if (getValueFromFileBasedConfig != null) { oauth2EndpointURLInFile = getValueFromFileBasedConfig.get(); } return buildServiceUrl(defaultContext, oauth2EndpointURLInFile); } /** * Returns the public service url given the default context and the url picked from the configuration based on * the 'tenant_context.enable_tenant_qualified_urls' mode set in deployment.toml. * * @param defaultContext default url context path * @param oauth2EndpointURLInFile url picked from the file configuration * @return absolute public url of the service if 'enable_tenant_qualified_urls' is 'true', else returns the url * from the file config */ public static String buildServiceUrl(String defaultContext, String oauth2EndpointURLInFile) { if (IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) { try { return ServiceURLBuilder.create().addPath(defaultContext).build().getAbsolutePublicURL(); } catch (URLBuilderException e) { throw new OAuthRuntimeException("Error while building url for context: " + defaultContext); } } else if (StringUtils.isNotBlank(oauth2EndpointURLInFile)) { // Use the value configured in the file. return oauth2EndpointURLInFile; } // Use the default context. try { return ServiceURLBuilder.create().addPath(defaultContext).build().getAbsolutePublicURL(); } catch (URLBuilderException e) { throw new OAuthRuntimeException("Error while building url for context: " + defaultContext); } } private static boolean isNotSuperTenant(String tenantDomain) { return (StringUtils.isNotBlank(tenantDomain) && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)); } public static boolean isOIDCAuthzRequest(Set<String> scope) { return scope.contains(OAuthConstants.Scope.OPENID); } public static boolean isOIDCAuthzRequest(String[] scope) { for (String openidscope : scope) { if (openidscope.equals(OAuthConstants.Scope.OPENID)) { return true; } } return false; } /** * Verifies if the PKCE code verifier is upto specification as per RFC 7636 * * @param codeVerifier PKCE Code Verifier sent with the token request * @return */ public static boolean validatePKCECodeVerifier(String codeVerifier) { Matcher pkceCodeVerifierMatcher = pkceCodeVerifierPattern.matcher(codeVerifier); if (!pkceCodeVerifierMatcher.matches() || (codeVerifier.length() < 43 || codeVerifier.length() > 128)) { return false; } return true; } /** * Verifies if the codeChallenge is upto specification as per RFC 7636 * * @param codeChallenge * @param codeChallengeMethod * @return */ public static boolean validatePKCECodeChallenge(String codeChallenge, String codeChallengeMethod) { if (codeChallengeMethod == null || OAuthConstants.OAUTH_PKCE_PLAIN_CHALLENGE.equals(codeChallengeMethod)) { return validatePKCECodeVerifier(codeChallenge); } else if (OAuthConstants.OAUTH_PKCE_S256_CHALLENGE.equals(codeChallengeMethod)) { // SHA256 code challenge is 256 bits that is 256 / 6 ~= 43 // See https://tools.ietf.org/html/rfc7636#section-3 if (codeChallenge != null && codeChallenge.trim().length() == 43) { return true; } } //provided code challenge method is wrong return false; } @Deprecated public static boolean doPKCEValidation(String referenceCodeChallenge, String codeVerifier, String challengeMethod, OAuthAppDO oAuthAppDO) throws IdentityOAuth2Exception { return validatePKCE(referenceCodeChallenge, codeVerifier, challengeMethod, oAuthAppDO); } public static boolean validatePKCE(String referenceCodeChallenge, String verificationCode, String challengeMethod, OAuthAppDO oAuthApp) throws IdentityOAuth2Exception { if (oAuthApp != null && oAuthApp.isPkceMandatory() || referenceCodeChallenge != null) { Map<String, Object> params = null; if (LoggerUtils.isDiagnosticLogsEnabled()) { params = new HashMap<>(); params.put("clientId", oAuthApp.getOauthConsumerKey()); params.put("verificationCode", verificationCode); params.put("codeChallenge", referenceCodeChallenge); params.put("challengeMethod", challengeMethod); } //As per RFC 7636 Fallback to 'plain' if no code_challenge_method parameter is sent if (challengeMethod == null || challengeMethod.trim().length() == 0) { challengeMethod = "plain"; } //if app with no PKCE code verifier arrives if ((verificationCode == null || verificationCode.trim().length() == 0)) { //if pkce is mandatory, throw error if (oAuthApp.isPkceMandatory()) { if (LoggerUtils.isDiagnosticLogsEnabled()) { LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "No PKCE code verifier found. PKCE is mandatory for the application.", "validate-pkce", null); } throw new IdentityOAuth2Exception("No PKCE code verifier found.PKCE is mandatory for this " + "oAuth 2.0 application."); } else { //PKCE is optional, see if the authz code was requested with a PKCE challenge if (referenceCodeChallenge == null || referenceCodeChallenge.trim().length() == 0) { //since no PKCE challenge was provided if (LoggerUtils.isDiagnosticLogsEnabled()) { LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "PKCE challenge is not provided.", "validate-pkce", null); } return true; } else { if (LoggerUtils.isDiagnosticLogsEnabled()) { LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Empty PKCE code_verifier sent. This authorization code requires a PKCE " + "verification to obtain an access token.", "validate-pkce", null); } throw new IdentityOAuth2Exception("Empty PKCE code_verifier sent. This authorization code " + "requires a PKCE verification to obtain an access token."); } } } //verify that the code verifier is upto spec as per RFC 7636 if (!validatePKCECodeVerifier(verificationCode)) { if (LoggerUtils.isDiagnosticLogsEnabled()) { LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Code verifier used is not up to RFC 7636 specifications.", "validate-pkce", null); } throw new IdentityOAuth2Exception("Code verifier used is not up to RFC 7636 specifications."); } if (OAuthConstants.OAUTH_PKCE_PLAIN_CHALLENGE.equals(challengeMethod)) { //if the current application explicitly doesn't support plain, throw exception if (!oAuthApp.isPkceSupportPlain()) { if (LoggerUtils.isDiagnosticLogsEnabled()) { LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "This application does not allow 'plain' transformation algorithm.", "validate-pkce", null); } throw new IdentityOAuth2Exception( "This application does not allow 'plain' transformation algorithm."); } if (!referenceCodeChallenge.equals(verificationCode)) { if (LoggerUtils.isDiagnosticLogsEnabled()) { LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Reference code challenge does not match with verification code.", "validate-pkce", null); } return false; } } else if (OAuthConstants.OAUTH_PKCE_S256_CHALLENGE.equals(challengeMethod)) { try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte[] hash = messageDigest.digest(verificationCode.getBytes(StandardCharsets.US_ASCII)); //Trim the base64 string to remove trailing CR LF characters. String referencePKCECodeChallenge = new String(Base64.encodeBase64URLSafe(hash), StandardCharsets.UTF_8).trim(); if (!referencePKCECodeChallenge.equals(referenceCodeChallenge)) { if (LoggerUtils.isDiagnosticLogsEnabled()) { LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Reference code challenge does not match with verification code.", "validate-pkce", null); } return false; } } catch (NoSuchAlgorithmException e) { if (log.isDebugEnabled()) { log.debug("Failed to create SHA256 Message Digest."); } if (LoggerUtils.isDiagnosticLogsEnabled()) { LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "System error occurred.", "validate-pkce", null); } return false; } } else { //Invalid OAuth2 token response if (LoggerUtils.isDiagnosticLogsEnabled()) { LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Invalid PKCE Code Challenge Method.", "validate-pkce", null); } throw new IdentityOAuth2Exception("Invalid OAuth2 Token Response. Invalid PKCE Code Challenge Method '" + challengeMethod + "'"); } } //pkce validation successful LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.SUCCESS, "PKCE validation is successful for the token request.", "validate-pkce", null); return true; } @Deprecated public static boolean isPKCESupportEnabled() { return OAuth2ServiceComponentHolder.isPkceEnabled(); } /** * To check whether the given response type is for Implicit flow. * * @param responseType response type * @return true if the response type is for Implicit flow */ public static boolean isImplicitResponseType(String responseType) { return (StringUtils.isNotBlank(responseType) && (OAuthConstants.ID_TOKEN).equals(responseType) || (OAuthConstants.TOKEN).equals(responseType) || (OAuthConstants.IDTOKEN_TOKEN).equals(responseType)); } /** * To check whether the given response type is for Hybrid flow. * * @param responseType response type * @return true if the response type is for Hybrid flow. */ public static boolean isHybridResponseType(String responseType) { return (StringUtils.isNotBlank(responseType) && (OAuthConstants.CODE_TOKEN).equals(responseType) || (OAuthConstants.CODE_IDTOKEN).equals(responseType) || (OAuthConstants.CODE_IDTOKEN_TOKEN).equals (responseType)); } /** * To populate the database in the very first server startup. * * @param tenantId tenant id */ public static void initiateOIDCScopes(int tenantId) { List<ScopeDTO> scopeClaimsList = OAuth2ServiceComponentHolder.getInstance().getOIDCScopesClaims(); try { OAuthTokenPersistenceFactory.getInstance().getScopeClaimMappingDAO().initScopeClaimMapping(tenantId, scopeClaimsList); } catch (IdentityOAuth2ClientException e) { if (log.isDebugEnabled()) { log.debug(e.getMessage(), e); } } catch (IdentityOAuth2Exception e) { log.error(e.getMessage(), e); } } public static List<String> getOIDCScopes(String tenantDomain) { List<String> scopes = new ArrayList<>(); try { int tenantId = OAuthComponentServiceHolder.getInstance().getRealmService().getTenantManager() .getTenantId(tenantDomain); // Get the scopes from the cache or the db List<ScopeDTO> scopesDTOList = OAuthTokenPersistenceFactory.getInstance().getScopeClaimMappingDAO(). getScopes(tenantId); if (CollectionUtils.isNotEmpty(scopesDTOList)) { for (ScopeDTO scope : scopesDTOList) { scopes.add(scope.getName()); } } } catch (UserStoreException | IdentityOAuth2Exception e) { log.error("Error while retrieving OIDC scopes.", e); } return scopes; } public static AccessTokenDO getAccessTokenDOfromTokenIdentifier(String accessTokenIdentifier) throws IdentityOAuth2Exception { return getAccessTokenDOFromTokenIdentifier(accessTokenIdentifier, false); } public static AccessTokenDO getAccessTokenDOFromTokenIdentifier(String accessTokenIdentifier, boolean includeExpired) throws IdentityOAuth2Exception { boolean cacheHit = false; AccessTokenDO accessTokenDO = null; // As the server implementation knows about the PersistenceProcessor Processed Access Token, // we are converting before adding to the cache. String processedToken = getPersistenceProcessor().getProcessedAccessTokenIdentifier(accessTokenIdentifier); // check the cache, if caching is enabled. OAuthCacheKey cacheKey = new OAuthCacheKey(accessTokenIdentifier); CacheEntry result = OAuthCache.getInstance().getValueFromCache(cacheKey); // cache hit, do the type check. if (result != null && result instanceof AccessTokenDO) { accessTokenDO = (AccessTokenDO) result; cacheHit = true; if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Hit OAuthCache for accessTokenIdentifier: " + accessTokenIdentifier); } else { if (log.isDebugEnabled()) { log.debug("Hit OAuthCache with accessTokenIdentifier"); } } } // cache miss, load the access token info from the database. if (accessTokenDO == null) { accessTokenDO = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO() .getAccessToken(accessTokenIdentifier, includeExpired); } else { if (log.isDebugEnabled()) { log.debug("Retrieved active access token from OAuthCache for token Identifier: " + accessTokenDO.getTokenId()); } } if (accessTokenDO == null) { // this means the token is not active so we can't proceed further throw new IllegalArgumentException(ACCESS_TOKEN_IS_NOT_ACTIVE_ERROR_MESSAGE); } // Add the token back to the cache in the case of a cache miss but don't add to cache when OAuth2 token // hashing feature enabled inorder to reduce the complexity. if (!cacheHit & OAuth2Util.isHashDisabled()) { OAuthCache.getInstance().addToCache(cacheKey, accessTokenDO); if (log.isDebugEnabled()) { log.debug("Access Token Info object was added back to the cache."); } } return accessTokenDO; } public static String getClientIdForAccessToken(String accessTokenIdentifier) throws IdentityOAuth2Exception { AccessTokenDO accessTokenDO = getAccessTokenDOfromTokenIdentifier(accessTokenIdentifier); return accessTokenDO.getConsumerKey(); } /*** * Read the configuration file at server start up. * @param tenantId * @deprecated due to UI implementation. */ @Deprecated public static void initTokenExpiryTimesOfSps(int tenantId) { try { Registry registry = OAuth2ServiceComponentHolder.getRegistryService().getConfigSystemRegistry(tenantId); if (!registry.resourceExists(OAuthConstants.TOKEN_EXPIRE_TIME_RESOURCE_PATH)) { Resource resource = registry.newResource(); registry.put(OAuthConstants.TOKEN_EXPIRE_TIME_RESOURCE_PATH, resource); } } catch (RegistryException e) { log.error("Error while creating registry collection for :" + OAuthConstants.TOKEN_EXPIRE_TIME_RESOURCE_PATH, e); } } /*** * Return the SP-token Expiry time configuration object when consumer key is given. * @param consumerKey * @param tenantId * @return A SpOAuth2ExpiryTimeConfiguration Object * @deprecated due to UI implementation */ @Deprecated public static SpOAuth2ExpiryTimeConfiguration getSpTokenExpiryTimeConfig(String consumerKey, int tenantId) { SpOAuth2ExpiryTimeConfiguration spTokenTimeObject = new SpOAuth2ExpiryTimeConfiguration(); try { if (log.isDebugEnabled()) { log.debug("SP wise token expiry time feature is applied for tenant id : " + tenantId + "and consumer key : " + consumerKey); } IdentityTenantUtil.initializeRegistry(tenantId, getTenantDomain(tenantId)); Registry registry = IdentityTenantUtil.getConfigRegistry(tenantId); if (registry.resourceExists(OAuthConstants.TOKEN_EXPIRE_TIME_RESOURCE_PATH)) { Resource resource = registry.get(OAuthConstants.TOKEN_EXPIRE_TIME_RESOURCE_PATH); String jsonString = "{}"; Object consumerKeyObject = resource.getProperties().get(consumerKey); if (consumerKeyObject instanceof List) { if (!((List) consumerKeyObject).isEmpty()) { jsonString = ((List) consumerKeyObject).get(0).toString(); } } JSONObject spTimeObject = new JSONObject(jsonString); if (spTimeObject.length() > 0) { if (spTimeObject.has(USER_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS) && !spTimeObject.isNull(USER_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS)) { try { spTokenTimeObject.setUserAccessTokenExpiryTime(Long.parseLong(spTimeObject .get(USER_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS).toString())); if (log.isDebugEnabled()) { log.debug("The user access token expiry time :" + spTimeObject .get(USER_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS).toString() + " for application id : " + consumerKey); } } catch (NumberFormatException e) { String errorMsg = String.format( "Invalid value provided as user access token expiry time for consumer " + "key %s, tenant id : %d. Given value: %s, Expected a long value", consumerKey, tenantId, spTimeObject.get(USER_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS).toString()); log.error(errorMsg, e); } } else { spTokenTimeObject.setUserAccessTokenExpiryTime(OAuthServerConfiguration.getInstance() .getUserAccessTokenValidityPeriodInSeconds() * 1000); } if (spTimeObject.has(APPLICATION_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS) && !spTimeObject.isNull(APPLICATION_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS)) { try { spTokenTimeObject.setApplicationAccessTokenExpiryTime(Long.parseLong(spTimeObject .get(APPLICATION_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS).toString())); if (log.isDebugEnabled()) { log.debug("The application access token expiry time :" + spTimeObject .get(APPLICATION_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS).toString() + " for application id : " + consumerKey); } } catch (NumberFormatException e) { String errorMsg = String.format( "Invalid value provided as application access token expiry time for consumer " + "key %s, tenant id : %d. Given value: %s, Expected a long value ", consumerKey, tenantId, spTimeObject.get(APPLICATION_ACCESS_TOKEN_EXP_TIME_IN_MILLISECONDS).toString()); log.error(errorMsg, e); } } else { spTokenTimeObject.setApplicationAccessTokenExpiryTime(OAuthServerConfiguration.getInstance() .getApplicationAccessTokenValidityPeriodInSeconds() * 1000); } if (spTimeObject.has(REFRESH_TOKEN_EXP_TIME_IN_MILLISECONDS) && !spTimeObject.isNull(REFRESH_TOKEN_EXP_TIME_IN_MILLISECONDS)) { try { spTokenTimeObject.setRefreshTokenExpiryTime(Long.parseLong(spTimeObject .get(REFRESH_TOKEN_EXP_TIME_IN_MILLISECONDS).toString())); if (log.isDebugEnabled()) { log.debug("The refresh token expiry time :" + spTimeObject .get(REFRESH_TOKEN_EXP_TIME_IN_MILLISECONDS).toString() + " for application id : " + consumerKey); } } catch (NumberFormatException e) { String errorMsg = String.format( "Invalid value provided as refresh token expiry time for consumer key %s, tenant " + "id : %d. Given value: %s, Expected a long value", consumerKey, tenantId, spTimeObject.get(REFRESH_TOKEN_EXP_TIME_IN_MILLISECONDS).toString()); log.error(errorMsg, e); } } else { spTokenTimeObject.setRefreshTokenExpiryTime(OAuthServerConfiguration.getInstance() .getRefreshTokenValidityPeriodInSeconds() * 1000); } } } } catch (RegistryException e) { log.error("Error while getting data from the registry.", e); } catch (IdentityException e) { log.error("Error while getting the tenant domain from tenant id : " + tenantId, e); } return spTokenTimeObject; } /** * Retrieve audience configured for the particular service provider. * * @param clientId * @param oAuthAppDO * @return */ public static List<String> getOIDCAudience(String clientId, OAuthAppDO oAuthAppDO) { List<String> oidcAudiences = getDefinedCustomOIDCAudiences(oAuthAppDO); // Need to add client_id as an audience value according to the spec. if (!oidcAudiences.contains(clientId)) { oidcAudiences.add(0, clientId); } else { Collections.swap(oidcAudiences, oidcAudiences.indexOf(clientId), 0); } return oidcAudiences; } private static List<String> getDefinedCustomOIDCAudiences(OAuthAppDO oAuthAppDO) { List<String> audiences = new ArrayList<>(); // Priority should be given to service provider specific audiences over globally configured ones. if (OAuth2ServiceComponentHolder.isAudienceEnabled()) { audiences = getAudienceListFromOAuthAppDO(oAuthAppDO); if (CollectionUtils.isNotEmpty(audiences)) { if (log.isDebugEnabled()) { log.debug("OIDC Audiences " + audiences + " had been retrieved for the client_id: " + oAuthAppDO.getOauthConsumerKey()); } return audiences; } } IdentityConfigParser configParser = IdentityConfigParser.getInstance(); OMElement oauthElem = configParser.getConfigElement(CONFIG_ELEM_OAUTH); if (oauthElem == null) { log.warn("Error in OAuth Configuration: <OAuth> configuration element is not available in identity.xml."); return audiences; } OMElement oidcConfig = oauthElem.getFirstChildWithName(new QName(IdentityCoreConstants. IDENTITY_DEFAULT_NAMESPACE, OPENID_CONNECT)); if (oidcConfig == null) { log.warn("Error in OAuth Configuration: <OpenIDConnect> element is not available in identity.xml."); return audiences; } OMElement audienceConfig = oidcConfig.getFirstChildWithName(new QName(IdentityCoreConstants. IDENTITY_DEFAULT_NAMESPACE, OPENID_CONNECT_AUDIENCES)); if (audienceConfig == null) { return audiences; } Iterator iterator = audienceConfig.getChildrenWithName(new QName(IdentityCoreConstants. IDENTITY_DEFAULT_NAMESPACE, OPENID_CONNECT_AUDIENCE_IDENTITY_CONFIG)); while (iterator.hasNext()) { OMElement supportedAudience = (OMElement) iterator.next(); String supportedAudienceName; if (supportedAudience != null) { supportedAudienceName = IdentityUtil.fillURLPlaceholders(supportedAudience.getText()); if (StringUtils.isNotBlank(supportedAudienceName)) { audiences.add(supportedAudienceName); } } } return audiences; } private static List<String> getAudienceListFromOAuthAppDO(OAuthAppDO oAuthAppDO) { if (oAuthAppDO.getAudiences() == null) { return new ArrayList<>(); } else { return new ArrayList<>(Arrays.asList(oAuthAppDO.getAudiences())); } } /** * Returns oauth token issuer registered in the service provider app * * @param clientId client id of the oauth app * @return oauth token issuer * @throws IdentityOAuth2Exception * @throws InvalidOAuthClientException */ public static OauthTokenIssuer getOAuthTokenIssuerForOAuthApp(String clientId) throws IdentityOAuth2Exception, InvalidOAuthClientException { OAuthAppDO appDO; try { appDO = getAppInformationByClientId(clientId); } catch (IdentityOAuth2Exception e) { throw new IdentityOAuth2Exception("Error while retrieving app information for clientId: " + clientId, e); } return getOAuthTokenIssuerForOAuthApp(appDO); } /** * Returns oauth token issuer registered in the service provider app. * * @param appDO oauth app data object * @return oauth token issuer * @throws IdentityOAuth2Exception * @throws InvalidOAuthClientException */ public static OauthTokenIssuer getOAuthTokenIssuerForOAuthApp(OAuthAppDO appDO) throws IdentityOAuth2Exception { OauthTokenIssuer oauthIdentityTokenGenerator; if (appDO.getTokenType() != null) { oauthIdentityTokenGenerator = OAuthServerConfiguration.getInstance() .addAndReturnTokenIssuerInstance(appDO.getTokenType()); if (oauthIdentityTokenGenerator == null) { //get server level configured token issuer oauthIdentityTokenGenerator = OAuthServerConfiguration.getInstance().getIdentityOauthTokenIssuer(); } } else { oauthIdentityTokenGenerator = OAuthServerConfiguration.getInstance().getIdentityOauthTokenIssuer(); if (log.isDebugEnabled()) { log.debug("Token type is not set for service provider app with client Id: " + appDO.getOauthConsumerKey() + ". Hence the default Identity OAuth token issuer will be used. " + "No custom token generator is set."); } } return oauthIdentityTokenGenerator; } /** * Get Oauth application information * * @param clientId * @return Oauth app information * @throws IdentityOAuth2Exception * @throws InvalidOAuthClientException */ public static OAuthAppDO getAppInformationByClientId(String clientId) throws IdentityOAuth2Exception, InvalidOAuthClientException { OAuthAppDO oAuthAppDO = AppInfoCache.getInstance().getValueFromCache(clientId); if (oAuthAppDO != null) { return oAuthAppDO; } else { oAuthAppDO = new OAuthAppDAO().getAppInformation(clientId); if (oAuthAppDO != null) { AppInfoCache.getInstance().addToCache(clientId, oAuthAppDO); } return oAuthAppDO; } } /** * Get the tenant domain of an oauth application * * @param oAuthAppDO * @return */ public static String getTenantDomainOfOauthApp(OAuthAppDO oAuthAppDO) { String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; if (oAuthAppDO != null && oAuthAppDO.getUser() != null) { tenantDomain = oAuthAppDO.getUser().getTenantDomain(); } return tenantDomain; } /** * This is used to get the tenant domain of an application by clientId. * * @param clientId Consumer key of Application * @return Tenant Domain * @throws IdentityOAuth2Exception * @throws InvalidOAuthClientException */ public static String getTenantDomainOfOauthApp(String clientId) throws IdentityOAuth2Exception, InvalidOAuthClientException { OAuthAppDO oAuthAppDO = getAppInformationByClientId(clientId); return getTenantDomainOfOauthApp(oAuthAppDO); } /** * Get the client secret of the application. * * @param consumerKey Consumer Key provided by the user. * @return Consumer Secret. * @throws IdentityOAuth2Exception Error when loading the application. * @throws InvalidOAuthClientException Error when loading the application. */ public static String getClientSecret(String consumerKey) throws IdentityOAuth2Exception, InvalidOAuthClientException { OAuthAppDO oAuthAppDO = getAppInformationByClientId(consumerKey); if (oAuthAppDO == null) { throw new InvalidOAuthClientException("Unable to retrieve app information for consumer key: " + consumerKey); } return oAuthAppDO.getOauthConsumerSecret(); } /** * This method map signature algorithm define in identity.xml to nimbus * signature algorithm * * @param signatureAlgorithm name of the signature algorithm * @return mapped JWSAlgorithm name * @throws IdentityOAuth2Exception */ @Deprecated public static String mapSignatureAlgorithm(String signatureAlgorithm) throws IdentityOAuth2Exception { return mapSignatureAlgorithmForJWSAlgorithm(signatureAlgorithm).getName(); } /** * This method maps the encryption algorithm name defined in identity.xml to a respective * nimbus encryption algorithm. * * @param encryptionAlgorithm name of the encryption algorithm * @return mapped JWEAlgorithm * @throws IdentityOAuth2Exception */ public static JWEAlgorithm mapEncryptionAlgorithmForJWEAlgorithm(String encryptionAlgorithm) throws IdentityOAuth2Exception { // Parse method in JWEAlgorithm is used to get a JWEAlgorithm object from the algorithm name. JWEAlgorithm jweAlgorithm = JWEAlgorithm.parse(encryptionAlgorithm); // Parse method returns a new JWEAlgorithm with requirement set to null if unknown algorithm name is passed. if (jweAlgorithm.getRequirement() != null) { return jweAlgorithm; } else { throw new IdentityOAuth2Exception("Unsupported Encryption Algorithm: " + encryptionAlgorithm); } } /** * This method maps the encryption method name defined in identity.xml to a respective nimbus * encryption method. * * @param encryptionMethod name of the encryption method * @return mapped EncryptionMethod * @throws IdentityOAuth2Exception */ public static EncryptionMethod mapEncryptionMethodForJWEAlgorithm(String encryptionMethod) throws IdentityOAuth2Exception { // Parse method in EncryptionMethod is used to get a EncryptionMethod object from the method name. EncryptionMethod method = EncryptionMethod.parse(encryptionMethod); // Parse method returns a new EncryptionMethod with requirement set to null if unknown method name is passed. if (method.getRequirement() != null) { return method; } else { log.error("Unsupported Encryption Method in identity.xml"); throw new IdentityOAuth2Exception("Unsupported Encryption Method: " + encryptionMethod); } } /** * This method map signature algorithm define in identity.xml to nimbus * signature algorithm * * @param signatureAlgorithm name of the signature algorithm * @return mapped JWSAlgorithm * @throws IdentityOAuth2Exception */ public static JWSAlgorithm mapSignatureAlgorithmForJWSAlgorithm(String signatureAlgorithm) throws IdentityOAuth2Exception { if (NONE.equalsIgnoreCase(signatureAlgorithm)) { return new JWSAlgorithm(JWSAlgorithm.NONE.getName()); } else if (SHA256_WITH_RSA.equals(signatureAlgorithm)) { return JWSAlgorithm.RS256; } else if (SHA384_WITH_RSA.equals(signatureAlgorithm)) { return JWSAlgorithm.RS384; } else if (SHA512_WITH_RSA.equals(signatureAlgorithm)) { return JWSAlgorithm.RS512; } else if (SHA256_WITH_HMAC.equals(signatureAlgorithm)) { return JWSAlgorithm.HS256; } else if (SHA384_WITH_HMAC.equals(signatureAlgorithm)) { return JWSAlgorithm.HS384; } else if (SHA512_WITH_HMAC.equals(signatureAlgorithm)) { return JWSAlgorithm.HS512; } else if (SHA256_WITH_EC.equals(signatureAlgorithm)) { return JWSAlgorithm.ES256; } else if (SHA384_WITH_EC.equals(signatureAlgorithm)) { return JWSAlgorithm.ES384; } else if (SHA512_WITH_EC.equals(signatureAlgorithm)) { return JWSAlgorithm.ES512; } else if (SHA256_WITH_PS.equals(signatureAlgorithm) || PS256.equals(signatureAlgorithm)) { return JWSAlgorithm.PS256; } else { log.error("Unsupported Signature Algorithm in identity.xml"); throw new IdentityOAuth2Exception("Unsupported Signature Algorithm in identity.xml"); } } /** * Check if audiences are enabled by reading configuration file at server startup. * * @return */ public static boolean checkAudienceEnabled() { boolean isAudienceEnabled = false; IdentityConfigParser configParser = IdentityConfigParser.getInstance(); OMElement oauthElem = configParser.getConfigElement(CONFIG_ELEM_OAUTH); if (oauthElem == null) { log.warn("Error in OAuth Configuration. OAuth element is not available."); return isAudienceEnabled; } OMElement configOpenIDConnect = oauthElem .getFirstChildWithName(new QName(IdentityCoreConstants.IDENTITY_DEFAULT_NAMESPACE, OPENID_CONNECT)); if (configOpenIDConnect == null) { log.warn("Error in OAuth Configuration. OpenID element is not available."); return isAudienceEnabled; } OMElement configAudience = configOpenIDConnect.getFirstChildWithName( new QName(IdentityCoreConstants.IDENTITY_DEFAULT_NAMESPACE, ENABLE_OPENID_CONNECT_AUDIENCES)); if (configAudience != null) { String configAudienceValue = configAudience.getText(); if (StringUtils.isNotBlank(configAudienceValue)) { isAudienceEnabled = Boolean.parseBoolean(configAudienceValue); } } return isAudienceEnabled; } /** * Generate the unique user domain value in the format of "FEDERATED:idp_name". * * @param authenticatedIDP : Name of the IDP, which authenticated the user. * @return */ public static String getFederatedUserDomain(String authenticatedIDP) { if (IdentityUtil.isNotBlank(authenticatedIDP)) { return OAuthConstants.UserType.FEDERATED_USER_DOMAIN_PREFIX + OAuthConstants.UserType.FEDERATED_USER_DOMAIN_SEPARATOR + authenticatedIDP; } else { return OAuthConstants.UserType.FEDERATED_USER_DOMAIN_PREFIX; } } /** * Validate Id token signature * * @param idToken Id token * @return validation state */ public static boolean validateIdToken(String idToken) { boolean isJWTSignedWithSPKey = OAuthServerConfiguration.getInstance().isJWTSignedWithSPKey(); String tenantDomain; try { String clientId = SignedJWT.parse(idToken).getJWTClaimsSet().getAudience().get(0); if (isJWTSignedWithSPKey) { OAuthAppDO oAuthAppDO = OAuth2Util.getAppInformationByClientId(clientId); tenantDomain = OAuth2Util.getTenantDomainOfOauthApp(oAuthAppDO); } else { //It is not sending tenant domain with the subject in id_token by default, So to work this as //expected, need to enable the option "Use tenant domain in local subject identifier" in SP config tenantDomain = MultitenantUtils.getTenantDomain(SignedJWT.parse(idToken).getJWTClaimsSet().getSubject()); } if (StringUtils.isEmpty(tenantDomain)) { return false; } int tenantId = IdentityTenantUtil.getTenantId(tenantDomain); RSAPublicKey publicKey; KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId); if (!tenantDomain.equals(org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { String ksName = tenantDomain.trim().replace(".", "-"); String jksName = ksName + ".jks"; publicKey = (RSAPublicKey) keyStoreManager.getKeyStore(jksName).getCertificate(tenantDomain) .getPublicKey(); } else { publicKey = (RSAPublicKey) keyStoreManager.getDefaultPublicKey(); } SignedJWT signedJWT = SignedJWT.parse(idToken); JWSVerifier verifier = new RSASSAVerifier(publicKey); return signedJWT.verify(verifier); } catch (JOSEException | ParseException e) { if (log.isDebugEnabled()) { log.debug("Error occurred while validating id token signature."); } return false; } catch (Exception e) { log.error("Error occurred while validating id token signature."); return false; } } /** * This method maps signature algorithm define in identity.xml to digest algorithms to generate the at_hash * * @param signatureAlgorithm * @return the mapped digest algorithm * @throws IdentityOAuth2Exception */ public static String mapDigestAlgorithm(Algorithm signatureAlgorithm) throws IdentityOAuth2Exception { if (JWSAlgorithm.RS256.equals(signatureAlgorithm) || JWSAlgorithm.HS256.equals(signatureAlgorithm) || JWSAlgorithm.ES256.equals(signatureAlgorithm) || JWSAlgorithm.PS256.equals(signatureAlgorithm)) { return SHA256; } else if (JWSAlgorithm.RS384.equals(signatureAlgorithm) || JWSAlgorithm.HS384.equals(signatureAlgorithm) || JWSAlgorithm.ES384.equals(signatureAlgorithm)) { return SHA384; } else if (JWSAlgorithm.RS512.equals(signatureAlgorithm) || JWSAlgorithm.HS512.equals(signatureAlgorithm) || JWSAlgorithm.ES512.equals(signatureAlgorithm)) { return SHA512; } else { throw new RuntimeException("Provided signature algorithm: " + signatureAlgorithm + " is not supported"); } } /** * This is the generic Encryption function which calls algorithm specific encryption function * depending on the algorithm name. * * @param jwtClaimsSet contains JWT body * @param encryptionAlgorithm JWT encryption algorithm * @param spTenantDomain Service provider tenant domain * @param clientId ID of the client * @return encrypted JWT token * @throws IdentityOAuth2Exception * @deprecated replaced by * {@link #encryptJWT(JWTClaimsSet, JWSAlgorithm, String, JWEAlgorithm, EncryptionMethod, String, String)} */ @Deprecated public static JWT encryptJWT(JWTClaimsSet jwtClaimsSet, JWEAlgorithm encryptionAlgorithm, EncryptionMethod encryptionMethod, String spTenantDomain, String clientId) throws IdentityOAuth2Exception { if (isRSAAlgorithm(encryptionAlgorithm)) { return encryptWithRSA(jwtClaimsSet, encryptionAlgorithm, encryptionMethod, spTenantDomain, clientId); } else { throw new RuntimeException("Provided encryption algorithm: " + encryptionAlgorithm + " is not supported"); } } /** * This is the generic Encryption function which calls algorithm specific encryption function * depending on the algorithm name. * * @param jwtClaimsSet JwtClaimsSet to encrypt * @param signatureAlgorithm Signature algorithm * @param signingTenantDomain Tenant Domain for signing * @param encryptionAlgorithm JWT encryption algorithm * @param spTenantDomain Service provider tenant domain * @param clientId ID of the client * @return encrypted JWT token * @throws IdentityOAuth2Exception */ public static JWT encryptJWT(JWTClaimsSet jwtClaimsSet, JWSAlgorithm signatureAlgorithm, String signingTenantDomain, JWEAlgorithm encryptionAlgorithm, EncryptionMethod encryptionMethod, String spTenantDomain, String clientId) throws IdentityOAuth2Exception { if (isRSAAlgorithm(encryptionAlgorithm)) { if (log.isDebugEnabled()) { log.debug(String.format("Signing JWT before encryption using the algorithm: %s ." , signatureAlgorithm)); } SignedJWT signedJwt = (SignedJWT) OAuth2Util.signJWT(jwtClaimsSet, signatureAlgorithm, signingTenantDomain); return encryptWithRSA(signedJwt, encryptionAlgorithm, encryptionMethod, spTenantDomain, clientId); } else { throw new RuntimeException("Provided encryption algorithm: " + encryptionAlgorithm + " is not supported"); } } /** * Encrypt JWT id token using RSA algorithm. * * @param jwtClaimsSet contains JWT body * @param encryptionAlgorithm JWT signing algorithm * @param spTenantDomain Service provider tenant domain * @param clientId ID of the client * @return encrypted JWT token * @throws IdentityOAuth2Exception * @deprecated replaced by {@link #encryptWithRSA(SignedJWT, JWEAlgorithm, EncryptionMethod, String, String)} */ @Deprecated private static JWT encryptWithRSA(JWTClaimsSet jwtClaimsSet, JWEAlgorithm encryptionAlgorithm, EncryptionMethod encryptionMethod, String spTenantDomain, String clientId) throws IdentityOAuth2Exception { if (StringUtils.isBlank(spTenantDomain)) { spTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; if (log.isDebugEnabled()) { log.debug("Assigned super tenant domain as signing domain when encrypting id token for " + "client_id: " + clientId); } } String jwksUri = getSPJwksUrl(clientId, spTenantDomain); Certificate publicCert; String thumbPrint; if (StringUtils.isBlank(jwksUri)) { if (log.isDebugEnabled()) { log.debug(String.format("Jwks uri is not configured for the service provider associated with " + "client_id: %s. Checking for x509 certificate", clientId)); } publicCert = getX509CertOfOAuthApp(clientId, spTenantDomain); thumbPrint = getThumbPrint(publicCert); } else { if (log.isDebugEnabled()) { log.debug(String.format("Fetching public keys for the client %s from jwks uri %s", clientId, jwksUri)); } publicCert = getPublicCertFromJWKS(jwksUri); thumbPrint = getJwkThumbPrint(publicCert); } Key publicKey = publicCert.getPublicKey(); return encryptWithPublicKey(publicKey, jwtClaimsSet, encryptionAlgorithm, encryptionMethod, spTenantDomain, clientId, thumbPrint); } /** * Encrypt JWT id token using RSA algorithm. * * @param signedJwt contains signed JWT body * @param encryptionAlgorithm JWT signing algorithm * @param spTenantDomain Service provider tenant domain * @param clientId ID of the client * @return encrypted JWT token * @throws IdentityOAuth2Exception */ private static JWT encryptWithRSA(SignedJWT signedJwt, JWEAlgorithm encryptionAlgorithm, EncryptionMethod encryptionMethod, String spTenantDomain, String clientId) throws IdentityOAuth2Exception { try { if (StringUtils.isBlank(spTenantDomain)) { spTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; if (log.isDebugEnabled()) { log.debug(String.format("Assigned super tenant domain as signing domain when encrypting id token " + "for client_id: %s .", clientId)); } } String jwksUri = getSPJwksUrl(clientId, spTenantDomain); if (StringUtils.isBlank(jwksUri)) { if (log.isDebugEnabled()) { log.debug(String.format("Jwks uri is not configured for the service provider associated with " + "client_id: %s , Checking for x509 certificate.", clientId)); } return encryptUsingSPX509Certificate(signedJwt, encryptionAlgorithm, encryptionMethod, spTenantDomain, clientId); } else { if (log.isDebugEnabled()) { log.debug(String.format("Jwks uri is configured for the service provider associated with" + " client %s from jwks uri %s .", clientId, jwksUri)); } return encryptUsingJwksPublicKey(signedJwt, encryptionAlgorithm, encryptionMethod, spTenantDomain, clientId, jwksUri); } } catch (JOSEException | ParseException e) { throw new IdentityOAuth2Exception("Error occurred while encrypting JWT for the client_id: " + clientId + " with the tenant domain: " + spTenantDomain, e); } } /** * Encrypt jwt using service provider's configured X509 certificate * * @param signedJwt contains signed JWT body * @param encryptionAlgorithm JWT signing algorithm * @param encryptionMethod Encryption method * @param spTenantDomain Service provider tenant domain * @param clientId ID of the client * @return * @throws IdentityOAuth2Exception */ private static JWT encryptUsingSPX509Certificate(SignedJWT signedJwt, JWEAlgorithm encryptionAlgorithm, EncryptionMethod encryptionMethod, String spTenantDomain, String clientId) throws IdentityOAuth2Exception { Certificate publicCert = getX509CertOfOAuthApp(clientId, spTenantDomain); if (publicCert == null) { throw new IdentityOAuth2Exception("Error while retrieving X509 cert from oauth app with " + "client_id: " + clientId + " of tenantDomain: " + spTenantDomain); } Key publicKey = publicCert.getPublicKey(); if (publicKey == null) { throw new IdentityOAuth2Exception("Error while retrieving public key from X509 cert of oauth app with " + "client_id: " + clientId + " of tenantDomain: " + spTenantDomain); } String kid = getThumbPrint(publicCert); return encryptWithPublicKey(publicKey, signedJwt, encryptionAlgorithm, encryptionMethod, spTenantDomain, clientId, kid); } /** * Encrypt jwt using publickey fetched from jwks * * @param signedJwt contains signed JWT body * @param encryptionAlgorithm JWT signing algorithm * @param encryptionMethod Encryption method * @param spTenantDomain Service provider tenant domain * @param clientId ID of the client * @param jwksUri jwks url * @return * @throws IdentityOAuth2Exception * @throws JOSEException * @throws ParseException */ private static JWT encryptUsingJwksPublicKey(SignedJWT signedJwt, JWEAlgorithm encryptionAlgorithm, EncryptionMethod encryptionMethod, String spTenantDomain, String clientId, String jwksUri) throws IdentityOAuth2Exception, JOSEException, ParseException { JWK encryptionJwk = getEncryptionJWKFromJWKS(jwksUri, encryptionAlgorithm); Key publicKey = RSAKey.parse(encryptionJwk.toJSONString()).toRSAPublicKey(); String kid = getKidValueFromJwk(encryptionJwk); return encryptWithPublicKey(publicKey, signedJwt, encryptionAlgorithm, encryptionMethod, spTenantDomain, clientId, kid); } /** * Get kid value from the jwk * * @param encryptionJwk Encryption jwk * @return */ private static String getKidValueFromJwk(JWK encryptionJwk) { String kid; Certificate publicCert; if (encryptionJwk.getKeyID() != null) { if (log.isDebugEnabled()) { log.debug(String.format("Kid value is available in jwk %s .", encryptionJwk.getKeyID())); } kid = encryptionJwk.getKeyID(); } else { if (log.isDebugEnabled()) { log.debug("Kid value is not available in jwk, attempting to set x5c thumbprint as kid."); } try { publicCert = getPublicCertFromJWK(encryptionJwk); kid = getJwkThumbPrint(publicCert); } catch (IdentityOAuth2Exception e) { log.error("Failed to set x5c thumbprint as kid value.", e); kid = null; } } return kid; } /** * Get encryption jwk from JWKS list when JWKS Uri is given. * * @param jwksUri - JWKS Uri * @param encryptionAlgorithm encryption algorithm * @return - encryption JWK from the jwks url * @throws IdentityOAuth2Exception - IdentityOAuth2Exception */ private static JWK getEncryptionJWKFromJWKS(String jwksUri, JWEAlgorithm encryptionAlgorithm) throws IdentityOAuth2Exception { if (log.isDebugEnabled()) { log.debug(String.format("Attempting to retrieve encryption jwk from the Jwks uri: %s , algorithm : %s", jwksUri, encryptionAlgorithm)); } try { JWKSet publicKeys = JWKSet.load(new URL(jwksUri)); // Get the first key, use as enc and alg from the list JWKMatcher keyMatcherWithAlgAndEncryptionUse = new JWKMatcher.Builder().algorithm(encryptionAlgorithm).keyUse(KeyUse.ENCRYPTION).build(); List<JWK> jwkList = new JWKSelector(keyMatcherWithAlgAndEncryptionUse).select(publicKeys); if (jwkList.isEmpty()) { // If empty, then get the first key, use as enc from the list JWKMatcher keyMatcherWithEncryptionUse = new JWKMatcher.Builder().keyUse(KeyUse.ENCRYPTION).build(); jwkList = new JWKSelector(keyMatcherWithEncryptionUse).select(publicKeys); if (jwkList.isEmpty()) { // failover defaults to ->, then get the first key, use as sig from the list JWKMatcher keyMatcherWithSignatureUse = new JWKMatcher.Builder().keyUse(KeyUse.SIGNATURE).build(); jwkList = new JWKSelector(keyMatcherWithSignatureUse).select(publicKeys); } } if (jwkList.isEmpty()) { throw new IdentityOAuth2Exception(String.format("Failed to retrieve valid jwk from " + "jwks uri: %s, algorithm : %s ", jwksUri, encryptionAlgorithm)); } else { return jwkList.get(0); } } catch (ParseException | IOException e) { throw new IdentityOAuth2Exception(String.format("Failed to retrieve jwk from jwks uri: %s, algorithm : %s", jwksUri, encryptionAlgorithm), e); } } /** * Get public certificate from JWK * * @param jwk * @return * @throws IdentityOAuth2Exception */ private static X509Certificate getPublicCertFromJWK(JWK jwk) throws IdentityOAuth2Exception { if (log.isDebugEnabled()) { log.debug(String.format("Attempting to retrieve public certificate from the Jwk kid: %s ." , jwk.getKeyID())); } X509Certificate certificate; if (jwk != null && jwk.getParsedX509CertChain() != null) { certificate = jwk.getParsedX509CertChain().get(0); if (log.isDebugEnabled()) { log.debug(String.format("Retrieved the public signing certificate successfully from the " + "jwk : %s .", jwk)); } return certificate; } throw new IdentityOAuth2Exception("Failed to retrieve public certificate from jwk due to null."); } /** * Encrypt the JWT token with with given public key. * * @param publicKey public key used to encrypt * @param jwtClaimsSet contains JWT body * @param encryptionAlgorithm JWT signing algorithm * @param spTenantDomain Service provider tenant domain * @param clientId ID of the client * @param thumbPrint value used as 'kid' * @return encrypted JWT token * @throws IdentityOAuth2Exception * @deprecated replaced by * {@link #encryptWithPublicKey(Key, SignedJWT, JWEAlgorithm, EncryptionMethod, String, String, String)} */ @Deprecated private static JWT encryptWithPublicKey(Key publicKey, JWTClaimsSet jwtClaimsSet, JWEAlgorithm encryptionAlgorithm, EncryptionMethod encryptionMethod, String spTenantDomain, String clientId, String thumbPrint) throws IdentityOAuth2Exception { JWEHeader.Builder headerBuilder = new JWEHeader.Builder(encryptionAlgorithm, encryptionMethod); try { headerBuilder.keyID(thumbPrint); JWEHeader header = headerBuilder.build(); EncryptedJWT encryptedJWT = new EncryptedJWT(header, jwtClaimsSet); if (log.isDebugEnabled()) { log.debug("Encrypting JWT using the algorithm: " + encryptionAlgorithm + ", method: " + encryptionMethod + ", tenant: " + spTenantDomain + " & header: " + header.toString()); } JWEEncrypter encrypter = new RSAEncrypter((RSAPublicKey) publicKey); encryptedJWT.encrypt(encrypter); return encryptedJWT; } catch (JOSEException e) { throw new IdentityOAuth2Exception("Error occurred while encrypting JWT for the client_id: " + clientId + " with the tenant domain: " + spTenantDomain, e); } } /** * Encrypt the JWT token with with given public key. * * @param publicKey public key used to encrypt * @param signedJwt contains signed JWT body * @param encryptionAlgorithm JWT signing algorithm * @param spTenantDomain Service provider tenant domain * @param clientId ID of the client * @param kid value used as 'kid' * @return encrypted JWT token * @throws IdentityOAuth2Exception */ private static JWT encryptWithPublicKey(Key publicKey, SignedJWT signedJwt, JWEAlgorithm encryptionAlgorithm, EncryptionMethod encryptionMethod, String spTenantDomain, String clientId, String kid) throws IdentityOAuth2Exception { JWEHeader.Builder headerBuilder = new JWEHeader.Builder(encryptionAlgorithm, encryptionMethod); try { if (StringUtils.isNotBlank(kid)) { headerBuilder.keyID(kid); } headerBuilder.contentType(JWT); // Required to indicate nested JWT. JWEHeader header = headerBuilder.build(); JWEObject jweObject = new JWEObject(header, new Payload(signedJwt)); // Encrypt with the recipient's public key. jweObject.encrypt(new RSAEncrypter((RSAPublicKey) publicKey)); EncryptedJWT encryptedJWT = EncryptedJWT.parse(jweObject.serialize()); if (log.isDebugEnabled()) { log.debug("Encrypting JWT using the algorithm: " + encryptionAlgorithm + ", method: " + encryptionMethod + ", tenant: " + spTenantDomain + " & header: " + header.toString()); } return encryptedJWT; } catch (JOSEException | ParseException e) { throw new IdentityOAuth2Exception("Error occurred while encrypting JWT for the client_id: " + clientId + " with the tenant domain: " + spTenantDomain, e); } } /** * Create JWSSigner using the server level configurations and return. * * @param privateKey RSA Private key. * @return JWSSigner */ public static JWSSigner createJWSSigner(RSAPrivateKey privateKey) { boolean allowWeakKey = Boolean.parseBoolean(System.getProperty(ALLOW_WEAK_RSA_SIGNER_KEY)); if (allowWeakKey && log.isDebugEnabled()) { log.debug("System flag 'allow_weak_rsa_signer_key' is enabled. So weak keys (key length less than 2048) " + " will be allowed for signing."); } return new RSASSASigner(privateKey, allowWeakKey); } /** * Generic Signing function * * @param jwtClaimsSet contains JWT body * @param signatureAlgorithm JWT signing algorithm * @param tenantDomain tenant domain * @return signed JWT token * @throws IdentityOAuth2Exception */ public static JWT signJWT(JWTClaimsSet jwtClaimsSet, JWSAlgorithm signatureAlgorithm, String tenantDomain) throws IdentityOAuth2Exception { if (JWSAlgorithm.RS256.equals(signatureAlgorithm) || JWSAlgorithm.RS384.equals(signatureAlgorithm) || JWSAlgorithm.RS512.equals(signatureAlgorithm) || JWSAlgorithm.PS256.equals(signatureAlgorithm)) { return signJWTWithRSA(jwtClaimsSet, signatureAlgorithm, tenantDomain); } else if (JWSAlgorithm.HS256.equals(signatureAlgorithm) || JWSAlgorithm.HS384.equals(signatureAlgorithm) || JWSAlgorithm.HS512.equals(signatureAlgorithm)) { // return signWithHMAC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done throw new RuntimeException("Provided signature algorithm: " + signatureAlgorithm + " is not supported"); } else { // return signWithEC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done throw new RuntimeException("Provided signature algorithm: " + signatureAlgorithm + " is not supported"); } } /** * sign JWT token from RSA algorithm * * @param jwtClaimsSet contains JWT body * @param signatureAlgorithm JWT signing algorithm * @param tenantDomain tenant domain * @return signed JWT token * @throws IdentityOAuth2Exception */ //TODO: Can make this private after removing deprecated "signJWTWithRSA" methods in DefaultIDTokenBuilder public static JWT signJWTWithRSA(JWTClaimsSet jwtClaimsSet, JWSAlgorithm signatureAlgorithm, String tenantDomain) throws IdentityOAuth2Exception { try { if (StringUtils.isBlank(tenantDomain)) { tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; if (log.isDebugEnabled()) { log.debug("Assign super tenant domain as signing domain."); } } if (log.isDebugEnabled()) { log.debug("Signing JWT using the algorithm: " + signatureAlgorithm + " & key of the tenant: " + tenantDomain); } int tenantId = IdentityTenantUtil.getTenantId(tenantDomain); Key privateKey = getPrivateKey(tenantDomain, tenantId); JWSSigner signer = OAuth2Util.createJWSSigner((RSAPrivateKey) privateKey); JWSHeader.Builder headerBuilder = new JWSHeader.Builder((JWSAlgorithm) signatureAlgorithm); headerBuilder.keyID(getKID(getCertificate(tenantDomain, tenantId), signatureAlgorithm, tenantDomain)); headerBuilder.x509CertThumbprint(new Base64URL(getThumbPrint(tenantDomain, tenantId))); SignedJWT signedJWT = new SignedJWT(headerBuilder.build(), jwtClaimsSet); signedJWT.sign(signer); return signedJWT; } catch (JOSEException e) { throw new IdentityOAuth2Exception("Error occurred while signing JWT", e); } } public static Key getPrivateKey(String tenantDomain, int tenantId) throws IdentityOAuth2Exception { Key privateKey; if (!(privateKeys.containsKey(tenantId))) { try { IdentityTenantUtil.initializeRegistry(tenantId, tenantDomain); } catch (IdentityException e) { throw new IdentityOAuth2Exception("Error occurred while loading registry for tenant " + tenantDomain, e); } // get tenant's key store manager KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId); if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { // derive key store name String ksName = tenantDomain.trim().replace(".", "-"); String jksName = ksName + ".jks"; // obtain private key privateKey = tenantKSM.getPrivateKey(jksName, tenantDomain); } else { try { privateKey = tenantKSM.getDefaultPrivateKey(); } catch (Exception e) { throw new IdentityOAuth2Exception("Error while obtaining private key for super tenant", e); } } //privateKey will not be null always privateKeys.put(tenantId, privateKey); } else { //privateKey will not be null because containsKey() true says given key is exist and ConcurrentHashMap // does not allow to store null values privateKey = privateKeys.get(tenantId); } return privateKey; } /** * Helper method to add algo into to JWT_HEADER to signature verification. * * @param certThumbprint * @param signatureAlgorithm * @return * */ public static String getKID(String certThumbprint, JWSAlgorithm signatureAlgorithm) { return certThumbprint + "_" + signatureAlgorithm.toString(); } /** * Method to obtain 'kid' value for the signing key to be included the JWT header. * * @param certificate Signing Certificate. * @param signatureAlgorithm relevant signature algorithm. * @return KID value as a String. */ public static String getKID(Certificate certificate, JWSAlgorithm signatureAlgorithm, String tenantDomain) throws IdentityOAuth2Exception { return OAuth2ServiceComponentHolder.getKeyIDProvider().getKeyId(certificate, signatureAlgorithm, tenantDomain); } /** * Helper method to add public certificate to JWT_HEADER to signature verification. * * @param tenantDomain * @param tenantId * @throws IdentityOAuth2Exception */ public static String getThumbPrint(String tenantDomain, int tenantId) throws IdentityOAuth2Exception { try { Certificate certificate = getCertificate(tenantDomain, tenantId); // TODO: maintain a hashmap with tenants' pubkey thumbprints after first initialization return getThumbPrint(certificate); } catch (Exception e) { String error = "Error in obtaining certificate for tenant " + tenantDomain; throw new IdentityOAuth2Exception(error, e); } } /** * Helper method to add public certificate to JWT_HEADER to signature verification. * This creates thumbPrints directly from given certificates * * @param certificate * @param alias * @return * @throws IdentityOAuth2Exception */ public static String getThumbPrint(Certificate certificate, String alias) throws IdentityOAuth2Exception { return getThumbPrint(certificate); } /** * Method to obtain certificate thumbprint. * * @param certificate java.security.cert type certificate. * @return Certificate thumbprint as a String. * @throws IdentityOAuth2Exception When failed to obtain the thumbprint. */ public static String getThumbPrint(Certificate certificate) throws IdentityOAuth2Exception { try { MessageDigest digestValue = MessageDigest.getInstance("SHA-256"); byte[] der = certificate.getEncoded(); digestValue.update(der); byte[] digestInBytes = digestValue.digest(); String publicCertThumbprint = hexify(digestInBytes); String thumbprint = new String(new Base64(0, null, true). encode(publicCertThumbprint.getBytes(Charsets.UTF_8)), Charsets.UTF_8); if (log.isDebugEnabled()) { log.debug(String.format("Thumbprint value: %s calculated for Certificate: %s using algorithm: %s", thumbprint, certificate, digestValue.getAlgorithm())); } return thumbprint; } catch (CertificateEncodingException e) { String error = "Error occurred while encoding thumbPrint from certificate."; throw new IdentityOAuth2Exception(error, e); } catch (NoSuchAlgorithmException e) { String error = "Error in obtaining SHA-256 thumbprint from certificate."; throw new IdentityOAuth2Exception(error, e); } } private static boolean isRSAAlgorithm(JWEAlgorithm algorithm) { return (JWEAlgorithm.RSA_OAEP.equals(algorithm) || JWEAlgorithm.RSA1_5.equals(algorithm) || JWEAlgorithm.RSA_OAEP_256.equals(algorithm)); } /** * Method to obatin Default Signing certificate for the tenant. * * @param tenantDomain Tenant Domain as a String. * @param tenantId Tenan ID as an integer. * @return Default Signing Certificate of the tenant domain. * @throws IdentityOAuth2Exception When failed to obtain the certificate for the requested tenant. */ public static Certificate getCertificate(String tenantDomain, int tenantId) throws IdentityOAuth2Exception { Certificate publicCert = null; if (!(publicCerts.containsKey(tenantId))) { if (log.isDebugEnabled()) { log.debug(String.format("Obtaining certificate for the tenant %s", tenantDomain)); } try { IdentityTenantUtil.initializeRegistry(tenantId, tenantDomain); } catch (IdentityException e) { throw new IdentityOAuth2Exception("Error occurred while loading registry for tenant " + tenantDomain, e); } // get tenant's key store manager KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId); KeyStore keyStore = null; if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { // derive key store name String ksName = tenantDomain.trim().replace(".", "-"); String jksName = ksName + ".jks"; if (log.isDebugEnabled()) { log.debug(String.format("Loading default tenant certificate for tenant : %s from the KeyStore" + " %s", tenantDomain, ksName)); } try { keyStore = tenantKSM.getKeyStore(jksName); publicCert = keyStore.getCertificate(tenantDomain); } catch (KeyStoreException e) { throw new IdentityOAuth2Exception("Error occurred while loading public certificate for tenant: " + tenantDomain, e); } catch (Exception e) { throw new IdentityOAuth2Exception("Error occurred while loading Keystore for tenant: " + tenantDomain, e); } } else { try { publicCert = tenantKSM.getDefaultPrimaryCertificate(); } catch (Exception e) { throw new IdentityOAuth2Exception("Error occurred while loading default public " + "certificate for tenant: " + tenantDomain, e); } } if (publicCert != null) { publicCerts.put(tenantId, publicCert); } } else { publicCert = publicCerts.get(tenantId); } return publicCert; } /** * Helper method to hexify a byte array. * TODO:need to verify the logic * * @param bytes * @return hexadecimal representation */ private static String hexify(byte bytes[]) { char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', +'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; StringBuilder buf = new StringBuilder(bytes.length * 2); for (int i = 0; i < bytes.length; ++i) { buf.append(hexDigits[(bytes[i] & 0xf0) >> 4]); buf.append(hexDigits[bytes[i] & 0x0f]); } return buf.toString(); } /** * Returns essential claims according to claim type: id_token/userinfo . * * @param essentialClaims * @param claimType * @return essential claims list */ public static List<String> getEssentialClaims(String essentialClaims, String claimType) { JSONObject jsonObjectClaims = new JSONObject(essentialClaims); List<String> essentialClaimsList = new ArrayList<>(); if (jsonObjectClaims.toString().contains(claimType)) { JSONObject newJSON = jsonObjectClaims.getJSONObject(claimType); if (newJSON != null) { Iterator<?> keys = newJSON.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (!newJSON.isNull(key)) { String value = newJSON.get(key).toString(); JSONObject jsonObjectValues = new JSONObject(value); Iterator<?> claimKeyValues = jsonObjectValues.keys(); while (claimKeyValues.hasNext()) { String claimKey = (String) claimKeyValues.next(); String claimValue = jsonObjectValues.get(claimKey).toString(); if (Boolean.parseBoolean(claimValue) && claimKey.equals(OAuthConstants.OAuth20Params.ESSENTIAL)) { essentialClaimsList.add(key); } } } } } } return essentialClaimsList; } /** * Returns the domain name convert to upper case if the domain is not not empty, else return primary domain name. * * @param userStoreDomain * @return */ public static String getSanitizedUserStoreDomain(String userStoreDomain) { if (StringUtils.isNotBlank(userStoreDomain)) { userStoreDomain = userStoreDomain.toUpperCase(); } else { userStoreDomain = IdentityUtil.getPrimaryDomainName(); } return userStoreDomain; } /** * Returns the mapped user store domain representation federated users according to the MapFederatedUsersToLocal * configuration in the identity.xml file. * * @param authenticatedUser * @return * @throws IdentityOAuth2Exception */ public static String getUserStoreForFederatedUser(AuthenticatedUser authenticatedUser) throws IdentityOAuth2Exception { if (authenticatedUser == null) { throw new IllegalArgumentException("Authenticated user cannot be null"); } String userStoreDomain = OAuth2Util.getUserStoreDomainFromUserId(authenticatedUser.toString()); if (!OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal() && authenticatedUser. isFederatedUser()) { if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) { // When the IDP_ID column is available it was decided to set the // domain name for federated users to 'FEDERATED'. // This is a system reserved word and users stores cannot be created with this name. userStoreDomain = FrameworkConstants.FEDERATED_IDP_NAME; } else { userStoreDomain = OAuth2Util.getFederatedUserDomain(authenticatedUser.getFederatedIdPName()); } } return userStoreDomain; } /** * Returns Base64 encoded token which have username appended. * * @param authenticatedUser * @param token * @return */ public static String addUsernameToToken(AuthenticatedUser authenticatedUser, String token) { if (authenticatedUser == null) { throw new IllegalArgumentException("Authenticated user cannot be null"); } if (StringUtils.isBlank(token)) { throw new IllegalArgumentException("Token cannot be blank"); } String usernameForToken = authenticatedUser.toString(); if (!OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal() && authenticatedUser.isFederatedUser()) { usernameForToken = OAuth2Util.getFederatedUserDomain(authenticatedUser.getFederatedIdPName()); usernameForToken = usernameForToken + UserCoreConstants.DOMAIN_SEPARATOR + authenticatedUser. getAuthenticatedSubjectIdentifier(); } //use ':' for token & userStoreDomain separation String tokenStrToEncode = token + ":" + usernameForToken; return Base64Utils.encode(tokenStrToEncode.getBytes(Charsets.UTF_8)); } /** * Validates the json provided. * * @param redirectURL redirect url * @return true if a valid json */ public static boolean isValidJson(String redirectURL) { try { new JSONObject(redirectURL); } catch (JSONException ex) { return false; } return true; } /** * This method returns essential:true claims list from the request parameter of OIDC authorization request * * @param claimRequestor claimrequestor is either id_token or userinfo * @param requestedClaimsFromRequestParam claims defined in the value of the request parameter * @return the claim list which have attribute vale essentail :true */ public static List<String> essentialClaimsFromRequestParam(String claimRequestor, Map<String, List<RequestedClaim>> requestedClaimsFromRequestParam) { List<String> essentialClaimsfromRequestParam = new ArrayList<>(); List<RequestedClaim> claimsforClaimRequestor = requestedClaimsFromRequestParam.get(claimRequestor); if (CollectionUtils.isNotEmpty(claimsforClaimRequestor)) { for (RequestedClaim claimforClaimRequestor : claimsforClaimRequestor) { String claim = claimforClaimRequestor.getName(); if (claimforClaimRequestor.isEssential()) { essentialClaimsfromRequestParam.add(claim); } } } return essentialClaimsfromRequestParam; } /* Get authorized user from the {@link AccessTokenDO}. When getting authorized user we also make sure flag to * determine whether the user is federated or not is set. * * @param accessTokenDO accessTokenDO * @return user */ public static AuthenticatedUser getAuthenticatedUser(AccessTokenDO accessTokenDO) { AuthenticatedUser authenticatedUser = null; if (accessTokenDO != null) { authenticatedUser = accessTokenDO.getAuthzUser(); } if (authenticatedUser != null) { authenticatedUser.setFederatedUser(isFederatedUser(authenticatedUser)); } return authenticatedUser; } /** * Determine whether the user represented by {@link AuthenticatedUser} object is a federated user. * * @param authenticatedUser * @return true if user is federated, false otherwise. */ public static boolean isFederatedUser(AuthenticatedUser authenticatedUser) { String userStoreDomain = authenticatedUser.getUserStoreDomain(); // We consider a user federated if the flag for federated user is set or the user store domain contain the // federated user store domain prefix. boolean isExplicitlyFederatedUser = StringUtils.startsWith(userStoreDomain, OAuthConstants.UserType.FEDERATED_USER_DOMAIN_PREFIX) || authenticatedUser.isFederatedUser(); // Flag to make sure federated user is not mapped to local users. boolean isFederatedUserNotMappedToLocalUser = !OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal(); return isExplicitlyFederatedUser && isFederatedUserNotMappedToLocalUser; } /** * Returns the service provider associated with the OAuth clientId. * * @param clientId OAuth2/OIDC Client Identifier * @param tenantDomain * @return * @throws IdentityOAuth2Exception */ public static ServiceProvider getServiceProvider(String clientId, String tenantDomain) throws IdentityOAuth2Exception { ApplicationManagementService applicationMgtService = OAuth2ServiceComponentHolder.getApplicationMgtService(); try { // Get the Service Provider. return applicationMgtService.getServiceProviderByClientId( clientId, IdentityApplicationConstants.OAuth2.NAME, tenantDomain); } catch (IdentityApplicationManagementException e) { throw new IdentityOAuth2Exception("Error while obtaining the service provider for client_id: " + clientId + " of tenantDomain: " + tenantDomain, e); } } /** * Returns the service provider associated with the OAuth clientId. * * @param clientId OAuth2/OIDC Client Identifier * @return * @throws IdentityOAuth2Exception */ public static ServiceProvider getServiceProvider(String clientId) throws IdentityOAuth2Exception { ApplicationManagementService applicationMgtService = OAuth2ServiceComponentHolder.getApplicationMgtService(); String tenantDomain = null; try { tenantDomain = getTenantDomainOfOauthApp(clientId); // Get the Service Provider. return applicationMgtService.getServiceProviderByClientId( clientId, IdentityApplicationConstants.OAuth2.NAME, tenantDomain); } catch (IdentityApplicationManagementException e) { throw new IdentityOAuth2Exception("Error while obtaining the service provider for client_id: " + clientId + " of tenantDomain: " + tenantDomain, e); } catch (InvalidOAuthClientException e) { throw new IdentityOAuth2ClientException("Could not find an existing app for clientId: " + clientId, e); } } /** * Returns the public certificate of the service provider associated with the OAuth consumer app as * an X509 @{@link Certificate} object. * * @param clientId OAuth2/OIDC Client Identifier * @param tenantDomain * @return * @throws IdentityOAuth2Exception */ public static Certificate getX509CertOfOAuthApp(String clientId, String tenantDomain) throws IdentityOAuth2Exception { try { ServiceProvider serviceProvider = OAuth2Util.getServiceProvider(clientId, tenantDomain); // Get the certificate content. String certificateContent = serviceProvider.getCertificateContent(); if (StringUtils.isNotBlank(certificateContent)) { // Build the Certificate object from cert content. return IdentityUtil.convertPEMEncodedContentToCertificate(certificateContent); } else { throw new IdentityOAuth2Exception("Public certificate not configured for Service Provider with " + "client_id: " + clientId + " of tenantDomain: " + tenantDomain); } } catch (CertificateException e) { throw new IdentityOAuth2Exception("Error while building X509 cert of oauth app with client_id: " + clientId + " of tenantDomain: " + tenantDomain, e); } } /** * Return true if the token identifier is a parsable JWT. * * @param tokenIdentifier String JWT token identifier. * @return true for a JWT token. */ public static boolean isParsableJWT(String tokenIdentifier) { if (StringUtils.isBlank(tokenIdentifier)) { return false; } try { JWTParser.parse(tokenIdentifier); return true; } catch (ParseException e) { if (log.isDebugEnabled()) { log.debug("Provided token identifier is not a parsable JWT.", e); } return false; } } /** * Return true if the token identifier is JWT. * * @param tokenIdentifier String JWT token identifier. * @return true for a JWT token. */ public static boolean isJWT(String tokenIdentifier) { // JWT token contains 3 base64 encoded components separated by periods. return StringUtils.countMatches(tokenIdentifier, DOT_SEPARATER) == 2; } /** * Return true if the JWT id token is encrypted. * * @param idToken String JWT ID token. * @return Boolean state of encryption. */ public static boolean isIDTokenEncrypted(String idToken) { // Encrypted ID token contains 5 base64 encoded components separated by periods. return StringUtils.countMatches(idToken, DOT_SEPARATER) == 4; } /** * @deprecated We cannot determine the token issuer this way. Have a look at the * {@link #findAccessToken(String, boolean)} method. */ @Deprecated public static OauthTokenIssuer getTokenIssuer(String accessToken) throws IdentityOAuth2Exception { OauthTokenIssuer oauthTokenIssuer = null; String consumerKey = null; if (isJWT(accessToken) || isIDTokenEncrypted(accessToken)) { oauthTokenIssuer = new JWTTokenIssuer(); } else { try { consumerKey = OAuth2Util.getClientIdForAccessToken(accessToken); if (consumerKey != null) { oauthTokenIssuer = OAuth2Util.getOAuthTokenIssuerForOAuthApp(consumerKey); } } catch (IllegalArgumentException e) { if (log.isDebugEnabled()) { log.debug("Consumer key is not found for token identifier: " + accessToken, e); } } catch (InvalidOAuthClientException e) { throw new IdentityOAuth2Exception( "Error while retrieving oauth issuer for the app with clientId: " + consumerKey, e); } } return oauthTokenIssuer; } /** * Publish event on token generation error. * * @param exception Exception occurred. * @param params Additional parameters. */ public static void triggerOnTokenExceptionListeners(Throwable exception, Map<String, Object> params) { try { OAuthEventInterceptor oAuthEventInterceptorProxy = OAuthComponentServiceHolder.getInstance().getOAuthEventInterceptorProxy(); if (oAuthEventInterceptorProxy != null) { try { oAuthEventInterceptorProxy.onTokenIssueException(exception, params); } catch (IdentityOAuth2Exception e) { log.error("Error while invoking OAuthEventInterceptor for onTokenIssueException", e); } } } catch (Throwable e) { // Catching a throwable as we do no need to interrupt the code flow since these are logging purposes. if (log.isDebugEnabled()) { log.debug("Error occurred while executing oAuthEventInterceptorProxy for onTokenIssueException.", e); } } } /** * Extract information related to the token introspection and publish the event on introspection error. * * @param */ public static void triggerOnIntrospectionExceptionListeners(OAuth2TokenValidationRequestDTO introspectionRequest, OAuth2IntrospectionResponseDTO introspectionResponse) { Map<String, Object> params = new HashMap<>(); params.put("error", introspectionResponse.getError()); try { OAuthEventInterceptor oAuthEventInterceptorProxy = OAuthComponentServiceHolder.getInstance() .getOAuthEventInterceptorProxy(); if (oAuthEventInterceptorProxy != null) { try { oAuthEventInterceptorProxy.onTokenValidationException(introspectionRequest, params); } catch (IdentityOAuth2Exception e) { log.error("Error while invoking OAuthEventInterceptor for onTokenValidationException", e); } } } catch (Throwable e) { // Catching a throwable as we do no need to interrupt the code flow since these are logging purposes. if (log.isDebugEnabled()) { log.debug("Error occurred while executing oAuthEventInterceptorProxy for onTokenValidationException.", e); } } } /** * Get the supported oauth grant types * * @return list of grant types */ public static List<String> getSupportedGrantTypes() { Map<String, AuthorizationGrantHandler> supportedGrantTypesMap = OAuthServerConfiguration.getInstance() .getSupportedGrantTypes(); List<String> supportedGrantTypes = new ArrayList<>(); if (supportedGrantTypesMap != null && !supportedGrantTypesMap.isEmpty()) { supportedGrantTypes = supportedGrantTypesMap.keySet().stream().collect(Collectors.toList()); } return supportedGrantTypes; } /** * Get the supported client authentication methods * * @return list of client authentication methods */ public static List<String> getSupportedClientAuthenticationMethods() { List<String> clientAuthenticationMethods = new ArrayList<>(); clientAuthenticationMethods.add(CLIENT_SECRET_BASIC); clientAuthenticationMethods.add(CLIENT_SECRET_POST); return clientAuthenticationMethods; } /** * Get the supported code challenge methods. * * @return list of code challenge methods. */ public static List<String> getSupportedCodeChallengeMethods() { List<String> codeChallengeMethods = new ArrayList<>(); codeChallengeMethods.add(OAuthConstants.OAUTH_PKCE_S256_CHALLENGE); codeChallengeMethods.add(OAuthConstants.OAUTH_PKCE_PLAIN_CHALLENGE); return codeChallengeMethods; } /** * Get the supported response modes. * * @return list of response modes supported. */ public static List<String> getSupportedResponseModes() { List<String> responseModes = new ArrayList<>(); responseModes.add(QUERY_RESPONSE_MODE); responseModes.add(FRAGMENT_RESPONSE_MODE); responseModes.add(FORM_POST_RESPONSE_MODE); return responseModes; } /** * Get the supported request object signing algorithms * * @return list of algorithms */ public static List<String> getRequestObjectSigningAlgValuesSupported() { List<String> requestObjectSigningAlgValues = new ArrayList<>(); requestObjectSigningAlgValues.add(JWSAlgorithm.RS256.getName()); requestObjectSigningAlgValues.add(JWSAlgorithm.RS384.getName()); requestObjectSigningAlgValues.add(JWSAlgorithm.RS512.getName()); requestObjectSigningAlgValues.add(JWSAlgorithm.PS256.getName()); requestObjectSigningAlgValues.add(JWSAlgorithm.NONE.getName()); return requestObjectSigningAlgValues; } /** * Check whether the request object parameter is supported * * @return true if supported */ public static boolean isRequestParameterSupported() { return Boolean.TRUE; } /** * Check whether the claims parameter is supported * * @return true if supported */ public static boolean isClaimsParameterSupported() { return Boolean.TRUE; } /** * Returns the federated IdP resolved from the given domain. * For a federated user the user store domain is in the format of FEDERATED:{federated-idp-name} * * @param userStoreDomain user store domain to be resolved from * @return federated IdP name if user store domain is of format FEDERATED:{federated-idp-name}. Else returns null. */ public static String getFederatedIdPFromDomain(String userStoreDomain) { if (StringUtils.startsWith(userStoreDomain, OAuthConstants.UserType.FEDERATED_USER_DOMAIN_PREFIX)) { String[] tokens = userStoreDomain.split(OAuthConstants.UserType.FEDERATED_USER_DOMAIN_SEPARATOR); if (tokens.length == 2) { return tokens[1]; } } return null; } /** * Creates an instance on AuthenticatedUser{@link AuthenticatedUser} for the given parameters. * If given user store domain is of format FEDERATED:{federated-idp-name}, the authenticated user instance will * be flagged as a federated user. * * @param username username of the user * @param userStoreDomain user store domain * @param tenantDomain tenent domain * @return an instance of AuthenticatedUser{@link AuthenticatedUser} * @deprecated use {@link #createAuthenticatedUser(String, String, String, String)} instead. */ @Deprecated public static AuthenticatedUser createAuthenticatedUser(String username, String userStoreDomain, String tenantDomain) { AuthenticatedUser authenticatedUser = new AuthenticatedUser(); authenticatedUser.setUserName(username); authenticatedUser.setTenantDomain(tenantDomain); if (StringUtils.startsWith(userStoreDomain, OAuthConstants.UserType.FEDERATED_USER_DOMAIN_PREFIX) && !OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal()) { if (log.isDebugEnabled()) { log.debug("Federated prefix found in domain: " + userStoreDomain + " for user: " + username + " in tenant domain: " + tenantDomain + ". Flag user as a federated user."); } authenticatedUser.setFederatedUser(true); authenticatedUser.setFederatedIdPName(OAuth2Util.getFederatedIdPFromDomain(userStoreDomain)); } else { authenticatedUser.setUserStoreDomain(userStoreDomain); } return authenticatedUser; } /** * Creates an instance of AuthenticatedUser{@link AuthenticatedUser} for the given parameters. * * @param username username of the user * @param userStoreDomain user store domain * @param tenantDomain tenent domain * @param idpName idp name * @return an instance of AuthenticatedUser{@link AuthenticatedUser} */ public static AuthenticatedUser createAuthenticatedUser(String username, String userStoreDomain, String tenantDomain, String idpName) { AuthenticatedUser authenticatedUser = new AuthenticatedUser(); authenticatedUser.setUserName(username); authenticatedUser.setTenantDomain(tenantDomain); /* When the IDP_ID column is available it was decided to set the domain name for federated users to 'FEDERATED'. This is a system reserved word and user stores cannot be created with this name. For jwt bearer grant and saml bearer grant types, assertion issuing idp is set as the authenticated idp, but this may not always be the idp user is in; i.e, for an assertion issued by IS, idp name will be 'LOCAL', yet the user could have been authenticated with some external idp. Therefore, we cannot stop setting 'FEDERATED' as the user store domain for federated users.*/ if (StringUtils.startsWith(userStoreDomain, OAuthConstants.UserType.FEDERATED_USER_DOMAIN_PREFIX) && !OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal()) { authenticatedUser.setFederatedUser(true); if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) { authenticatedUser.setFederatedIdPName(idpName); } else { authenticatedUser.setFederatedIdPName(OAuth2Util.getFederatedIdPFromDomain(userStoreDomain)); } authenticatedUser.setUserId(getUserIdOfFederatedUser(username, tenantDomain, idpName)); if (log.isDebugEnabled()) { log.debug("Federated prefix found in domain: " + userStoreDomain + " for user: " + username + " in tenant domain: " + tenantDomain + ". Flag user as a federated user. " + authenticatedUser.getFederatedIdPName() + " is set as the authenticated idp."); } } else { authenticatedUser.setUserStoreDomain(userStoreDomain); authenticatedUser.setFederatedIdPName(idpName); } return authenticatedUser; } /** * Get the user if of the federated user from the user session store. * * @param username Username. * @param tenantDomain Tenant domain. * @param idpName IDP name. * @return User id associated with the given federated user. */ private static String getUserIdOfFederatedUser(String username, String tenantDomain, String idpName) { String userId = null; int tenantId = IdentityTenantUtil.getTenantId(tenantDomain); try { int idpId = UserSessionStore.getInstance().getIdPId(idpName, tenantId); userId = UserSessionStore.getInstance().getFederatedUserId(username, tenantId, idpId); } catch (UserSessionException e) { // In here we better not log the user id. log.error("Error occurred while resolving the user id from the username for the federated user", e); } return userId; } public static String getIdTokenIssuer(String tenantDomain) throws IdentityOAuth2Exception { if (IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) { try { return ServiceURLBuilder.create().addPath(OAUTH2_TOKEN_EP_URL).build().getAbsolutePublicURL(); } catch (URLBuilderException e) { String errorMsg = String.format("Error while building the absolute url of the context: '%s', for the" + " tenant domain: '%s'", OAUTH2_TOKEN_EP_URL, tenantDomain); throw new IdentityOAuth2Exception(errorMsg, e); } } else { return getIssuerLocation(tenantDomain); } } /** * Used to get the issuer url for a given tenant. * * @param tenantDomain Tenant domain. * @return Token issuer url. * @throws IdentityOAuth2Exception IdentityOAuth2Exception. */ public static String getIssuerLocation(String tenantDomain) throws IdentityOAuth2Exception { /* * IMPORTANT: * This method should only honor the given tenant. * Do not add any auto tenant resolving logic. */ if (IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) { try { startTenantFlow(tenantDomain); return ServiceURLBuilder.create().addPath(OAUTH2_TOKEN_EP_URL).build().getAbsolutePublicURL(); } catch (URLBuilderException e) { String errorMsg = String.format("Error while building the absolute url of the context: '%s', for the" + " tenant domain: '%s'", OAUTH2_TOKEN_EP_URL, tenantDomain); throw new IdentityOAuth2Exception(errorMsg, e); } finally { endTenantFlow(); } } else { return getResidentIdpEntityId(tenantDomain); } } /** * Retrieve entity id of the resident identity provider. * * @param tenantDomain tenant domain. * @return idp entity id. * @throws IdentityOAuth2Exception when failed to retrieve the idp entity id. */ public static String getResidentIdpEntityId(String tenantDomain) throws IdentityOAuth2Exception { IdentityProvider identityProvider = getResidentIdp(tenantDomain); FederatedAuthenticatorConfig[] fedAuthnConfigs = identityProvider.getFederatedAuthenticatorConfigs(); // Get OIDC authenticator FederatedAuthenticatorConfig oidcAuthenticatorConfig = IdentityApplicationManagementUtil.getFederatedAuthenticator(fedAuthnConfigs, IdentityApplicationConstants.Authenticator.OIDC.NAME); return IdentityApplicationManagementUtil.getProperty(oidcAuthenticatorConfig.getProperties(), IDP_ENTITY_ID).getValue(); } private static IdentityProvider getResidentIdp(String tenantDomain) throws IdentityOAuth2Exception { try { return IdentityProviderManager.getInstance().getResidentIdP(tenantDomain); } catch (IdentityProviderManagementException e) { String errorMsg = String.format("Error while getting Resident Identity Provider of '%s' tenant.", tenantDomain); throw new IdentityOAuth2Exception(errorMsg, e); } } /** * Used to build an OAuth revocation request DTO. * * @param oAuthClientAuthnContext OAuth client authentication context. * @param accessToken Access token to be revoked. * @return Returns a OAuth revocation request DTO. */ public static OAuthRevocationRequestDTO buildOAuthRevocationRequest(OAuthClientAuthnContext oAuthClientAuthnContext, String accessToken) { OAuthRevocationRequestDTO revocationRequestDTO = new OAuthRevocationRequestDTO(); revocationRequestDTO.setToken(accessToken); revocationRequestDTO.setOauthClientAuthnContext(oAuthClientAuthnContext); revocationRequestDTO.setConsumerKey(oAuthClientAuthnContext.getClientId()); return revocationRequestDTO; } /** * Find access tokenDO from token identifier by chaining through all available token issuers. * * @param tokenIdentifier access token data object from the validation request. * @return AccessTokenDO * @throws IdentityOAuth2Exception */ public static AccessTokenDO findAccessToken(String tokenIdentifier, boolean includeExpired) throws IdentityOAuth2Exception { AccessTokenDO accessTokenDO; // Get a copy of the list of token issuers . Map<String, OauthTokenIssuer> allOAuthTokenIssuerMap = new HashMap<>( OAuthServerConfiguration.getInstance().getOauthTokenIssuerMap()); // Differentiate default token issuers and other issuers for better performance. Map<String, OauthTokenIssuer> defaultOAuthTokenIssuerMap = new HashMap<>(); extractDefaultOauthTokenIssuers(allOAuthTokenIssuerMap, defaultOAuthTokenIssuerMap); // First try default token issuers. accessTokenDO = getAccessTokenDOFromMatchingTokenIssuer(tokenIdentifier, defaultOAuthTokenIssuerMap, includeExpired); if (accessTokenDO != null) { return accessTokenDO; } // Loop through other issuer and try to get the hash. accessTokenDO = getAccessTokenDOFromMatchingTokenIssuer(tokenIdentifier, allOAuthTokenIssuerMap, includeExpired); // If the lookup is only for tokens in 'ACTIVE' state, APIs calling this method expect an // IllegalArgumentException to be thrown to identify inactive/invalid tokens. if (accessTokenDO == null && !includeExpired) { throw new IllegalArgumentException("Invalid Access Token. ACTIVE access token is not found."); } return accessTokenDO; } /** * Loop through provided token issuer list and tries to get the access token DO. * * @param tokenIdentifier Provided token identifier. * @param tokenIssuerMap List of token issuers. * @return Obtained matching access token DO if possible. * @throws IdentityOAuth2Exception */ private static AccessTokenDO getAccessTokenDOFromMatchingTokenIssuer(String tokenIdentifier, Map<String, OauthTokenIssuer> tokenIssuerMap, boolean includeExpired) throws IdentityOAuth2Exception { AccessTokenDO accessTokenDO; if (tokenIssuerMap != null) { for (Map.Entry<String, OauthTokenIssuer> oauthTokenIssuerEntry: tokenIssuerMap.entrySet()) { try { OauthTokenIssuer oauthTokenIssuer = oauthTokenIssuerEntry.getValue(); String tokenAlias = oauthTokenIssuer.getAccessTokenHash(tokenIdentifier); if (oauthTokenIssuer.usePersistedAccessTokenAlias()) { accessTokenDO = OAuth2Util.getAccessTokenDOFromTokenIdentifier(tokenAlias, includeExpired); } else { accessTokenDO = OAuth2Util.getAccessTokenDOFromTokenIdentifier(tokenIdentifier, includeExpired); } if (accessTokenDO != null) { return accessTokenDO; } } catch (OAuthSystemException e) { if (log.isDebugEnabled()) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Token issuer: " + oauthTokenIssuerEntry.getKey() + " was tried and" + " failed to parse the received token: " + tokenIdentifier); } else { log.debug("Token issuer: " + oauthTokenIssuerEntry.getKey() + " was tried and" + " failed to parse the received token."); } } } catch (IllegalArgumentException e) { if (log.isDebugEnabled()) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Token issuer: " + oauthTokenIssuerEntry.getKey() + " was tried and" + " failed to get the token from database: " + tokenIdentifier); } else { log.debug("Token issuer: " + oauthTokenIssuerEntry.getKey() + " was tried and" + " failed to get the token from database."); } } } } } return null; } /** * Differentiate default token issuers from all available token issuers map. * * @param allOAuthTokenIssuerMap Map of all available token issuers. * @param defaultOAuthTokenIssuerMap default token issuers */ private static void extractDefaultOauthTokenIssuers(Map<String, OauthTokenIssuer> allOAuthTokenIssuerMap, Map<String, OauthTokenIssuer> defaultOAuthTokenIssuerMap) { // TODO: 4/9/19 Implement logic to read default issuer from config. // TODO: 4/9/19 add sorting mechanism to use JWT issuer first. defaultOAuthTokenIssuerMap.put(OAuthServerConfiguration.JWT_TOKEN_TYPE, allOAuthTokenIssuerMap.get(OAuthServerConfiguration.JWT_TOKEN_TYPE)); allOAuthTokenIssuerMap.remove(OAuthServerConfiguration.JWT_TOKEN_TYPE); defaultOAuthTokenIssuerMap.put(OAuthServerConfiguration.DEFAULT_TOKEN_TYPE, allOAuthTokenIssuerMap.get(OAuthServerConfiguration.DEFAULT_TOKEN_TYPE)); allOAuthTokenIssuerMap.remove(OAuthServerConfiguration.DEFAULT_TOKEN_TYPE); } /** * Return access token identifier from OAuth2TokenValidationResponseDTO. This method validated the token against * the cache and the DB. * * @param tokenResponse OAuth2TokenValidationResponseDTO object. * @return extracted access token identifier. * @throws UserInfoEndpointException */ public static String getAccessTokenIdentifier(OAuth2TokenValidationResponseDTO tokenResponse) throws UserInfoEndpointException { if (tokenResponse.getAuthorizationContextToken().getTokenString() != null) { AccessTokenDO accessTokenDO = null; try { accessTokenDO = OAuth2Util.findAccessToken( tokenResponse.getAuthorizationContextToken().getTokenString(), false); } catch (IdentityOAuth2Exception e) { throw new UserInfoEndpointException("Error occurred while obtaining access token.", e); } if (accessTokenDO != null) { return accessTokenDO.getAccessToken(); } } return null; } /** * There are cases where we store an 'alias' of the token returned to the client as the token inside IS. * For example, in the case of JWT access tokens we store the 'jti' claim in the database instead of the * actual JWT. Therefore we need to cache an AccessTokenDO with the stored token identifier. * * @param newTokenBean token DO to be added to the cache. */ public static void addTokenDOtoCache(AccessTokenDO newTokenBean) throws IdentityOAuth2Exception { OauthTokenIssuer tokenIssuer = null; try { tokenIssuer = OAuth2Util.getOAuthTokenIssuerForOAuthApp(newTokenBean.getConsumerKey()); String tokenAlias = tokenIssuer.getAccessTokenHash(newTokenBean.getAccessToken()); OAuthCacheKey accessTokenCacheKey = new OAuthCacheKey(tokenAlias); AccessTokenDO tokenDO = AccessTokenDO.clone(newTokenBean); tokenDO.setAccessToken(tokenAlias); OAuthCache.getInstance().addToCache(accessTokenCacheKey, tokenDO); if (log.isDebugEnabled()) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Access token DO was added to OAuthCache with cache key: " + accessTokenCacheKey.getCacheKeyString()); } else { log.debug("Access token DO was added to OAuthCache"); } } } catch (OAuthSystemException e) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { throw new IdentityOAuth2Exception("Error while getting the token alias from token issuer: " + tokenIssuer.toString() + " for the token: " + newTokenBean.getAccessToken(), e); } else { throw new IdentityOAuth2Exception("Error while getting the token alias from token issuer: " + tokenIssuer.toString(), e); } } catch (InvalidOAuthClientException e) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { throw new IdentityOAuth2Exception("Error while getting the token issuer for the token: " + newTokenBean.getAccessToken(), e); } else { throw new IdentityOAuth2Exception("Error while getting the token issuer", e); } } } /** * Used to get the authenticated IDP name from a user. * * @param user Authenticated User. * @return Returns the authenticated IDP name. */ public static String getAuthenticatedIDP(AuthenticatedUser user) { String authenticatedIDP; if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) { if (!OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal() && user.isFederatedUser()) { authenticatedIDP = user.getFederatedIdPName(); if (log.isDebugEnabled()) { log.debug("IDP_ID column is available. User is federated and not mapped to local users. " + "Authenticated IDP is set to:" + authenticatedIDP + " for user:" + user.getLoggableUserId()); } } else { authenticatedIDP = FrameworkConstants.LOCAL_IDP_NAME; if (log.isDebugEnabled()) { log.debug("IDP_ID column is available. Authenticated IDP is set to:" + authenticatedIDP + " for user:" + user.getLoggableUserId()); } } } else { authenticatedIDP = user.getFederatedIdPName(); if (log.isDebugEnabled()) { log.debug("IDP_ID column is not available. Authenticated IDP is set to:" + authenticatedIDP + " for user:" + user.getLoggableUserId()); } } return authenticatedIDP; } /** * Used to get the user store domain name from a user. * * @param user Authenticated User. * @return Returns the sanitized user store domain. */ public static String getUserStoreDomain(AuthenticatedUser user) { String userDomain; if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled() && !OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal() && user.isFederatedUser()) { if (log.isDebugEnabled()) { log.debug("IDP_ID column is available. User is federated and not mapped to local users."); } // When the IDP_ID column is available it was decided to set the // domain name for federated users to 'FEDERATED'. // This is a system reserved word and users stores cannot be created with this name. userDomain = FrameworkConstants.FEDERATED_IDP_NAME; } else if (!OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal() && user.isFederatedUser()) { if (log.isDebugEnabled()) { log.debug("IDP_ID column is not available. User is federated and not mapped to local users."); } userDomain = OAuth2Util.getFederatedUserDomain(user.getFederatedIdPName()); } else { userDomain = user.getUserStoreDomain(); if (log.isDebugEnabled()) { if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) { log.debug("IDP_ID column is available. User is not federated or mapped to local users."); } else { log.debug("IDP_ID column is not available. User is not federated or mapped to local users."); } } } String sanitizedUserDomain = OAuth2Util.getSanitizedUserStoreDomain(userDomain); if (log.isDebugEnabled()) { log.debug("User domain is set to:" + sanitizedUserDomain + " for user:" + user.getLoggableUserId()); } return sanitizedUserDomain; } /** * Check if the IDP_ID column is available in the relevant tables. * * @return True if IDP_ID column is available in all the relevant table. */ public static boolean checkIDPIdColumnAvailable() { boolean isIdpIdAvailableInAuthzCodeTable; boolean isIdpIdAvailableInTokenTable; boolean isIdpIdAvailableInTokenAuditTable; String columnIdpId = "IDP_ID"; isIdpIdAvailableInAuthzCodeTable = FrameworkUtils .isTableColumnExists("IDN_OAUTH2_AUTHORIZATION_CODE", columnIdpId); isIdpIdAvailableInTokenTable = FrameworkUtils .isTableColumnExists("IDN_OAUTH2_ACCESS_TOKEN", columnIdpId); if (OAuthServerConfiguration.getInstance().useRetainOldAccessTokens()) { isIdpIdAvailableInTokenAuditTable = FrameworkUtils .isTableColumnExists("IDN_OAUTH2_ACCESS_TOKEN_AUDIT", columnIdpId); } else { isIdpIdAvailableInTokenAuditTable = true; if (log.isDebugEnabled()) { log.debug("Retaining old access tokens in IDN_OAUTH2_ACCESS_TOKEN_AUDIT is disabled, therefore " + "ignoring the availability of IDP_ID column in IDN_OAUTH2_ACCESS_TOKEN_AUDIT table."); } } return isIdpIdAvailableInAuthzCodeTable && isIdpIdAvailableInTokenTable && isIdpIdAvailableInTokenAuditTable; } /** * Check whether the CONSENTED_TOKEN column is available in IDN_OAUTH2_ACCESS_TOKEN table. * * @return True if the column is available. */ public static boolean checkConsentedTokenColumnAvailable() { return FrameworkUtils.isTableColumnExists("IDN_OAUTH2_ACCESS_TOKEN", "CONSENTED_TOKEN"); } /** * This can be used to load the oauth scope permissions bindings in oauth-scope-bindings.xml file. */ public static void initiateOAuthScopePermissionsBindings(int tenantId) { if (Oauth2ScopeUtils.isSystemLevelInternalSystemScopeManagementEnabled()) { if (log.isDebugEnabled()) { log.debug("OAuth internal scopes permission binding initialization is skipped as the scopes " + "are managed globally."); } return; } try { //Check login scope is available. If exists, assumes all scopes are loaded using the file. if (!hasScopesAlreadyAdded(tenantId)) { List<Scope> scopes = OAuth2ServiceComponentHolder.getInstance().getOauthScopeBinding(); for (Scope scope : scopes) { OAuthTokenPersistenceFactory.getInstance().getOAuthScopeDAO().addScope(scope, tenantId); } if (log.isDebugEnabled()) { log.debug("OAuth scopes are loaded for the tenant : " + tenantId); } } else { if (log.isDebugEnabled()) { log.debug("OAuth scopes are already loaded"); } } } catch (IdentityOAuth2ScopeException e) { log.error("Error while registering OAuth scopes with permissions bindings", e); } } private static boolean hasScopesAlreadyAdded(int tenantId) throws IdentityOAuth2ScopeServerException { Scope loginScope = OAuthTokenPersistenceFactory.getInstance().getOAuthScopeDAO().getScopeByName( INTERNAL_LOGIN_SCOPE, tenantId); if (loginScope == null) { return false; } else { List<ScopeBinding> scopeBindings = loginScope.getScopeBindings(); for (ScopeBinding scopeBinding : scopeBindings) { if (PERMISSIONS_BINDING_TYPE.equalsIgnoreCase(scopeBinding.getBindingType())) { return true; } } } return false; } /** * Check whether required token binding available in the request. * * @param tokenBinding token binding. * @param request http request. * @return true if binding is valid. */ public static boolean isValidTokenBinding(TokenBinding tokenBinding, HttpServletRequest request) { if (request == null || tokenBinding == null || StringUtils.isBlank(tokenBinding.getBindingReference()) || StringUtils.isBlank(tokenBinding.getBindingType())) { return true; } Optional<TokenBinder> tokenBinderOptional = OAuth2ServiceComponentHolder.getInstance() .getTokenBinder(tokenBinding.getBindingType()); if (!tokenBinderOptional.isPresent()) { log.warn("Token binder with type: " + tokenBinding.getBindingType() + " is not available."); return false; } return tokenBinderOptional.get().isValidTokenBinding(request, tokenBinding); } /** * Get public certificate from JWKS when kid and JWKS Uri is given. * * @param jwksUri - JWKS Uri * @return - X509Certificate * @throws IdentityOAuth2Exception - IdentityOAuth2Exception * @deprecated replaced with {@link #getEncryptionJWKFromJWKS(String, JWEAlgorithm)} */ @Deprecated private static X509Certificate getPublicCertFromJWKS(String jwksUri) throws IdentityOAuth2Exception { if (log.isDebugEnabled()) { log.debug(String.format("Attempting to retrieve public certificate from the Jwks uri: %s.", jwksUri)); } try { JWKSet publicKeys = JWKSet.load(new URL(jwksUri)); JWK jwk = null; X509Certificate certificate; //Get the first signing JWK from the list List<JWK> jwkList = publicKeys.getKeys(); for (JWK currentJwk : jwkList) { if (KeyUse.SIGNATURE == currentJwk.getKeyUse()) { jwk = currentJwk; break; } } if (jwk != null) { certificate = jwk.getParsedX509CertChain().get(0); if (log.isDebugEnabled()) { log.debug(String.format("Retrieved the public signing certificate successfully from the " + "jwks uri: %s", jwksUri)); } return certificate; } else { throw new IdentityOAuth2Exception(String.format("Failed to retrieve public certificate from " + "jwks uri: %s", jwksUri)); } } catch (ParseException | IOException e) { throw new IdentityOAuth2Exception(String.format("Failed to retrieve public certificate from " + "jwks uri: %s", jwksUri), e); } } /** * Get Jwks uri of SP when clientId and spTenantDomain is provided. * * @param clientId - ClientId * @param spTenantDomain - Tenant domain * @return Jwks Url * @throws IdentityOAuth2Exception */ public static String getSPJwksUrl(String clientId, String spTenantDomain) throws IdentityOAuth2Exception { ServiceProvider serviceProvider = OAuth2Util.getServiceProvider(clientId, spTenantDomain); String jwksUri = serviceProvider.getJwksUri(); if (StringUtils.isNotBlank(jwksUri)) { if (log.isDebugEnabled()) { log.debug(String.format("Retrieved jwks uri: %s for the service provider associated with client_id: %s", jwksUri, clientId)); } } return jwksUri; } /** * Method to extract the SHA-1 JWK thumbprint from certificates. * * @param certificate x509 certificate * @return String thumbprint * @throws IdentityOAuth2Exception When failed to extract thumbprint */ public static String getJwkThumbPrint(Certificate certificate) throws IdentityOAuth2Exception { if (log.isDebugEnabled()) { log.debug(String.format("Calculating SHA-1 JWK thumb-print for certificate: %s", certificate.toString())); } try { CertificateFactory cf = CertificateFactory.getInstance(Constants.X509); ByteArrayInputStream bais = new ByteArrayInputStream(certificate.getEncoded()); X509Certificate x509 = (X509Certificate) cf.generateCertificate(bais); Base64URL jwkThumbprint = RSAKey.parse(x509).computeThumbprint(Constants.SHA1); String thumbprintString = jwkThumbprint.toString(); if (log.isDebugEnabled()) { log.debug(String.format("Calculated SHA-1 JWK thumbprint %s from the certificate", thumbprintString)); } return thumbprintString; } catch (CertificateException | JOSEException e) { throw new IdentityOAuth2Exception("Error occurred while generating SHA-1 JWK thumbprint", e); } } /** * Validates whether the tenant domain set in context matches with the app's tenant domain in tenant qualified * URL mode. * * @param tenantDomainOfApp Tenant domain of the app. * @throws InvalidOAuthClientException */ public static void validateRequestTenantDomain(String tenantDomainOfApp) throws InvalidOAuthClientException { if (IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) { // In tenant qualified URL mode we would always have the tenant domain in the context. String tenantDomainFromContext = IdentityTenantUtil.getTenantDomainFromContext(); if (!StringUtils.equals(tenantDomainFromContext, tenantDomainOfApp)) { // This means the tenant domain sent in the request and app's tenant domain do not match. if (log.isDebugEnabled()) { log.debug("A valid client with the given client_id cannot be found in " + "tenantDomain: " + tenantDomainFromContext); } throw new InvalidOAuthClientException("no.valid.client.in.tenant"); } } } /** * Validates whether the tenant domain set in context matches with the app's tenant domain in tenant qualified * URL mode. * * @param tenantDomainOfApp Tenant domain of the app. * @param tokenReqDTO Access token request DTO object that contains request parameters. * @throws InvalidOAuthClientException */ public static void validateRequestTenantDomain(String tenantDomainOfApp, OAuth2AccessTokenReqDTO tokenReqDTO) throws InvalidOAuthClientException { if (IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) { Optional<String> contextTenantDomainFromTokenReqDTO = getContextTenantDomainFromTokenReqDTO(tokenReqDTO); String tenantDomainFromContext; if (contextTenantDomainFromTokenReqDTO.isPresent()) { tenantDomainFromContext = contextTenantDomainFromTokenReqDTO.get(); // In tenant qualified URL mode we would always have the tenant domain in the context. if (!StringUtils.equals(tenantDomainFromContext, tenantDomainOfApp)) { // This means the tenant domain sent in the request and app's tenant domain do not match. throw new InvalidOAuthClientException("A valid client with the given client_id cannot be found in " + "tenantDomain: " + tenantDomainFromContext); } } else { validateRequestTenantDomain(tenantDomainOfApp); } } } private static Optional<String> getContextTenantDomainFromTokenReqDTO(OAuth2AccessTokenReqDTO tokenReqDTO) { if (tokenReqDTO == null || tokenReqDTO.getParameters() == null) { return Optional.empty(); } String tenantDomainFromContext = tokenReqDTO.getParameters().get(OAuthConstants.TENANT_DOMAIN_FROM_CONTEXT); if (StringUtils.isNotBlank(tenantDomainFromContext)) { return Optional.of(tenantDomainFromContext); } return Optional.empty(); } private static void startTenantFlow(String tenantDomain) { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(IdentityTenantUtil.getTenantId(tenantDomain)); } private static void endTenantFlow() { PrivilegedCarbonContext.endTenantFlow(); } /** * Determines if the scope is specified in the allowed scopes list. * * @param allowedScopesList Allowed scopes list * @param scope The scope key to check. * @return - 'true' if the scope is allowed. 'false' if not. */ public static boolean isAllowedScope(List<String> allowedScopesList, String scope) { for (String scopeTobeSkipped : allowedScopesList) { if (scope.matches(scopeTobeSkipped)) { if (log.isDebugEnabled()) { log.debug(scope + " is found in the allowed list of scopes."); } return true; } } return false; } /** * Util method to get Identity Provider by name and tenant domain. * * @param identityProviderName Identity provider * @param tenantDomain Tenant domain * @return Identity Provider * @throws IdentityOAuth2Exception If were unable to get Identity provider. */ public static IdentityProvider getIdentityProvider(String identityProviderName, String tenantDomain) throws IdentityOAuth2Exception { try { if (OAuth2ServiceComponentHolder.getInstance().getIdpManager() != null) { return OAuth2ServiceComponentHolder.getInstance().getIdpManager().getIdPByName(identityProviderName, tenantDomain); } else { String errorMsg = String.format("Unable to retrieve Idp manager. Error while " + "getting '%s' Identity Provider of '%s' tenant.", identityProviderName, tenantDomain); throw new IdentityOAuth2Exception(errorMsg); } } catch (IdentityProviderManagementException e) { String errorMsg = String.format("Error while getting '%s' Identity Provider of '%s' tenant.", identityProviderName, tenantDomain); throw new IdentityOAuth2Exception(errorMsg, e); } } /** * Get Internal/everyone role for corresponding user using realm configuration. * * @param user Authenticated user * @return Internal/everyone role * @throws IdentityOAuth2Exception IdentityOAuth2Exception */ public static String getInternalEveryoneRole(AuthenticatedUser user) throws IdentityOAuth2Exception { try { RealmConfiguration realmConfiguration; RealmService realmService = OAuthComponentServiceHolder.getInstance().getRealmService(); int tenantId = getTenantId(user.getTenantDomain()); if (realmService != null && tenantId != org.wso2.carbon.base.MultitenantConstants.INVALID_TENANT_ID) { UserStoreManager userStoreManager; userStoreManager = (UserStoreManager) realmService.getTenantUserRealm(tenantId).getUserStoreManager(); if (userStoreManager != null) { realmConfiguration = userStoreManager.getRealmConfiguration(); return realmConfiguration.getEveryOneRoleName(); } } return null; } catch (UserStoreException e) { String errorMsg = "Error while getting Realm configuration of tenant " + user.getTenantDomain(); throw new IdentityOAuth2Exception(errorMsg, e); } } /** * Get a filtered set of scopes after dropping unregistered scopes. * * @param requestedScopesArr Array of requested scopes. * @param tenantDomain Tenant domain. * @return Filtered set of scopes after dropping unregistered scopes. * @throws IdentityOAuth2Exception IdentityOAuth2Exception */ public static String[] dropUnregisteredScopes(String[] requestedScopesArr, String tenantDomain) throws IdentityOAuth2Exception { if (ArrayUtils.isEmpty(requestedScopesArr)) { if (log.isDebugEnabled()) { log.debug("Scope string is empty. No scopes to check for unregistered scopes."); } return requestedScopesArr; } try { int tenantId = IdentityTenantUtil.getTenantId(tenantDomain); String requestedScopes = StringUtils.join(requestedScopesArr, " "); Set<Scope> registeredScopeSet = OAuthTokenPersistenceFactory.getInstance().getOAuthScopeDAO() .getRequestedScopesOnly(tenantId, true, requestedScopes); List<String> filteredScopes = new ArrayList<>(); registeredScopeSet.forEach(scope -> filteredScopes.add(scope.getName())); if (log.isDebugEnabled()) { log.debug(String.format("Dropping unregistered scopes. Requested scopes: %s | Filtered result: %s", requestedScopes, StringUtils.join(filteredScopes, " "))); } return filteredScopes.toArray(new String[0]); } catch (IdentityOAuth2ScopeServerException e) { throw new IdentityOAuth2Exception("Error occurred while retrieving registered scopes.", e); } } public static String resolveUsernameFromUserId(String tenantDomain, String userId) throws UserStoreException { RealmService realmService = OAuthComponentServiceHolder.getInstance().getRealmService(); int tenantId = realmService.getTenantManager().getTenantId(tenantDomain); AbstractUserStoreManager userStoreManager = (AbstractUserStoreManager) realmService.getTenantUserRealm(tenantId).getUserStoreManager(); return userStoreManager.getUserNameFromUserID(userId); } /** * Resolve tenant domain from the httpServlet request. * * @param request HttpServlet Request. * @return Tenant Domain. */ public static String resolveTenantDomain(HttpServletRequest request) { if (!IdentityTenantUtil.isTenantedSessionsEnabled()) { return MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; } if (request != null) { String tenantDomainFromReq = request.getParameter(FrameworkConstants.RequestParams.LOGIN_TENANT_DOMAIN); if (StringUtils.isNotBlank(tenantDomainFromReq)) { return tenantDomainFromReq; } } return IdentityTenantUtil.getTenantDomainFromContext(); } /** * Get user role list from federated user attributes. * * @param userAttributes User attribute. * @return User role-list. */ public static List<String> getRolesFromFederatedUserAttributes(Map<ClaimMapping, String> userAttributes) { Optional<ClaimMapping> roleClaimMapping = Optional.ofNullable(userAttributes).get().entrySet().stream() .map(entry -> entry.getKey()) .filter(claim -> StringUtils.equals(OIDC_ROLE_CLAIM_URI, claim.getRemoteClaim().getClaimUri())) .findFirst(); if (roleClaimMapping.isPresent()) { return Arrays.asList(userAttributes.get(roleClaimMapping.get()) .split(Pattern.quote(FrameworkUtils.getMultiAttributeSeparator()))); } return Collections.emptyList(); } /** * Check federated role based authorization enabled or not. * * @param requestMsgCtx Token request message context. * @return Role based authz flow enabled or not. * @throws IdentityOAuth2Exception IdentityOAuth2Exception. */ public static boolean isFederatedRoleBasedAuthzEnabled(OAuthTokenReqMessageContext requestMsgCtx) throws IdentityOAuth2Exception { String clientId = requestMsgCtx.getOauth2AccessTokenReqDTO().getClientId(); return isFederatedRoleBasedAuthzEnabled(clientId); } /** * Check federated role based authorization enabled or not. * * @param oauthAuthzMsgCtx OAuth authorization request message context. * @return Role based authz flow enabled or not. * @throws IdentityOAuth2Exception IdentityOAuth2Exception. */ public static boolean isFederatedRoleBasedAuthzEnabled(OAuthAuthzReqMessageContext oauthAuthzMsgCtx) throws IdentityOAuth2Exception { String clientId = oauthAuthzMsgCtx.getAuthorizationReqDTO().getConsumerKey(); return isFederatedRoleBasedAuthzEnabled(clientId); } /** * Check federated role based authorization enabled or not. * * @param clientId Application's client ID. * @return Role based authz flow enabled or not. * @throws IdentityOAuth2Exception IdentityOAuth2Exception. */ public static boolean isFederatedRoleBasedAuthzEnabled(String clientId) throws IdentityOAuth2Exception { List<String> federatedRoleBasedAuthzApps = IdentityUtil.getPropertyAsList(FIDP_ROLE_BASED_AUTHZ_APP_CONFIG); boolean isFederatedRoleBasedAuthzEnabled = false; if (!federatedRoleBasedAuthzApps.isEmpty()) { OAuthAppDO app = null; try { app = getAppInformationByClientId(clientId); } catch (InvalidOAuthClientException e) { if (log.isDebugEnabled()) { log.debug("Error while retrieving the Application Information for client id: " + clientId, e); } throw new IdentityOAuth2Exception(e.getMessage(), e); } String appTenantDomain = getTenantDomainOfOauthApp(app); if (StringUtils.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, appTenantDomain) && federatedRoleBasedAuthzApps.contains(app.getApplicationName())) { isFederatedRoleBasedAuthzEnabled = true; } } return isFederatedRoleBasedAuthzEnabled; } /** * Is carbon role based validation enabled for first level organizations in the deployment. * * @return True if carbon role based validation enabled for first level organizations. */ public static boolean isCarbonRoleValidationEnabledForLevelOneOrgs() { return Boolean.parseBoolean(IdentityUtil.getProperty(IS_CARBON_ROLE_VALIDATION_ENABLED_FOR_LEVEL_ONE_ORGS)); } /** * Return whether organization role based validation is used. * * @param organizationId Organization id. * @return False if the organization is a first level organization in the deployment and * IS_CARBON_ROLE_VALIDATION_ENABLED_FOR_LEVEL_ONE_ORGS config is enabled. Other true. */ public static boolean useOrganizationRolesForValidation(String organizationId) { if (!isCarbonRoleValidationEnabledForLevelOneOrgs()) { return true; } try { // Return true if the organization is in depth 1. return OAuth2ServiceComponentHolder.getOrganizationManagementService() .getOrganizationDepthInHierarchy(organizationId) == 1; } catch (OrganizationManagementServerException e) { log.error("Error while checking the depth of the given organization."); } return true; } }
Update components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/util/OAuth2Util.java Co-authored-by: sadilchamishka <f76b74d2234162f3d08b7e671390eb494cf97d3d@users.noreply.github.com>
components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/util/OAuth2Util.java
Update components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/util/OAuth2Util.java
<ide><path>omponents/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/util/OAuth2Util.java <ide> return true; <ide> } <ide> try { <del> // Return true if the organization is in depth 1. <add> // Return false if the organization is in depth 1. <ide> return OAuth2ServiceComponentHolder.getOrganizationManagementService() <ide> .getOrganizationDepthInHierarchy(organizationId) == 1; <ide> } catch (OrganizationManagementServerException e) {
JavaScript
mit
130c13d9665aaebc8023f9ac58a86713dc2e1ff7
0
PencilCode/pencilcode,PencilCode/pencilcode,cacticouncil/pencilcode,PencilCode/pencilcode,cacticouncil/pencilcode,cacticouncil/pencilcode,cacticouncil/pencilcode,PencilCode/pencilcode
var path = require('path'); var fs = require('fs-ext'); var lb = require('binary-search-bounds').ge; var utils = require('./utils'); // A DirLoader represents a listing of a specific directory. // In Pencil Code, we use it to load directories. // It supports a few actions: // rebuild(callback) - reads the directory on disk (which may take // a sequence of async operations), then update the cache atomically // at the end, calling callback with "true" if successful, "false" // if not. Importantly, if rebuild is requested when a rebuild // is already in progress, it just shares the work and notifies // all callbacks when the single job is done. // update(name, callback) - updates a single entry (with one single // async call to "stat"), then updates that single directory // entry (adding, removing, or reordering it). exports.DirLoader = function DirLoader(path) { this.path = path; // List is sorted by-modification-date (newest first). this.list = []; // Map is indexed by-name. this.map = {}; // Array of callbacks to call if there is a rebuilding going on. this.rebuilding = null; // When was the last rebuild? this.rebuildTime = 0; // How long did it take? this.rebuildMs = 0; // Configuration: do work in 64 parallel async tasks. this.batchSize = 64; // Configuration: give up after 10 miutes this.timeLimit = 10 * 60 * 1000; } // Encode the stat object for a file as a json record to be // returned from our public API. function encodeStat(name, statObj, itempath) { var modestr = ''; if (statObj.isDirectory()) { modestr += 'd'; } if (statObj.mode & 00400) { modestr += 'r'; } if (statObj.mode & 00200) { modestr += 'w'; } if (statObj.mode & 00100) { modestr += 'x'; } var mtime = statObj.mtime.getTime(); var absthumb = utils.makeThumbPath(itempath); return { name: name, thumbnail: fs.existsSync(absthumb), // whether there is a thumbnail mode: modestr, size: statObj.size, mtime: mtime }; } // Predicate to sort by modification-time. If two entries have // the same mtime, they are sorted alphabetically. function byMtime(a, b) { if (a.mtime > b.mtime) { // later first. return -1 } if (a.mtime < b.mtime) { // earlier last. return 1 } if (a.name < b.name) { // a first. return -1; } if (a.name > b.name) { // z last. return 1; } return 0; } exports.DirLoader.prototype = { // Async rebuild. Does the work, then refreshes atomically at the // end, then calls the callback. rebuild: function(callback) { var batch = this.batchSize; var timeLimit = this.timeLimit; // If requested a rebuild while a rebuild is in progress, just // queue up with the rebuild-in-progress. if (this.rebuilding) { if (callback) { this.rebuilding.push(callback); } return; } // We're the first: queue up our callback and note the start time. var self = this; var notify = self.rebuilding = []; if (callback) { notify.push(callback); } var startTime = (new Date).getTime(); // Set up an abort (signalled by timeout === true) after a few minutes. var timeout = setTimeout(function() { timeout = true; notifyAll(false); }, timeLimit); // Kick off an async readdir. fs.readdir(self.path, function(err, names) { // On error, we notify false and finish up. if (err) { clearTimeout(timeout); notifyAll(false); return; } // Set up data structures to receive work in progress. var list = []; var map = {}; var next = 0; var inprogress = 0; var finished = false; // Kick off parallel work tasks. while (inprogress < batch && next < names.length) { loopTask(); } function loopTask() { if (timeout === true) { // When aborted, tasks stop looping. return; } else if (next < names.length) { // If there is still more work, tasks loop via doWork. doWork(names[next++], loopTask); } else if (inprogress == 0) { // If there is no more work, and nothing in progress, we complete. completeWork(); } } // An individual item of work is to stat a single file. function doWork(name, next) { if (name[0] == '.') { // Skip past any dirs starting with a '.' next(); return; } inprogress += 1; var itempath = path.join(self.path, name); fs.stat(itempath, function(err, statobj) { // Errors are treated as non-existent files. if (!err) { // Accumulate the results of the stat into list and map. var result = encodeStat(name, statobj, itempath); list.push(result); map[name] = result; } inprogress -= 1; next(); }); } // When work is done, save it and notify callbacks. function completeWork() { if (!finished) { finished = true; clearTimeout(timeout); list.sort(byMtime); self.list = list; self.map = map; self.rebuildTime = (new Date).getTime(); self.rebuildMs = self.rebuildTime - startTime; notifyAll(true); } } }); function notifyAll(ok) { if (notify && notify === self.rebuilding) { self.rebuilding = null; while (notify.length) { notify.pop().call(null, ok); } } } }, // Get the time since the last rebuildTime. age: function() { return (new Date).getTime() - this.rebuildTime; }, // Synchronous update of a specific name. updateSync: function(name) { var itempath = path.join(this.path, name); var obj = null; try { obj = encodeStat(names[i], fs.statSync(itempath), itempath); } catch (e) { // File is gone: let obj be null. } this.updateObject(name, obj); }, // Async update of a specific name. update: function(name, callback) { var itempath = path.join(this.path, name); var obj = null; var self = this; fs.stat(itempath, function(err, statObj) { if (!err) { obj = encodeStat(name, statObj, itempath); } self.updateObject(name, obj); callback(true); }); }, // Updates the object for 'name' with obj (may be null) updateObject: function(name, obj) { var oldindex = -1; if (this.map.hasOwnProperty(name)) { var oldobj = this.map[name]; // Already up to date: nothing to do! if (obj !== null && oldobj.mtime == obj.mtime) { return; } oldindex = lb(this.list, oldobj, byMtime); if (obj === null) { // Remove the item at its old position this.list.splice(oldindex, 1); delete this.map[name]; return; } } if (obj == null) { // If the file doesn't exist, there is nothing to insert. return; } // Insert the item at its new position this.map[name] = obj; var index = lb(this.list, obj, byMtime); if (oldindex == -1) { // It's a new item: insert it. this.list.splice(index, 0, obj); } else { // It's moving in the list: shift the old items over, then set it. if (index < oldindex) { for (var j = oldindex; j > index; --j) { this.list[j] = this.list[j - 1]; } } else if (index > oldindex) { // If shifting right, our target index is off-by-one because // we ourselves are to the left of our destination index. index -= 1; for (var j = oldindex; j < index; ++j) { this.list[j] = this.list[j + 1]; } } this.list[index] = obj; } }, // Reads an array of at most "count" items that include an exact // matched name (if any) and the most recent prefix matches. // Items will be returned in modification order (most recent first), // except that any exact match will be listed first. readPrefix: function(prefix, count) { var result = []; // ex is 1 if we need to reserve space for an exact match. var ex = this.map.hasOwnProperty(prefix) ? 1 : 0; // fill result with all objects matching the requested prefix. for (var j = 0; result.length + ex < count && j < this.list.length; ++j) { var obj = this.list[j]; var name = obj.name; if (name == prefix) { // If the exact match is included due to recency, set ex to zero. ex = 0; result.unshift(obj); } else if (name.length > prefix.length && name.substr(0, prefix.length) == prefix) { // Include prefix matches by recency. result.push(obj); } } if (ex) { // If an exact match wasn't included due to recency, include it now. result.unshift(this.map[prefix]); } return result; } };
server/dirloader.js
var path = require('path'); var fs = require('fs-ext'); var lb = require('binary-search-bounds').ge; var utils = require('./utils'); // A DirLoader represents a listing of a specific directory. // In Pencil Code, we use it to load directories. // It supports a few actions: // rebuild(callback) - reads the directory on disk (which may take // a sequence of async operations), then update the cache atomically // at the end, calling callback with "true" if successful, "false" // if not. Importantly, if rebuild is requested when a rebuild // is already in progress, it just shares the work and notifies // all callbacks when the single job is done. // update(name, callback) - updates a single entry (with one single // async call to "stat"), then updates that single directory // entry (adding, removing, or reordering it). exports.DirLoader = function DirLoader(path) { this.path = path; // List is sorted by-modification-date (newest first). this.list = []; // Map is indexed by-name. this.map = {}; // Array of callbacks to call if there is a rebuilding going on. this.rebuilding = null; // When was the last rebuild? this.rebuildTime = 0; // How long did it take? this.rebuildMs = 0; } // Encode the stat object for a file as a json record to be // returned from our public API. function encodeStat(name, statObj, itempath) { var modestr = ''; if (statObj.isDirectory()) { modestr += 'd'; } if (statObj.mode & 00400) { modestr += 'r'; } if (statObj.mode & 00200) { modestr += 'w'; } if (statObj.mode & 00100) { modestr += 'x'; } var mtime = statObj.mtime.getTime(); var absthumb = utils.makeThumbPath(itempath); return { name: name, thumbnail: fs.existsSync(absthumb), // whether there is a thumbnail mode: modestr, size: statObj.size, mtime: mtime }; } // Predicate to sort by modification-time. If two entries have // the same mtime, they are sorted alphabetically. function byMtime(a, b) { if (a.mtime > b.mtime) { // later first. return -1 } if (a.mtime < b.mtime) { // earlier last. return 1 } if (a.name < b.name) { // a first. return -1; } if (a.name > b.name) { // z last. return 1; } return 0; } exports.DirLoader.prototype = { // Async rebuild. Does the work, then refreshes atomically at the // end, then calls the callback. rebuild: function(callback) { var batch = 32; // Do work in 32 parallel async tasks. var timeLimit = 300 * 1000; // Timeout after 300 seconds. // If requested a rebuild while a rebuild is in progress, just // queue up with the rebuild-in-progress. if (this.rebuilding) { if (callback) { this.rebuilding.push(callback); } return; } // We're the first: queue up our callback and note the start time. var self = this; var notify = self.rebuilding = []; if (callback) { notify.push(callback); } var startTime = (new Date).getTime(); // Set up an abort (signalled by timeout === true) after 60 seconds. var timeout = setTimeout(function() { timeout = true; notifyAll(false); }, timeLimit); // Kick off an async readdir. fs.readdir(self.path, function(err, names) { // On error, we notify false and finish up. if (err) { clearTimeout(timeout); notifyAll(false); return; } // Set up data structures to receive work in progress. var list = []; var map = {}; var next = 0; var inprogress = 0; var finished = false; // Kick off parallel work tasks. while (inprogress < batch && next < names.length) { loopTask(); } function loopTask() { if (timeout === true) { // When aborted, tasks stop looping. return; } else if (next < names.length) { // If there is still more work, tasks loop via doWork. doWork(names[next++], loopTask); } else if (inprogress == 0) { // If there is no more work, and nothing in progress, we complete. completeWork(); } } // An individual item of work is to stat a single file. function doWork(name, next) { if (name[0] == '.') { // Skip past any dirs starting with a '.' next(); return; } inprogress += 1; var itempath = path.join(self.path, name); fs.stat(itempath, function(err, statobj) { // Errors are treated as non-existent files. if (!err) { // Accumulate the results of the stat into list and map. var result = encodeStat(name, statobj, itempath); list.push(result); map[name] = result; } inprogress -= 1; next(); }); } // When work is done, save it and notify callbacks. function completeWork() { if (!finished) { finished = true; clearTimeout(timeout); list.sort(byMtime); self.list = list; self.map = map; self.rebuildTime = (new Date).getTime(); self.rebuildMs = self.rebuildTime - startTime; notifyAll(true); } } }); function notifyAll(ok) { if (notify && notify === self.rebuilding) { self.rebuilding = null; while (notify.length) { notify.pop().call(null, ok); } } } }, // Get the time since the last rebuildTime. age: function() { return (new Date).getTime() - this.rebuildTime; }, // Synchronous update of a specific name. updateSync: function(name) { var itempath = path.join(this.path, name); var obj = null; try { obj = encodeStat(names[i], fs.statSync(itempath), itempath); } catch (e) { // File is gone: let obj be null. } this.updateObject(name, obj); }, // Async update of a specific name. update: function(name, callback) { var itempath = path.join(this.path, name); var obj = null; var self = this; fs.stat(itempath, function(err, statObj) { if (!err) { obj = encodeStat(name, statObj, itempath); } self.updateObject(name, obj); callback(true); }); }, // Updates the object for 'name' with obj (may be null) updateObject: function(name, obj) { var oldindex = -1; if (this.map.hasOwnProperty(name)) { var oldobj = this.map[name]; // Already up to date: nothing to do! if (obj !== null && oldobj.mtime == obj.mtime) { return; } oldindex = lb(this.list, oldobj, byMtime); if (obj === null) { // Remove the item at its old position this.list.splice(oldindex, 1); delete this.map[name]; return; } } if (obj == null) { // If the file doesn't exist, there is nothing to insert. return; } // Insert the item at its new position this.map[name] = obj; var index = lb(this.list, obj, byMtime); if (oldindex == -1) { // It's a new item: insert it. this.list.splice(index, 0, obj); } else { // It's moving in the list: shift the old items over, then set it. if (index < oldindex) { for (var j = oldindex; j > index; --j) { this.list[j] = this.list[j - 1]; } } else if (index > oldindex) { // If shifting right, our target index is off-by-one because // we ourselves are to the left of our destination index. index -= 1; for (var j = oldindex; j < index; ++j) { this.list[j] = this.list[j + 1]; } } this.list[index] = obj; } }, // Reads an array of at most "count" items that include an exact // matched name (if any) and the most recent prefix matches. // Items will be returned in modification order (most recent first), // except that any exact match will be listed first. readPrefix: function(prefix, count) { var result = []; // ex is 1 if we need to reserve space for an exact match. var ex = this.map.hasOwnProperty(prefix) ? 1 : 0; // fill result with all objects matching the requested prefix. for (var j = 0; result.length + ex < count && j < this.list.length; ++j) { var obj = this.list[j]; var name = obj.name; if (name == prefix) { // If the exact match is included due to recency, set ex to zero. ex = 0; result.unshift(obj); } else if (name.length > prefix.length && name.substr(0, prefix.length) == prefix) { // Include prefix matches by recency. result.push(obj); } } if (ex) { // If an exact match wasn't included due to recency, include it now. result.unshift(this.map[prefix]); } return result; } };
Increase timeout limits.
server/dirloader.js
Increase timeout limits.
<ide><path>erver/dirloader.js <ide> this.rebuildTime = 0; <ide> // How long did it take? <ide> this.rebuildMs = 0; <add> // Configuration: do work in 64 parallel async tasks. <add> this.batchSize = 64; <add> // Configuration: give up after 10 miutes <add> this.timeLimit = 10 * 60 * 1000; <ide> } <ide> <ide> // Encode the stat object for a file as a json record to be <ide> // Async rebuild. Does the work, then refreshes atomically at the <ide> // end, then calls the callback. <ide> rebuild: function(callback) { <del> var batch = 32; // Do work in 32 parallel async tasks. <del> var timeLimit = 300 * 1000; // Timeout after 300 seconds. <add> var batch = this.batchSize; <add> var timeLimit = this.timeLimit; <ide> <ide> // If requested a rebuild while a rebuild is in progress, just <ide> // queue up with the rebuild-in-progress. <ide> if (callback) { notify.push(callback); } <ide> var startTime = (new Date).getTime(); <ide> <del> // Set up an abort (signalled by timeout === true) after 60 seconds. <add> // Set up an abort (signalled by timeout === true) after a few minutes. <ide> var timeout = setTimeout(function() { <ide> timeout = true; <ide> notifyAll(false);
Java
mit
d6d002d88ec227c31fbe6d1f79512b0bd081d883
0
pardiralli-dev/pardiralli,pardiralli-dev/pardiralli,pardiralli-dev/pardiralli
package ee.pardiralli.configuration; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Value("${admin.password}") private String adminPassword; @Value("${admin.username}") private String adminUsername; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/", "/login", "/counter_ajax", "/rest/**", "/ducks/search", "/banklink/**") .permitAll() .anyRequest() .fullyAuthenticated(); http.formLogin().loginPage("/login").failureUrl("/login?error"); http.logout().logoutUrl("/logout").logoutSuccessUrl("/?logoutsuccess"); http.csrf().ignoringAntMatchers("/banklink/**", "/counter_ajax", "/rest/**"); } @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser(adminUsername).password(adminPassword).roles("ADMIN"); } }
src/main/java/ee/pardiralli/configuration/SecurityConfiguration.java
package ee.pardiralli.configuration; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Value("${admin.password}") private String adminPassword; @Value("${admin.username}") private String adminUsername; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/", "/login", "/counter_ajax", "/rest/**", "/ducks/search", "/banklink/**").permitAll().anyRequest().fullyAuthenticated().and() .formLogin().loginPage("/login").failureUrl("/login?error").and() .logout().logoutUrl("/logout").logoutSuccessUrl("/?logoutsuccess").and() .csrf().ignoringAntMatchers("/banklink/**", "/counter_ajax", "/rest/**"); } @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser(adminUsername).password(adminPassword).roles("ADMIN"); } }
Refactored security configuration
src/main/java/ee/pardiralli/configuration/SecurityConfiguration.java
Refactored security configuration
<ide><path>rc/main/java/ee/pardiralli/configuration/SecurityConfiguration.java <ide> package ee.pardiralli.configuration; <ide> <del>import lombok.extern.slf4j.Slf4j; <ide> import org.springframework.beans.factory.annotation.Value; <ide> import org.springframework.context.annotation.Configuration; <ide> import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; <ide> @Override <ide> protected void configure(HttpSecurity http) throws Exception { <ide> http.authorizeRequests() <del> .antMatchers("/", <del> "/login", <del> "/counter_ajax", <del> "/rest/**", <del> "/ducks/search", <del> "/banklink/**").permitAll().anyRequest().fullyAuthenticated().and() <del> .formLogin().loginPage("/login").failureUrl("/login?error").and() <del> .logout().logoutUrl("/logout").logoutSuccessUrl("/?logoutsuccess").and() <del> .csrf().ignoringAntMatchers("/banklink/**", "/counter_ajax", "/rest/**"); <add> .antMatchers("/", "/login", "/counter_ajax", "/rest/**", "/ducks/search", "/banklink/**") <add> .permitAll() <add> .anyRequest() <add> .fullyAuthenticated(); <add> <add> http.formLogin().loginPage("/login").failureUrl("/login?error"); <add> http.logout().logoutUrl("/logout").logoutSuccessUrl("/?logoutsuccess"); <add> http.csrf().ignoringAntMatchers("/banklink/**", "/counter_ajax", "/rest/**"); <ide> } <ide> <ide> @Override
JavaScript
mit
373381a052e31cb5b9bdf58777bc0a3967ab8c3e
0
kanongil/ember-cli,balinterdi/ember-cli,akatov/ember-cli,calderas/ember-cli,jgwhite/ember-cli,pzuraq/ember-cli,romulomachado/ember-cli,romulomachado/ember-cli,Turbo87/ember-cli,sivakumar-kailasam/ember-cli,twokul/ember-cli,HeroicEric/ember-cli,trentmwillis/ember-cli,ef4/ember-cli,trentmwillis/ember-cli,ef4/ember-cli,cibernox/ember-cli,HeroicEric/ember-cli,calderas/ember-cli,sivakumar-kailasam/ember-cli,jgwhite/ember-cli,patocallaghan/ember-cli,fpauser/ember-cli,elwayman02/ember-cli,thoov/ember-cli,ef4/ember-cli,kellyselden/ember-cli,sivakumar-kailasam/ember-cli,gfvcastro/ember-cli,pzuraq/ember-cli,Turbo87/ember-cli,thoov/ember-cli,HeroicEric/ember-cli,patocallaghan/ember-cli,fpauser/ember-cli,seawatts/ember-cli,jgwhite/ember-cli,akatov/ember-cli,rtablada/ember-cli,jrjohnson/ember-cli,thoov/ember-cli,trentmwillis/ember-cli,kellyselden/ember-cli,HeroicEric/ember-cli,twokul/ember-cli,twokul/ember-cli,ember-cli/ember-cli,kategengler/ember-cli,calderas/ember-cli,seawatts/ember-cli,cibernox/ember-cli,kategengler/ember-cli,Turbo87/ember-cli,ef4/ember-cli,patocallaghan/ember-cli,ember-cli/ember-cli,kanongil/ember-cli,mike-north/ember-cli,rtablada/ember-cli,twokul/ember-cli,fpauser/ember-cli,asakusuma/ember-cli,calderas/ember-cli,jrjohnson/ember-cli,akatov/ember-cli,gfvcastro/ember-cli,kellyselden/ember-cli,balinterdi/ember-cli,sivakumar-kailasam/ember-cli,trentmwillis/ember-cli,rtablada/ember-cli,Turbo87/ember-cli,buschtoens/ember-cli,jgwhite/ember-cli,mike-north/ember-cli,kanongil/ember-cli,buschtoens/ember-cli,ember-cli/ember-cli,seawatts/ember-cli,akatov/ember-cli,gfvcastro/ember-cli,elwayman02/ember-cli,patocallaghan/ember-cli,cibernox/ember-cli,seawatts/ember-cli,romulomachado/ember-cli,pzuraq/ember-cli,mike-north/ember-cli,thoov/ember-cli,fpauser/ember-cli,kanongil/ember-cli,gfvcastro/ember-cli,raycohen/ember-cli,pzuraq/ember-cli,mike-north/ember-cli,raycohen/ember-cli,cibernox/ember-cli,asakusuma/ember-cli,romulomachado/ember-cli,kellyselden/ember-cli,rtablada/ember-cli
'use strict'; const expect = require('chai').expect; const ExpressServer = require('../../../../lib/tasks/server/express-server'); const Promise = require('rsvp').Promise; const MockUI = require('console-ui/mock'); const MockProject = require('../../../helpers/mock-project'); const MockWatcher = require('../../../helpers/mock-watcher'); const MockServerWatcher = require('../../../helpers/mock-server-watcher'); const ProxyServer = require('../../../helpers/proxy-server'); const chalk = require('chalk'); const request = require('supertest'); const net = require('net'); const EOL = require('os').EOL; const nock = require('nock'); const express = require('express'); describe('express-server', function() { let subject, ui, project, proxy, nockProxy; nock.enableNetConnect(); beforeEach(function() { this.timeout(10000); ui = new MockUI(); project = new MockProject(); proxy = new ProxyServer(); subject = new ExpressServer({ ui, project, watcher: new MockWatcher(), serverWatcher: new MockServerWatcher(), serverRestartDelayTime: 100, serverRoot: './server', environment: 'development', }); }); afterEach(function() { try { subject.httpServer.close(); } catch (err) { /* ignore */ } try { proxy.httpServer.close(); } catch (err) { /* ignore */ } }); describe('displayHost', function() { it('should use the specified host if specified', function() { expect(subject.displayHost('1.2.3.4')).to.equal('1.2.3.4'); }); it('should use the use localhost if host is not specified', function() { expect(subject.displayHost(undefined)).to.equal('localhost'); }); }); describe('processAppMiddlewares', function() { it('has a good error message if a file exists, but does not export a function', function() { subject.project = { has() { return true; }, require() { return {}; }, }; expect(function() { subject.processAppMiddlewares(); }).to.throw(TypeError, 'ember-cli expected ./server/index.js to be the entry for your mock or proxy server'); }); it('returns values returned by server/index', function() { subject.project = { has() { return true; }, require() { return function() { return 'foo'; }; }, }; expect(subject.processAppMiddlewares()).to.equal('foo'); }); }); describe('output', function() { this.timeout(40000); it('with ssl', function() { return subject.start({ host: undefined, port: '1337', ssl: true, sslCert: 'tests/fixtures/ssl/server.crt', sslKey: 'tests/fixtures/ssl/server.key', rootURL: '/', }).then(function() { let output = ui.output.trim().split(EOL); expect(output[0]).to.equal('Serving on https://localhost:1337/'); }); }); it('with proxy', function() { return subject.start({ proxy: 'http://localhost:3001/', host: undefined, port: '1337', rootURL: '/', }).then(function() { let output = ui.output.trim().split(EOL); expect(output[1]).to.equal('Serving on http://localhost:1337/'); expect(output[0]).to.equal('Proxying to http://localhost:3001/'); expect(output.length).to.equal(2, 'expected only two lines of output'); }); }); it('without proxy', function() { return subject.start({ host: undefined, port: '1337', rootURL: '/', }).then(function() { let output = ui.output.trim().split(EOL); expect(output[0]).to.equal('Serving on http://localhost:1337/'); expect(output.length).to.equal(1, 'expected only one line of output'); }); }); it('with baseURL', function() { return subject.start({ host: undefined, port: '1337', baseURL: '/foo', }).then(function() { let output = ui.output.trim().split(EOL); expect(output[0]).to.equal('Serving on http://localhost:1337/foo/'); expect(output.length).to.equal(1, 'expected only one line of output'); }); }); it('with rootURL', function() { return subject.start({ host: undefined, port: '1337', rootURL: '/foo', }).then(function() { let output = ui.output.trim().split(EOL); expect(output[0]).to.equal('Serving on http://localhost:1337/foo/'); expect(output.length).to.equal(1, 'expected only one line of output'); }); }); it('with empty rootURL', function() { return subject.start({ host: undefined, port: '1337', rootURL: '', }).then(function() { let output = ui.output.trim().split(EOL); expect(output[0]).to.equal('Serving on http://localhost:1337/'); expect(output.length).to.equal(1, 'expected only one line of output'); }); }); it('address in use', function() { let preexistingServer = net.createServer(); preexistingServer.listen(1337); return subject.start({ host: undefined, port: '1337', }) .then(function() { expect(false, 'should have rejected').to.be.ok; }) .catch(function(reason) { expect(reason.message).to.equal('Could not serve on http://localhost:1337. It is either in use or you do not have permission.'); }) .finally(function() { preexistingServer.close(); }); }); }); describe('behaviour', function() { it('starts with ssl if ssl option is passed', function() { return subject.start({ host: 'localhost', port: '1337', ssl: true, sslCert: 'tests/fixtures/ssl/server.crt', sslKey: 'tests/fixtures/ssl/server.key', rootURL: '/', }) .then(function() { return new Promise(function(resolve, reject) { process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; request('https://localhost:1337', { strictSSL: false }). get('/').expect(200, function(err, value) { process.env.NODE_TLS_REJECT_UNAUTHORIZED = '1'; if (err) { reject(err); } else { resolve(value); } }); }); }); }); it('app middlewares are processed before the proxy', function(done) { let expected = '/foo was hit'; project.require = function() { return function(app) { app.use('/foo', function(req, res) { res.send(expected); }); }; }; subject.start({ proxy: 'http://localhost:3001/', host: undefined, port: '1337', rootURL: '/', }) .then(function() { request(subject.app) .get('/foo') .set('accept', 'application/json, */*') .expect(function(res) { expect(res.text).to.equal(expected); }) .end(function(err) { if (err) { return done(err); } expect(proxy.called).to.equal(false); done(); }); }); }); it('works with a regular express app', function(done) { let expected = '/foo was hit'; project.require = function() { let app = express(); app.use('/foo', function(req, res) { res.send(expected); }); return app; }; subject.start({ proxy: 'http://localhost:3001/', host: undefined, port: '1337', rootURL: '/', }) .then(function() { request(subject.app) .get('/foo') .set('accept', 'application/json, */*') .expect(function(res) { expect(res.text).to.equal(expected); }) .end(function(err) { if (err) { return done(err); } expect(proxy.called).to.equal(false); done(); }); }); }); describe('with proxy', function() { beforeEach(function() { return subject.start({ proxy: 'http://localhost:3001/', host: undefined, port: '1337', rootURL: '/', }); }); function bypassTest(app, url, done, responseCallback) { request(app) .get(url) .set('accept', 'text/html') .end(function(err, response) { if (err) { return done(err); } expect(proxy.called).to.equal(false); if (responseCallback) { responseCallback(response); } done(); }); } it('bypasses proxy for /', function(done) { bypassTest(subject.app, '/', done); }); it('bypasses proxy for files that exist', function(done) { bypassTest(subject.app, '/test-file.txt', done, function(response) { expect(response.text.trim()).to.equal('some contents'); }); }); function apiTest(app, method, url, done) { let req = request(app); return req[method].call(req, url) .set('content-length', 0) .set('accept', 'text/json') .end(function(err) { if (err) { return done(err); } expect(proxy.called, 'proxy receives the request').to.equal(true); expect(proxy.lastReq.method).to.equal(method.toUpperCase()); expect(proxy.lastReq.url).to.equal(url); done(); }); } it('proxies GET', function(done) { apiTest(subject.app, 'get', '/api/get', done); }); it('proxies PUT', function(done) { apiTest(subject.app, 'put', '/api/put', done); }); it('proxies POST', function(done) { apiTest(subject.app, 'post', '/api/post', done); }); it('proxies DELETE', function(done) { apiTest(subject.app, 'delete', '/api/delete', done); }); // test for #1263 it('proxies when accept contains */*', function(done) { request(subject.app) .get('/api/get') .set('accept', 'application/json, */*') .end(function(err) { if (err) { return done(err); } expect(proxy.called, 'proxy receives the request').to.equal(true); done(); }); }); }); describe('proxy with subdomain', function() { beforeEach(function() { nockProxy = { called: null, method: null, url: null, }; return subject.start({ proxy: 'http://api.lvh.me', host: undefined, port: '1337', rootURL: '/', }); }); function apiTest(app, method, url, done) { let req = request(app); return req[method].call(req, url) .set('accept', 'text/json') .end(function(err) { if (err) { return done(err); } expect(nockProxy.called, 'proxy receives the request').to.equal(true); expect(nockProxy.method).to.equal(method.toUpperCase()); expect(nockProxy.url).to.equal(url); done(); }); } it('proxies GET', function(done) { nock('http://api.lvh.me', { reqheaders: { 'host': 'api.lvh.me', }, }).get('/api/get') .reply(200, function() { nockProxy.called = true; nockProxy.method = 'GET'; nockProxy.url = '/api/get'; return ''; }); apiTest(subject.app, 'get', '/api/get', done); }); it('proxies PUT', function(done) { nock('http://api.lvh.me', { reqheaders: { 'host': 'api.lvh.me', }, }).put('/api/put') .reply(204, function() { nockProxy.called = true; nockProxy.method = 'PUT'; nockProxy.url = '/api/put'; return ''; }); apiTest(subject.app, 'put', '/api/put', done); }); it('proxies POST', function(done) { nock('http://api.lvh.me', { reqheaders: { 'host': 'api.lvh.me', }, }).post('/api/post') .reply(201, function() { nockProxy.called = true; nockProxy.method = 'POST'; nockProxy.url = '/api/post'; return ''; }); apiTest(subject.app, 'post', '/api/post', done); }); it('proxies DELETE', function(done) { nock('http://api.lvh.me', { reqheaders: { 'host': 'api.lvh.me', }, }).delete('/api/delete') .reply(204, function() { nockProxy.called = true; nockProxy.method = 'DELETE'; nockProxy.url = '/api/delete'; return ''; }); apiTest(subject.app, 'delete', '/api/delete', done); }); // test for #1263 it('proxies when accept contains */*', function(done) { nock('http://api.lvh.me') .get('/api/get') .reply(200, function() { nockProxy.called = true; nockProxy.method = 'GET'; nockProxy.url = '/api/get'; return ''; }); request(subject.app) .get('/api/get') .set('accept', 'application/json, */*') .end(function(err) { if (err) { return done(err); } expect(nockProxy.called, 'proxy receives the request').to.equal(true); done(); }); }); }); describe('without proxy', function() { function startServer(rootURL) { return subject.start({ host: undefined, port: '1337', rootURL: rootURL || '/', }); } it('serves index.html when file not found with auto/history location', function(done) { startServer() .then(function() { request(subject.app) .get('/someurl.withperiod') .set('accept', 'text/html') .expect(200) .expect('Content-Type', /html/) .end(function(err) { if (err) { return done(err); } done(); }); }); }); it('GET /tests serves tests/index.html for mime of */* (hash location)', function(done) { project._config = { rootURL: '/', locationType: 'hash', }; startServer() .then(function() { request(subject.app) .get('/tests') .set('accept', '*/*') .expect(200) .expect('Content-Type', /html/) .end(function(err) { if (err) { return done(err); } done(); }); }); }); it('GET /tests serves tests/index.html for mime of */* (auto location)', function(done) { startServer() .then(function() { request(subject.app) .get('/tests') .set('accept', '*/*') .expect(200) .expect('Content-Type', /html/) .end(function(err) { if (err) { return done(err); } done(); }); }); }); it('GET /tests/whatever serves tests/index.html when file not found', function(done) { startServer() .then(function() { request(subject.app) .get('/tests/whatever') .set('accept', 'text/html') .expect(200) .expect('Content-Type', /html/) .end(function(err) { if (err) { return done(err); } done(); }); }); }); it('GET /tests/an-existing-file.tla serves tests/an-existing-file.tla if it is found', function(done) { startServer() .then(function() { request(subject.app) .get('/tests/test-file.txt') .set('accept', 'text/html') .expect(200) .expect(/some contents/) .expect('Content-Type', /text/) .end(function(err) { if (err) { return done(err); } done(); }); }); }); it('serves index.html when file not found (with rootURL) with auto/history location', function(done) { startServer('/foo') .then(function() { request(subject.app) .get('/foo/someurl') .set('accept', 'text/html') .expect(200) .expect('Content-Type', /html/) .end(function(err) { if (err) { return done(err); } done(); }); }); }); it('serves index.html when file not found (with rootURL) with custom history location', function(done) { project._config = { rootURL: '/', locationType: 'blahr', historySupportMiddleware: true, }; startServer('/foo') .then(function() { request(subject.app) .get('/foo/someurl') .set('accept', 'text/html') .expect(200) .expect('Content-Type', /html/) .end(function(err) { if (err) { return done(err); } done(); }); }); }); it('returns a 404 when file not found with hash location', function(done) { project._config = { rootURL: '/', locationType: 'hash', }; startServer() .then(function() { request(subject.app) .get('/someurl.withperiod') .set('accept', 'text/html') .expect(404) .end(done); }); }); it('files that exist in broccoli directory are served up', function(done) { startServer() .then(function() { request(subject.app) .get('/test-file.txt') .end(function(err, response) { expect(response.text.trim()).to.equal('some contents'); done(); }); }); }); it('serves static asset up from build output without a period in name', function(done) { startServer() .then(function() { request(subject.app) .get('/someurl-without-period') .expect(200) .end(function(err, response) { if (err) { return done(err); } expect(response.body.toString().trim()).to.equal('some other content'); done(); }); }); }); it('serves static asset up from build output without a period in name (with rootURL)', function(done) { startServer('/foo') .then(function() { request(subject.app) .get('/foo/someurl-without-period') .expect(200) .end(function(err, response) { if (err) { return done(err); } expect(response.body.toString().trim()).to.equal('some other content'); done(); }); }); }); }); describe('addons', function() { let calls; beforeEach(function() { calls = 0; subject.processAddonMiddlewares = function() { calls++; }; }); it('calls processAddonMiddlewares upon start', function() { return subject.start({ host: undefined, port: '1337', }).then(function() { expect(calls).to.equal(1); }); }); }); describe('addon middleware', function() { let firstCalls; let secondCalls; beforeEach(function() { firstCalls = 0; secondCalls = 0; project.initializeAddons = function() { }; project.addons = [{ serverMiddleware() { firstCalls++; }, }, { serverMiddleware() { secondCalls++; }, }, { doesntGoBoom: null, }]; }); it('calls serverMiddleware on the addons on start', function() { return subject.start({ host: undefined, port: '1337', }).then(function() { expect(firstCalls).to.equal(1); expect(secondCalls).to.equal(1); }); }); it('calls serverMiddleware on the addons on restart', function() { return subject.start({ host: undefined, port: '1337', }).then(function() { subject.changedFiles = ['bar.js']; return subject.restartHttpServer(); }).then(function() { expect(firstCalls).to.equal(2); expect(secondCalls).to.equal(2); }); }); }); describe('addon middleware is async', function() { let order = []; beforeEach(function() { project.initializeAddons = function() { }; project.addons = [ { serverMiddleware() { order.push('first'); }, }, { serverMiddleware() { return new Promise(function(resolve) { setTimeout(function() { order.push('second'); resolve(); }, 50); }); }, }, { serverMiddleware() { order.push('third'); }, }, ]; }); it('waits for async middleware to complete before the next middleware', function() { return subject.start({ host: undefined, port: '1337', }).then(function() { expect(order[0]).to.equal('first'); expect(order[1]).to.equal('second'); expect(order[2]).to.equal('third'); }); }); }); describe('addon middleware bubble errors', function() { beforeEach(function() { project.initializeAddons = function() { }; project.addons = [{ serverMiddleware() { return Promise.reject('addon middleware fail'); }, }, ]; }); it('up to server start', function() { return subject.start({ host: undefined, port: '1337', }) .catch(function(reason) { expect(reason).to.equal('addon middleware fail'); }); }); }); describe('app middleware', function() { let passedOptions; let calls; beforeEach(function() { passedOptions = null; calls = 0; subject.processAppMiddlewares = function(options) { passedOptions = options; calls++; }; }); it('calls processAppMiddlewares upon start', function() { let realOptions = { host: undefined, port: '1337', }; return subject.start(realOptions).then(function() { expect(passedOptions === realOptions).to.equal(true); expect(calls).to.equal(1); }); }); it('calls processAppMiddlewares upon restart', function() { let realOptions = { host: undefined, port: '1337', }; let originalApp; return subject.start(realOptions) .then(function() { originalApp = subject.app; subject.changedFiles = ['bar.js']; return subject.restartHttpServer(); }) .then(function() { expect(subject.app).to.be.ok; expect(originalApp).to.not.equal(subject.app); expect(passedOptions === realOptions).to.equal(true); expect(calls).to.equal(2); }); }); it('includes httpServer instance in options', function() { let passedOptions; subject.processAppMiddlewares = function(options) { passedOptions = options; }; let realOptions = { host: undefined, port: '1337', }; return subject.start(realOptions).then(function() { expect(!!passedOptions.httpServer.listen).to.be.ok; }); }); }); describe('serverWatcherDidChange', function() { it('is called on file change', function() { let calls = 0; subject.serverWatcherDidChange = function() { calls++; }; return subject.start({ host: undefined, port: '1337', }).then(function() { subject.serverWatcher.emit('change', 'foo.txt'); expect(calls).to.equal(1); }); }); it('schedules a server restart', function() { let calls = 0; subject.scheduleServerRestart = function() { calls++; }; return subject.start({ host: undefined, port: '1337', }).then(function() { subject.serverWatcher.emit('change', 'foo.txt'); subject.serverWatcher.emit('change', 'bar.txt'); expect(calls).to.equal(2); }); }); }); describe('scheduleServerRestart', function() { it('schedules exactly one call of restartHttpServer', function(done) { let calls = 0; subject.restartHttpServer = function() { calls++; }; subject.scheduleServerRestart(); expect(calls).to.equal(0); setTimeout(function() { expect(calls).to.equal(0); subject.scheduleServerRestart(); }, 50); setTimeout(function() { expect(calls).to.equal(1); done(); }, 175); }); }); describe('restartHttpServer', function() { it('restarts the server', function() { let originalHttpServer; let originalApp; return subject.start({ host: undefined, port: '1337', }).then(function() { ui.output = ''; originalHttpServer = subject.httpServer; originalApp = subject.app; subject.changedFiles = ['bar.js']; return subject.restartHttpServer(); }).then(function() { expect(ui.output).to.equal(EOL + chalk.green('Server restarted.') + EOL + EOL); expect(subject.httpServer, 'HTTP server exists').to.be.ok; expect(subject.httpServer).to.not.equal(originalHttpServer, 'HTTP server has changed'); expect(!!subject.app).to.equal(true, 'App exists'); expect(subject.app).to.not.equal(originalApp, 'App has changed'); }); }); it('restarts the server again if one or more files change during a previous restart', function() { let originalHttpServer; let originalApp; return subject.start({ host: undefined, port: '1337', }).then(function() { originalHttpServer = subject.httpServer; originalApp = subject.app; subject.serverRestartPromise = new Promise(function(resolve) { setTimeout(function() { subject.serverRestartPromise = null; resolve(); }, 20); }); subject.changedFiles = ['bar.js']; return subject.restartHttpServer(); }).then(function() { expect(!!subject.httpServer).to.equal(true, 'HTTP server exists'); expect(subject.httpServer).to.not.equal(originalHttpServer, 'HTTP server has changed'); expect(!!subject.app).to.equal(true, 'App exists'); expect(subject.app).to.not.equal(originalApp, 'App has changed'); }); }); it('emits the restart event', function() { let calls = 0; subject.on('restart', function() { calls++; }); return subject.start({ host: undefined, port: '1337', }).then(function() { subject.changedFiles = ['bar.js']; return subject.restartHttpServer(); }).then(function() { expect(calls).to.equal(1); }); }); }); }); });
tests/unit/tasks/server/express-server-test.js
'use strict'; const expect = require('chai').expect; const ExpressServer = require('../../../../lib/tasks/server/express-server'); const Promise = require('rsvp').Promise; const MockUI = require('console-ui/mock'); const MockProject = require('../../../helpers/mock-project'); const MockWatcher = require('../../../helpers/mock-watcher'); const MockServerWatcher = require('../../../helpers/mock-server-watcher'); const ProxyServer = require('../../../helpers/proxy-server'); const chalk = require('chalk'); const request = require('supertest'); const net = require('net'); const EOL = require('os').EOL; const nock = require('nock'); const express = require('express'); describe('express-server', function() { let subject, ui, project, proxy, nockProxy; nock.enableNetConnect(); beforeEach(function() { this.timeout(10000); ui = new MockUI(); project = new MockProject(); proxy = new ProxyServer(); subject = new ExpressServer({ ui, project, watcher: new MockWatcher(), serverWatcher: new MockServerWatcher(), serverRestartDelayTime: 100, serverRoot: './server', environment: 'development', }); }); afterEach(function() { try { subject.httpServer.close(); } catch (err) { /* ignore */ } try { proxy.httpServer.close(); } catch (err) { /* ignore */ } }); describe('displayHost', function() { it('should use the specified host if specified', function() { expect(subject.displayHost('1.2.3.4')).to.equal('1.2.3.4'); }); it('should use the use localhost if host is not specified', function() { expect(subject.displayHost(undefined)).to.equal('localhost'); }); }); describe('processAppMiddlewares', function() { it('has a good error message if a file exists, but does not export a function', function() { subject.project = { has() { return true; }, require() { return {}; }, }; expect(function() { subject.processAppMiddlewares(); }).to.throw(TypeError, 'ember-cli expected ./server/index.js to be the entry for your mock or proxy server'); }); it('returns values returned by server/index', function() { subject.project = { has() { return true; }, require() { return function() { return 'foo'; }; }, }; expect(subject.processAppMiddlewares()).to.equal('foo'); }); }); describe('output', function() { this.timeout(40000); it('with ssl', function() { return subject.start({ host: undefined, port: '1337', ssl: true, sslCert: 'tests/fixtures/ssl/server.crt', sslKey: 'tests/fixtures/ssl/server.key', rootURL: '/', }).then(function() { let output = ui.output.trim().split(EOL); expect(output[0]).to.equal('Serving on https://localhost:1337/'); }); }); it('with proxy', function() { return subject.start({ proxy: 'http://localhost:3001/', host: undefined, port: '1337', rootURL: '/', }).then(function() { let output = ui.output.trim().split(EOL); expect(output[1]).to.equal('Serving on http://localhost:1337/'); expect(output[0]).to.equal('Proxying to http://localhost:3001/'); expect(output.length).to.equal(2, 'expected only two lines of output'); }); }); it('without proxy', function() { return subject.start({ host: undefined, port: '1337', rootURL: '/', }).then(function() { let output = ui.output.trim().split(EOL); expect(output[0]).to.equal('Serving on http://localhost:1337/'); expect(output.length).to.equal(1, 'expected only one line of output'); }); }); it('with baseURL', function() { return subject.start({ host: undefined, port: '1337', baseURL: '/foo', }).then(function() { let output = ui.output.trim().split(EOL); expect(output[0]).to.equal('Serving on http://localhost:1337/foo/'); expect(output.length).to.equal(1, 'expected only one line of output'); }); }); it('with rootURL', function() { return subject.start({ host: undefined, port: '1337', rootURL: '/foo', }).then(function() { let output = ui.output.trim().split(EOL); expect(output[0]).to.equal('Serving on http://localhost:1337/foo/'); expect(output.length).to.equal(1, 'expected only one line of output'); }); }); it('with empty rootURL', function() { return subject.start({ host: undefined, port: '1337', rootURL: '', }).then(function() { let output = ui.output.trim().split(EOL); expect(output[0]).to.equal('Serving on http://localhost:1337/'); expect(output.length).to.equal(1, 'expected only one line of output'); }); }); it('address in use', function() { let preexistingServer = net.createServer(); preexistingServer.listen(1337); return subject.start({ host: undefined, port: '1337', }) .then(function() { expect(false, 'should have rejected').to.be.ok; }) .catch(function(reason) { expect(reason.message).to.equal('Could not serve on http://localhost:1337. It is either in use or you do not have permission.'); }) .finally(function() { preexistingServer.close(); }); }); }); describe('behaviour', function() { it('starts with ssl if ssl option is passed', function() { return subject.start({ host: 'localhost', port: '1337', ssl: true, sslCert: 'tests/fixtures/ssl/server.crt', sslKey: 'tests/fixtures/ssl/server.key', rootURL: '/', }) .then(function() { return new Promise(function(resolve, reject) { process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; request('https://localhost:1337', { strictSSL: false }). get('/').expect(200, function(err, value) { process.env.NODE_TLS_REJECT_UNAUTHORIZED = '1'; if (err) { reject(err); } else { resolve(value); } }); }); }); }); it('app middlewares are processed before the proxy', function(done) { let expected = '/foo was hit'; project.require = function() { return function(app) { app.use('/foo', function(req, res) { res.send(expected); }); }; }; subject.start({ proxy: 'http://localhost:3001/', host: undefined, port: '1337', rootURL: '/', }) .then(function() { request(subject.app) .get('/foo') .set('accept', 'application/json, */*') .expect(function(res) { expect(res.text).to.equal(expected); }) .end(function(err) { if (err) { return done(err); } expect(proxy.called).to.equal(false); done(); }); }); }); it('works with a regular express app', function(done) { let expected = '/foo was hit'; project.require = function() { let app = express(); app.use('/foo', function(req, res) { res.send(expected); }); return app; }; subject.start({ proxy: 'http://localhost:3001/', host: undefined, port: '1337', rootURL: '/', }) .then(function() { request(subject.app) .get('/foo') .set('accept', 'application/json, */*') .expect(function(res) { expect(res.text).to.equal(expected); }) .end(function(err) { if (err) { return done(err); } expect(proxy.called).to.equal(false); done(); }); }); }); describe('with proxy', function() { beforeEach(function() { return subject.start({ proxy: 'http://localhost:3001/', host: undefined, port: '1337', rootURL: '/', }); }); function bypassTest(app, url, done, responseCallback) { request(app) .get(url) .set('accept', 'text/html') .end(function(err, response) { if (err) { return done(err); } expect(proxy.called).to.equal(false); if (responseCallback) { responseCallback(response); } done(); }); } it('bypasses proxy for /', function(done) { bypassTest(subject.app, '/', done); }); it('bypasses proxy for files that exist', function(done) { bypassTest(subject.app, '/test-file.txt', done, function(response) { expect(response.text.trim()).to.equal('some contents'); }); }); function apiTest(app, method, url, done) { let req = request(app); return req[method].call(req, url) .set('content-length', 0) .set('accept', 'text/json') .end(function(err) { if (err) { return done(err); } expect(proxy.called, 'proxy receives the request').to.equal(true); expect(proxy.lastReq.method).to.equal(method.toUpperCase()); expect(proxy.lastReq.url).to.equal(url); done(); }); } it('proxies GET', function(done) { apiTest(subject.app, 'get', '/api/get', done); }); it('proxies PUT', function(done) { apiTest(subject.app, 'put', '/api/put', done); }); it('proxies POST', function(done) { apiTest(subject.app, 'post', '/api/post', done); }); it('proxies DELETE', function(done) { apiTest(subject.app, 'delete', '/api/delete', done); }); // test for #1263 it('proxies when accept contains */*', function(done) { request(subject.app) .get('/api/get') .set('accept', 'application/json, */*') .end(function(err) { if (err) { return done(err); } expect(proxy.called, 'proxy receives the request').to.equal(true); done(); }); }); }); describe('proxy with subdomain', function() { beforeEach(function() { nockProxy = { called: null, method: null, url: null, }; return subject.start({ proxy: 'http://api.lvh.me', host: undefined, port: '1337', rootURL: '/', }); }); function apiTest(app, method, url, done) { let req = request(app); return req[method].call(req, url) .set('accept', 'text/json') .end(function(err) { if (err) { return done(err); } expect(nockProxy.called, 'proxy receives the request').to.equal(true); expect(nockProxy.method).to.equal(method.toUpperCase()); expect(nockProxy.url).to.equal(url); done(); }); } it('proxies GET', function(done) { nock('http://api.lvh.me', { reqheaders: { 'host': 'api.lvh.me', }, }).get('/api/get') .reply(200, function() { nockProxy.called = true; nockProxy.method = 'GET'; nockProxy.url = '/api/get'; return ''; }); apiTest(subject.app, 'get', '/api/get', done); }); it('proxies PUT', function(done) { nock('http://api.lvh.me', { reqheaders: { 'host': 'api.lvh.me', }, }).put('/api/put') .reply(204, function() { nockProxy.called = true; nockProxy.method = 'PUT'; nockProxy.url = '/api/put'; return ''; }); apiTest(subject.app, 'put', '/api/put', done); }); it('proxies POST', function(done) { nock('http://api.lvh.me', { reqheaders: { 'host': 'api.lvh.me', }, }).post('/api/post') .reply(201, function() { nockProxy.called = true; nockProxy.method = 'POST'; nockProxy.url = '/api/post'; return ''; }); apiTest(subject.app, 'post', '/api/post', done); }); it('proxies DELETE', function(done) { nock('http://api.lvh.me', { reqheaders: { 'host': 'api.lvh.me', }, }).delete('/api/delete') .reply(204, function() { nockProxy.called = true; nockProxy.method = 'DELETE'; nockProxy.url = '/api/delete'; return ''; }); apiTest(subject.app, 'delete', '/api/delete', done); }); // test for #1263 it('proxies when accept contains */*', function(done) { nock('http://api.lvh.me') .get('/api/get') .reply(200, function() { nockProxy.called = true; nockProxy.method = 'GET'; nockProxy.url = '/api/get'; return ''; }); request(subject.app) .get('/api/get') .set('accept', 'application/json, */*') .end(function(err) { if (err) { return done(err); } expect(nockProxy.called, 'proxy receives the request').to.equal(true); done(); }); }); }); describe('without proxy', function() { function startServer(rootURL) { return subject.start({ host: undefined, port: '1337', rootURL: rootURL || '/', }); } it('serves index.html when file not found with auto/history location', function(done) { startServer() .then(function() { request(subject.app) .get('/someurl.withperiod') .set('accept', 'text/html') .expect(200) .expect('Content-Type', /html/) .end(function(err) { if (err) { return done(err); } done(); }); }); }); it('GET /tests serves tests/index.html for mime of */* (hash location)', function(done) { project._config = { rootURL: '/', locationType: 'hash', }; startServer() .then(function() { request(subject.app) .get('/tests') .set('accept', '*/*') .expect(200) .expect('Content-Type', /html/) .end(function(err) { if (err) { return done(err); } done(); }); }); }); it('GET /tests serves tests/index.html for mime of */* (auto location)', function(done) { startServer() .then(function() { request(subject.app) .get('/tests') .set('accept', '*/*') .expect(200) .expect('Content-Type', /html/) .end(function(err) { if (err) { return done(err); } done(); }); }); }); it('GET /tests/whatever serves tests/index.html when file not found', function(done) { startServer() .then(function() { request(subject.app) .get('/tests/whatever') .set('accept', 'text/html') .expect(200) .expect('Content-Type', /html/) .end(function(err) { if (err) { return done(err); } done(); }); }); }); it('GET /tests/an-existing-file.tla serves tests/an-existing-file.tla if it is found', function(done) { startServer() .then(function() { request(subject.app) .get('/tests/test-file.txt') .set('accept', 'text/html') .expect(200) .expect(/some contents/) .expect('Content-Type', /text/) .end(function(err) { if (err) { return done(err); } done(); }); }); }); it('serves index.html when file not found (with rootURL) with auto/history location', function(done) { startServer('/foo') .then(function() { request(subject.app) .get('/foo/someurl') .set('accept', 'text/html') .expect(200) .expect('Content-Type', /html/) .end(function(err) { if (err) { return done(err); } done(); }); }); }); it('serves index.html when file not found (with rootURL) with custom history location', function(done) { project._config = { rootURL: '/', locationType: 'blahr', historySupportMiddleware: true, }; startServer('/foo') .then(function() { request(subject.app) .get('/foo/someurl') .set('accept', 'text/html') .expect(200) .expect('Content-Type', /html/) .end(function(err) { if (err) { return done(err); } done(); }); }); }); it('returns a 404 when file not found with hash location', function(done) { project._config = { rootURL: '/', locationType: 'hash', }; startServer() .then(function() { request(subject.app) .get('/someurl.withperiod') .set('accept', 'text/html') .expect(404) .end(done); }); }); it('files that exist in broccoli directory are served up', function(done) { startServer() .then(function() { request(subject.app) .get('/test-file.txt') .end(function(err, response) { expect(response.text.trim()).to.equal('some contents'); done(); }); }); }); it('serves static asset up from build output without a period in name', function(done) { startServer() .then(function() { request(subject.app) .get('/someurl-without-period') .expect(200) .end(function(err, response) { if (err) { return done(err); } expect(response.text.trim()).to.equal('some other content'); done(); }); }); }); it('serves static asset up from build output without a period in name (with rootURL)', function(done) { startServer('/foo') .then(function() { request(subject.app) .get('/foo/someurl-without-period') .expect(200) .end(function(err, response) { if (err) { return done(err); } expect(response.text.trim()).to.equal('some other content'); done(); }); }); }); }); describe('addons', function() { let calls; beforeEach(function() { calls = 0; subject.processAddonMiddlewares = function() { calls++; }; }); it('calls processAddonMiddlewares upon start', function() { return subject.start({ host: undefined, port: '1337', }).then(function() { expect(calls).to.equal(1); }); }); }); describe('addon middleware', function() { let firstCalls; let secondCalls; beforeEach(function() { firstCalls = 0; secondCalls = 0; project.initializeAddons = function() { }; project.addons = [{ serverMiddleware() { firstCalls++; }, }, { serverMiddleware() { secondCalls++; }, }, { doesntGoBoom: null, }]; }); it('calls serverMiddleware on the addons on start', function() { return subject.start({ host: undefined, port: '1337', }).then(function() { expect(firstCalls).to.equal(1); expect(secondCalls).to.equal(1); }); }); it('calls serverMiddleware on the addons on restart', function() { return subject.start({ host: undefined, port: '1337', }).then(function() { subject.changedFiles = ['bar.js']; return subject.restartHttpServer(); }).then(function() { expect(firstCalls).to.equal(2); expect(secondCalls).to.equal(2); }); }); }); describe('addon middleware is async', function() { let order = []; beforeEach(function() { project.initializeAddons = function() { }; project.addons = [ { serverMiddleware() { order.push('first'); }, }, { serverMiddleware() { return new Promise(function(resolve) { setTimeout(function() { order.push('second'); resolve(); }, 50); }); }, }, { serverMiddleware() { order.push('third'); }, }, ]; }); it('waits for async middleware to complete before the next middleware', function() { return subject.start({ host: undefined, port: '1337', }).then(function() { expect(order[0]).to.equal('first'); expect(order[1]).to.equal('second'); expect(order[2]).to.equal('third'); }); }); }); describe('addon middleware bubble errors', function() { beforeEach(function() { project.initializeAddons = function() { }; project.addons = [{ serverMiddleware() { return Promise.reject('addon middleware fail'); }, }, ]; }); it('up to server start', function() { return subject.start({ host: undefined, port: '1337', }) .catch(function(reason) { expect(reason).to.equal('addon middleware fail'); }); }); }); describe('app middleware', function() { let passedOptions; let calls; beforeEach(function() { passedOptions = null; calls = 0; subject.processAppMiddlewares = function(options) { passedOptions = options; calls++; }; }); it('calls processAppMiddlewares upon start', function() { let realOptions = { host: undefined, port: '1337', }; return subject.start(realOptions).then(function() { expect(passedOptions === realOptions).to.equal(true); expect(calls).to.equal(1); }); }); it('calls processAppMiddlewares upon restart', function() { let realOptions = { host: undefined, port: '1337', }; let originalApp; return subject.start(realOptions) .then(function() { originalApp = subject.app; subject.changedFiles = ['bar.js']; return subject.restartHttpServer(); }) .then(function() { expect(subject.app).to.be.ok; expect(originalApp).to.not.equal(subject.app); expect(passedOptions === realOptions).to.equal(true); expect(calls).to.equal(2); }); }); it('includes httpServer instance in options', function() { let passedOptions; subject.processAppMiddlewares = function(options) { passedOptions = options; }; let realOptions = { host: undefined, port: '1337', }; return subject.start(realOptions).then(function() { expect(!!passedOptions.httpServer.listen).to.be.ok; }); }); }); describe('serverWatcherDidChange', function() { it('is called on file change', function() { let calls = 0; subject.serverWatcherDidChange = function() { calls++; }; return subject.start({ host: undefined, port: '1337', }).then(function() { subject.serverWatcher.emit('change', 'foo.txt'); expect(calls).to.equal(1); }); }); it('schedules a server restart', function() { let calls = 0; subject.scheduleServerRestart = function() { calls++; }; return subject.start({ host: undefined, port: '1337', }).then(function() { subject.serverWatcher.emit('change', 'foo.txt'); subject.serverWatcher.emit('change', 'bar.txt'); expect(calls).to.equal(2); }); }); }); describe('scheduleServerRestart', function() { it('schedules exactly one call of restartHttpServer', function(done) { let calls = 0; subject.restartHttpServer = function() { calls++; }; subject.scheduleServerRestart(); expect(calls).to.equal(0); setTimeout(function() { expect(calls).to.equal(0); subject.scheduleServerRestart(); }, 50); setTimeout(function() { expect(calls).to.equal(1); done(); }, 175); }); }); describe('restartHttpServer', function() { it('restarts the server', function() { let originalHttpServer; let originalApp; return subject.start({ host: undefined, port: '1337', }).then(function() { ui.output = ''; originalHttpServer = subject.httpServer; originalApp = subject.app; subject.changedFiles = ['bar.js']; return subject.restartHttpServer(); }).then(function() { expect(ui.output).to.equal(EOL + chalk.green('Server restarted.') + EOL + EOL); expect(subject.httpServer, 'HTTP server exists').to.be.ok; expect(subject.httpServer).to.not.equal(originalHttpServer, 'HTTP server has changed'); expect(!!subject.app).to.equal(true, 'App exists'); expect(subject.app).to.not.equal(originalApp, 'App has changed'); }); }); it('restarts the server again if one or more files change during a previous restart', function() { let originalHttpServer; let originalApp; return subject.start({ host: undefined, port: '1337', }).then(function() { originalHttpServer = subject.httpServer; originalApp = subject.app; subject.serverRestartPromise = new Promise(function(resolve) { setTimeout(function() { subject.serverRestartPromise = null; resolve(); }, 20); }); subject.changedFiles = ['bar.js']; return subject.restartHttpServer(); }).then(function() { expect(!!subject.httpServer).to.equal(true, 'HTTP server exists'); expect(subject.httpServer).to.not.equal(originalHttpServer, 'HTTP server has changed'); expect(!!subject.app).to.equal(true, 'App exists'); expect(subject.app).to.not.equal(originalApp, 'App has changed'); }); }); it('emits the restart event', function() { let calls = 0; subject.on('restart', function() { calls++; }); return subject.start({ host: undefined, port: '1337', }).then(function() { subject.changedFiles = ['bar.js']; return subject.restartHttpServer(); }).then(function() { expect(calls).to.equal(1); }); }); }); }); });
Fix tests for supertest@3 changes. When the associated mimetype is _not_ `"text/"`, `"/json"`, or `"x-www-form-urlencoded"` the `response.text` is not populated on node (the libraries reasoning is to conserve memory on potentially large response bodies). This uses `response.body.toString()` (`toString` is required to convert from buffer to simple string) instead.
tests/unit/tasks/server/express-server-test.js
Fix tests for supertest@3 changes.
<ide><path>ests/unit/tasks/server/express-server-test.js <ide> return done(err); <ide> } <ide> <del> expect(response.text.trim()).to.equal('some other content'); <add> expect(response.body.toString().trim()).to.equal('some other content'); <ide> <ide> done(); <ide> }); <ide> return done(err); <ide> } <ide> <del> expect(response.text.trim()).to.equal('some other content'); <add> expect(response.body.toString().trim()).to.equal('some other content'); <ide> <ide> done(); <ide> });
JavaScript
mit
ffd87818f65df3995e41311d9ed8f64a9698dcce
0
ColorfulCakeChen/query-submit-canvas,ColorfulCakeChen/query-submit-canvas
export { FiltersArray_BiasesArray }; import * as FloatValue from "../../Unpacker/FloatValue.js"; import * as ValueDesc from "../../Unpacker/ValueDesc.js"; import * as Weights from "../../Unpacker/Weights.js"; import * as ConvBiasActivation from "../ConvBiasActivation.js"; import { ChannelPartInfo, FiltersBiasesPartInfo } from "./Pointwise_ChannelPartInfo.js"; import { BoundsArraySet } from "./Pointwise_BoundsArraySet.js"; /** * Extract pointwise convolution filters and biases. * * * @member {number} byteOffsetBegin * The position which is started (inclusive) to extract from inputFloat32Array.buffer by init(). This is relative to the * inputFloat32Array.buffer (not to the inputFloat32Array.byteOffset). * * @member {number} byteOffsetEnd * The position which is ended to (non-inclusive) extract from inputFloat32Array.buffer by init(). Where to extract next weights. * Only meaningful when ( this.bInitOk == true ). This is relative to the inputFloat32Array.buffer (not to the inputFloat32Array.byteOffset). * * @member {BoundsArraySet} boundsArraySet * The element value bounds (per channel) of input, beforeActivation, and output for this pointwise convolution. * * @member {number} outputChannelCount * The output channel count of this pointwise convolutiuon. * - Usually, if ( outputChannelCount == 0 ), it means no operation at all (i.e. bPointwise == bExisted == false ). * - However, if ( outputChannelCount == 0 ) but ( channelShuffler_outputGroupCount > 0 ), this pointwise will exist * (i.e. bPointwise == bExisted == true ) and always will not have biases (no matter how bBias is). It is * all-pass-through-and-channel-shuffling mode. * * @member {number} outputChannelCount_Real * Usually, the same as outputChannelCount. But when ( this.bAllPassThrough == true ) or ( this.bAllPassThroughShuffle == true ), * outputChannelCount_Real will be the same as inputChannelCount (in this case, the outputChannelCount is zero). * * @member {ValueDesc.Pointwise_HigherHalfDifferent} nHigherHalfDifferent * - 0. If ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.NONE ), it is just a normal poitwise convolution. * * - 0.1 If ( outputChannelCount > 0 ), normal poitwise convolution. * * - 0.2 If ( outputChannelCount <= 0 ), no poitwise convolution, no bias, no channel shuffler. ( bPointwise == bExisted == false ). * * - 1. If ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF__LOWER_HALF_PASS_THROUGH ): * * - 1.1 If ( outputChannelCount > 0 ), (i.e. bHigherHalfCopyLowerHalf_LowerHalfPassThrough), * (for pointwise1 of ShuffleNetV2_ByMopbileNetV1's head), * the filters for the output channels between 0 and ( outputChannelCount_lowerHalf - 1 ) will just pass * through the input to output. The filters for the output channels between ( outputChannelCount_lowerHalf ) * and ( outputChannelCount - 1 ) will just copy the input channels between 0 and ( outputChannelCount_lowerHalf - 1 ). * In this case, it will always have no biases (no matter how bBias is). * * - 1.2 If ( outputChannelCount <= 0 ), no poitwise convolution, no bias, no channel shuffler. ( bPointwise == bExisted == false ). * * - 2. If ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF ): * * - 2.1 If ( outputChannelCount > 0 ), (i.e. bHigherHalfCopyLowerHalf), * (for pointwise1 of ShuffleNetV2_ByMopbileNetV1's head), * the filters for the output channels between ( outputChannelCount_lowerHalf ) and ( outputChannelCount - 1 ) will just copy * the input channels between 0 and ( outputChannelCount_lowerHalf - 1 ). * * - 2.2 If ( outputChannelCount <= 0 ), no poitwise convolution, no bias, no channel shuffler. ( bPointwise == bExisted == false ). * * - 3. If ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_ANOTHER_POINTWISE ): * * - 3.1 If ( outputChannelCount > 0 ), (i.e. bHigherHalfAnotherPointwise), * (for pointwise2 of ShuffleNetV2_ByMopbileNetV1's head), * the filters for the input channels between 0 and ( inputChannelCount_lowerHalf - 1 ) are pointwise21, between * ( inputChannelCount_lowerHalf ) and ( inputChannelCount - 1 ) are pointwise212. These two filters (and biases) * will be extracted in sequence, but they will be combined into one larger filters (and biases). This makes these * filters' (and biases') weights are arranged the same as pointwise2 of ShuffleNetV2_ByPointwise22's head. So that * the same filters weights could be used in these two architectures for comparing performance and correctness. * * - 3.2 If ( outputChannelCount <= 0 ), no poitwise convolution, no bias, no channel shuffler. ( bPointwise == bExisted == false ). * * - 4. If ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_PASS_THROUGH ): * (for pointwise1/pointwise2 of ShuffleNetV2_ByMopbileNetV1's body/tail) * * - 4.1 If ( outputChannelCount > 0 ), the filters for the output channels between ( outputChannelCount_lowerHalf ) * and ( outputChannelCount - 1 ) will just pass through the input to output. * * - 4.1.1 If ( channelShuffler_outputGroupCount <= 0 ), (i.e. bHigherHalfPassThrough). * (for pointwise1 of ShuffleNetV2_ByMopbileNetV1's body/tail) * * - 4.1.2 If ( channelShuffler_outputGroupCount > 0 ), (i.e. bHigherHalfPassThroughShuffle). * (for pointwise2 of ShuffleNetV2_ByMopbileNetV1's body/tail) * The output channels will be arranged just like applying channel shuffler on them. * * - 4.2 If ( outputChannelCount <= 0 ), the filters will just pass through all input channels to output. In this case, * the ( bPointwise == bExisted == true ) (not false), although the specified outputChannelCount is zero. And, it * will always have no biases (no matter how bBias is). * * - 4.2.1 If ( channelShuffler_outputGroupCount <= 0 ), (i.e. bAllPassThrough; no pointwise and no channel shuffler). * (for pointwise1 of ShuffleNetV2_ByMopbileNetV1's body/tail) * * - 4.2.2 If ( channelShuffler_outputGroupCount > 0 ), (i.e. bAllPassThroughShuffle). * (for pointwise2 of ShuffleNetV2_ByMopbileNetV1's body/tail) * The output channels will be arranged just like applying channel shuffler on them. * * @member {boolean} bHigherHalfDifferent * It will be false, if ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.NONE ) * or ( outputChannelCount <= 0 ) or ( inputChannelCount_lowerHalf <= 0 ) or ( outputChannelCount_lowerHalf <= 0 ). * * @member {number} inputChannelCount_lowerHalf * The lower half input channel count when ( bHigherHalfDifferent == true ). It is ignored when ( bHigherHalfDifferent == false ). * * @member {number} outputChannelCount_lowerHalf * The lower half output channel count when ( bHigherHalfDifferent == true ). It is ignored when ( bHigherHalfDifferent == false ). * * @member {number} channelShuffler_outputGroupCount * The output group count of the channel shuffler. Usually, it is used when * ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_PASS_THROUGH ). * * @member {number} tensorWeightCountTotal * The total wieght count used in tensors. Not including Params, because they are not used in tensors. Including inferenced * weights, if they are used in tensors. * * @member {number} tensorWeightCountExtracted * The wieght count extracted from inputFloat32Array and used in tensors. Not including Params, because they are not used in * tensors. Not including inferenced weights (even if they are used in tensors), because they are not extracted from inputFloat32Array. * * @member {number[]} filtersShape * The shape of the pointwise convolution filters array. * * @member {number[]} biasesShape * The shape of the pointwise convolution biases array. * * @member {number[]} filtersArray * The pointwise convolution filters array. * * @member {number[]} biasesArray * The pointwise convolution biases array. * */ let FiltersArray_BiasesArray = ( Base = Object ) => class extends Base { /** */ constructor( inputChannelCount, outputChannelCount, bBias, nActivationId, nHigherHalfDifferent, inputChannelCount_lowerHalf, outputChannelCount_lowerHalf, channelShuffler_outputGroupCount ) { super(); this.inputChannelCount = inputChannelCount; this.outputChannelCount = outputChannelCount; this.bBias = bBias; this.nActivationId = nActivationId; this.nHigherHalfDifferent = nHigherHalfDifferent; this.inputChannelCount_lowerHalf = inputChannelCount_lowerHalf; this.outputChannelCount_lowerHalf = outputChannelCount_lowerHalf; this.channelShuffler_outputGroupCount = channelShuffler_outputGroupCount; this.bHigherHalfDifferent = ( nHigherHalfDifferent != ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.NONE ) && ( outputChannelCount > 0 ) && ( inputChannelCount_lowerHalf > 0 ) && ( outputChannelCount_lowerHalf > 0 ); tf.util.assert( ( inputChannelCount > 0 ), `Pointwise.FiltersArray_BiasesArray.constructor(): ` + `inputChannelCount ( ${this.inputChannelCount} ) must be positive integer.` ); tf.util.assert( ( this.inputChannelCount_lowerHalf <= inputChannelCount ), `Pointwise.FiltersArray_BiasesArray.constructor(): ` + `inputChannelCount_lowerHalf ( ${this.inputChannelCount_lowerHalf} ) can not be larger than ` + `inputChannelCount ( ${this.inputChannelCount} ).` ); if ( this.outputChannelCount > 0 ) { tf.util.assert( ( this.outputChannelCount_lowerHalf <= outputChannelCount ), `Pointwise.FiltersArray_BiasesArray.constructor(): ` + `outputChannelCount_lowerHalf ( ${this.outputChannelCount_lowerHalf} ) can not be larger than ` + `outputChannelCount ( ${this.outputChannelCount} ).` ); } else { // ( this.outputChannelCount <= 0 ), the outputChannelCount_Real will be inputChannelCount. tf.util.assert( ( this.outputChannelCount_lowerHalf <= inputChannelCount ), `Pointwise.FiltersArray_BiasesArray.constructor(): ` + `outputChannelCount_lowerHalf ( ${this.outputChannelCount_lowerHalf} ) can not be larger than ` + `inputChannelCount ( ${this.inputChannelCount} ) when ` + `outputChannelCount ( ${this.outputChannelCount} ) is zero or negative.` ); } tf.util.assert( ( this.inputChannelCount_lowerHalf > 0 ) == ( this.outputChannelCount_lowerHalf > 0 ), `Pointwise.FiltersArray_BiasesArray.constructor(): ` + `inputChannelCount_lowerHalf ( ${this.inputChannelCount_lowerHalf} ) and ` + `outputChannelCount_lowerHalf ( ${this.outputChannelCount_lowerHalf} ) ` + `should be both positive or both not.` ); } /** * Extract pointwise filters and biases. * * The following properties will be modified: * - this.byteOffsetBegin * - this.byteOffsetEnd * - this.tensorWeightCountExtracted * - this.tensorWeightCountTotal * - this.boundsArraySet * - this.filtersShape * - this.filtersArray * - this.biasesShape ( if ( this.bBias == true ) ) * - this.biasesArray ( if ( this.bBias == true ) ) * * * @param {Float32Array} inputFloat32Array * A Float32Array whose values will be interpreted as weights. * * @param {ConvBiasActivation.BoundsArraySet} previous_ConvBiasActivation_BoundsArraySet * The previous convolution-bias-activation value bounds set of this depthwise convolution. * * @return {boolean} Return true, if succeeded. */ init( inputFloat32Array, byteOffsetBegin, previous_ConvBiasActivation_BoundsArraySet ) { // Q1: Why is the inputFloat32Array not a parameter of constructor? // A1: The reason is to avoid keeping it as this.inputFloat32Array so that it could be released by memory garbage collector. // // Q2: Why is not the sourceWeights kept in this? // A2: So that inputFloat32Array could be released. tf.util.assert( ( this.inputChannelCount == previous_ConvBiasActivation_BoundsArraySet.output.length ), `Pointwise.FiltersArray_BiasesArray.init(): ` + `inputChannelCount ( ${this.inputChannelCount} ) should be the same as ` + `outputChannelCount of previous convolution-bias-activation ( ${previous_ConvBiasActivation_BoundsArraySet.output.length} ).` ); tf.util.assert( ( this.inputChannelCount == previous_ConvBiasActivation_BoundsArraySet.activationEscaping_ScaleArraySet.undo.length ), `Pointwise.FiltersArray_BiasesArray.init(): ` + `inputChannelCount ( ${this.inputChannelCount} ) should be the same as the length of ` + `activationEscaping_ScaleArraySet.undo of previous convolution-bias-activation ` + `( ${previous_ConvBiasActivation_BoundsArraySet.activationEscaping_ScaleArraySet.undo.length} ).` ); // // Note: Even if ( this.outputChannelCount <= 0 ), this function should work correctly as pass-through input to output. // In fact, this condition is used for all-pass-through-shuffle. // this.byteOffsetBegin = this.byteOffsetEnd = byteOffsetBegin; // Determine shape of the filters, biases, channels. let aFiltersBiasesPartInfoArray; let filtersShape_extracted, biasesShape_extracted; // Set up aFiltersBiasesPartInfoArray and filtersShape and biasesShape. { switch ( this.nHigherHalfDifferent ) { // 3.0 Normal pointwise convolution and bias. case ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.NONE: // (0) this.outputChannelCount_Real = this.outputChannelCount; this.inputChannelCount_toBeExtracted = this.inputChannelCount; // Extract all weights as specified input/output channels. this.outputChannelCount_toBeExtracted = this.outputChannelCount; aFiltersBiasesPartInfoArray = [ //!!! (2022/04/05 Remarked) Always run through all input channels. // new FiltersBiasesPartInfo( this.inputChannelCount, [ new FiltersBiasesPartInfo( [ new ChannelPartInfo( 0, this.inputChannelCount, this.outputChannelCount, false ) ] ) ]; break; // 3.1 bHigherHalfCopyLowerHalf_LowerHalfPassThrough case ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF__LOWER_HALF_PASS_THROUGH: // (1) this.outputChannelCount_Real = this.outputChannelCount; this.inputChannelCount_toBeExtracted = this.outputChannelCount_toBeExtracted = 0; // Does not extract any weights. //this.inputChannelCount_higherHalf = this.inputChannelCount - this.inputChannelCount_lowerHalf; // Not used in this case. this.outputChannelCount_higherHalf = this.outputChannelCount - this.outputChannelCount_lowerHalf; aFiltersBiasesPartInfoArray = [ //!!! (2022/04/05 Remarked) Always run through all input channels. // new FiltersBiasesPartInfo( this.inputChannelCount, [ new FiltersBiasesPartInfo( [ new ChannelPartInfo( 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_lowerHalf, true ), new ChannelPartInfo( 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_higherHalf, true ) ] ) ]; break; // 3.2 bHigherHalfCopyLowerHalf case ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF: // (2) this.outputChannelCount_Real = this.outputChannelCount; this.inputChannelCount_toBeExtracted = this.inputChannelCount_lowerHalf; this.outputChannelCount_toBeExtracted = this.outputChannelCount_lowerHalf; this.inputChannelCount_higherHalf = this.inputChannelCount - this.inputChannelCount_lowerHalf; this.outputChannelCount_higherHalf = this.outputChannelCount - this.outputChannelCount_lowerHalf; aFiltersBiasesPartInfoArray = [ //!!! (2022/04/05 Remarked) Always run through all input channels. // new FiltersBiasesPartInfo( this.inputChannelCount, [ new FiltersBiasesPartInfo( [ new ChannelPartInfo( 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_lowerHalf, false ), new ChannelPartInfo( 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_higherHalf, true ) ] ) ]; break; // 3.3 bHigherHalfAnotherPointwise case ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_ANOTHER_POINTWISE: // (3) this.outputChannelCount_Real = this.outputChannelCount; this.inputChannelCount_toBeExtracted = this.inputChannelCount; // Extract all weights as specified input/output channels. this.outputChannelCount_toBeExtracted = this.outputChannelCount; // (like a normal pointwise convolution, but with a different arrangement.) this.inputChannelCount_higherHalf = this.inputChannelCount - this.inputChannelCount_lowerHalf; this.outputChannelCount_higherHalf = this.outputChannelCount - this.outputChannelCount_lowerHalf; //!!! ...unfinished... (2022/04/05) Need whole input channels for both two pointiwse. // this.outputChannelCount_toBeExtracted = this.outputChannelCount; // (So that biasesShape_extracted will be correct.) // // //!!! ...unfinished... (2022/04/03) should assert if can not be divisible. // // this.inputChannelCount_toBeExtracted // = ( ( this.inputChannelCount_lowerHalf * this.outputChannelCount_lowerHalf ) // + ( this.inputChannelCount_higherHalf * this.outputChannelCount_higherHalf ) ) // / this.outputChannelCount; // (So that this.outputChannelCount_toBeExtracted will be correct.) // // aFiltersBiasesPartInfoArray = [ // new FiltersBiasesPartInfo( this.inputChannelCount_lowerHalf, [ // new ChannelPartInfo( 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_lowerHalf, false ), // new ChannelPartInfo( 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_higherHalf, true ), // ] ), // new FiltersBiasesPartInfo( this.inputChannelCount_higherHalf, [ // new ChannelPartInfo( this.inputChannelCount_lowerHalf, this.inputChannelCount, this.outputChannelCount_lowerHalf, true ), // new ChannelPartInfo( this.inputChannelCount_lowerHalf, this.inputChannelCount, this.outputChannelCount_higherHalf, false ), // ] ) // ]; aFiltersBiasesPartInfoArray = [ new FiltersBiasesPartInfo( [ new ChannelPartInfo( 0, this.inputChannelCount, this.outputChannelCount_lowerHalf, false ), //!!! (2022/04/05 Remarked) // new ChannelPartInfo( 0, this.inputChannelCount, this.outputChannelCount_higherHalf, true ), ] ), new FiltersBiasesPartInfo( [ //!!! (2022/04/05 Remarked) // new ChannelPartInfo( 0, this.inputChannelCount, this.outputChannelCount_lowerHalf, true ), new ChannelPartInfo( 0, this.inputChannelCount, this.outputChannelCount_higherHalf, false ), ] ) ]; //!!! (2022/04/02 Remarked) Whole output channels should be used. // aFiltersBiasesPartInfoArray = [ // // //!!! (2022/04/01 Remarked) Whole input channels are used, but higher half is past-through. // // new FiltersBiasesPartInfo( this.inputChannelCount_lowerHalf, [ // new FiltersBiasesPartInfo( this.inputChannelCount, [ // Whole input channels are used, but higher half is ignored. // new ChannelPartInfo( 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_lowerHalf, false ) // //!!! (2022/04/01 Remarked) Whole input channels are used, but higher half is ignored. // // new ChannelPartInfo( this.inputChannelCount_lowerHalf, this.inputChannelCount, 0, true ) // ] ), // // //!!! (2022/04/01 Remarked) Whole input channels are used, but lower half is past-through. // // new FiltersBiasesPartInfo( this.inputChannelCount_higherHalf, [ // new FiltersBiasesPartInfo( this.inputChannelCount, [ // Whole input channels are used, but lower half is ignored. // //!!! (2022/04/01 Remarked) Whole input channels are used, but lower half is ignored. // // new ChannelPartInfo( 0, this.inputChannelCount_lowerHalf, 0, true ), // new ChannelPartInfo( this.inputChannelCount_lowerHalf, this.inputChannelCount, this.outputChannelCount_higherHalf, false ) // ] ) // ]; break; // 3.4 case ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_PASS_THROUGH: // (4) if ( this.outputChannelCount > 0 ) { // 3.4.1.1 bHigherHalfPassThrough this.outputChannelCount_Real = this.outputChannelCount; this.inputChannelCount_toBeExtracted = this.inputChannelCount_lowerHalf; this.outputChannelCount_toBeExtracted = this.outputChannelCount_lowerHalf; this.inputChannelCount_higherHalf = this.inputChannelCount - this.inputChannelCount_lowerHalf; this.outputChannelCount_higherHalf = this.outputChannelCount - this.outputChannelCount_lowerHalf; aFiltersBiasesPartInfoArray = [ //!!! (2022/04/05 Remarked) Always run through all input channels. // new FiltersBiasesPartInfo( this.inputChannelCount, new FiltersBiasesPartInfo( [ new ChannelPartInfo( 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_lowerHalf, false ), new ChannelPartInfo( this.inputChannelCount_lowerHalf, this.inputChannelCount, this.outputChannelCount_higherHalf, true ) ] ) ]; // Note: If ( HIGHER_HALF_PASS_THROUGH ) with ( inputChannelCount_lowerHalf == 0 ) and ( outputChannelCount_lowerHalf == 0 ), // the result should be the same as AllPassThrough without using special ( outputChannelCount <= 0 ). In that case, however, // the bAllPassThrough will be false. } else { // ( outputChannelCount <= 0 ), // 3.4.2.1 bAllPassThrough this.bAllPassThrough = true; // Marked for this special case. this.outputChannelCount_Real = this.inputChannelCount; // (Note: In this case, this.outputChannelCount is zero. So use inputChannelCount.) this.inputChannelCount_toBeExtracted = this.outputChannelCount_toBeExtracted = 0; // Does not extract any weights. aFiltersBiasesPartInfoArray = [ //!!! (2022/04/05 Remarked) Always run through all input channels. // new FiltersBiasesPartInfo( this.inputChannelCount, new FiltersBiasesPartInfo( [ new ChannelPartInfo( 0, this.inputChannelCount, this.outputChannelCount_Real, true ) ] ) ]; } break; default: tf.util.assert( ( false ), `Pointwise.FiltersArray_BiasesArray.init(): ` + `nHigherHalfDifferent ( ${this.nHigherHalfDifferent} ) is unknown value.` ); break; } this.filtersShape = [ 1, 1, this.inputChannelCount, this.outputChannelCount_Real ]; filtersShape_extracted = [ 1, 1, this.inputChannelCount_toBeExtracted, this.outputChannelCount_toBeExtracted ]; if ( this.bBias ) { //!!! ...unfinished... (2022/04/03) // For ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_ANOTHER_POINTWISE (3), // is this still right? this.biasesShape = [ this.outputChannelCount_Real ]; biasesShape_extracted = [ this.outputChannelCount_toBeExtracted ]; } } // Prepare result filters and biases array. if ( this.filtersShape ) this.filtersArray = new Array( tf.util.sizeFromShape( this.filtersShape ) ); if ( this.biasesShape ) this.biasesArray = new Array( tf.util.sizeFromShape( this.biasesShape ) ); // Calculate weights count of filters and biases to be extracted. let weightsCount_extracted = 0; if ( filtersShape_extracted ) weightsCount_extracted += tf.util.sizeFromShape( filtersShape_extracted ); if ( biasesShape_extracted ) weightsCount_extracted += tf.util.sizeFromShape( biasesShape_extracted ); // Prepare source weights to be extracted. let sourceWeights = new Weights.Base( inputFloat32Array, this.byteOffsetEnd, weightsCount_extracted ); if ( !sourceWeights.extract() ) return false; // e.g. input array does not have enough data. this.byteOffsetEnd = sourceWeights.defaultByteOffsetEnd; this.tensorWeightCountExtracted = weightsCount_extracted; // filters and bias: weights and value bounds. // // It should be better to calculate per channel value bounds by real filter and bias value (i.e. not by an estimated value bounds). // This is especially important for ActivationEscaping. Because inputDomainLinear of activation function is not wide, using looser // value bounds estimation has higher possibility to lost information. // // Two-rounds processing is used: // // - In the 1st round, extracting filter and bias value from sourceWeights[]. At the same time, calculating .afterFilter and // .afterBias by these extracted values combined with undoPreviousEscapingScale // (i.e. previous_ConvBiasActivation_BoundsArraySet.activationEscaping_ScaleArraySet.undo.scales[ inChannel ]). And then, // Find out .activationEscaping_ScaleArraySet, .afterActivationEscaping, .afterActivation. // // - In the 2nd round, apply doEscapingScale (i.e. .activationEscaping_ScaleArraySet.do.scales[ outChannel ] ) // to filter and bias value (and also .afterFilter and .afterBias). // { // Round 0 { this.boundsArraySet = new BoundsArraySet( this.inputChannelCount, this.outputChannelCount_Real ); // Determine .input this.boundsArraySet.input.set_all_byBoundsArray( previous_ConvBiasActivation_BoundsArraySet.output ); // Determine .afterUndoPreviousActivationEscaping this.boundsArraySet.afterUndoPreviousActivationEscaping .set_all_byBoundsArray( this.boundsArraySet.input ) .multiply_all_byNs( previous_ConvBiasActivation_BoundsArraySet.activationEscaping_ScaleArraySet.undo.scales ); } // Round 1 { this.set_filtersArray_biasesArray_afterFilter_afterBias_apply_undoPreviousEscapingScale( sourceWeights.weights, previous_ConvBiasActivation_BoundsArraySet, aFiltersBiasesPartInfoArray ); // Determine .activationEscaping_ScaleArraySet, .afterActivationEscaping, .afterActivation this.boundsArraySet.set_bPassThrough_all_byChannelPartInfoArray( aFiltersBiasesPartInfoArray ); this.boundsArraySet.set_activationEscaping_afterActivationEscaping_afterActivation_by_afterBias_bPassThrough_nActivationId( this.nActivationId ); } // Round 2 this.apply_doEscapingScale_to_filtersArray_biasesArray(); // Apply doEscapingScale. } // Shuffle channels. { switch ( this.nHigherHalfDifferent ) { // 3.4 case ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_PASS_THROUGH: // (4) // 3.4.1.2 bHigherHalfPassThroughShuffle // 3.4.2.2 bAllPassThroughShuffle if ( this.channelShuffler_outputGroupCount > 0 ) { this.output_interleave_asGrouptTwo(); // Pre-shuffle channels by shuffling the filters and biases. } break; } } { this.tensorWeightCountTotal = 0; if ( this.filtersShape ) this.tensorWeightCountTotal += tf.util.sizeFromShape( this.filtersShape ); if ( this.biasesShape ) this.tensorWeightCountTotal += tf.util.sizeFromShape( this.biasesShape ); } return true; } /** * Extract this.filtersArray and this.biasesArray from sourceFloat32Array and * apply this.boundsArraySet.activationEscaping_ScaleArraySet.undo.scales[]. Also set the .afterFilter and .afterBias. * * @param {Float32Array} sourceFloat32Array * A Float32Array whose values will be interpreted as weights. * * @param {ConvBiasActivation.BoundsArraySet} previous_ConvBiasActivation_BoundsArraySet * The previous convolution-bias-activation value bounds set of this pointwise convolution. * * @param {Pointwise.FiltersBiasesPartInfo[]} aFiltersBiasesPartInfoArray * The input channel range array which describe lower/higher half channels index range. */ set_filtersArray_biasesArray_afterFilter_afterBias_apply_undoPreviousEscapingScale( sourceFloat32Array, previous_ConvBiasActivation_BoundsArraySet, aFiltersBiasesPartInfoArray ) { let tBounds = new FloatValue.Bounds( 0, 0 ); // Init { this.boundsArraySet.afterFilter.set_all_byN( 0 ); // Init .afterFilter this.boundsArraySet.afterBias.set_all_byN( 0 ); // Init .afterBias if ( this.biasesArray ) { this.biasesArray.fill( 0 ); } } // Extracting weights of filters and biases. (Including extra scale.) let sourceIndex = 0, filterIndex = 0, biasIndex = 0; //!!! (2022/04/05 Remarked) Always run through all input channels. // let inChannel = 0; let outChannelBegin = 0, outChannelEnd = 0; // [ outChannelBegin, outChannelEnd ) are output channels of the current FiltersBiasesPart. FiltersBiasesPartIndexLoop: for ( let aFiltersBiasesPartIndex = 0; aFiltersBiasesPartIndex < aFiltersBiasesPartInfoArray.length; ++aFiltersBiasesPartIndex ) { let aFiltersBiasesPartInfo = aFiltersBiasesPartInfoArray[ aFiltersBiasesPartIndex ]; let inChannelPartInfoArray = aFiltersBiasesPartInfo.aChannelPartInfoArray; filterIndex = outChannelBegin = outChannelEnd; // Begin from the ending of the previous FiltersBiasesPart. { // this.filtersArray //!!! (2022/04/05 Remarked) Always run through all input channels. // for ( let inChannelSub = 0; inChannelSub < aFiltersBiasesPartInfo.inputChannelCount; ++inChannelSub, ++inChannel ) { // if ( inChannel >= this.inputChannelCount ) // break FiltersBiasesPartIndexLoop; // Never exceeds the total input channel count. for ( let inChannel = 0; inChannel < this.inputChannelCount; ++inChannel ) { let undoPreviousEscapingScale = previous_ConvBiasActivation_BoundsArraySet.activationEscaping_ScaleArraySet.undo.scales[ inChannel ]; let outChannel = outChannelBegin; InChannelPartIndexLoop: for ( let inChannelPartIndex = 0; inChannelPartIndex < inChannelPartInfoArray.length; ++inChannelPartIndex ) { let inChannelPartInfo = inChannelPartInfoArray[ inChannelPartIndex ]; let inChannelToPartBegin = inChannel - inChannelPartInfo.inChannelBegin; for ( let outChannelSub = 0; outChannelSub < inChannelPartInfo.outputChannelCount; ++outChannelSub, ++outChannel ) { if ( outChannel >= this.outputChannelCount ) break InChannelPartIndexLoop; // Never exceeds the total output channel count. if ( ( inChannelToPartBegin >= 0 ) && ( inChannel < inChannelPartInfo.inChannelEnd ) ) { if ( inChannelPartInfo.bPassThrough ) { // For pass-through half channels. if ( inChannelToPartBegin == outChannelSub ) { // The only one filter position (in the pass-through part) has non-zero value. this.filtersArray[ filterIndex ] = undoPreviousEscapingScale; } else { this.filtersArray[ filterIndex ] = 0; // All other filter positions (in the pass-through part) are zero. } } else { // Non-pass-through half channels. this.filtersArray[ filterIndex ] = sourceFloat32Array[ sourceIndex ] * undoPreviousEscapingScale; ++sourceIndex; } // Determine .afterFilter tBounds .set_byBoundsArray( this.boundsArraySet.afterUndoPreviousActivationEscaping, inChannel ) .multiply_byN( this.filtersArray[ filterIndex ] ); this.boundsArraySet.afterFilter.add_one_byBounds( outChannel, tBounds ); } else { this.filtersArray[ filterIndex ] = 0; // All input channels which is not in range use zero filter to ignore the inputs. } ++filterIndex; } // outChannelSub, outChannel } // inChannelPartIndex outChannelEnd = outChannel; // Record the ending output channel index of the current FiltersBiasesPart. filterIndex += ( this.outputChannelCount_Real - outChannel ) + outChannelBegin; // Jump to the outChannelBegin of the next inChannel. } // inChannelSub, inChannel } // this.filtersArray if ( this.biasesArray ) { let outChannel = outChannelBegin; InChannelPartIndexLoop: for ( let inChannelPartIndex = 0; inChannelPartIndex < inChannelPartInfoArray.length; ++inChannelPartIndex ) { let inChannelPartInfo = inChannelPartInfoArray[ inChannelPartIndex ]; for ( let outChannelSub = 0; outChannelSub < inChannelPartInfo.outputChannelCount; ++outChannelSub, ++outChannel ) { if ( outChannel >= this.outputChannelCount ) break InChannelPartIndexLoop; // Never exceeds the total output channel count. // Note: bias is not responsible for undoPreviousEscapingScale. (i.e. the filter already done it) if ( inChannelPartInfo.bPassThrough ) { // For pass-through half channels. // Do nothing because pass-through needs no bias. } else { // Non-pass-through half channels. let biasValue = sourceFloat32Array[ sourceIndex ]; this.biasesArray[ biasIndex ] += biasValue; // Note: Use adding instead assignment. ++sourceIndex; // Determine .afterBias this.boundsArraySet.afterBias.add_one_byN( outChannel, biasValue ); // Shift the value bounds by the bias. } ++biasIndex; } // outChannelSub, outChannel } // inChannelPartIndex } else { // ( !this.biasesArray ). No biases array to be extracted. // Do nothing. } } // aFiltersBiasesPartIndex // Combine .afterFilter to .afterBias. // // Q: Why not combine when initializing .afterBias ? // A: Because .afterFilter is unknown before FiltersBiasesPartInfoArray has been visited totally. // this.boundsArraySet.afterBias.add_all_byBoundsArray( this.boundsArraySet.afterFilter ); //!!! (2022/04/05 Remarked) Always run through all input channels. // tf.util.assert( ( inChannel == this.inputChannelCount ), // `Pointwise.FiltersArray_BiasesArray.set_filtersArray_biasesArray_afterFilter_afterBias_apply_undoPreviousEscapingScale(): ` // + `aFiltersBiasesPartInfoArray[] total input channel count ( ${inChannel} ) should be ( ${this.inputChannelCount} ).` ); tf.util.assert( ( outChannelEnd == this.outputChannelCount_Real ), `Pointwise.FiltersArray_BiasesArray.set_filtersArray_biasesArray_afterFilter_afterBias_apply_undoPreviousEscapingScale(): ` + `aFiltersBiasesPartInfoArray[ inChannelPartInfoArray[] ] total output channel count ( ${outChannelEnd} ) ` + `should be ( ${this.outputChannelCount_Real} ).` ); } /** * Apply this.boundsArraySet.activationEscaping_ScaleArraySet.do.scales[] to this.filtersArray and this.biasesArray. */ apply_doEscapingScale_to_filtersArray_biasesArray() { { // this.filtersArray let filterIndex = 0; for ( let inChannel = 0; inChannel < this.inputChannelCount; ++inChannel ) { for ( let outChannel = 0; outChannel < this.outputChannelCount; ++outChannel, ++outChannel ) { let doEscapingScale = this.boundsArraySet.activationEscaping_ScaleArraySet.do.scales[ outChannel ]; this.filtersArray[ filterIndex ] *= doEscapingScale; // filter wieghts scaled. this.boundsArraySet.afterFilter.multiply_one_byN( outChannel, doEscapingScale ); // value bounds after filter also scaled. ++filterIndex; } // outChannel } // inChannel } // this.filtersArray if ( this.biasesArray ) { let biasIndex = 0; for ( let outChannel = 0; outChannel < this.outputChannelCount; ++outChannel, ++outChannel ) { let doEscapingScale = this.boundsArraySet.activationEscaping_ScaleArraySet.do.scales[ outChannel ]; this.biasesArray[ biasIndex ] *= doEscapingScale; // bias wieghts scaled. this.boundsArraySet.afterBias.multiply_one_byN( outChannel, doEscapingScale ); // value bounds after bias also scaled. ++biasIndex; } // outChannel } else { // ( !this.biasesArray ). No biases array to be extracted. // Do nothing. } } /** * Shuffle (.filtersArray, .biasesArray, .boundsArraySet) by interleaving. * - Only ( outputGroupCount == 2 ) is supported. * - The output channel count must be even (i.e. divisible by 2). * * */ output_interleave_asGrouptTwo() { tf.util.assert( ( this.channelShuffler_outputGroupCount == 2 ), `Pointwise.FiltersArray_BiasesArray.interleave_byGrouptTwo(): ` + `channelShuffler_outputGroupCount ( ${this.channelShuffler_outputGroupCount} ) only 2 is supported.` ); tf.util.assert( ( ( this.outputChannelCount % 2 ) == 0 ), `Pointwise.FiltersArray_BiasesArray.interleave_byGrouptTwo(): ` + `output channel count ( ${this.outputChannelCount} ) must be even (i.e. divisible by 2).` ); let arrayTemp = new Array( this.outputChannelCount ); for ( let indexBegin = 0; indexBegin < this.inputChannelCount; indexBegin += this.outputChannelCount ) { // Shuffle filters. FloatValue.ArrayInterleaver.interleave_asGrouptTwo( this.filtersArray, indexBegin, this.outputChannelCount, arrayTemp ); } if ( this.biasesArray ) FloatValue.ArrayInterleaver.interleave_asGrouptTwo( this.biasesArray, 0, this.biasesArray.length, arrayTemp ); // Shuffle biases. this.boundsArraySet.output_interleave_asGrouptTwo( arrayTemp ); // Shuffle bounds array set of output. } }
CNN/Conv/Pointwise/Pointwise_FiltersArray_BiasesArray.js
export { FiltersArray_BiasesArray }; import * as FloatValue from "../../Unpacker/FloatValue.js"; import * as ValueDesc from "../../Unpacker/ValueDesc.js"; import * as Weights from "../../Unpacker/Weights.js"; import * as ConvBiasActivation from "../ConvBiasActivation.js"; import { ChannelPartInfo, FiltersBiasesPartInfo } from "./Pointwise_ChannelPartInfo.js"; import { BoundsArraySet } from "./Pointwise_BoundsArraySet.js"; /** * Extract pointwise convolution filters and biases. * * * @member {number} byteOffsetBegin * The position which is started (inclusive) to extract from inputFloat32Array.buffer by init(). This is relative to the * inputFloat32Array.buffer (not to the inputFloat32Array.byteOffset). * * @member {number} byteOffsetEnd * The position which is ended to (non-inclusive) extract from inputFloat32Array.buffer by init(). Where to extract next weights. * Only meaningful when ( this.bInitOk == true ). This is relative to the inputFloat32Array.buffer (not to the inputFloat32Array.byteOffset). * * @member {BoundsArraySet} boundsArraySet * The element value bounds (per channel) of input, beforeActivation, and output for this pointwise convolution. * * @member {number} outputChannelCount * The output channel count of this pointwise convolutiuon. * - Usually, if ( outputChannelCount == 0 ), it means no operation at all (i.e. bPointwise == bExisted == false ). * - However, if ( outputChannelCount == 0 ) but ( channelShuffler_outputGroupCount > 0 ), this pointwise will exist * (i.e. bPointwise == bExisted == true ) and always will not have biases (no matter how bBias is). It is * all-pass-through-and-channel-shuffling mode. * * @member {number} outputChannelCount_Real * Usually, the same as outputChannelCount. But when ( this.bAllPassThrough == true ) or ( this.bAllPassThroughShuffle == true ), * outputChannelCount_Real will be the same as inputChannelCount (in this case, the outputChannelCount is zero). * * @member {ValueDesc.Pointwise_HigherHalfDifferent} nHigherHalfDifferent * - 0. If ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.NONE ), it is just a normal poitwise convolution. * * - 0.1 If ( outputChannelCount > 0 ), normal poitwise convolution. * * - 0.2 If ( outputChannelCount <= 0 ), no poitwise convolution, no bias, no channel shuffler. ( bPointwise == bExisted == false ). * * - 1. If ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF__LOWER_HALF_PASS_THROUGH ): * * - 1.1 If ( outputChannelCount > 0 ), (i.e. bHigherHalfCopyLowerHalf_LowerHalfPassThrough), * (for pointwise1 of ShuffleNetV2_ByMopbileNetV1's head), * the filters for the output channels between 0 and ( outputChannelCount_lowerHalf - 1 ) will just pass * through the input to output. The filters for the output channels between ( outputChannelCount_lowerHalf ) * and ( outputChannelCount - 1 ) will just copy the input channels between 0 and ( outputChannelCount_lowerHalf - 1 ). * In this case, it will always have no biases (no matter how bBias is). * * - 1.2 If ( outputChannelCount <= 0 ), no poitwise convolution, no bias, no channel shuffler. ( bPointwise == bExisted == false ). * * - 2. If ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF ): * * - 2.1 If ( outputChannelCount > 0 ), (i.e. bHigherHalfCopyLowerHalf), * (for pointwise1 of ShuffleNetV2_ByMopbileNetV1's head), * the filters for the output channels between ( outputChannelCount_lowerHalf ) and ( outputChannelCount - 1 ) will just copy * the input channels between 0 and ( outputChannelCount_lowerHalf - 1 ). * * - 2.2 If ( outputChannelCount <= 0 ), no poitwise convolution, no bias, no channel shuffler. ( bPointwise == bExisted == false ). * * - 3. If ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_ANOTHER_POINTWISE ): * * - 3.1 If ( outputChannelCount > 0 ), (i.e. bHigherHalfAnotherPointwise), * (for pointwise2 of ShuffleNetV2_ByMopbileNetV1's head), * the filters for the input channels between 0 and ( inputChannelCount_lowerHalf - 1 ) are pointwise21, between * ( inputChannelCount_lowerHalf ) and ( inputChannelCount - 1 ) are pointwise212. These two filters (and biases) * will be extracted in sequence, but they will be combined into one larger filters (and biases). This makes these * filters' (and biases') weights are arranged the same as pointwise2 of ShuffleNetV2_ByPointwise22's head. So that * the same filters weights could be used in these two architectures for comparing performance and correctness. * * - 3.2 If ( outputChannelCount <= 0 ), no poitwise convolution, no bias, no channel shuffler. ( bPointwise == bExisted == false ). * * - 4. If ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_PASS_THROUGH ): * (for pointwise1/pointwise2 of ShuffleNetV2_ByMopbileNetV1's body/tail) * * - 4.1 If ( outputChannelCount > 0 ), the filters for the output channels between ( outputChannelCount_lowerHalf ) * and ( outputChannelCount - 1 ) will just pass through the input to output. * * - 4.1.1 If ( channelShuffler_outputGroupCount <= 0 ), (i.e. bHigherHalfPassThrough). * (for pointwise1 of ShuffleNetV2_ByMopbileNetV1's body/tail) * * - 4.1.2 If ( channelShuffler_outputGroupCount > 0 ), (i.e. bHigherHalfPassThroughShuffle). * (for pointwise2 of ShuffleNetV2_ByMopbileNetV1's body/tail) * The output channels will be arranged just like applying channel shuffler on them. * * - 4.2 If ( outputChannelCount <= 0 ), the filters will just pass through all input channels to output. In this case, * the ( bPointwise == bExisted == true ) (not false), although the specified outputChannelCount is zero. And, it * will always have no biases (no matter how bBias is). * * - 4.2.1 If ( channelShuffler_outputGroupCount <= 0 ), (i.e. bAllPassThrough; no pointwise and no channel shuffler). * (for pointwise1 of ShuffleNetV2_ByMopbileNetV1's body/tail) * * - 4.2.2 If ( channelShuffler_outputGroupCount > 0 ), (i.e. bAllPassThroughShuffle). * (for pointwise2 of ShuffleNetV2_ByMopbileNetV1's body/tail) * The output channels will be arranged just like applying channel shuffler on them. * * @member {boolean} bHigherHalfDifferent * It will be false, if ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.NONE ) * or ( outputChannelCount <= 0 ) or ( inputChannelCount_lowerHalf <= 0 ) or ( outputChannelCount_lowerHalf <= 0 ). * * @member {number} inputChannelCount_lowerHalf * The lower half input channel count when ( bHigherHalfDifferent == true ). It is ignored when ( bHigherHalfDifferent == false ). * * @member {number} outputChannelCount_lowerHalf * The lower half output channel count when ( bHigherHalfDifferent == true ). It is ignored when ( bHigherHalfDifferent == false ). * * @member {number} channelShuffler_outputGroupCount * The output group count of the channel shuffler. Usually, it is used when * ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_PASS_THROUGH ). * * @member {number} tensorWeightCountTotal * The total wieght count used in tensors. Not including Params, because they are not used in tensors. Including inferenced * weights, if they are used in tensors. * * @member {number} tensorWeightCountExtracted * The wieght count extracted from inputFloat32Array and used in tensors. Not including Params, because they are not used in * tensors. Not including inferenced weights (even if they are used in tensors), because they are not extracted from inputFloat32Array. * * @member {number[]} filtersShape * The shape of the pointwise convolution filters array. * * @member {number[]} biasesShape * The shape of the pointwise convolution biases array. * * @member {number[]} filtersArray * The pointwise convolution filters array. * * @member {number[]} biasesArray * The pointwise convolution biases array. * */ let FiltersArray_BiasesArray = ( Base = Object ) => class extends Base { /** */ constructor( inputChannelCount, outputChannelCount, bBias, nActivationId, nHigherHalfDifferent, inputChannelCount_lowerHalf, outputChannelCount_lowerHalf, channelShuffler_outputGroupCount ) { super(); this.inputChannelCount = inputChannelCount; this.outputChannelCount = outputChannelCount; this.bBias = bBias; this.nActivationId = nActivationId; this.nHigherHalfDifferent = nHigherHalfDifferent; this.inputChannelCount_lowerHalf = inputChannelCount_lowerHalf; this.outputChannelCount_lowerHalf = outputChannelCount_lowerHalf; this.channelShuffler_outputGroupCount = channelShuffler_outputGroupCount; this.bHigherHalfDifferent = ( nHigherHalfDifferent != ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.NONE ) && ( outputChannelCount > 0 ) && ( inputChannelCount_lowerHalf > 0 ) && ( outputChannelCount_lowerHalf > 0 ); tf.util.assert( ( inputChannelCount > 0 ), `Pointwise.FiltersArray_BiasesArray.constructor(): ` + `inputChannelCount ( ${this.inputChannelCount} ) must be positive integer.` ); tf.util.assert( ( this.inputChannelCount_lowerHalf <= inputChannelCount ), `Pointwise.FiltersArray_BiasesArray.constructor(): ` + `inputChannelCount_lowerHalf ( ${this.inputChannelCount_lowerHalf} ) can not be larger than ` + `inputChannelCount ( ${this.inputChannelCount} ).` ); if ( this.outputChannelCount > 0 ) { tf.util.assert( ( this.outputChannelCount_lowerHalf <= outputChannelCount ), `Pointwise.FiltersArray_BiasesArray.constructor(): ` + `outputChannelCount_lowerHalf ( ${this.outputChannelCount_lowerHalf} ) can not be larger than ` + `outputChannelCount ( ${this.outputChannelCount} ).` ); } else { // ( this.outputChannelCount <= 0 ), the outputChannelCount_Real will be inputChannelCount. tf.util.assert( ( this.outputChannelCount_lowerHalf <= inputChannelCount ), `Pointwise.FiltersArray_BiasesArray.constructor(): ` + `outputChannelCount_lowerHalf ( ${this.outputChannelCount_lowerHalf} ) can not be larger than ` + `inputChannelCount ( ${this.inputChannelCount} ) when ` + `outputChannelCount ( ${this.outputChannelCount} ) is zero or negative.` ); } tf.util.assert( ( this.inputChannelCount_lowerHalf > 0 ) == ( this.outputChannelCount_lowerHalf > 0 ), `Pointwise.FiltersArray_BiasesArray.constructor(): ` + `inputChannelCount_lowerHalf ( ${this.inputChannelCount_lowerHalf} ) and ` + `outputChannelCount_lowerHalf ( ${this.outputChannelCount_lowerHalf} ) ` + `should be both positive or both not.` ); } /** * Extract pointwise filters and biases. * * The following properties will be modified: * - this.byteOffsetBegin * - this.byteOffsetEnd * - this.tensorWeightCountExtracted * - this.tensorWeightCountTotal * - this.boundsArraySet * - this.filtersShape * - this.filtersArray * - this.biasesShape ( if ( this.bBias == true ) ) * - this.biasesArray ( if ( this.bBias == true ) ) * * * @param {Float32Array} inputFloat32Array * A Float32Array whose values will be interpreted as weights. * * @param {ConvBiasActivation.BoundsArraySet} previous_ConvBiasActivation_BoundsArraySet * The previous convolution-bias-activation value bounds set of this depthwise convolution. * * @return {boolean} Return true, if succeeded. */ init( inputFloat32Array, byteOffsetBegin, previous_ConvBiasActivation_BoundsArraySet ) { // Q1: Why is the inputFloat32Array not a parameter of constructor? // A1: The reason is to avoid keeping it as this.inputFloat32Array so that it could be released by memory garbage collector. // // Q2: Why is not the sourceWeights kept in this? // A2: So that inputFloat32Array could be released. tf.util.assert( ( this.inputChannelCount == previous_ConvBiasActivation_BoundsArraySet.output.length ), `Pointwise.FiltersArray_BiasesArray.init(): ` + `inputChannelCount ( ${this.inputChannelCount} ) should be the same as ` + `outputChannelCount of previous convolution-bias-activation ( ${previous_ConvBiasActivation_BoundsArraySet.output.length} ).` ); tf.util.assert( ( this.inputChannelCount == previous_ConvBiasActivation_BoundsArraySet.activationEscaping_ScaleArraySet.undo.length ), `Pointwise.FiltersArray_BiasesArray.init(): ` + `inputChannelCount ( ${this.inputChannelCount} ) should be the same as the length of ` + `activationEscaping_ScaleArraySet.undo of previous convolution-bias-activation ` + `( ${previous_ConvBiasActivation_BoundsArraySet.activationEscaping_ScaleArraySet.undo.length} ).` ); // // Note: Even if ( this.outputChannelCount <= 0 ), this function should work correctly as pass-through input to output. // In fact, this condition is used for all-pass-through-shuffle. // this.byteOffsetBegin = this.byteOffsetEnd = byteOffsetBegin; // Determine shape of the filters, biases, channels. let aFiltersBiasesPartInfoArray; let filtersShape_extracted, biasesShape_extracted; // Set up aFiltersBiasesPartInfoArray and filtersShape and biasesShape. { switch ( this.nHigherHalfDifferent ) { // 3.0 Normal pointwise convolution and bias. case ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.NONE: // (0) this.outputChannelCount_Real = this.outputChannelCount; this.inputChannelCount_toBeExtracted = this.inputChannelCount; // Extract all weights as specified input/output channels. this.outputChannelCount_toBeExtracted = this.outputChannelCount; aFiltersBiasesPartInfoArray = [ //!!! (2022/04/05 Remarked) Always run through all input channels. // new FiltersBiasesPartInfo( this.inputChannelCount, [ new FiltersBiasesPartInfo( [ new ChannelPartInfo( 0, this.inputChannelCount, this.outputChannelCount, false ) ] ) ]; break; // 3.1 bHigherHalfCopyLowerHalf_LowerHalfPassThrough case ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF__LOWER_HALF_PASS_THROUGH: // (1) this.outputChannelCount_Real = this.outputChannelCount; this.inputChannelCount_toBeExtracted = this.outputChannelCount_toBeExtracted = 0; // Does not extract any weights. //this.inputChannelCount_higherHalf = this.inputChannelCount - this.inputChannelCount_lowerHalf; // Not used in this case. this.outputChannelCount_higherHalf = this.outputChannelCount - this.outputChannelCount_lowerHalf; aFiltersBiasesPartInfoArray = [ //!!! (2022/04/05 Remarked) Always run through all input channels. // new FiltersBiasesPartInfo( this.inputChannelCount, [ new FiltersBiasesPartInfo( [ new ChannelPartInfo( 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_lowerHalf, true ), new ChannelPartInfo( 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_higherHalf, true ) ] ) ]; break; // 3.2 bHigherHalfCopyLowerHalf case ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF: // (2) this.outputChannelCount_Real = this.outputChannelCount; this.inputChannelCount_toBeExtracted = this.inputChannelCount_lowerHalf; this.outputChannelCount_toBeExtracted = this.outputChannelCount_lowerHalf; this.inputChannelCount_higherHalf = this.inputChannelCount - this.inputChannelCount_lowerHalf; this.outputChannelCount_higherHalf = this.outputChannelCount - this.outputChannelCount_lowerHalf; aFiltersBiasesPartInfoArray = [ //!!! (2022/04/05 Remarked) Always run through all input channels. // new FiltersBiasesPartInfo( this.inputChannelCount, [ new FiltersBiasesPartInfo( [ new ChannelPartInfo( 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_lowerHalf, false ), new ChannelPartInfo( 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_higherHalf, true ) ] ) ]; break; // 3.3 bHigherHalfAnotherPointwise case ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_ANOTHER_POINTWISE: // (3) this.outputChannelCount_Real = this.outputChannelCount; this.inputChannelCount_toBeExtracted = this.inputChannelCount; // Extract all weights as specified input/output channels. this.outputChannelCount_toBeExtracted = this.outputChannelCount; // (like a normal pointwise convolution, but with a different arrangement.) this.inputChannelCount_higherHalf = this.inputChannelCount - this.inputChannelCount_lowerHalf; this.outputChannelCount_higherHalf = this.outputChannelCount - this.outputChannelCount_lowerHalf; //!!! ...unfinished... (2022/04/05) Need whole input channels for both two pointiwse. // this.outputChannelCount_toBeExtracted = this.outputChannelCount; // (So that biasesShape_extracted will be correct.) // // //!!! ...unfinished... (2022/04/03) should assert if can not be divisible. // // this.inputChannelCount_toBeExtracted // = ( ( this.inputChannelCount_lowerHalf * this.outputChannelCount_lowerHalf ) // + ( this.inputChannelCount_higherHalf * this.outputChannelCount_higherHalf ) ) // / this.outputChannelCount; // (So that this.outputChannelCount_toBeExtracted will be correct.) // // aFiltersBiasesPartInfoArray = [ // new FiltersBiasesPartInfo( this.inputChannelCount_lowerHalf, [ // new ChannelPartInfo( 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_lowerHalf, false ), // new ChannelPartInfo( 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_higherHalf, true ), // ] ), // new FiltersBiasesPartInfo( this.inputChannelCount_higherHalf, [ // new ChannelPartInfo( this.inputChannelCount_lowerHalf, this.inputChannelCount, this.outputChannelCount_lowerHalf, true ), // new ChannelPartInfo( this.inputChannelCount_lowerHalf, this.inputChannelCount, this.outputChannelCount_higherHalf, false ), // ] ) // ]; aFiltersBiasesPartInfoArray = [ new FiltersBiasesPartInfo( [ new ChannelPartInfo( 0, this.inputChannelCount, this.outputChannelCount_lowerHalf, false ), //!!! (2022/04/05 Remarked) // new ChannelPartInfo( 0, this.inputChannelCount, this.outputChannelCount_higherHalf, true ), ] ), new FiltersBiasesPartInfo( [ //!!! (2022/04/05 Remarked) // new ChannelPartInfo( 0, this.inputChannelCount, this.outputChannelCount_lowerHalf, true ), new ChannelPartInfo( 0, this.inputChannelCount, this.outputChannelCount_higherHalf, false ), ] ) ]; //!!! (2022/04/02 Remarked) Whole output channels should be used. // aFiltersBiasesPartInfoArray = [ // // //!!! (2022/04/01 Remarked) Whole input channels are used, but higher half is past-through. // // new FiltersBiasesPartInfo( this.inputChannelCount_lowerHalf, [ // new FiltersBiasesPartInfo( this.inputChannelCount, [ // Whole input channels are used, but higher half is ignored. // new ChannelPartInfo( 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_lowerHalf, false ) // //!!! (2022/04/01 Remarked) Whole input channels are used, but higher half is ignored. // // new ChannelPartInfo( this.inputChannelCount_lowerHalf, this.inputChannelCount, 0, true ) // ] ), // // //!!! (2022/04/01 Remarked) Whole input channels are used, but lower half is past-through. // // new FiltersBiasesPartInfo( this.inputChannelCount_higherHalf, [ // new FiltersBiasesPartInfo( this.inputChannelCount, [ // Whole input channels are used, but lower half is ignored. // //!!! (2022/04/01 Remarked) Whole input channels are used, but lower half is ignored. // // new ChannelPartInfo( 0, this.inputChannelCount_lowerHalf, 0, true ), // new ChannelPartInfo( this.inputChannelCount_lowerHalf, this.inputChannelCount, this.outputChannelCount_higherHalf, false ) // ] ) // ]; break; // 3.4 case ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_PASS_THROUGH: // (4) if ( this.outputChannelCount > 0 ) { // 3.4.1.1 bHigherHalfPassThrough this.outputChannelCount_Real = this.outputChannelCount; this.inputChannelCount_toBeExtracted = this.inputChannelCount_lowerHalf; this.outputChannelCount_toBeExtracted = this.outputChannelCount_lowerHalf; this.inputChannelCount_higherHalf = this.inputChannelCount - this.inputChannelCount_lowerHalf; this.outputChannelCount_higherHalf = this.outputChannelCount - this.outputChannelCount_lowerHalf; aFiltersBiasesPartInfoArray = [ //!!! (2022/04/05 Remarked) Always run through all input channels. // new FiltersBiasesPartInfo( this.inputChannelCount, new FiltersBiasesPartInfo( [ new ChannelPartInfo( 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_lowerHalf, false ), new ChannelPartInfo( this.inputChannelCount_lowerHalf, this.inputChannelCount, this.outputChannelCount_higherHalf, true ) ] ) ]; // Note: If ( HIGHER_HALF_PASS_THROUGH ) with ( inputChannelCount_lowerHalf == 0 ) and ( outputChannelCount_lowerHalf == 0 ), // the result should be the same as AllPassThrough without using special ( outputChannelCount <= 0 ). In that case, however, // the bAllPassThrough will be false. } else { // ( outputChannelCount <= 0 ), // 3.4.2.1 bAllPassThrough this.bAllPassThrough = true; // Marked for this special case. this.outputChannelCount_Real = this.inputChannelCount; // (Note: In this case, this.outputChannelCount is zero. So use inputChannelCount.) this.inputChannelCount_toBeExtracted = this.outputChannelCount_toBeExtracted = 0; // Does not extract any weights. aFiltersBiasesPartInfoArray = [ //!!! (2022/04/05 Remarked) Always run through all input channels. // new FiltersBiasesPartInfo( this.inputChannelCount, new FiltersBiasesPartInfo( [ new ChannelPartInfo( 0, this.inputChannelCount, this.outputChannelCount_Real, true ) ] ) ]; } break; default: tf.util.assert( ( false ), `Pointwise.FiltersArray_BiasesArray.init(): ` + `nHigherHalfDifferent ( ${this.nHigherHalfDifferent} ) is unknown value.` ); break; } this.filtersShape = [ 1, 1, this.inputChannelCount, this.outputChannelCount_Real ]; filtersShape_extracted = [ 1, 1, this.inputChannelCount_toBeExtracted, this.outputChannelCount_toBeExtracted ]; if ( this.bBias ) { //!!! ...unfinished... (2022/04/03) // For ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_ANOTHER_POINTWISE (3), // is this still right? this.biasesShape = [ this.outputChannelCount_Real ]; biasesShape_extracted = [ this.outputChannelCount_toBeExtracted ]; } } // Prepare result filters and biases array. if ( this.filtersShape ) this.filtersArray = new Array( tf.util.sizeFromShape( this.filtersShape ) ); if ( this.biasesShape ) this.biasesArray = new Array( tf.util.sizeFromShape( this.biasesShape ) ); // Calculate weights count of filters and biases to be extracted. let weightsCount_extracted = 0; if ( filtersShape_extracted ) weightsCount_extracted += tf.util.sizeFromShape( filtersShape_extracted ); if ( biasesShape_extracted ) weightsCount_extracted += tf.util.sizeFromShape( biasesShape_extracted ); // Prepare source weights to be extracted. let sourceWeights = new Weights.Base( inputFloat32Array, this.byteOffsetEnd, weightsCount_extracted ); if ( !sourceWeights.extract() ) return false; // e.g. input array does not have enough data. this.byteOffsetEnd = sourceWeights.defaultByteOffsetEnd; this.tensorWeightCountExtracted = weightsCount_extracted; // filters and bias: weights and value bounds. // // It should be better to calculate per channel value bounds by real filter and bias value (i.e. not by an estimated value bounds). // This is especially important for ActivationEscaping. Because inputDomainLinear of activation function is not wide, using looser // value bounds estimation has higher possibility to lost information. // // Two-rounds processing is used: // // - In the 1st round, extracting filter and bias value from sourceWeights[]. At the same time, calculating .afterFilter and // .afterBias by these extracted values combined with undoPreviousEscapingScale // (i.e. previous_ConvBiasActivation_BoundsArraySet.activationEscaping_ScaleArraySet.undo.scales[ inChannel ]). And then, // Find out .activationEscaping_ScaleArraySet, .afterActivationEscaping, .afterActivation. // // - In the 2nd round, apply doEscapingScale (i.e. .activationEscaping_ScaleArraySet.do.scales[ outChannel ] ) // to filter and bias value (and also .afterFilter and .afterBias). // { // Round 0 { this.boundsArraySet = new BoundsArraySet( this.inputChannelCount, this.outputChannelCount_Real ); // Determine .input this.boundsArraySet.input.set_all_byBoundsArray( previous_ConvBiasActivation_BoundsArraySet.output ); // Determine .afterUndoPreviousActivationEscaping this.boundsArraySet.afterUndoPreviousActivationEscaping .set_all_byBoundsArray( this.boundsArraySet.input ) .multiply_all_byNs( previous_ConvBiasActivation_BoundsArraySet.activationEscaping_ScaleArraySet.undo.scales ); } // Round 1 { this.set_filtersArray_biasesArray_afterFilter_afterBias_apply_undoPreviousEscapingScale( sourceWeights.weights, previous_ConvBiasActivation_BoundsArraySet, aFiltersBiasesPartInfoArray ); // Determine .activationEscaping_ScaleArraySet, .afterActivationEscaping, .afterActivation this.boundsArraySet.set_bPassThrough_all_byChannelPartInfoArray( aFiltersBiasesPartInfoArray ); this.boundsArraySet.set_activationEscaping_afterActivationEscaping_afterActivation_by_afterBias_bPassThrough_nActivationId( this.nActivationId ); } // Round 2 this.apply_doEscapingScale_to_filtersArray_biasesArray(); // Apply doEscapingScale. } // Shuffle channels. { switch ( this.nHigherHalfDifferent ) { // 3.4 case ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_PASS_THROUGH: // (4) // 3.4.1.2 bHigherHalfPassThroughShuffle // 3.4.2.2 bAllPassThroughShuffle if ( this.channelShuffler_outputGroupCount > 0 ) { this.output_interleave_asGrouptTwo(); // Pre-shuffle channels by shuffling the filters and biases. } break; } } { this.tensorWeightCountTotal = 0; if ( this.filtersShape ) this.tensorWeightCountTotal += tf.util.sizeFromShape( this.filtersShape ); if ( this.biasesShape ) this.tensorWeightCountTotal += tf.util.sizeFromShape( this.biasesShape ); } return true; } /** * Extract this.filtersArray and this.biasesArray from sourceFloat32Array and * apply this.boundsArraySet.activationEscaping_ScaleArraySet.undo.scales[]. Also set the .afterFilter and .afterBias. * * @param {Float32Array} sourceFloat32Array * A Float32Array whose values will be interpreted as weights. * * @param {ConvBiasActivation.BoundsArraySet} previous_ConvBiasActivation_BoundsArraySet * The previous convolution-bias-activation value bounds set of this pointwise convolution. * * @param {Pointwise.FiltersBiasesPartInfo[]} aFiltersBiasesPartInfoArray * The input channel range array which describe lower/higher half channels index range. */ set_filtersArray_biasesArray_afterFilter_afterBias_apply_undoPreviousEscapingScale( sourceFloat32Array, previous_ConvBiasActivation_BoundsArraySet, aFiltersBiasesPartInfoArray ) { let tBounds = new FloatValue.Bounds( 0, 0 ); // Init { this.boundsArraySet.afterFilter.set_all_byN( 0 ); // Init .afterFilter this.boundsArraySet.afterBias.set_all_byN( 0 ); // Init .afterBias if ( this.biasesArray ) { this.biasesArray.fill( 0 ); } } // Extracting weights of filters and biases. (Including extra scale.) let sourceIndex = 0, filterIndex = 0, biasIndex = 0; //!!! (2022/04/05 Remarked) Always run through all input channels. // let inChannel = 0; let outChannelBegin = 0, outChannelEnd = 0; // [ outChannelBegin, outChannelEnd ) are output channels of the current FiltersBiasesPart. FiltersBiasesPartIndexLoop: for ( let aFiltersBiasesPartIndex = 0; aFiltersBiasesPartIndex < aFiltersBiasesPartInfoArray.length; ++aFiltersBiasesPartIndex ) { let aFiltersBiasesPartInfo = aFiltersBiasesPartInfoArray[ aFiltersBiasesPartIndex ]; let inChannelPartInfoArray = aFiltersBiasesPartInfo.aChannelPartInfoArray; filterIndex = outChannelBegin = outChannelEnd; // Begin from the ending of the previous FiltersBiasesPart. { // this.filtersArray //!!! (2022/04/05 Remarked) Always run through all input channels. // for ( let inChannelSub = 0; inChannelSub < aFiltersBiasesPartInfo.inputChannelCount; ++inChannelSub, ++inChannel ) { // if ( inChannel >= this.inputChannelCount ) // break FiltersBiasesPartIndexLoop; // Never exceeds the total input channel count. for ( let inChannel = 0; inChannel < this.inputChannelCount; ++inChannel ) { let undoPreviousEscapingScale = previous_ConvBiasActivation_BoundsArraySet.activationEscaping_ScaleArraySet.undo.scales[ inChannel ]; let outChannel = outChannelBegin; InChannelPartIndexLoop: for ( let inChannelPartIndex = 0; inChannelPartIndex < inChannelPartInfoArray.length; ++inChannelPartIndex ) { let inChannelPartInfo = inChannelPartInfoArray[ inChannelPartIndex ]; let inChannelToPartBegin = inChannel - inChannelPartInfo.inChannelBegin; for ( let outChannelSub = 0; outChannelSub < inChannelPartInfo.outputChannelCount; ++outChannelSub, ++outChannel ) { if ( outChannel >= this.outputChannelCount ) break InChannelPartIndexLoop; // Never exceeds the total output channel count. if ( ( inChannelToPartBegin >= 0 ) && ( inChannel < inChannelPartInfo.inChannelEnd ) ) { if ( inChannelPartInfo.bPassThrough ) { // For pass-through half channels. if ( inChannelToPartBegin == outChannelSub ) { // The only one filter position (in the pass-through part) has non-zero value. this.filtersArray[ filterIndex ] = undoPreviousEscapingScale; } else { this.filtersArray[ filterIndex ] = 0; // All other filter positions (in the pass-through part) are zero. } } else { // Non-pass-through half channels. this.filtersArray[ filterIndex ] = sourceFloat32Array[ sourceIndex ] * undoPreviousEscapingScale; ++sourceIndex; } // Determine .afterFilter tBounds .set_byBoundsArray( this.boundsArraySet.afterUndoPreviousActivationEscaping, inChannel ) .multiply_byN( this.filtersArray[ filterIndex ] ); this.boundsArraySet.afterFilter.add_one_byBounds( outChannel, tBounds ); } else { this.filtersArray[ filterIndex ] = 0; // All input channels which is not in range use zero filter to ignore the inputs. } ++filterIndex; } // outChannelSub, outChannel } // inChannelPartIndex outChannelEnd = outChannel; // Record the ending output channel index of the current FiltersBiasesPart. filterIndex += ( this.outputChannelCount_Real - outChannel ) + outChannelBegin; // Jump to the outChannelBegin of the next inChannel. } // inChannelSub, inChannel } // this.filtersArray if ( this.biasesArray ) { let outChannel = outChannelBegin; InChannelPartIndexLoop: for ( let inChannelPartIndex = 0; inChannelPartIndex < inChannelPartInfoArray.length; ++inChannelPartIndex ) { let inChannelPartInfo = inChannelPartInfoArray[ inChannelPartIndex ]; for ( let outChannelSub = 0; outChannelSub < inChannelPartInfo.outputChannelCount; ++outChannelSub, ++outChannel ) { if ( outChannel >= this.outputChannelCount ) break InChannelPartIndexLoop; // Never exceeds the total output channel count. // Note: bias is not responsible for undoPreviousEscapingScale. (i.e. the filter already done it) if ( inChannelPartInfo.bPassThrough ) { // For pass-through half channels. // Do nothing because pass-through needs no bias. } else { // Non-pass-through half channels. let biasValue = sourceFloat32Array[ sourceIndex ]; this.biasesArray[ biasIndex ] += biasValue; // Note: Use adding instead assignment. ++sourceIndex; // Determine .afterBias this.boundsArraySet.afterBias.add_one_byN( outChannel, biasValue ); // Shift the value bounds by the bias. } ++biasIndex; } // outChannelSub, outChannel } // inChannelPartIndex } else { // ( !this.biasesArray ). No biases array to be extracted. // Do nothing. } } // aFiltersBiasesPartIndex // Combine .afterFilter to .afterBias. // // Q: Why not combine when initializing .afterBias ? // A: Because .afterFilter is unknown before FiltersBiasesPartInfoArray has been visited totally. // this.boundsArraySet.afterBias.add_all_byBoundsArray( this.boundsArraySet.afterFilter ); tf.util.assert( ( inChannel == this.inputChannelCount ), `Pointwise.FiltersArray_BiasesArray.set_filtersArray_biasesArray_afterFilter_afterBias_apply_undoPreviousEscapingScale(): ` + `aFiltersBiasesPartInfoArray[] total input channel count ( ${inChannel} ) should be ( ${this.inputChannelCount} ).` ); tf.util.assert( ( outChannelEnd == this.outputChannelCount_Real ), `Pointwise.FiltersArray_BiasesArray.set_filtersArray_biasesArray_afterFilter_afterBias_apply_undoPreviousEscapingScale(): ` + `aFiltersBiasesPartInfoArray[ inChannelPartInfoArray[] ] total output channel count ( ${outChannelEnd} ) ` + `should be ( ${this.outputChannelCount_Real} ).` ); } /** * Apply this.boundsArraySet.activationEscaping_ScaleArraySet.do.scales[] to this.filtersArray and this.biasesArray. */ apply_doEscapingScale_to_filtersArray_biasesArray() { { // this.filtersArray let filterIndex = 0; for ( let inChannel = 0; inChannel < this.inputChannelCount; ++inChannel ) { for ( let outChannel = 0; outChannel < this.outputChannelCount; ++outChannel, ++outChannel ) { let doEscapingScale = this.boundsArraySet.activationEscaping_ScaleArraySet.do.scales[ outChannel ]; this.filtersArray[ filterIndex ] *= doEscapingScale; // filter wieghts scaled. this.boundsArraySet.afterFilter.multiply_one_byN( outChannel, doEscapingScale ); // value bounds after filter also scaled. ++filterIndex; } // outChannel } // inChannel } // this.filtersArray if ( this.biasesArray ) { let biasIndex = 0; for ( let outChannel = 0; outChannel < this.outputChannelCount; ++outChannel, ++outChannel ) { let doEscapingScale = this.boundsArraySet.activationEscaping_ScaleArraySet.do.scales[ outChannel ]; this.biasesArray[ biasIndex ] *= doEscapingScale; // bias wieghts scaled. this.boundsArraySet.afterBias.multiply_one_byN( outChannel, doEscapingScale ); // value bounds after bias also scaled. ++biasIndex; } // outChannel } else { // ( !this.biasesArray ). No biases array to be extracted. // Do nothing. } } /** * Shuffle (.filtersArray, .biasesArray, .boundsArraySet) by interleaving. * - Only ( outputGroupCount == 2 ) is supported. * - The output channel count must be even (i.e. divisible by 2). * * */ output_interleave_asGrouptTwo() { tf.util.assert( ( this.channelShuffler_outputGroupCount == 2 ), `Pointwise.FiltersArray_BiasesArray.interleave_byGrouptTwo(): ` + `channelShuffler_outputGroupCount ( ${this.channelShuffler_outputGroupCount} ) only 2 is supported.` ); tf.util.assert( ( ( this.outputChannelCount % 2 ) == 0 ), `Pointwise.FiltersArray_BiasesArray.interleave_byGrouptTwo(): ` + `output channel count ( ${this.outputChannelCount} ) must be even (i.e. divisible by 2).` ); let arrayTemp = new Array( this.outputChannelCount ); for ( let indexBegin = 0; indexBegin < this.inputChannelCount; indexBegin += this.outputChannelCount ) { // Shuffle filters. FloatValue.ArrayInterleaver.interleave_asGrouptTwo( this.filtersArray, indexBegin, this.outputChannelCount, arrayTemp ); } if ( this.biasesArray ) FloatValue.ArrayInterleaver.interleave_asGrouptTwo( this.biasesArray, 0, this.biasesArray.length, arrayTemp ); // Shuffle biases. this.boundsArraySet.output_interleave_asGrouptTwo( arrayTemp ); // Shuffle bounds array set of output. } }
Update Pointwise_FiltersArray_BiasesArray.js
CNN/Conv/Pointwise/Pointwise_FiltersArray_BiasesArray.js
Update Pointwise_FiltersArray_BiasesArray.js
<ide><path>NN/Conv/Pointwise/Pointwise_FiltersArray_BiasesArray.js <ide> // <ide> this.boundsArraySet.afterBias.add_all_byBoundsArray( this.boundsArraySet.afterFilter ); <ide> <del> tf.util.assert( ( inChannel == this.inputChannelCount ), <del> `Pointwise.FiltersArray_BiasesArray.set_filtersArray_biasesArray_afterFilter_afterBias_apply_undoPreviousEscapingScale(): ` <del> + `aFiltersBiasesPartInfoArray[] total input channel count ( ${inChannel} ) should be ( ${this.inputChannelCount} ).` ); <add>//!!! (2022/04/05 Remarked) Always run through all input channels. <add>// tf.util.assert( ( inChannel == this.inputChannelCount ), <add>// `Pointwise.FiltersArray_BiasesArray.set_filtersArray_biasesArray_afterFilter_afterBias_apply_undoPreviousEscapingScale(): ` <add>// + `aFiltersBiasesPartInfoArray[] total input channel count ( ${inChannel} ) should be ( ${this.inputChannelCount} ).` ); <ide> <ide> tf.util.assert( ( outChannelEnd == this.outputChannelCount_Real ), <ide> `Pointwise.FiltersArray_BiasesArray.set_filtersArray_biasesArray_afterFilter_afterBias_apply_undoPreviousEscapingScale(): `
Java
unlicense
1f731a9ef3dc8dc290c46d2218b2c847c35425ac
0
danieljohnson2/HomeSoil
package homesoil; import com.google.common.collect.*; import java.io.*; import java.util.*; import org.bukkit.*; import org.bukkit.entity.*; import org.bukkit.event.*; import org.bukkit.event.entity.*; import org.bukkit.event.inventory.*; import org.bukkit.event.player.*; import org.bukkit.inventory.*; import org.bukkit.inventory.meta.*; import org.bukkit.plugin.java.*; import org.bukkit.scheduler.*; /** * This is the plugin class itself, which acts as the main entry point for a * Bukkit plugin. This also doubles as the listener, and handles events for us. * * @author DanJ */ public class HomeSoilPlugin extends JavaPlugin implements Listener { private static final File playersFile = new File("HomeSoil.txt"); private static final File regenFile = new File("HomeSoilDoom.txt"); private final PlayerInfoMap playerInfos = new PlayerInfoMap(); private final DoomSchedule doomSchedule = new DoomSchedule(this, regenFile); /** * This method provides access to the player info so we can move some logic * out to other classes. * * @return The PlayerInfoMap, from which PlayerInfos may be obtained. */ public PlayerInfoMap getPlayerInfos() { return playerInfos; } /** * This method loads player data from the HomeSoil file. */ private void load() { getLogger().info("Loading HomeSoil State"); if (playersFile.exists()) { playerInfos.load(playersFile); } } /** * This method saves any changes to the HomeSoil file; however this checks * for changes and only saves if there might be some. */ private void saveIfNeeded() { if (playerInfos.shouldSave()) { getLogger().info("Saving HomeSoil State"); playerInfos.save(playersFile); } } //////////////////////////////// // Event Handlers @Override public void onEnable() { super.onEnable(); load(); getServer().getPluginManager().registerEvents(this, this); doomSchedule.start(); } @Override public void onDisable() { saveIfNeeded(); doomSchedule.stop(); super.onDisable(); } @EventHandler public void onProjectileLaunch(ProjectileLaunchEvent e) { Projectile projectile = e.getEntity(); LivingEntity shooter = projectile.getShooter(); if (shooter instanceof Player) { ItemStack held = shooter.getEquipment().getItemInHand(); if (held != null && held.getType() == Material.SNOW_BALL) { ItemMeta itemMeta = held.getItemMeta(); if (itemMeta.hasDisplayName()) { String displayName = held.getItemMeta().getDisplayName(); OfflinePlayer victimPlayer = getServer().getOfflinePlayer(displayName); if (victimPlayer != null) { tryToStealHomeChunk((Player) shooter, victimPlayer); directFlamingSnowball(projectile, victimPlayer); saveIfNeeded(); } } } } } /** * This method will try to steal the home chunk that 'shooter' is standing * in from 'victim'; it does nothing if the victim does not own the chunk, * which can happen because the victim is identified by the name of the * snowball. * * @param shooter The snowball-throwing miscreant. * @param victim The poor fellow named by the snowball. */ private void tryToStealHomeChunk(final Player shooter, OfflinePlayer victim) { if (playerInfos.isKnown(victim)) { PlayerInfo victimInfo = playerInfos.get(victim); ChunkPosition victimChunk = ChunkPosition.of(shooter.getLocation()); if (victimInfo.getHomeChunks().contains(victimChunk)) { playerInfos.removeHomeChunk(victim, victimChunk, getServer()); if (victim.getPlayer() != shooter) { PlayerInfo shooterInfo = playerInfos.get(shooter); shooterInfo.addHomeChunk(victimChunk); String shooterName = shooter.getName(); String victimName = victim.getName(); int numberOfFireworks = shooterInfo.getHomeChunks().size(); List<ChunkPosition> homes = shooterInfo.getHomeChunks(); String msg = null; msg = String.format( "§6%s took over %s's chunk and now controls %d!§r", shooterName, victimName, homes.size()); if (msg != null) { for (Player p : Bukkit.getOnlinePlayers()) { p.sendMessage(msg); } } numberOfFireworks = Math.min(500, numberOfFireworks * numberOfFireworks); if (numberOfFireworks > 0) { launchFireworksLater(shooter.getLocation(), numberOfFireworks); } } else { shooter.setHealth(shooter.getMaxHealth()); //bump up shooter health to full, because //they are sacrificing their chunk for a health buff } } } } /** * This method schedules a firework barrage to be launched; the task * launches one every ten ticks until it has fired off enough. * * @param spawnLocation The point from which the firework will spawn. * @param numberOfFireworks The number of fireworks. */ private void launchFireworksLater(final Location spawnLocation, final int numberOfFireworks) { new BukkitRunnable() { // lets be safe and not let the location change while we are doing this! private Location fixedSpawnLocation = spawnLocation.clone(); // this field will count down the firewsorks so we know when to stop private int fireworksRemaining = numberOfFireworks; @Override public void run() { if (fireworksRemaining > 0) { launchFirework(fixedSpawnLocation); --fireworksRemaining; } else { // once there are no more fireworks, we can finally stop // the madness. cancel(); } } }.runTaskTimer(this, 0, 10); } /** * This method spawns a firework to celebrate stealing a chunk. * * @param spawnLocation The point from which the firework will spawn. */ private void launchFirework(Location spawnLocation) { // but let's launch a firework too! // Language note: (Firework) here is a cast- spawnEntity does not return the correct type, // but we can ask Java to override. This is checked: an error occurs if it's not // a firework. World world = spawnLocation.getWorld(); Firework firework = (Firework) world.spawnEntity(spawnLocation, EntityType.FIREWORK); FireworkMeta meta = firework.getFireworkMeta().clone(); // Make it fancy! This is a 'fluent' style class, where we chain method // calls with '.'. FireworkEffect effect = FireworkEffect.builder(). withColor(Color.LIME). withFlicker(). withTrail(). with(FireworkEffect.Type.CREEPER). build(); meta.addEffect(effect); meta.setPower(2); firework.setFireworkMeta(meta); } /** * This method creates a scheduled task that manipulates the projectile * given so that it flies towards the player start of the indicated victim. * * @param projectile The snowball. * @param victim The guy whose name is on the snowball. */ private void directFlamingSnowball(Projectile projectile, OfflinePlayer victim) { List<Location> victimSpawns = Lists.newArrayList(playerInfos.getPlayerStarts(victim, getServer())); if (!victimSpawns.isEmpty()) { // ugly, but we can only work with spawns in the same world, so // we translate them all. This relies on getPlayerStarts() returning // clones, which it does, but ew. for (Location spawn : victimSpawns) { ChunkPosition.translateToWorld(spawn, projectile.getWorld()); } final Location start = projectile.getLocation().clone(); start.add(0, 1, 0); projectile.teleport(start); class DistanceComparator implements Comparator<Location> { @Override public int compare(Location left, Location right) { // this compares by distance from 'start', ascending, so the // nearest location is first. return (int) Math.signum(start.distanceSquared(left) - start.distanceSquared(right)); } } // we target the closest spawn the victim has. Collections.sort(victimSpawns, new DistanceComparator()); Location destination = victimSpawns.get(0); // the snowball will be moved by the server updating its position // periodically; this is done in a scheduled task. ProjectileDirector.begin(projectile, destination, this); } } /** * This method gives a player a snowball in a designated snowball slot. * * @param player The player to be gifted with snow! */ @SuppressWarnings("deprecation") private void bestowSnowball(Player player) { PlayerInventory inventory = player.getInventory(); ItemStack itemStack = new ItemStack(Material.SNOW_BALL, 4); ItemMeta meta = itemStack.getItemMeta().clone(); meta.setDisplayName(player.getName()); meta.setLore(Arrays.asList( String.format("Seeks %s's", player.getName()), "home soil")); itemStack.setItemMeta(meta); inventory.setItem(35, itemStack); player.updateInventory(); } @EventHandler public void onInventoryClick(InventoryClickEvent e) { final HumanEntity clicked = e.getWhoClicked(); if (clicked instanceof Player) { new BukkitRunnable() { @Override public void run() { bestowSnowball((Player) clicked); } }.runTaskLater(this, 1); } } @EventHandler public void onPlayerJoin(PlayerJoinEvent e) { Player player = e.getPlayer(); if (!playerInfos.isKnown(player)) { String name = player.getName(); for (ChunkPosition homeChunk : playerInfos.get(player).getHomeChunks()) { getLogger().warning(String.format("'%s' joined the game, and has been given home chunk %s.", name, homeChunk)); } saveIfNeeded(); } bestowSnowball(player); } @EventHandler public void onPlayerRespawn(PlayerRespawnEvent e) { Player player = e.getPlayer(); bestowSnowball(player); e.setRespawnLocation(playerInfos.getPlayerStart(player)); } @EventHandler public void onPlayerMove(PlayerMoveEvent e) { // We decided to keep this, but try to optimize by only checking // when a player moves from chunk to chunk. if (e.getTo().getChunk() != e.getFrom().getChunk()) { ChunkPosition fromChunk = ChunkPosition.of(e.getFrom()); ChunkPosition toChunk = ChunkPosition.of(e.getTo()); String fromPlayerName = playerInfos.identifyChunkOwner(fromChunk); String toPlayerName = playerInfos.identifyChunkOwner(toChunk); if (!fromPlayerName.equals(toPlayerName)) { Player player = e.getPlayer(); PlayerInfo playerInfo = playerInfos.get(player); boolean isEntering = !toPlayerName.isEmpty(); boolean isEnteringFormerHome = isEntering && playerInfo.getHistoricalHomeChunks().contains(toChunk); if (fromPlayerName.equals(player.getName())) { player.getWorld().playEffect(player.getLocation(), Effect.CLICK2, 0); } if (isEntering) { OfflinePlayer toPlayer = getServer().getOfflinePlayer(toPlayerName); if (toPlayer != null && playerInfos.isKnown(toPlayer)) { PlayerInfo toInfo = playerInfos.get(toPlayer); List<ChunkPosition> homes = toInfo.getHomeChunks(); int chunkNo = homes.indexOf(toChunk); String msg = null; if (toPlayer.getPlayer() == player) { // silly rabbit, clicks are for kids! (sorry) player.getWorld().playEffect(player.getLocation(), Effect.CLICK1, 0); msg = String.format( "§6This is §lyour§r§6 home chunk (#%d of %d)§r", chunkNo + 1, homes.size()); } else if (isEnteringFormerHome) { msg = String.format( "§6This is §l%s's§r§6 home chunk (#%d of %d)§r", toPlayerName, chunkNo + 1, homes.size()); } if (msg != null) { player.sendMessage(msg); } } } } } } }
src/homesoil/HomeSoilPlugin.java
package homesoil; import com.google.common.collect.*; import java.io.*; import java.util.*; import org.bukkit.*; import org.bukkit.entity.*; import org.bukkit.event.*; import org.bukkit.event.entity.*; import org.bukkit.event.inventory.*; import org.bukkit.event.player.*; import org.bukkit.inventory.*; import org.bukkit.inventory.meta.*; import org.bukkit.plugin.java.*; import org.bukkit.scheduler.*; /** * This is the plugin class itself, which acts as the main entry point for a * Bukkit plugin. This also doubles as the listener, and handles events for us. * * @author DanJ */ public class HomeSoilPlugin extends JavaPlugin implements Listener { private static final File playersFile = new File("HomeSoil.txt"); private static final File regenFile = new File("HomeSoilDoom.txt"); private final PlayerInfoMap playerInfos = new PlayerInfoMap(); private final DoomSchedule doomSchedule = new DoomSchedule(this, regenFile); /** * This method provides access to the player info so we can move some logic * out to other classes. * * @return The PlayerInfoMap, from which PlayerInfos may be obtained. */ public PlayerInfoMap getPlayerInfos() { return playerInfos; } /** * This method loads player data from the HomeSoil file. */ private void load() { getLogger().info("Loading HomeSoil State"); if (playersFile.exists()) { playerInfos.load(playersFile); } } /** * This method saves any changes to the HomeSoil file; however this checks * for changes and only saves if there might be some. */ private void saveIfNeeded() { if (playerInfos.shouldSave()) { getLogger().info("Saving HomeSoil State"); playerInfos.save(playersFile); } } //////////////////////////////// // Event Handlers @Override public void onEnable() { super.onEnable(); load(); getServer().getPluginManager().registerEvents(this, this); doomSchedule.start(); } @Override public void onDisable() { saveIfNeeded(); doomSchedule.stop(); super.onDisable(); } @EventHandler public void onProjectileLaunch(ProjectileLaunchEvent e) { Projectile projectile = e.getEntity(); LivingEntity shooter = projectile.getShooter(); if (shooter instanceof Player) { ItemStack held = shooter.getEquipment().getItemInHand(); if (held != null && held.getType() == Material.SNOW_BALL) { ItemMeta itemMeta = held.getItemMeta(); if (itemMeta.hasDisplayName()) { String displayName = held.getItemMeta().getDisplayName(); OfflinePlayer victimPlayer = getServer().getOfflinePlayer(displayName); if (victimPlayer != null) { tryToStealHomeChunk((Player) shooter, victimPlayer); directFlamingSnowball(projectile, victimPlayer); saveIfNeeded(); } } } } } /** * This method will try to steal the home chunk that 'shooter' is standing * in from 'victim'; it does nothing if the victim does not own the chunk, * which can happen because the victim is identified by the name of the * snowball. * * @param shooter The snowball-throwing miscreant. * @param victim The poor fellow named by the snowball. */ private void tryToStealHomeChunk(final Player shooter, OfflinePlayer victim) { if (playerInfos.isKnown(victim)) { PlayerInfo victimInfo = playerInfos.get(victim); ChunkPosition victimChunk = ChunkPosition.of(shooter.getLocation()); if (victimInfo.getHomeChunks().contains(victimChunk)) { playerInfos.removeHomeChunk(victim, victimChunk, getServer()); if (victim.getPlayer() != shooter) { PlayerInfo shooterInfo = playerInfos.get(shooter); shooterInfo.addHomeChunk(victimChunk); int numberOfFireworks = shooterInfo.getHomeChunks().size(); //here, we play a server message to everyone on the server //it says, "Foo took over Bar's chunk, and now controls Baz!" //Foo shooter, Bar victim, Baz numberOfFireworks (before we multiply it) numberOfFireworks = Math.min(500, numberOfFireworks * numberOfFireworks); if (numberOfFireworks > 0) { launchFireworksLater(shooter.getLocation(), numberOfFireworks); } } else { shooter.setHealth(shooter.getMaxHealth()); //bump up shooter health to full, because //they are sacrificing their chunk for a health buff } } } } /** * This method schedules a firework barrage to be launched; the task * launches one every ten ticks until it has fired off enough. * * @param spawnLocation The point from which the firework will spawn. * @param numberOfFireworks The number of fireworks. */ private void launchFireworksLater(final Location spawnLocation, final int numberOfFireworks) { new BukkitRunnable() { // lets be safe and not let the location change while we are doing this! private Location fixedSpawnLocation = spawnLocation.clone(); // this field will count down the firewsorks so we know when to stop private int fireworksRemaining = numberOfFireworks; @Override public void run() { if (fireworksRemaining > 0) { launchFirework(fixedSpawnLocation); --fireworksRemaining; } else { // once there are no more fireworks, we can finally stop // the madness. cancel(); } } }.runTaskTimer(this, 0, 10); } /** * This method spawns a firework to celebrate stealing a chunk. * * @param spawnLocation The point from which the firework will spawn. */ private void launchFirework(Location spawnLocation) { // but let's launch a firework too! // Language note: (Firework) here is a cast- spawnEntity does not return the correct type, // but we can ask Java to override. This is checked: an error occurs if it's not // a firework. World world = spawnLocation.getWorld(); Firework firework = (Firework) world.spawnEntity(spawnLocation, EntityType.FIREWORK); FireworkMeta meta = firework.getFireworkMeta().clone(); // Make it fancy! This is a 'fluent' style class, where we chain method // calls with '.'. FireworkEffect effect = FireworkEffect.builder(). withColor(Color.LIME). withFlicker(). withTrail(). with(FireworkEffect.Type.CREEPER). build(); meta.addEffect(effect); meta.setPower(2); firework.setFireworkMeta(meta); } /** * This method creates a scheduled task that manipulates the projectile * given so that it flies towards the player start of the indicated victim. * * @param projectile The snowball. * @param victim The guy whose name is on the snowball. */ private void directFlamingSnowball(Projectile projectile, OfflinePlayer victim) { List<Location> victimSpawns = Lists.newArrayList(playerInfos.getPlayerStarts(victim, getServer())); if (!victimSpawns.isEmpty()) { // ugly, but we can only work with spawns in the same world, so // we translate them all. This relies on getPlayerStarts() returning // clones, which it does, but ew. for (Location spawn : victimSpawns) { ChunkPosition.translateToWorld(spawn, projectile.getWorld()); } final Location start = projectile.getLocation().clone(); start.add(0, 1, 0); projectile.teleport(start); class DistanceComparator implements Comparator<Location> { @Override public int compare(Location left, Location right) { // this compares by distance from 'start', ascending, so the // nearest location is first. return (int) Math.signum(start.distanceSquared(left) - start.distanceSquared(right)); } } // we target the closest spawn the victim has. Collections.sort(victimSpawns, new DistanceComparator()); Location destination = victimSpawns.get(0); // the snowball will be moved by the server updating its position // periodically; this is done in a scheduled task. ProjectileDirector.begin(projectile, destination, this); } } /** * This method gives a player a snowball in a designated snowball slot. * * @param player The player to be gifted with snow! */ @SuppressWarnings("deprecation") private void bestowSnowball(Player player) { PlayerInventory inventory = player.getInventory(); ItemStack itemStack = new ItemStack(Material.SNOW_BALL, 4); ItemMeta meta = itemStack.getItemMeta().clone(); meta.setDisplayName(player.getName()); meta.setLore(Arrays.asList( String.format("Seeks %s's", player.getName()), "home soil")); itemStack.setItemMeta(meta); inventory.setItem(35, itemStack); player.updateInventory(); } @EventHandler public void onInventoryClick(InventoryClickEvent e) { final HumanEntity clicked = e.getWhoClicked(); if (clicked instanceof Player) { new BukkitRunnable() { @Override public void run() { bestowSnowball((Player) clicked); } }.runTaskLater(this, 1); } } @EventHandler public void onPlayerJoin(PlayerJoinEvent e) { Player player = e.getPlayer(); if (!playerInfos.isKnown(player)) { String name = player.getName(); for (ChunkPosition homeChunk : playerInfos.get(player).getHomeChunks()) { getLogger().warning(String.format("'%s' joined the game, and has been given home chunk %s.", name, homeChunk)); } saveIfNeeded(); } bestowSnowball(player); } @EventHandler public void onPlayerRespawn(PlayerRespawnEvent e) { Player player = e.getPlayer(); bestowSnowball(player); e.setRespawnLocation(playerInfos.getPlayerStart(player)); } @EventHandler public void onPlayerMove(PlayerMoveEvent e) { // We decided to keep this, but try to optimize by only checking // when a player moves from chunk to chunk. if (e.getTo().getChunk() != e.getFrom().getChunk()) { ChunkPosition fromChunk = ChunkPosition.of(e.getFrom()); ChunkPosition toChunk = ChunkPosition.of(e.getTo()); String fromPlayerName = playerInfos.identifyChunkOwner(fromChunk); String toPlayerName = playerInfos.identifyChunkOwner(toChunk); if (!fromPlayerName.equals(toPlayerName)) { Player player = e.getPlayer(); PlayerInfo playerInfo = playerInfos.get(player); boolean isEntering = !toPlayerName.isEmpty(); boolean isEnteringFormerHome = isEntering && playerInfo.getHistoricalHomeChunks().contains(toChunk); if (fromPlayerName.equals(player.getName())) { player.getWorld().playEffect(player.getLocation(), Effect.CLICK2, 0); } if (isEntering) { OfflinePlayer toPlayer = getServer().getOfflinePlayer(toPlayerName); if (toPlayer != null && playerInfos.isKnown(toPlayer)) { PlayerInfo toInfo = playerInfos.get(toPlayer); List<ChunkPosition> homes = toInfo.getHomeChunks(); int chunkNo = homes.indexOf(toChunk); String msg = null; if (toPlayer.getPlayer() == player) { // silly rabbit, clicks are for kids! (sorry) player.getWorld().playEffect(player.getLocation(), Effect.CLICK1, 0); msg = String.format( "§6This is §lyour§r§6 home chunk (#%d of %d)§r", chunkNo + 1, homes.size()); } else if (isEnteringFormerHome) { msg = String.format( "§6This is §l%s's§r§6 home chunk (#%d of %d)§r", toPlayerName, chunkNo + 1, homes.size()); } if (msg != null) { player.sendMessage(msg); } } } } } } }
Implemented server message to all players, when a chunk is taken over.
src/homesoil/HomeSoilPlugin.java
Implemented server message to all players, when a chunk is taken over.
<ide><path>rc/homesoil/HomeSoilPlugin.java <ide> if (victim.getPlayer() != shooter) { <ide> PlayerInfo shooterInfo = playerInfos.get(shooter); <ide> shooterInfo.addHomeChunk(victimChunk); <add> String shooterName = shooter.getName(); <add> String victimName = victim.getName(); <ide> int numberOfFireworks = shooterInfo.getHomeChunks().size(); <del> <del> //here, we play a server message to everyone on the server <del> //it says, "Foo took over Bar's chunk, and now controls Baz!" <del> //Foo shooter, Bar victim, Baz numberOfFireworks (before we multiply it) <add> List<ChunkPosition> homes = shooterInfo.getHomeChunks(); <add> String msg = null; <add> msg = String.format( <add> "§6%s took over %s's chunk and now controls %d!§r", <add> shooterName, <add> victimName, <add> homes.size()); <add> if (msg != null) { <add> for (Player p : Bukkit.getOnlinePlayers()) { <add> p.sendMessage(msg); <add> } <add> } <ide> <ide> numberOfFireworks = Math.min(500, numberOfFireworks * numberOfFireworks); <ide>
Java
apache-2.0
89316e9405dd7ef4f30f5745648118d2a6e231c3
0
EvilMcJerkface/atlasdb,EvilMcJerkface/atlasdb,palantir/atlasdb,palantir/atlasdb,EvilMcJerkface/atlasdb,palantir/atlasdb
/** * Copyright 2016 Palantir Technologies * * Licensed under the BSD-3 License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.cassandra.multinode; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.everyItem; import static org.hamcrest.MatcherAssert.assertThat; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.hamcrest.Description; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.rules.RuleChain; import com.google.common.base.Optional; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.jayway.awaitility.Awaitility; import com.jayway.awaitility.Duration; import com.palantir.atlasdb.AtlasDbConstants; import com.palantir.atlasdb.cassandra.CassandraKeyValueServiceConfigManager; import com.palantir.atlasdb.cassandra.ImmutableCassandraCredentialsConfig; import com.palantir.atlasdb.cassandra.ImmutableCassandraKeyValueServiceConfig; import com.palantir.atlasdb.config.ImmutableLeaderConfig; import com.palantir.atlasdb.config.LeaderConfig; import com.palantir.atlasdb.ete.Gradle; import com.palantir.atlasdb.keyvalue.api.TableReference; import com.palantir.atlasdb.keyvalue.cassandra.CassandraKeyValueService; import com.palantir.docker.compose.DockerComposition; import com.palantir.docker.compose.connection.DockerPort; import com.palantir.docker.compose.connection.waiting.HealthCheck; import com.palantir.docker.compose.connection.waiting.SuccessOrFailure; public class CassandraSchemaLockTest { public static final int THRIFT_PORT_NUMBER = 9160; public static final DockerComposition composition = DockerComposition.of("src/test/resources/docker-compose-multinode.yml") .waitingForHostNetworkedPort(THRIFT_PORT_NUMBER, toBeOpen()) .saveLogsTo("container-logs-multinode") .build(); public static final Gradle GRADLE_PREPARE_TASK = Gradle.ensureTaskHasRun(":atlasdb-ete-test-utils:buildCassandraImage"); @ClassRule public static final RuleChain CASSANDRA_DOCKER_SET_UP = RuleChain.outerRule(GRADLE_PREPARE_TASK).around(composition); static InetSocketAddress CASSANDRA_THRIFT_ADDRESS; static ImmutableCassandraKeyValueServiceConfig CASSANDRA_KVS_CONFIG; static Optional<LeaderConfig> LEADER_CONFIG; private final ExecutorService executorService = Executors.newFixedThreadPool(32); static private CassandraKeyValueServiceConfigManager CONFIG_MANAGER; @BeforeClass public static void waitUntilCassandraIsUp() throws IOException, InterruptedException { DockerPort port = composition.hostNetworkedPort(THRIFT_PORT_NUMBER); String hostname = port.getIp(); CASSANDRA_THRIFT_ADDRESS = new InetSocketAddress(hostname, port.getExternalPort()); CASSANDRA_KVS_CONFIG = ImmutableCassandraKeyValueServiceConfig.builder() .addServers(CASSANDRA_THRIFT_ADDRESS) .poolSize(20) .keyspace("atlasdb") .credentials(ImmutableCassandraCredentialsConfig.builder() .username("cassandra") .password("cassandra") .build()) .ssl(false) .replicationFactor(1) .mutationBatchCount(10000) .mutationBatchSizeBytes(10000000) .fetchBatchCount(1000) .safetyDisabled(false) .autoRefreshNodes(false) .build(); CONFIG_MANAGER = CassandraKeyValueServiceConfigManager.createSimpleManager(CASSANDRA_KVS_CONFIG); LEADER_CONFIG = Optional.of(ImmutableLeaderConfig .builder() .quorumSize(1) .localServer(hostname) .leaders(ImmutableSet.of(hostname)) .build()); Awaitility.await() .atMost(Duration.TWO_MINUTES) .pollInterval(Duration.ONE_SECOND) .until(canCreateKeyValueService()); } @Test public void shouldCreateTablesConsistentlyWithMultipleCassandraNodes() throws Exception { TableReference table1 = TableReference.createFromFullyQualifiedName("ns.table1"); CyclicBarrier barrier = new CyclicBarrier(32); try { for(int i=0; i < 32; i++) { async(() -> { CassandraKeyValueService keyValueService = CassandraKeyValueService.create(CONFIG_MANAGER, Optional.absent()); barrier.await(); keyValueService.createTable(table1, AtlasDbConstants.GENERIC_TABLE_METADATA); return null; }); } } catch (Exception e) { throw e; } executorService.shutdown(); executorService.awaitTermination(5L, TimeUnit.MINUTES); assertThat(new File("container-logs-multinode"), containsFiles(everyItem(doesNotContainTheColumnFamilyIdMismatchError()))); } private Matcher<File> containsFiles(Matcher<Iterable<File>> fileMatcher) { return new FeatureMatcher<File, List<File>>(fileMatcher, "Directory with files such that", "Directory contains") { @Override protected List<File> featureValueOf(File actual) { return Lists.newArrayList(actual.listFiles()); } }; } private Matcher<File> doesNotContainTheColumnFamilyIdMismatchError() { return new TypeSafeDiagnosingMatcher<File>() { @Override protected boolean matchesSafely(File file, Description mismatchDescription) { try { List<String> badLines = Files.lines(Paths.get(file.getAbsolutePath())) .filter(line -> line.contains("Column family ID mismatch")) .collect(toList()); mismatchDescription .appendText("file called " + file.getAbsolutePath() + " which contains lines") .appendValueList("\n", "\n", "", badLines); return badLines.isEmpty(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void describeTo(Description description) { description.appendText("a file with no column family ID mismatch errors"); } }; } private static Callable<Boolean> canCreateKeyValueService() { return () -> { try { CassandraKeyValueService.create(CassandraKeyValueServiceConfigManager.createSimpleManager(CASSANDRA_KVS_CONFIG), LEADER_CONFIG); return true; } catch (Exception e) { return false; } }; } protected void async(Callable callable) { executorService.submit(callable); } private static HealthCheck<DockerPort> toBeOpen() { return port -> SuccessOrFailure.fromBoolean(port.isListeningNow(), "" + "" + port + " was not open"); } }
atlasdb-cassandra-multinode-tests/src/test/java/com/palantir/cassandra/multinode/CassandraSchemaLockTest.java
/** * Copyright 2016 Palantir Technologies * * Licensed under the BSD-3 License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.cassandra.multinode; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.everyItem; import static org.hamcrest.MatcherAssert.assertThat; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.hamcrest.Description; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.rules.RuleChain; import com.google.common.base.Optional; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.jayway.awaitility.Awaitility; import com.jayway.awaitility.Duration; import com.palantir.atlasdb.AtlasDbConstants; import com.palantir.atlasdb.cassandra.CassandraKeyValueServiceConfigManager; import com.palantir.atlasdb.cassandra.ImmutableCassandraCredentialsConfig; import com.palantir.atlasdb.cassandra.ImmutableCassandraKeyValueServiceConfig; import com.palantir.atlasdb.config.ImmutableLeaderConfig; import com.palantir.atlasdb.config.LeaderConfig; import com.palantir.atlasdb.ete.Gradle; import com.palantir.atlasdb.keyvalue.api.TableReference; import com.palantir.atlasdb.keyvalue.cassandra.CassandraKeyValueService; import com.palantir.docker.compose.DockerComposition; import com.palantir.docker.compose.connection.DockerPort; import com.palantir.docker.compose.connection.waiting.HealthCheck; import com.palantir.docker.compose.connection.waiting.SuccessOrFailure; public class CassandraSchemaLockTest { public static final int THRIFT_PORT_NUMBER = 9160; public static final DockerComposition composition = DockerComposition.of("src/test/resources/docker-compose-multinode.yml") .waitingForHostNetworkedPort(THRIFT_PORT_NUMBER, toBeOpen()) .saveLogsTo("container-logs-multinode") .build(); public static final Gradle GRADLE_PREPARE_TASK = Gradle.ensureTaskHasRun(":atlasdb-ete-test-utils:buildCassandraImage"); @ClassRule public static final RuleChain CASSANDRA_DOCKER_SET_UP = RuleChain.outerRule(GRADLE_PREPARE_TASK).around(composition); static InetSocketAddress CASSANDRA_THRIFT_ADDRESS; static ImmutableCassandraKeyValueServiceConfig CASSANDRA_KVS_CONFIG; static Optional<LeaderConfig> LEADER_CONFIG; private final ExecutorService executorService = Executors.newFixedThreadPool(32); static private CassandraKeyValueServiceConfigManager CONFIG_MANAGER; @BeforeClass public static void waitUntilCassandraIsUp() throws IOException, InterruptedException { DockerPort port = composition.hostNetworkedPort(THRIFT_PORT_NUMBER); String hostname = port.getIp(); CASSANDRA_THRIFT_ADDRESS = new InetSocketAddress(hostname, port.getExternalPort()); CASSANDRA_KVS_CONFIG = ImmutableCassandraKeyValueServiceConfig.builder() .addServers(CASSANDRA_THRIFT_ADDRESS) .poolSize(20) .keyspace("atlasdb") .credentials(ImmutableCassandraCredentialsConfig.builder() .username("cassandra") .password("cassandra") .build()) .ssl(false) .replicationFactor(1) .mutationBatchCount(10000) .mutationBatchSizeBytes(10000000) .fetchBatchCount(1000) .safetyDisabled(false) .autoRefreshNodes(false) .build(); CONFIG_MANAGER = CassandraKeyValueServiceConfigManager.createSimpleManager(CASSANDRA_KVS_CONFIG); LEADER_CONFIG = Optional.of(ImmutableLeaderConfig .builder() .quorumSize(1) .localServer(hostname) .leaders(ImmutableSet.of(hostname)) .build()); Awaitility.await() .atMost(Duration.FIVE_MINUTES) .pollInterval(Duration.ONE_SECOND) .until(canCreateKeyValueService()); } @Test public void shouldCreateTablesConsistentlyWithMultipleCassandraNodes() throws Exception { TableReference table1 = TableReference.createFromFullyQualifiedName("ns.table1"); CyclicBarrier barrier = new CyclicBarrier(32); try { for(int i=0; i < 32; i++) { async(() -> { CassandraKeyValueService keyValueService = CassandraKeyValueService.create(CONFIG_MANAGER, Optional.absent()); barrier.await(); keyValueService.createTable(table1, AtlasDbConstants.GENERIC_TABLE_METADATA); return null; }); } } catch (Exception e) { throw e; } executorService.shutdown(); executorService.awaitTermination(5L, TimeUnit.MINUTES); assertThat(new File("container-logs-multinode"), containsFiles(everyItem(doesNotContainTheColumnFamilyIdMismatchError()))); } private Matcher<File> containsFiles(Matcher<Iterable<File>> fileMatcher) { return new FeatureMatcher<File, List<File>>(fileMatcher, "Directory with files such that", "Directory contains") { @Override protected List<File> featureValueOf(File actual) { return Lists.newArrayList(actual.listFiles()); } }; } private Matcher<File> doesNotContainTheColumnFamilyIdMismatchError() { return new TypeSafeDiagnosingMatcher<File>() { @Override protected boolean matchesSafely(File file, Description mismatchDescription) { try { List<String> badLines = Files.lines(Paths.get(file.getAbsolutePath())) .filter(line -> line.contains("Column family ID mismatch")) .collect(toList()); mismatchDescription .appendText("file called " + file.getAbsolutePath() + " which contains lines") .appendValueList("\n", "\n", "", badLines); return badLines.isEmpty(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void describeTo(Description description) { description.appendText("a file with no column family ID mismatch errors"); } }; } private static Callable<Boolean> canCreateKeyValueService() { return () -> { try { CassandraKeyValueService.create(CassandraKeyValueServiceConfigManager.createSimpleManager(CASSANDRA_KVS_CONFIG), LEADER_CONFIG); return true; } catch (Exception e) { return false; } }; } protected void async(Callable callable) { executorService.submit(callable); } private static HealthCheck<DockerPort> toBeOpen() { return port -> SuccessOrFailure.fromBoolean(port.isListeningNow(), "" + "" + port + " was not open"); } }
Make timeout 2 minutes
atlasdb-cassandra-multinode-tests/src/test/java/com/palantir/cassandra/multinode/CassandraSchemaLockTest.java
Make timeout 2 minutes
<ide><path>tlasdb-cassandra-multinode-tests/src/test/java/com/palantir/cassandra/multinode/CassandraSchemaLockTest.java <ide> .build()); <ide> <ide> Awaitility.await() <del> .atMost(Duration.FIVE_MINUTES) <add> .atMost(Duration.TWO_MINUTES) <ide> .pollInterval(Duration.ONE_SECOND) <ide> .until(canCreateKeyValueService()); <ide> }
Java
bsd-2-clause
3bc8e01b69bf2530207086cc6ea1765491117573
0
bonej-org/BoneJ2,bonej-org/BoneJ2
/* BSD 2-Clause License Copyright (c) 2018, Michael Doube, Richard Domander, Alessandro Felder All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.bonej.wrapperPlugins.wrapperUtils; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.scijava.ui.DialogPrompt.Result.CANCEL_OPTION; import static org.scijava.ui.DialogPrompt.Result.CLOSED_OPTION; import static org.scijava.ui.DialogPrompt.Result.OK_OPTION; import java.util.stream.IntStream; import net.imagej.ImageJ; import net.imagej.ImgPlus; import net.imagej.axis.Axes; import net.imagej.axis.DefaultLinearAxis; import net.imglib2.img.Img; import net.imglib2.img.array.ArrayImgs; import net.imglib2.type.logic.BitType; import net.imglib2.type.numeric.real.DoubleType; import org.junit.AfterClass; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.categories.Category; import org.scijava.ui.DialogPrompt.MessageType; import org.scijava.ui.UIService; import ij.ImagePlus; import ij.measure.Calibration; /** * Unit tests for the {@link Common} utility class. * * @author Richard Domander */ public class CommonTest { private static final ImageJ IMAGE_J = new ImageJ(); @Test public void testToBitTypeImgPlus() throws AssertionError { final String unit = "mm"; final String name = "Test image"; final double scale = 0.5; final DefaultLinearAxis xAxis = new DefaultLinearAxis(Axes.X, unit, scale); final Img<DoubleType> img = ArrayImgs.doubles(3); final ImgPlus<DoubleType> source = new ImgPlus<>(img, name, xAxis); final ImgPlus<BitType> result = Common.toBitTypeImgPlus(IMAGE_J.op(), source); final int dimensions = source.numDimensions(); assertEquals("Number of dimensions copied incorrectly", dimensions, result .numDimensions()); assertTrue("Dimensions copied incorrectly", IntStream.range(0, dimensions) .allMatch(d -> source.dimension(d) == result.dimension(d))); assertEquals("Image name was not copied", name, result.getName()); assertEquals("Axis type was not copied", Axes.X, result.axis(0).type()); assertEquals("Axis unit was not copied", unit, result.axis(0).unit()); assertEquals("Axis scale was not copied", scale, result.axis(0) .averageScale(0, 1), 1e-12); } @Test public void testWarnAnisotropyReturnsFalseIfAnisotropicImageAndUserCancels() { final ImagePlus imagePlus = mock(ImagePlus.class); final Calibration anisotropicCalibration = new Calibration(); anisotropicCalibration.pixelWidth = 0.5; when(imagePlus.getCalibration()).thenReturn(anisotropicCalibration); final UIService uiService = mock(UIService.class); when(uiService.showDialog(anyString(), any(MessageType.class), any())) .thenReturn(CANCEL_OPTION); assertFalse(Common.warnAnisotropy(imagePlus, uiService)); verify(uiService, timeout(1000)).showDialog(anyString(), any( MessageType.class), any()); } @Test @Category(org.bonej.wrapperPlugins.SlowWrapperTest.class) public void testWarnAnisotropyReturnsFalseIfAnisotropicImageAndUserCloses() { final ImagePlus imagePlus = mock(ImagePlus.class); final Calibration anisotropicCalibration = new Calibration(); anisotropicCalibration.pixelWidth = 0.5; when(imagePlus.getCalibration()).thenReturn(anisotropicCalibration); final UIService uiService = mock(UIService.class); when(uiService.showDialog(anyString(), any(MessageType.class), any())) .thenReturn(CLOSED_OPTION); assertFalse(Common.warnAnisotropy(imagePlus, uiService)); verify(uiService, timeout(1000)).showDialog(anyString(), any( MessageType.class), any()); } @Test @Category(org.bonej.wrapperPlugins.SlowWrapperTest.class) public void testWarnAnisotropyReturnsTrueIfAnisotropicImageAndUserOK() { final ImagePlus imagePlus = mock(ImagePlus.class); final Calibration anisotropicCalibration = new Calibration(); anisotropicCalibration.pixelWidth = 0.5; when(imagePlus.getCalibration()).thenReturn(anisotropicCalibration); final UIService uiService = mock(UIService.class); when(uiService.showDialog(anyString(), any(MessageType.class), any())) .thenReturn(OK_OPTION); assertTrue(Common.warnAnisotropy(imagePlus, uiService)); verify(uiService, timeout(1000)).showDialog(anyString(), any( MessageType.class), any()); } @Test @Category(org.bonej.wrapperPlugins.SlowWrapperTest.class) public void testWarnAnisotropyReturnsTrueIfIsotropicImage() { final ImagePlus imagePlus = mock(ImagePlus.class); final Calibration isotropic = new Calibration(); when(imagePlus.getCalibration()).thenReturn(isotropic); final UIService uiService = mock(UIService.class); assertTrue(Common.warnAnisotropy(imagePlus, uiService)); } @AfterClass public static void oneTimeTearDown() { IMAGE_J.context().dispose(); } }
Modern/wrapperPlugins/src/test/java/org/bonej/wrapperPlugins/wrapperUtils/CommonTest.java
/* BSD 2-Clause License Copyright (c) 2018, Michael Doube, Richard Domander, Alessandro Felder All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.bonej.wrapperPlugins.wrapperUtils; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.scijava.ui.DialogPrompt.Result.CANCEL_OPTION; import static org.scijava.ui.DialogPrompt.Result.CLOSED_OPTION; import static org.scijava.ui.DialogPrompt.Result.OK_OPTION; import java.util.stream.IntStream; import net.imagej.ImageJ; import net.imagej.ImgPlus; import net.imagej.axis.Axes; import net.imagej.axis.DefaultLinearAxis; import net.imglib2.img.Img; import net.imglib2.img.array.ArrayImgs; import net.imglib2.type.logic.BitType; import net.imglib2.type.numeric.real.DoubleType; import org.junit.AfterClass; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.categories.Category; import org.scijava.ui.DialogPrompt.MessageType; import org.scijava.ui.UIService; import ij.ImagePlus; import ij.measure.Calibration; /** * Unit tests for the {@link Common} utility class. * * @author Richard Domander */ public class CommonTest { private static final ImageJ IMAGE_J = new ImageJ(); @Ignore @Test public void testToBitTypeImgPlus() throws AssertionError { final String unit = "mm"; final String name = "Test image"; final double scale = 0.5; final DefaultLinearAxis xAxis = new DefaultLinearAxis(Axes.X, unit, scale); final Img<DoubleType> img = ArrayImgs.doubles(3); final ImgPlus<DoubleType> source = new ImgPlus<>(img, name, xAxis); final ImgPlus<BitType> result = Common.toBitTypeImgPlus(IMAGE_J.op(), source); final int dimensions = source.numDimensions(); assertEquals("Number of dimensions copied incorrectly", dimensions, result .numDimensions()); assertTrue("Dimensions copied incorrectly", IntStream.range(0, dimensions) .allMatch(d -> source.dimension(d) == result.dimension(d))); assertEquals("Image name was not copied", name, result.getName()); assertEquals("Axis type was not copied", Axes.X, result.axis(0).type()); assertEquals("Axis unit was not copied", unit, result.axis(0).unit()); assertEquals("Axis scale was not copied", scale, result.axis(0) .averageScale(0, 1), 1e-12); } @Test public void testWarnAnisotropyReturnsFalseIfAnisotropicImageAndUserCancels() { final ImagePlus imagePlus = mock(ImagePlus.class); final Calibration anisotropicCalibration = new Calibration(); anisotropicCalibration.pixelWidth = 0.5; when(imagePlus.getCalibration()).thenReturn(anisotropicCalibration); final UIService uiService = mock(UIService.class); when(uiService.showDialog(anyString(), any(MessageType.class), any())) .thenReturn(CANCEL_OPTION); assertFalse(Common.warnAnisotropy(imagePlus, uiService)); verify(uiService, timeout(1000)).showDialog(anyString(), any( MessageType.class), any()); } @Test @Category(org.bonej.wrapperPlugins.SlowWrapperTest.class) public void testWarnAnisotropyReturnsFalseIfAnisotropicImageAndUserCloses() { final ImagePlus imagePlus = mock(ImagePlus.class); final Calibration anisotropicCalibration = new Calibration(); anisotropicCalibration.pixelWidth = 0.5; when(imagePlus.getCalibration()).thenReturn(anisotropicCalibration); final UIService uiService = mock(UIService.class); when(uiService.showDialog(anyString(), any(MessageType.class), any())) .thenReturn(CLOSED_OPTION); assertFalse(Common.warnAnisotropy(imagePlus, uiService)); verify(uiService, timeout(1000)).showDialog(anyString(), any( MessageType.class), any()); } @Test @Category(org.bonej.wrapperPlugins.SlowWrapperTest.class) public void testWarnAnisotropyReturnsTrueIfAnisotropicImageAndUserOK() { final ImagePlus imagePlus = mock(ImagePlus.class); final Calibration anisotropicCalibration = new Calibration(); anisotropicCalibration.pixelWidth = 0.5; when(imagePlus.getCalibration()).thenReturn(anisotropicCalibration); final UIService uiService = mock(UIService.class); when(uiService.showDialog(anyString(), any(MessageType.class), any())) .thenReturn(OK_OPTION); assertTrue(Common.warnAnisotropy(imagePlus, uiService)); verify(uiService, timeout(1000)).showDialog(anyString(), any( MessageType.class), any()); } @Test @Category(org.bonej.wrapperPlugins.SlowWrapperTest.class) public void testWarnAnisotropyReturnsTrueIfIsotropicImage() { final ImagePlus imagePlus = mock(ImagePlus.class); final Calibration isotropic = new Calibration(); when(imagePlus.getCalibration()).thenReturn(isotropic); final UIService uiService = mock(UIService.class); assertTrue(Common.warnAnisotropy(imagePlus, uiService)); } @AfterClass public static void oneTimeTearDown() { IMAGE_J.context().dispose(); } }
Fix issue #100 Updating to pom-scijava:22.3.0 seems to have fixed the issue with the test method.
Modern/wrapperPlugins/src/test/java/org/bonej/wrapperPlugins/wrapperUtils/CommonTest.java
Fix issue #100
<ide><path>odern/wrapperPlugins/src/test/java/org/bonej/wrapperPlugins/wrapperUtils/CommonTest.java <ide> <ide> private static final ImageJ IMAGE_J = new ImageJ(); <ide> <del> @Ignore <ide> @Test <ide> public void testToBitTypeImgPlus() throws AssertionError { <ide> final String unit = "mm";
Java
lgpl-2.1
aa23b2c29fa67afb1fcc926ecea481892c0226f5
0
alkacon/opencms-core,it-tavis/opencms-core,mediaworx/opencms-core,MenZil/opencms-core,gallardo/opencms-core,gallardo/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,sbonoc/opencms-core,mediaworx/opencms-core,MenZil/opencms-core,MenZil/opencms-core,victos/opencms-core,ggiudetti/opencms-core,mediaworx/opencms-core,alkacon/opencms-core,ggiudetti/opencms-core,sbonoc/opencms-core,sbonoc/opencms-core,it-tavis/opencms-core,gallardo/opencms-core,alkacon/opencms-core,ggiudetti/opencms-core,victos/opencms-core,serrapos/opencms-core,gallardo/opencms-core,serrapos/opencms-core,sbonoc/opencms-core,mediaworx/opencms-core,victos/opencms-core,serrapos/opencms-core,MenZil/opencms-core,victos/opencms-core,serrapos/opencms-core,serrapos/opencms-core,ggiudetti/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,alkacon/opencms-core
/* * File : $Source: /alkacon/cvs/opencms/src/com/opencms/file/genericSql/Attic/CmsResourceBroker.java,v $ * Date : $Date: 2001/12/03 12:55:48 $ * Version: $Revision: 1.293 $ * * This library is part of OpenCms - * the Open Source Content Mananagement System * * Copyright (C) 2001 The OpenCms Group * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about OpenCms, please see the * OpenCms Website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.opencms.file.genericSql; import javax.servlet.http.*; import java.util.*; import java.net.*; import java.io.*; import source.org.apache.java.io.*; import source.org.apache.java.util.*; import com.opencms.boot.CmsClassLoader; import com.opencms.boot.CmsBase; import com.opencms.core.*; import com.opencms.file.*; import com.opencms.template.*; import java.sql.SQLException; /** * This is THE resource broker. It merges all resource broker * into one public class. The interface is local to package. <B>All</B> methods * get additional parameters (callingUser and currentproject) to check the security- * police. * * @author Andreas Schouten * @author Michaela Schleich * @author Michael Emmerich * @author Anders Fugmann * @version $Revision: 1.293 $ $Date: 2001/12/03 12:55:48 $ * */ public class CmsResourceBroker implements I_CmsResourceBroker, I_CmsConstants { //create a compare class to be used in the vector. class Resource { private String path = null; public Resource(String path) { this.path = path; } public boolean equals(Object obj) { return ( (obj instanceof CmsResource) && path.equals( ((CmsResource) obj).getResourceName() )); } } /** * Constant to count the file-system changes. */ protected long m_fileSystemChanges = 0; /** * Constant to count the file-system changes if Folders are involved. */ protected long m_fileSystemFolderChanges = 0; /** * Hashtable with resource-types. */ protected Hashtable m_resourceTypes = null; /** * The configuration of the property-file. */ protected Configurations m_configuration = null; /** * The access-module. */ protected CmsDbAccess m_dbAccess = null; /** * The Registry */ protected I_CmsRegistry m_registry = null; /** * Define the caches */ protected CmsCache m_userCache = null; protected CmsCache m_groupCache = null; protected CmsCache m_usergroupsCache = null; //protected CmsCache m_resourceCache = null; protected CmsResourceCache m_resourceCache = null; protected CmsCache m_subresCache = null; protected CmsCache m_projectCache = null; protected CmsCache m_onlineProjectCache = null; protected CmsCache m_propertyCache = null; protected CmsCache m_propertyDefCache = null; protected CmsCache m_propertyDefVectorCache = null; protected CmsCache m_accessCache = null; protected int m_cachelimit = 0; protected String m_refresh = null; /** * backup published resources for history */ protected boolean m_enableHistory = true; /** * Accept a task from the Cms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task to accept. * * @exception CmsException Throws CmsException if something goes wrong. */ public void acceptTask(CmsUser currentUser, CmsProject currentProject, int taskId) throws CmsException { CmsTask task = m_dbAccess.readTask(taskId); task.setPercentage(1); task = m_dbAccess.writeTask(task); m_dbAccess.writeSystemTaskLog(taskId, "Task was accepted from " + currentUser.getFirstname() + " " + currentUser.getLastname() + "."); } /** * Checks, if the user may create this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user has access, or not. */ public boolean accessCreate(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { // check, if this is the onlineproject if(onlineProject(currentUser, currentProject).equals(currentProject)){ // the online-project is not writeable! return(false); } // check the access to the project if( ! accessProject(currentUser, currentProject, currentProject.getId()) ) { // no access to the project! return(false); } // check if the resource belongs to the current project if(resource.getProjectId() != currentProject.getId()) { return false; } // is the resource locked? if( resource.isLocked() && (resource.isLockedBy() != currentUser.getId() || (resource.getLockedInProject() != currentProject.getId() && currentProject.getFlags() != C_PROJECT_STATE_INVISIBLE)) ) { // resource locked by anopther user, no creation allowed return(false); } // check the rights for the current resource if( ! ( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_WRITE) || accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_WRITE) || accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_WRITE) ) ) { // no write access to this resource! return false; } // read the parent folder if(resource.getParent() != null) { // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getRootName()+resource.getParent()); } else { // no parent folder! return true; } // check the rights and if the resource is not locked do { if( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_READ) || accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_READ) || accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_READ) ) { // is the resource locked? if( resource.isLocked() && resource.isLockedBy() != currentUser.getId() ) { // resource locked by anopther user, no creation allowed return(false); } // read next resource if(resource.getParent() != null) { // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getRootName()+resource.getParent()); } } else { // last check was negative return(false); } } while(resource.getParent() != null); // all checks are done positive return(true); } /** * Checks, if the user may create this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user has access, or not. */ public boolean accessCreate(CmsUser currentUser, CmsProject currentProject, String resourceName) throws CmsException { CmsResource resource = m_dbAccess.readFileHeader(currentProject.getId(), resourceName); return accessCreate(currentUser, currentProject, resource); } /** * Checks, if the group may access this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * @param flags The flags to check. * * @return wether the user has access, or not. */ protected boolean accessGroup(CmsUser currentUser, CmsProject currentProject, CmsResource resource, int flags) throws CmsException { // is the user in the group for the resource? if(userInGroup(currentUser, currentProject, currentUser.getName(), readGroup(currentUser, currentProject, resource).getName())) { if( (resource.getAccessFlags() & flags) == flags ) { return true; } } // the resource isn't accesible by the user. return false; } /** * Checks, if the user may lock this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user may lock this resource, or not. */ public boolean accessLock(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { // check, if this is the onlineproject if(onlineProject(currentUser, currentProject).equals(currentProject)){ // the online-project is not writeable! return(false); } // check the access to the project if( ! accessProject(currentUser, currentProject, currentProject.getId()) ) { // no access to the project! return(false); } // check if the resource belongs to the current project if(resource.getProjectId() != currentProject.getId()) { return false; } // read the parent folder if(resource.getParent() != null) { // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getRootName()+resource.getParent()); } else { // no parent folder! return true; } // check the rights and if the resource is not locked do { // is the resource locked? if( resource.isLocked() && (resource.isLockedBy() != currentUser.getId() || (resource.getLockedInProject() != currentProject.getId() && currentProject.getFlags() != C_PROJECT_STATE_INVISIBLE)) ) { // resource locked by anopther user, no creation allowed return(false); } // read next resource if(resource.getParent() != null) { // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getRootName()+resource.getParent()); } } while(resource.getParent() != null); // all checks are done positive return(true); } /** * Checks, if the user may lock this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user may lock this resource, or not. */ public boolean accessLock(CmsUser currentUser, CmsProject currentProject, String resourceName) throws CmsException { CmsResource resource = m_dbAccess.readFileHeader(currentProject.getId(), resourceName); return accessLock(currentUser,currentProject,resource); } /** * Checks, if others may access this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * @param flags The flags to check. * * @return wether the user has access, or not. */ protected boolean accessOther(CmsUser currentUser, CmsProject currentProject, CmsResource resource, int flags) throws CmsException { if ((resource.getAccessFlags() & flags) == flags) { return true; } else { return false; } } /** * Checks, if the owner may access this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * @param flags The flags to check. * * @return wether the user has access, or not. */ protected boolean accessOwner(CmsUser currentUser, CmsProject currentProject, CmsResource resource, int flags) throws CmsException { // The Admin has always access if( isAdmin(currentUser, currentProject) ) { return(true); } // is the resource owned by this user? if(resource.getOwnerId() == currentUser.getId()) { if( (resource.getAccessFlags() & flags) == flags ) { return true ; } } // the resource isn't accesible by the user. return false; } // Methods working with projects /** * Tests if the user can access the project. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId the id of the project. * @return true, if the user has access, else returns false. * @exception CmsException Throws CmsException if something goes wrong. */ public boolean accessProject(CmsUser currentUser, CmsProject currentProject, int projectId) throws CmsException { CmsProject testProject = readProject(currentUser, currentProject, projectId); if (projectId==C_PROJECT_ONLINE_ID) { return true; } // is the project unlocked? if( testProject.getFlags() != C_PROJECT_STATE_UNLOCKED && testProject.getFlags() != C_PROJECT_STATE_INVISIBLE) { return(false); } // is the current-user admin, or the owner of the project? if( (currentProject.getOwnerId() == currentUser.getId()) || isAdmin(currentUser, currentProject) ) { return(true); } // get all groups of the user Vector groups = getGroupsOfUser(currentUser, currentProject, currentUser.getName()); // test, if the user is in the same groups like the project. for(int i = 0; i < groups.size(); i++) { int groupId = ((CmsGroup) groups.elementAt(i)).getId(); if( ( groupId == testProject.getGroupId() ) || ( groupId == testProject.getManagerGroupId() ) ) { return( true ); } } return( false ); } /** * Checks, if the user may read this resource. * NOTE: If the ressource is in the project you never have to fallback. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return weather the user has access, or not. */ public boolean accessRead(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { Boolean access=(Boolean)m_accessCache.get(currentUser.getId()+":"+currentProject.getId()+":"+resource.getResourceName()); if (access != null) { return access.booleanValue(); } else { if ((resource == null) || !accessProject(currentUser, currentProject, resource.getProjectId()) || (!accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_READ) && !accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_READ) && !accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_READ))) { m_accessCache.put(currentUser.getId()+":"+currentProject.getId()+":"+resource.getResourceName(), new Boolean(false)); return false; } // check the rights for all CmsResource res = resource; // save the original resource name to be used if an error occurs. while (res.getParent() != null) { // readFolder without checking access res = m_dbAccess.readFolder(currentProject.getId(), res.getRootName()+res.getParent()); if (res == null) { if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(A_OpenCms.C_OPENCMS_DEBUG, "Resource has no parent: " + resource.getAbsolutePath()); } throw new CmsException(this.getClass().getName() + ".accessRead(): Cannot find \'" + resource.getName(), CmsException.C_NOT_FOUND); } if (!accessOther(currentUser, currentProject, res, C_ACCESS_PUBLIC_READ) && !accessOwner(currentUser, currentProject, res, C_ACCESS_OWNER_READ) && !accessGroup(currentUser, currentProject, res, C_ACCESS_GROUP_READ)) { m_accessCache.put(currentUser.getId()+":"+currentProject.getId()+":"+resource.getResourceName(), new Boolean(false)); return false; } } m_accessCache.put(currentUser.getId()+":"+currentProject.getId()+":"+resource.getResourceName(), new Boolean(true)); return true; } } /** * Checks, if the user may read this resource. * NOTE: If the ressource is in the project you never have to fallback. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return weather the user has access, or not. */ public boolean accessRead(CmsUser currentUser, CmsProject currentProject, String resourceName) throws CmsException { CmsResource resource = m_dbAccess.readFileHeader(currentProject.getId(), resourceName); return accessRead(currentUser, currentProject, resource); } /** * Checks, if the user may unlock this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user may unlock this resource, or not. */ public boolean accessUnlock(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { // check, if this is the onlineproject if(onlineProject(currentUser, currentProject).equals(currentProject)){ // the online-project is not writeable! return(false); } // check the access to the project if( ! accessProject(currentUser, currentProject, currentProject.getId()) ) { // no access to the project! return(false); } // check if the resource belongs to the current project if(resource.getProjectId() != currentProject.getId()) { return false; } // read the parent folder if(resource.getParent() != null) { // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getRootName()+resource.getParent()); } else { // no parent folder! return true; } // check if the resource is not locked do { // is the resource locked? if( resource.isLocked() ) { // resource locked by anopther user, no creation allowed return(false); } // read next resource if(resource.getParent() != null) { // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getRootName()+resource.getParent()); } } while(resource.getParent() != null); // all checks are done positive return(true); } /** * Checks, if the user may write this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user has access, or not. */ public boolean accessWrite(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { // check, if this is the onlineproject if(onlineProject(currentUser, currentProject).equals(currentProject)){ // the online-project is not writeable! return(false); } // check the access to the project if( ! accessProject(currentUser, currentProject, currentProject.getId()) ) { // no access to the project! return(false); } // check if the resource belongs to the current project if(resource.getProjectId() != currentProject.getId()) { return false; } // check, if the resource is locked by the current user if(resource.isLockedBy() != currentUser.getId()) { // resource is not locked by the current user, no writing allowed return(false); } else { //check if the project that has locked the resource is the current project if((resource.getLockedInProject() != currentProject.getId())){ return (false); } } // check the rights for the current resource if( ! ( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_WRITE) || accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_WRITE) || accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_WRITE) ) ) { // no write access to this resource! return false; } // read the parent folder if(resource.getParent() != null) { // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getRootName()+resource.getParent()); } else { // no parent folder! return true; } // check the rights and if the resource is not locked // for parent folders only read access is needed do { if( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_READ) || accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_READ) || accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_READ) ) { // is the resource locked? if( resource.isLocked() && (resource.isLockedBy() != currentUser.getId() ) ) { // resource locked by anopther user, no creation allowed return(false); } // read next resource if(resource.getParent() != null) { // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getRootName()+resource.getParent()); } } else { // last check was negative return(false); } } while(resource.getParent() != null); // all checks are done positive return(true); } /** * Checks, if the user may write this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user has access, or not. */ public boolean accessWrite(CmsUser currentUser, CmsProject currentProject, String resourceName) throws CmsException { CmsResource resource = m_dbAccess.readFileHeader(currentProject.getId(), resourceName); return accessWrite(currentUser,currentProject,resource); } /** * Checks, if the user may write the unlocked resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user has access, or not. */ public boolean accessWriteUnlocked(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { // check, if this is the onlineproject if(onlineProject(currentUser, currentProject).equals(currentProject)){ // the online-project is not writeable! return(false); } // check the access to the project if( ! accessProject(currentUser, currentProject, currentProject.getId()) ) { // no access to the project! return(false); } // check if the resource belongs to the current project if(resource.getProjectId() != currentProject.getId()) { return false; } // check the rights for the current resource if( ! ( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_WRITE) || accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_WRITE) || accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_WRITE) ) ) { // no write access to this resource! return false; } // read the parent folder if(resource.getParent() != null) { // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getRootName()+resource.getParent()); } else { // no parent folder! return true; } // check the rights and if the resource is not locked // for parent folders only read access is needed do { if( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_READ) || accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_READ) || accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_READ) ) { // is the resource locked? if( resource.isLocked() && (resource.isLockedBy() != currentUser.getId() ) ) { // resource locked by anopther user, no creation allowed return(false); } // read next resource if(resource.getParent() != null) { // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getRootName()+resource.getParent()); } } else { // last check was negative return(false); } } while(resource.getParent() != null); // all checks are done positive return(true); } /** * adds a file extension to the list of known file extensions * * <B>Security:</B> * Users, which are in the group "administrators" are granted.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param extension a file extension like 'html' * @param resTypeName name of the resource type associated to the extension */ public void addFileExtension(CmsUser currentUser, CmsProject currentProject, String extension, String resTypeName) throws CmsException { if (extension != null && resTypeName != null) { if (isAdmin(currentUser, currentProject)) { Hashtable suffixes=(Hashtable) m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS); if (suffixes == null) { suffixes = new Hashtable(); suffixes.put(extension, resTypeName); m_dbAccess.addSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS, suffixes); } else { suffixes.put(extension, resTypeName); m_dbAccess.writeSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS, suffixes); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + extension, CmsException.C_NO_ACCESS); } } } /** * Add a new group to the Cms.<BR/> * * Only the admin can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name of the new group. * @param description The description for the new group. * @int flags The flags for the new group. * @param name The name of the parent group (or null). * * @return Group * * @exception CmsException Throws CmsException if operation was not succesfull. */ public CmsGroup addGroup(CmsUser currentUser, CmsProject currentProject, String name, String description, int flags, String parent) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) ) { name = name.trim(); validFilename(name); // check the lenght of the groupname if(name.length() > 1) { return( m_dbAccess.createGroup(name, description, flags, parent) ); } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } /** * Adds a user to the Cms. * * Only a adminstrator can add users to the cms.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The new name for the user. * @param password The new password for the user. * @param group The default groupname for the user. * @param description The description for the user. * @param additionalInfos A Hashtable with additional infos for the user. These * Infos may be stored into the Usertables (depending on the implementation). * @param flags The flags for a user (e.g. C_FLAG_ENABLED) * * @return user The added user will be returned. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public CmsUser addUser(CmsUser currentUser, CmsProject currentProject, String name, String password, String group, String description, Hashtable additionalInfos, int flags) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) ) { // no space before or after the name name = name.trim(); // check the username validFilename(name); // check the password minimumsize if( (name.length() > 0) && (password.length() >= C_PASSWORD_MINIMUMSIZE) ) { CmsGroup defaultGroup = readGroup(currentUser, currentProject, group); CmsUser newUser = m_dbAccess.addUser(name, password, description, " ", " ", " ", 0, 0, C_FLAG_ENABLED, additionalInfos, defaultGroup, " ", " ", C_USER_TYPE_SYSTEMUSER); addUserToGroup(currentUser, currentProject, newUser.getName(),defaultGroup.getName()); return newUser; } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_SHORT_PASSWORD); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } /** * Adds a user to the Cms. * * Only a adminstrator can add users to the cms.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name for the user. * @param password The password for the user. * @param recoveryPassword The recoveryPassword for the user. * @param description The description for the user. * @param firstname The firstname of the user. * @param lastname The lastname of the user. * @param email The email of the user. * @param flags The flags for a user (e.g. C_FLAG_ENABLED) * @param additionalInfos A Hashtable with additional infos for the user. These * Infos may be stored into the Usertables (depending on the implementation). * @param defaultGroup The default groupname for the user. * @param address The address of the user * @param section The section of the user * @param type The type of the user * * @return user The added user will be returned. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public CmsUser addImportUser(CmsUser currentUser, CmsProject currentProject, String name, String password, String recoveryPassword, String description, String firstname, String lastname, String email, int flags, Hashtable additionalInfos, String defaultGroup, String address, String section, int type) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) ) { // no space before or after the name name = name.trim(); // check the username validFilename(name); CmsGroup group = readGroup(currentUser, currentProject, defaultGroup); CmsUser newUser = m_dbAccess.addImportUser(name, password, recoveryPassword, description, firstname, lastname, email, 0, 0, flags, additionalInfos, group, address, section, type); addUserToGroup(currentUser, currentProject, newUser.getName(), group.getName()); return newUser; } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } /** * Adds a user to a group.<BR/> * * Only the admin can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user that is to be added to the group. * @param groupname The name of the group. * @exception CmsException Throws CmsException if operation was not succesfull. */ public void addUserToGroup(CmsUser currentUser, CmsProject currentProject, String username, String groupname) throws CmsException { if (!userInGroup(currentUser, currentProject, username, groupname)) { // Check the security if (isAdmin(currentUser, currentProject)) { CmsUser user; CmsGroup group; try{ user = readUser(currentUser, currentProject, username); } catch (CmsException e){ if (e.getType() == CmsException.C_NO_USER){ user = readWebUser(currentUser, currentProject, username); } else { throw e; } } //check if the user exists if (user != null) { group = readGroup(currentUser, currentProject, groupname); //check if group exists if (group != null) { //add this user to the group m_dbAccess.addUserToGroup(user.getId(), group.getId()); // update the cache m_usergroupsCache.clear(); } else { throw new CmsException("[" + this.getClass().getName() + "]" + groupname, CmsException.C_NO_GROUP); } } else { throw new CmsException("[" + this.getClass().getName() + "]" + username, CmsException.C_NO_USER); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS); } } } /** * Adds a web user to the Cms. <br> * * A web user has no access to the workplace but is able to access personalized * functions controlled by the OpenCms. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The new name for the user. * @param password The new password for the user. * @param group The default groupname for the user. * @param description The description for the user. * @param additionalInfos A Hashtable with additional infos for the user. These * Infos may be stored into the Usertables (depending on the implementation). * @param flags The flags for a user (e.g. C_FLAG_ENABLED) * * @return user The added user will be returned. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public CmsUser addWebUser(CmsUser currentUser, CmsProject currentProject, String name, String password, String group, String description, Hashtable additionalInfos, int flags) throws CmsException { // no space before or after the name name = name.trim(); // check the username validFilename(name); // check the password minimumsize if( (name.length() > 0) && (password.length() >= C_PASSWORD_MINIMUMSIZE) ) { CmsGroup defaultGroup = readGroup(currentUser, currentProject, group); CmsUser newUser = m_dbAccess.addUser(name, password, description, " ", " ", " ", 0, 0, C_FLAG_ENABLED, additionalInfos, defaultGroup, " ", " ", C_USER_TYPE_WEBUSER); CmsUser user; CmsGroup usergroup; user=m_dbAccess.readUser(newUser.getName(),C_USER_TYPE_WEBUSER); //check if the user exists if (user != null) { usergroup=readGroup(currentUser,currentProject,group); //check if group exists if (usergroup != null){ //add this user to the group m_dbAccess.addUserToGroup(user.getId(),usergroup.getId()); // update the cache m_usergroupsCache.clear(); } else { throw new CmsException("["+this.getClass().getName()+"]"+group,CmsException.C_NO_GROUP); } } else { throw new CmsException("["+this.getClass().getName()+"]"+name,CmsException.C_NO_USER); } return newUser; } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_SHORT_PASSWORD); } } /** * Adds a web user to the Cms. <br> * * A web user has no access to the workplace but is able to access personalized * functions controlled by the OpenCms. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The new name for the user. * @param password The new password for the user. * @param group The default groupname for the user. * @param additionalGroup An additional group for the user. * @param description The description for the user. * @param additionalInfos A Hashtable with additional infos for the user. These * Infos may be stored into the Usertables (depending on the implementation). * @param flags The flags for a user (e.g. C_FLAG_ENABLED) * * @return user The added user will be returned. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public CmsUser addWebUser(CmsUser currentUser, CmsProject currentProject, String name, String password, String group, String additionalGroup, String description, Hashtable additionalInfos, int flags) throws CmsException { // no space before or after the name name = name.trim(); // check the username validFilename(name); // check the password minimumsize if( (name.length() > 0) && (password.length() >= C_PASSWORD_MINIMUMSIZE) ) { CmsGroup defaultGroup = readGroup(currentUser, currentProject, group); CmsUser newUser = m_dbAccess.addUser(name, password, description, " ", " ", " ", 0, 0, C_FLAG_ENABLED, additionalInfos, defaultGroup, " ", " ", C_USER_TYPE_WEBUSER); CmsUser user; CmsGroup usergroup; CmsGroup addGroup; user=m_dbAccess.readUser(newUser.getName(),C_USER_TYPE_WEBUSER); //check if the user exists if (user != null) { usergroup=readGroup(currentUser,currentProject,group); //check if group exists if (usergroup != null && isWebgroup(usergroup)){ //add this user to the group m_dbAccess.addUserToGroup(user.getId(),usergroup.getId()); // update the cache m_usergroupsCache.clear(); } else { throw new CmsException("["+this.getClass().getName()+"]"+group,CmsException.C_NO_GROUP); } // if an additional groupname is given and the group does not belong to // Users, Administrators or Projectmanager add the user to this group if (additionalGroup != null && !"".equals(additionalGroup)){ addGroup = readGroup(currentUser, currentProject, additionalGroup); if(addGroup != null && isWebgroup(addGroup)){ //add this user to the group m_dbAccess.addUserToGroup(user.getId(), addGroup.getId()); // update the cache m_usergroupsCache.clear(); } else { throw new CmsException("["+this.getClass().getName()+"]"+additionalGroup,CmsException.C_NO_GROUP); } } } else { throw new CmsException("["+this.getClass().getName()+"]"+name,CmsException.C_NO_USER); } return newUser; } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_SHORT_PASSWORD); } } /** * Returns the anonymous user object.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return the anonymous user object. * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser anonymousUser(CmsUser currentUser, CmsProject currentProject) throws CmsException { return readUser(currentUser, currentProject, C_USER_GUEST); } /** * Changes the group for this resource<br> * * Only the group of a resource in an offline project can be changed. The state * of the resource is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * The user may change this, if he is admin of the resource. <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user is owner of the resource or is admin</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The complete path to the resource. * @param newGroup The name of the new group for this resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void chgrp(CmsUser currentUser, CmsProject currentProject, String filename, String newGroup) throws CmsException { CmsResource resource=null; // read the resource to check the access if (filename.endsWith("/")) { resource = readFolder(currentUser,currentProject,filename); } else { resource = (CmsFile)readFileHeader(currentUser,currentProject,filename); } // has the user write-access? and is he owner or admin? if( accessWrite(currentUser, currentProject, resource) && ( (resource.getOwnerId() == currentUser.getId()) || isAdmin(currentUser, currentProject))) { CmsGroup group = readGroup(currentUser, currentProject, newGroup); resource.setGroupId(group.getId()); // write-acces was granted - write the file. if (filename.endsWith("/")) { if (resource.getState()==C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } m_dbAccess.writeFolder(currentProject,(CmsFolder)resource,true, currentUser.getId()); // update the cache m_resourceCache.remove(filename); } else { m_dbAccess.writeFileHeader(currentProject,(CmsFile)resource,true, currentUser.getId()); if (resource.getState()==C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.remove(filename); } m_subresCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS); } } /** * Changes the flags for this resource.<br> * * Only the flags of a resource in an offline project can be changed. The state * of the resource is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * The user may change the flags, if he is admin of the resource <br>. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The complete path to the resource. * @param flags The new accessflags for the resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void chmod(CmsUser currentUser, CmsProject currentProject, String filename, int flags) throws CmsException { CmsResource resource=null; // read the resource to check the access if (filename.endsWith("/")) { resource = readFolder(currentUser,currentProject,filename); } else { resource = (CmsFile)readFileHeader(currentUser,currentProject,filename); } // has the user write-access? if( accessWrite(currentUser, currentProject, resource)|| ((resource.isLockedBy() == currentUser.getId() && resource.getLockedInProject() == currentProject.getId()) && (resource.getOwnerId() == currentUser.getId()||isAdmin(currentUser, currentProject))) ) { // write-acces was granted - write the file. //set the flags resource.setAccessFlags(flags); //update file if (filename.endsWith("/")) { if (resource.getState()==C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } m_dbAccess.writeFolder(currentProject,(CmsFolder)resource,true, currentUser.getId()); // update the cache m_resourceCache.remove(filename); } else { m_dbAccess.writeFileHeader(currentProject,(CmsFile)resource,true, currentUser.getId()); if (resource.getState()==C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.remove(filename); } m_subresCache.clear(); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS); } } /** * Changes the owner for this resource.<br> * * Only the owner of a resource in an offline project can be changed. The state * of the resource is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * The user may change this, if he is admin of the resource. <br> * * <B>Security:</B> * Access is cranted, if: * <ul> * <li>the user has access to the project</li> * <li>the user is owner of the resource or the user is admin</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The complete path to the resource. * @param newOwner The name of the new owner for this resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void chown(CmsUser currentUser, CmsProject currentProject, String filename, String newOwner) throws CmsException { CmsResource resource = null; // read the resource to check the access if (filename.endsWith("/")) { resource = readFolder(currentUser, currentProject, filename); } else { resource = (CmsFile) readFileHeader(currentUser, currentProject, filename); } // has the user write-access? and is he owner or admin? if (((resource.getOwnerId() == currentUser.getId()) || isAdmin(currentUser, currentProject)) && (resource.isLockedBy() == currentUser.getId() && resource.getLockedInProject() == currentProject.getId())) { CmsUser owner = readUser(currentUser, currentProject, newOwner); resource.setUserId(owner.getId()); // write-acces was granted - write the file. if (filename.endsWith("/")) { if (resource.getState() == C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } m_dbAccess.writeFolder(currentProject, (CmsFolder) resource, true, currentUser.getId()); // update the cache m_resourceCache.remove(filename); } else { m_dbAccess.writeFileHeader(currentProject, (CmsFile) resource, true, currentUser.getId()); if (resource.getState() == C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.remove(filename); } m_subresCache.clear(); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS); } } /** * Changes the state for this resource<BR/> * * The user may change this, if he is admin of the resource. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user is owner of the resource or is admin</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param filename The complete path to the resource. * @param state The new state of this resource. * * @exception CmsException will be thrown, if the user has not the rights * for this resource. */ public void chstate(CmsUser currentUser, CmsProject currentProject, String filename, int state) throws CmsException { boolean isFolder=false; CmsResource resource=null; // read the resource to check the access if (filename.endsWith("/")) { isFolder=true; resource = readFolder(currentUser,currentProject,filename); } else { resource = (CmsFile)readFileHeader(currentUser,currentProject,filename); } // has the user write-access? if( accessWrite(currentUser, currentProject, resource)) { resource.setState(state); // write-acces was granted - write the file. if (filename.endsWith("/")) { m_dbAccess.writeFolder(currentProject,(CmsFolder)resource,false, currentUser.getId()); // update the cache m_resourceCache.remove(filename); } else { m_dbAccess.writeFileHeader(currentProject,(CmsFile)resource,false, currentUser.getId()); // update the cache m_resourceCache.remove(filename); } m_subresCache.clear(); // inform about the file-system-change fileSystemChanged(isFolder); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS); } } /** * Changes the resourcetype for this resource<br> * * Only the resourcetype of a resource in an offline project can be changed. The state * of the resource is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * The user may change this, if he is admin of the resource. <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user is owner of the resource or is admin</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The complete path to the resource. * @param newType The name of the new resourcetype for this resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void chtype(CmsUser currentUser, CmsProject currentProject, String filename, String newType) throws CmsException { I_CmsResourceType type = getResourceType(currentUser, currentProject, newType); // read the resource to check the access CmsResource resource = readFileHeader(currentUser,currentProject, filename); // has the user write-access? and is he owner or admin? if( accessWrite(currentUser, currentProject, resource) && ( (resource.getOwnerId() == currentUser.getId()) || isAdmin(currentUser, currentProject))) { // write-acces was granted - write the file. resource.setType(type.getResourceType()); resource.setLauncherType(type.getLauncherType()); m_dbAccess.writeFileHeader(currentProject, (CmsFile)resource,true, currentUser.getId()); if (resource.getState()==C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.remove(filename); m_subresCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS); } } /** * Clears all internal DB-Caches. */ public void clearcache() { m_userCache.clear(); m_groupCache.clear(); m_usergroupsCache.clear(); m_projectCache.clear(); m_resourceCache.clear(); m_subresCache.clear(); m_propertyCache.clear(); m_propertyDefCache.clear(); m_propertyDefVectorCache.clear(); m_onlineProjectCache.clear(); m_accessCache.clear(); CmsTemplateClassManager.clearCache(); } /** * Copies a file in the Cms. <br> * * <B>Security:</B> * Access is cranted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the sourceresource</li> * <li>the user can create the destinationresource</li> * <li>the destinationresource dosn't exists</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param source The complete path of the sourcefile. * @param destination The complete path to the destination. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void copyFile(CmsUser currentUser, CmsProject currentProject, String source, String destination) throws CmsException { // the name of the new file. String filename; // the name of the folder. String foldername; // checks, if the destinateion is valid, if not it throws a exception validFilename(destination.replace('/', 'a')); // read the source-file, to check readaccess CmsResource file = readFileHeader(currentUser, currentProject, source); // split the destination into file and foldername if (destination.endsWith("/")) { filename = file.getName(); foldername = destination; }else{ foldername = destination.substring(0, destination.lastIndexOf("/")+1); filename = destination.substring(destination.lastIndexOf("/")+1, destination.length()); } CmsFolder cmsFolder = readFolder(currentUser,currentProject, foldername); if( accessCreate(currentUser, currentProject, (CmsResource)cmsFolder) ) { if(( accessOther(currentUser, currentProject, file, C_ACCESS_PUBLIC_WRITE) || accessOwner(currentUser, currentProject, file, C_ACCESS_OWNER_WRITE) || accessGroup(currentUser, currentProject, file, C_ACCESS_GROUP_WRITE) )){ // write-acces was granted - copy the file and the metainfos m_dbAccess.copyFile(currentProject, onlineProject(currentUser, currentProject), currentUser.getId(),source,cmsFolder.getResourceId(), foldername + filename); // copy the metainfos lockResource(currentUser, currentProject, destination, true); writeProperties(currentUser,currentProject, destination, readAllProperties(currentUser,currentProject,file.getResourceName())); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(file.isFolder()); } else { throw new CmsException("[" + this.getClass().getName() + "] " + source, CmsException.C_NO_ACCESS); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + destination, CmsException.C_NO_ACCESS); } } /** * Copies a folder in the Cms. <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the sourceresource</li> * <li>the user can create the destinationresource</li> * <li>the destinationresource dosn't exists</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param source The complete path of the sourcefolder. * @param destination The complete path to the destination. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void copyFolder(CmsUser currentUser, CmsProject currentProject, String source, String destination) throws CmsException { // the name of the new file. String filename; // the name of the folder. String foldername; // checks, if the destinateion is valid, if not it throws a exception validFilename(destination.replace('/', 'a')); foldername = destination.substring(0, destination.substring(0,destination.length()-1).lastIndexOf("/")+1); CmsFolder cmsFolder = readFolder(currentUser,currentProject, foldername); if( accessCreate(currentUser, currentProject, (CmsResource)cmsFolder) ) { // write-acces was granted - copy the folder and the properties CmsFolder folder=readFolder(currentUser,currentProject,source); // check write access to the folder that has to be copied if(( accessOther(currentUser, currentProject, (CmsResource)folder, C_ACCESS_PUBLIC_WRITE) || accessOwner(currentUser, currentProject, (CmsResource)folder, C_ACCESS_OWNER_WRITE) || accessGroup(currentUser, currentProject, (CmsResource)folder, C_ACCESS_GROUP_WRITE) )){ m_dbAccess.createFolder(currentUser,currentProject,onlineProject(currentUser, currentProject),folder,cmsFolder.getResourceId(),destination); // copy the properties lockResource(currentUser, currentProject, destination, true); writeProperties(currentUser,currentProject, destination, readAllProperties(currentUser,currentProject,folder.getResourceName())); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(true); } else { throw new CmsException("[" + this.getClass().getName() + "] " + source, CmsException.C_ACCESS_DENIED); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + destination, CmsException.C_ACCESS_DENIED); } } /** * Copies a resource from the online project to a new, specified project.<br> * Copying a resource will copy the file header or folder into the specified * offline project and set its state to UNCHANGED. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user is the owner of the project</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource. * @exception CmsException Throws CmsException if operation was not succesful. */ public void copyResourceToProject(CmsUser currentUser, CmsProject currentProject, String resource) throws CmsException { // read the onlineproject CmsProject online = onlineProject(currentUser, currentProject); // is the current project the onlineproject? // and is the current user the owner of the project? // and is the current project state UNLOCKED? if ((!currentProject.equals(online)) && (isManagerOfProject(currentUser, currentProject)) && (currentProject.getFlags() == C_PROJECT_STATE_UNLOCKED)) { // is offlineproject and is owner // try to read the resource from the offline project, include deleted CmsResource offlineRes = null; try{ m_resourceCache.remove(resource); Vector subFiles = getFilesInFolder(currentUser, currentProject, resource, true); Vector subFolders = getSubFolders(currentUser, currentProject, resource, true); for(int i=0; i<subFolders.size(); i++){ String foldername = ((CmsResource)subFolders.elementAt(i)).getResourceName(); m_resourceCache.remove(foldername); } for(int i=0; i<subFiles.size(); i++){ String filename = ((CmsResource)subFiles.elementAt(i)).getResourceName(); m_resourceCache.remove(filename); } m_subresCache.clear(); m_accessCache.clear(); offlineRes = readFileHeader(currentUser, currentProject, currentProject.getId(),resource); } catch (CmsException exc){ // if the resource does not exist in the offlineProject - it's ok } // create the projectresource only if the resource is not in the current project if ((offlineRes == null) || (offlineRes.getProjectId() != currentProject.getId())){ // check if there are already any subfolders of this resource if(resource.endsWith("/")){ Vector projectResources = m_dbAccess.readAllProjectResources(currentProject.getId()); for(int i=0; i<projectResources.size(); i++){ String resname = (String)projectResources.elementAt(i); if(resname.startsWith(resource)){ // delete the existing project resource first m_dbAccess.deleteProjectResource(currentProject.getId(), resname); } } } try { m_dbAccess.createProjectResource(currentProject.getId(), resource); } catch (CmsException exc) { // if the subfolder exists already - all is ok } } } else { // no changes on the onlineproject! throw new CmsException("[" + this.getClass().getName() + "] " + currentProject.getName(), CmsException.C_NO_ACCESS); } } /** * Counts the locked resources in this project. * * <B>Security</B> * Only the admin or the owner of the project can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id of the project * @return the amount of locked resources in this project. * * @exception CmsException Throws CmsException if something goes wrong. */ public int countLockedResources(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { // read the project. CmsProject project = readProject(currentUser, currentProject, id); // check the security if( isAdmin(currentUser, currentProject) || isManagerOfProject(currentUser, project) || (project.getFlags() == C_PROJECT_STATE_UNLOCKED )) { // count locks return m_dbAccess.countLockedResources(project); } else { throw new CmsException("[" + this.getClass().getName() + "] " + id, CmsException.C_NO_ACCESS); } } /** * return the correct DbAccess class. * This method should be overloaded by all other Database Drivers * Creation date: (09/15/00 %r) * @return com.opencms.file.genericSql.CmsDbAccess * @param configurations source.org.apache.java.util.Configurations * @exception com.opencms.core.CmsException Thrown if CmsDbAccess class could not be instantiated. */ public com.opencms.file.genericSql.CmsDbAccess createDbAccess(Configurations configurations) throws CmsException { return new com.opencms.file.genericSql.CmsDbAccess(configurations); } /** * Creates a new file with the given content and resourcetype. <br> * * Files can only be created in an offline project, the state of the new file * is set to NEW (2). <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the folder-resource is not locked by another user</li> * <li>the file dosn't exists</li> * </ul> * * @param currentUser The user who owns this file. * @param currentGroup The group who owns this file. * @param currentProject The project in which the resource will be used. * @param folder The complete path to the folder in which the new folder will * be created. * @param file The name of the new file (No pathinformation allowed). * @param contents The contents of the new file. * @param type The name of the resourcetype of the new file. * @param propertyinfos A Hashtable of propertyinfos, that should be set for this folder. * The keys for this Hashtable are the names for propertydefinitions, the values are * the values for the propertyinfos. * @return file The created file. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsFile createFile(CmsUser currentUser, CmsGroup currentGroup, CmsProject currentProject, String folder, String filename, byte[] contents, String type, Hashtable propertyinfos) throws CmsException { // checks, if the filename is valid, if not it throws a exception validFilename(filename); CmsFolder cmsFolder = readFolder(currentUser,currentProject, folder); if( accessCreate(currentUser, currentProject, (CmsResource)cmsFolder) ) { // write-access was granted - create and return the file. CmsFile file = m_dbAccess.createFile(currentUser, currentProject, onlineProject(currentUser, currentProject), folder + filename, 0, cmsFolder.getResourceId(), contents, getResourceType(currentUser, currentProject, type)); // update the access flags Hashtable startSettings=null; Integer accessFlags=null; startSettings=(Hashtable)currentUser.getAdditionalInfo(C_ADDITIONAL_INFO_STARTSETTINGS); if (startSettings != null) { accessFlags=(Integer)startSettings.get(C_START_ACCESSFLAGS); if (accessFlags != null) { file.setAccessFlags(accessFlags.intValue()); } } if(currentGroup != null) { file.setGroupId(currentGroup.getId()); } m_dbAccess.writeFileHeader(currentProject, file,false); m_subresCache.clear(); // write the metainfos m_dbAccess.writeProperties(propertyinfos, currentProject.getId(),file, file.getType()); // inform about the file-system-change fileSystemChanged(false); return file ; } else { throw new CmsException("[" + this.getClass().getName() + "] " + folder + filename, CmsException.C_NO_ACCESS); } } /** * Creates a new folder. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is not locked by another user</li> * </ul> * * @param currentUser The user who requested this method. * @param currentGroup The group who requested this method. * @param currentProject The current project of the user. * @param folder The complete path to the folder in which the new folder will * be created. * @param newFolderName The name of the new folder (No pathinformation allowed). * @param propertyinfos A Hashtable of propertyinfos, that should be set for this folder. * The keys for this Hashtable are the names for propertydefinitions, the values are * the values for the propertyinfos. * * @return file The created file. * * @exception CmsException will be thrown for missing propertyinfos, for worng propertydefs * or if the filename is not valid. The CmsException will also be thrown, if the * user has not the rights for this resource. */ public CmsFolder createFolder(CmsUser currentUser, CmsGroup currentGroup, CmsProject currentProject, String folder, String newFolderName, Hashtable propertyinfos) throws CmsException { // checks, if the filename is valid, if not it throws a exception validFilename(newFolderName); CmsFolder cmsFolder = readFolder(currentUser,currentProject, folder); if( accessCreate(currentUser, currentProject, (CmsResource)cmsFolder) ) { // write-acces was granted - create the folder. CmsFolder newFolder = m_dbAccess.createFolder(currentUser, currentProject, cmsFolder.getResourceId(), C_UNKNOWN_ID, folder + newFolderName + C_FOLDER_SEPERATOR, 0); // update the access flags Hashtable startSettings=null; Integer accessFlags=null; startSettings=(Hashtable)currentUser.getAdditionalInfo(C_ADDITIONAL_INFO_STARTSETTINGS); if (startSettings != null) { accessFlags=(Integer)startSettings.get(C_START_ACCESSFLAGS); if (accessFlags != null) { newFolder.setAccessFlags(accessFlags.intValue()); } } if(currentGroup != null) { newFolder.setGroupId(currentGroup.getId()); } newFolder.setState(C_STATE_NEW); m_dbAccess.writeFolder(currentProject, newFolder, false); m_subresCache.clear(); // write metainfos for the folder m_dbAccess.writeProperties(propertyinfos, currentProject.getId(), newFolder, newFolder.getType()); // inform about the file-system-change fileSystemChanged(true); // return the folder return newFolder ; } else { throw new CmsException("[" + this.getClass().getName() + "] " + folder + newFolderName, CmsException.C_NO_ACCESS); } } /** * Creates a project. * * <B>Security</B> * Only the users which are in the admin or projectleader-group are granted. * * Changed: added the parent id * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name of the project to read. * @param description The description for the new project. * @param group the group to be set. * @param managergroup the managergroup to be set. * @param parentId the parent project * @exception CmsException Throws CmsException if something goes wrong. * @author Martin Langelund */ public CmsProject createProject(CmsUser currentUser, CmsProject currentProject, String name, String description, String groupname, String managergroupname) throws CmsException { if (isAdmin(currentUser, currentProject) || isProjectManager(currentUser, currentProject)) { if (C_PROJECT_ONLINE.equals(name)){ throw new CmsException ("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME); } // read the needed groups from the cms CmsGroup group = readGroup(currentUser, currentProject, groupname); CmsGroup managergroup = readGroup(currentUser, currentProject, managergroupname); // create a new task for the project CmsTask task = createProject(currentUser, name, 1, group.getName(), System.currentTimeMillis(), C_TASK_PRIORITY_NORMAL); return m_dbAccess.createProject(currentUser, group, managergroup, task, name, description, C_PROJECT_STATE_UNLOCKED, C_PROJECT_TYPE_NORMAL); } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } /** * Creates a project. * * <B>Security</B> * Only the users which are in the admin or projectleader-group are granted. * * Changed: added the project type * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name of the project to read. * @param description The description for the new project. * @param group the group to be set. * @param managergroup the managergroup to be set. * @param project type the type of the project * @exception CmsException Throws CmsException if something goes wrong. * @author Edna Falkenhan */ public CmsProject createProject(CmsUser currentUser, CmsProject currentProject, String name, String description, String groupname, String managergroupname, int projecttype) throws CmsException { if (isAdmin(currentUser, currentProject) || isProjectManager(currentUser, currentProject)) { if (C_PROJECT_ONLINE.equals(name)){ throw new CmsException ("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME); } // read the needed groups from the cms CmsGroup group = readGroup(currentUser, currentProject, groupname); CmsGroup managergroup = readGroup(currentUser, currentProject, managergroupname); // create a new task for the project CmsTask task = createProject(currentUser, name, 1, group.getName(), System.currentTimeMillis(), C_TASK_PRIORITY_NORMAL); return m_dbAccess.createProject(currentUser, group, managergroup, task, name, description, C_PROJECT_STATE_UNLOCKED, projecttype); } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } /** * Creates a project for the temporary files. * * <B>Security</B> * Only the users which are in the admin or projectleader-group are granted. * * Changed: added the project type * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @exception CmsException Throws CmsException if something goes wrong. * @author Edna Falkenhan */ public CmsProject createTempfileProject(CmsObject cms, CmsUser currentUser, CmsProject currentProject) throws CmsException { String name = "tempFileProject"; String description = "Project for temporary files"; if (isAdmin(currentUser, currentProject)) { // read the needed groups from the cms CmsGroup group = readGroup(currentUser, currentProject, "Users"); CmsGroup managergroup = readGroup(currentUser, currentProject, "Administrators"); // create a new task for the project CmsTask task = createProject(currentUser, name, 1, group.getName(), System.currentTimeMillis(), C_TASK_PRIORITY_NORMAL); CmsProject tempProject = m_dbAccess.createProject(currentUser, group, managergroup, task, name, description, C_PROJECT_STATE_INVISIBLE, C_PROJECT_STATE_INVISIBLE); m_dbAccess.createProjectResource(tempProject.getId(), "/"); cms.getRegistry().setSystemValue("tempfileproject",""+tempProject.getId()); return tempProject; } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } /** * Creates a new project for task handling. * * @param currentUser User who creates the project * @param projectName Name of the project * @param projectType Type of the Project * @param role Usergroup for the project * @param timeout Time when the Project must finished * @param priority Priority for the Project * * @return The new task project * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsTask createProject(CmsUser currentUser, String projectName, int projectType, String roleName, long timeout, int priority) throws CmsException { CmsGroup role = null; // read the role if(roleName!=null && !roleName.equals("")) { role = readGroup(currentUser, null, roleName); } // create the timestamp java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout); java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis()); return m_dbAccess.createTask(0,0, 1, // standart project type, currentUser.getId(), currentUser.getId(), role.getId(), projectName, now, timestamp, priority); } // Methods working with properties and propertydefinitions /** * Creates the propertydefinition for the resource type.<BR/> * * <B>Security</B> * Only the admin can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name of the propertydefinition to overwrite. * @param resourcetype The name of the resource-type for the propertydefinition. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsPropertydefinition createPropertydefinition(CmsUser currentUser, CmsProject currentProject, String name, String resourcetype) throws CmsException { // check the security if( isAdmin(currentUser, currentProject) ) { // no space before or after the name name = name.trim(); // check the name validFilename(name); m_propertyDefVectorCache.clear(); return( m_dbAccess.createPropertydefinition(name, getResourceType(currentUser, currentProject, resourcetype)) ); } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } /** * Creates a new task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param projectid The Id of the current project task of the user. * @param agentName User who will edit the task * @param roleName Usergroup for the task * @param taskName Name of the task * @param taskType Type of the task * @param taskComment Description of the task * @param timeout Time when the task must finished * @param priority Id for the priority * * @return A new Task Object * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsTask createTask(CmsUser currentUser, int projectid, String agentName, String roleName, String taskName, String taskComment, int taskType, long timeout, int priority) throws CmsException { CmsUser agent = m_dbAccess.readUser(agentName, C_USER_TYPE_SYSTEMUSER); CmsGroup role = m_dbAccess.readGroup(roleName); java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout); java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis()); validTaskname(taskName); // check for valid Filename CmsTask task = m_dbAccess.createTask(projectid, projectid, taskType, currentUser.getId(), agent.getId(), role.getId(), taskName, now, timestamp, priority); if(taskComment!=null && !taskComment.equals("")) { m_dbAccess.writeTaskLog(task.getId(), currentUser.getId(), new java.sql.Timestamp(System.currentTimeMillis()), taskComment, C_TASKLOG_USER); } return task; } /** * Creates a new task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param agent Username who will edit the task * @param role Usergroupname for the task * @param taskname Name of the task * @param taskcomment Description of the task. * @param timeout Time when the task must finished * @param priority Id for the priority * * @return A new Task Object * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsTask createTask(CmsUser currentUser, CmsProject currentProject, String agentName, String roleName, String taskname, String taskcomment, long timeout, int priority) throws CmsException { CmsGroup role = m_dbAccess.readGroup(roleName); java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout); java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis()); int agentId = C_UNKNOWN_ID; validTaskname(taskname); // check for valid Filename try { agentId = m_dbAccess.readUser(agentName, C_USER_TYPE_SYSTEMUSER).getId(); } catch (Exception e) { // ignore that this user doesn't exist and create a task for the role } return m_dbAccess.createTask(currentProject.getTaskId(), currentProject.getTaskId(), 1, // standart Task Type currentUser.getId(), agentId, role.getId(), taskname, now, timestamp, priority); } /** * Deletes all propertyinformation for a file or folder. * * <B>Security</B> * Only the user is granted, who has the right to write the resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource of which the propertyinformations * have to be deleted. * * @exception CmsException Throws CmsException if operation was not succesful */ public void deleteAllProperties(CmsUser currentUser, CmsProject currentProject, String resource) throws CmsException { // read the resource CmsResource res = readFileHeader(currentUser,currentProject, resource); // check the security if( ! accessWrite(currentUser, currentProject, res) ) { throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_NO_ACCESS); } //delete all Properties m_dbAccess.deleteAllProperties(currentProject.getId(),res); m_propertyCache.clear(); } /** * Deletes a file in the Cms.<br> * * A file can only be deleteed in an offline project. * A file is deleted by setting its state to DELETED (3). <br> * * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is locked by the callinUser</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The complete path of the file. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void deleteFile(CmsUser currentUser, CmsProject currentProject, String filename) throws CmsException { // read the file CmsResource onlineFile; CmsResource file = readFileHeader(currentUser,currentProject, filename); try { onlineFile = readFileHeader(currentUser,onlineProject(currentUser, currentProject), filename); } catch (CmsException exc) { // the file dosent exist onlineFile = null; } // has the user write-access? if( accessWrite(currentUser, currentProject, file) ) { // write-acces was granted - delete the file. // and the metainfos if(onlineFile == null) { // the onlinefile dosent exist => remove the file realy! deleteAllProperties(currentUser,currentProject,file.getResourceName()); m_dbAccess.removeFile(currentProject.getId(), filename); } else { m_dbAccess.deleteFile(currentProject, filename); } // update the cache m_resourceCache.remove(filename); m_subresCache.clear(); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { if(file.getState() == C_STATE_DELETED){ throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_RESOURCE_DELETED); } throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS); } } /** * Deletes a folder in the Cms.<br> * * Only folders in an offline Project can be deleted. A folder is deleted by * setting its state to DELETED (3). <br> * * In its current implmentation, this method can ONLY delete empty folders. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read and write this resource and all subresources</li> * <li>the resource is not locked</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername The complete path of the folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void deleteFolder(CmsUser currentUser, CmsProject currentProject, String foldername) throws CmsException { CmsResource onlineFolder; // read the folder, that shold be deleted CmsFolder cmsFolder = readFolder(currentUser,currentProject,foldername); try { onlineFolder = readFolder(currentUser,onlineProject(currentUser, currentProject), foldername); } catch (CmsException exc) { // the file dosent exist onlineFolder = null; } // check, if the user may delete the resource if( accessWrite(currentUser, currentProject, cmsFolder) ) { // write-acces was granted - delete the folder and metainfos. if(onlineFolder == null) { // the onlinefile dosent exist => remove the file realy! deleteAllProperties(currentUser,currentProject, cmsFolder.getResourceName()); m_dbAccess.removeFolder(currentProject.getId(),cmsFolder); } else { m_dbAccess.deleteFolder(currentProject,cmsFolder, false); } // update cache m_resourceCache.remove(foldername); m_subresCache.clear(); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(true); } else { throw new CmsException("[" + this.getClass().getName() + "] " + foldername, CmsException.C_NO_ACCESS); } } /** * Undeletes a file in the Cms.<br> * * A file can only be undeleted in an offline project. * A file is undeleted by setting its state to CHANGED (1). <br> * * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is locked by the callinUser</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The complete path of the file. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void undeleteResource(CmsUser currentUser, CmsProject currentProject, String filename) throws CmsException { boolean isFolder=false; CmsResource resource=null; int state = C_STATE_CHANGED; // read the resource to check the access if (filename.endsWith("/")) { isFolder=true; resource = m_dbAccess.readFolder(currentProject.getId(),filename); } else { resource = (CmsFile)m_dbAccess.readFileHeader(currentProject.getId(),filename, true); } // has the user write-access? if( accessWriteUnlocked(currentUser, currentProject, resource)) { resource.setState(state); resource.setLocked(currentUser.getId()); // write-access was granted - write the file. if (filename.endsWith("/")) { m_dbAccess.writeFolder(currentProject,(CmsFolder)resource,false, currentUser.getId()); // update the cache m_resourceCache.remove(filename); } else { m_dbAccess.writeFileHeader(currentProject,(CmsFile)resource,false, currentUser.getId()); // update the cache m_resourceCache.remove(filename); } m_subresCache.clear(); // inform about the file-system-change fileSystemChanged(isFolder); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS); } } /** * Delete a group from the Cms.<BR/> * Only groups that contain no subgroups can be deleted. * * Only the admin can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param delgroup The name of the group that is to be deleted. * @exception CmsException Throws CmsException if operation was not succesfull. */ public void deleteGroup(CmsUser currentUser, CmsProject currentProject, String delgroup) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) ) { Vector childs=null; Vector users=null; // get all child groups of the group childs=getChild(currentUser,currentProject,delgroup); // get all users in this group users=getUsersOfGroup(currentUser,currentProject,delgroup); // delete group only if it has no childs and there are no users in this group. if ((childs == null) && ((users == null) || (users.size() == 0))) { m_dbAccess.deleteGroup(delgroup); m_groupCache.remove(delgroup); } else { throw new CmsException(delgroup, CmsException.C_GROUP_NOT_EMPTY); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + delgroup, CmsException.C_NO_ACCESS); } } /** * Deletes a project. * * <B>Security</B> * Only the admin or the owner of the project can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id of the project to be published. * * @exception CmsException Throws CmsException if something goes wrong. */ public void deleteProject(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { Vector deletedFolders = new Vector(); // read the project that should be deleted. CmsProject deleteProject = readProject(currentUser, currentProject, id); if((isAdmin(currentUser, currentProject) || isManagerOfProject(currentUser, deleteProject)) && (id != C_PROJECT_ONLINE_ID)) { Vector allFiles = m_dbAccess.readFiles(deleteProject.getId(), false, true); Vector allFolders = m_dbAccess.readFolders(deleteProject.getId(), false, true); // first delete files or undo changes in files for(int i=0; i<allFiles.size();i++){ CmsFile currentFile = (CmsFile)allFiles.elementAt(i); if(currentFile.getState() == C_STATE_NEW){ // delete the properties m_dbAccess.deleteAllProperties(id, currentFile.getResourceId()); // delete the file m_dbAccess.removeFile(id, currentFile.getResourceName()); } else if (currentFile.getState() == C_STATE_CHANGED){ if(!currentFile.isLocked()){ // lock the resource lockResource(currentUser,deleteProject,currentFile.getResourceName(),true); } // undo all changes in the file undoChanges(currentUser, deleteProject, currentFile.getResourceName()); } else if (currentFile.getState() == C_STATE_DELETED){ // first undelete the file undeleteResource(currentUser, deleteProject, currentFile.getResourceName()); if(!currentFile.isLocked()){ // lock the resource lockResource(currentUser,deleteProject,currentFile.getResourceName(),true); } // then undo all changes in the file undoChanges(currentUser, deleteProject, currentFile.getResourceName()); } } // now delete folders or undo changes in folders for(int i=0; i<allFolders.size();i++){ CmsFolder currentFolder = (CmsFolder)allFolders.elementAt(i); if(currentFolder.getState() == C_STATE_NEW){ // delete the properties m_dbAccess.deleteAllProperties(id, currentFolder.getResourceId()); // add the folder to the vector of folders that has to be deleted deletedFolders.addElement(currentFolder); } else if (currentFolder.getState() == C_STATE_CHANGED){ if(!currentFolder.isLocked()){ // lock the resource lockResource(currentUser,deleteProject,currentFolder.getResourceName(),true); } // undo all changes in the folder undoChanges(currentUser, deleteProject, currentFolder.getResourceName()); } else if (currentFolder.getState() == C_STATE_DELETED){ // undelete the folder undeleteResource(currentUser, deleteProject, currentFolder.getResourceName()); if(!currentFolder.isLocked()){ // lock the resource lockResource(currentUser,deleteProject,currentFolder.getResourceName(),true); } // then undo all changes in the folder undoChanges(currentUser, deleteProject, currentFolder.getResourceName()); } } // now delete the folders in the vector for (int i = deletedFolders.size() - 1; i > -1; i--){ CmsFolder delFolder = ((CmsFolder) deletedFolders.elementAt(i)); m_dbAccess.removeFolder(id, delFolder); } // unlock all resources in the project m_dbAccess.unlockProject(deleteProject); m_resourceCache.clear(); //m_projectCache.clear(); // delete the project m_dbAccess.deleteProject(deleteProject); m_projectCache.remove(id); } else { throw new CmsException("[" + this.getClass().getName() + "] " + id, CmsException.C_NO_ACCESS); } } /** * Deletes a propertyinformation for a file or folder. * * <B>Security</B> * Only the user is granted, who has the right to write the resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource of which the propertyinformation * has to be read. * @param property The propertydefinition-name of which the propertyinformation has to be set. * * @exception CmsException Throws CmsException if operation was not succesful */ public void deleteProperty(CmsUser currentUser, CmsProject currentProject, String resource, String property) throws CmsException { // read the resource CmsResource res = readFileHeader(currentUser,currentProject, resource); // check the security if( ! accessWrite(currentUser, currentProject, res) ) { throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_NO_ACCESS); } // read the metadefinition I_CmsResourceType resType = getResourceType(currentUser,currentProject,res.getType()); CmsPropertydefinition metadef = readPropertydefinition(currentUser,currentProject,property, resType.getResourceTypeName()); if( (metadef != null) ) { m_dbAccess.deleteProperty(property,currentProject.getId(),res,res.getType()); // set the file-state to changed if(res.isFile()){ m_dbAccess.writeFileHeader(currentProject, (CmsFile) res, true, currentUser.getId()); if (res.getState()==C_STATE_UNCHANGED) { res.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.remove(resource); } else { if (res.getState()==C_STATE_UNCHANGED) { res.setState(C_STATE_CHANGED); } m_dbAccess.writeFolder(currentProject, readFolder(currentUser,currentProject, resource), true, currentUser.getId()); // update the cache m_resourceCache.remove(resource); } m_subresCache.clear(); m_propertyCache.clear(); } else { // yes - throw exception throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_UNKNOWN_EXCEPTION); } } /** * Delete the propertydefinition for the resource type.<BR/> * * <B>Security</B> * Only the admin can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name of the propertydefinition to read. * @param resourcetype The name of the resource type for which the * propertydefinition is valid. * * @exception CmsException Throws CmsException if something goes wrong. */ public void deletePropertydefinition(CmsUser currentUser, CmsProject currentProject, String name, String resourcetype) throws CmsException { // check the security if( isAdmin(currentUser, currentProject) ) { // first read and then delete the metadefinition. m_propertyDefVectorCache.clear(); m_propertyDefCache.remove(name + (getResourceType(currentUser,currentProject,resourcetype)).getResourceType()); m_dbAccess.deletePropertydefinition( readPropertydefinition(currentUser,currentProject,name,resourcetype)); } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } /** * Deletes a user from the Cms. * * Only a adminstrator can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param userId The Id of the user to be deleted. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void deleteUser(CmsUser currentUser, CmsProject currentProject, int userId) throws CmsException { CmsUser user = readUser(currentUser,currentProject,userId); deleteUser(currentUser,currentProject,user.getName()); } /** * Deletes a user from the Cms. * * Only a adminstrator can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name of the user to be deleted. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void deleteUser(CmsUser currentUser, CmsProject currentProject, String username) throws CmsException { // Test is this user is existing CmsUser user=readUser(currentUser,currentProject,username); // Check the security // Avoid to delete admin or guest-user if( isAdmin(currentUser, currentProject) && !(username.equals(C_USER_ADMIN) || username.equals(C_USER_GUEST))) { m_dbAccess.deleteUser(username); // delete user from cache m_userCache.remove(username+user.getType()); } else { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS); } } /** * Deletes a web user from the Cms. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param userId The Id of the user to be deleted. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void deleteWebUser(CmsUser currentUser, CmsProject currentProject, int userId) throws CmsException { CmsUser user = readUser(currentUser,currentProject,userId); m_dbAccess.deleteUser(user.getName()); // delete user from cache m_userCache.remove(user.getName()+user.getType()); } /** * Destroys the resource broker and required modules and connections. * @exception CmsException Throws CmsException if something goes wrong. */ public void destroy() throws CmsException { // destroy the db-access. m_dbAccess.destroy(); } /** * Ends a task from the Cms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The ID of the task to end. * * @exception CmsException Throws CmsException if something goes wrong. */ public void endTask(CmsUser currentUser, CmsProject currentProject, int taskid) throws CmsException { m_dbAccess.endTask(taskid); if(currentUser == null) { m_dbAccess.writeSystemTaskLog(taskid, "Task finished."); } else { m_dbAccess.writeSystemTaskLog(taskid, "Task finished by " + currentUser.getFirstname() + " " + currentUser.getLastname() + "."); } } /** * Exports cms-resources to zip. * * <B>Security:</B> * only Administrators can do this; * * @param currentUser user who requestd themethod * @param currentProject current project of the user * @param exportFile the name (absolute Path) of the export resource (zip) * @param exportPath the names (absolute Path) of folders and files which should be exported * @param cms the cms-object to use for the export. * * @exception Throws CmsException if something goes wrong. */ public void exportResources(CmsUser currentUser, CmsProject currentProject, String exportFile, String[] exportPaths, CmsObject cms) throws CmsException { if(isAdmin(currentUser, currentProject)) { new CmsExport(exportFile, exportPaths, cms); } else { throw new CmsException("[" + this.getClass().getName() + "] exportResources", CmsException.C_NO_ACCESS); } } /** * Exports cms-resources to zip. * * <B>Security:</B> * only Administrators can do this; * * @param currentUser user who requestd themethod * @param currentProject current project of the user * @param exportFile the name (absolute Path) of the export resource (zip) * @param exportPath the name (absolute Path) of folder from which should be exported * @param excludeSystem, decides whether to exclude the system * @param excludeUnchanged <code>true</code>, if unchanged files should be excluded. * @param cms the cms-object to use for the export. * * @exception Throws CmsException if something goes wrong. */ public void exportResources(CmsUser currentUser, CmsProject currentProject, String exportFile, String[] exportPaths, CmsObject cms, boolean excludeSystem, boolean excludeUnchanged) throws CmsException { if(isAdmin(currentUser, currentProject)) { new CmsExport(exportFile, exportPaths, cms, excludeSystem, excludeUnchanged); } else { throw new CmsException("[" + this.getClass().getName() + "] exportResources", CmsException.C_NO_ACCESS); } } /** * Exports cms-resources to zip. * * <B>Security:</B> * only Administrators can do this; * * @param currentUser user who requestd themethod * @param currentProject current project of the user * @param exportFile the name (absolute Path) of the export resource (zip) * @param exportPath the name (absolute Path) of folder from which should be exported * @param excludeSystem, decides whether to exclude the system * @param excludeUnchanged <code>true</code>, if unchanged files should be excluded. * @param cms the cms-object to use for the export. * * @exception Throws CmsException if something goes wrong. */ public void exportResources(CmsUser currentUser, CmsProject currentProject, String exportFile, String[] exportPaths, CmsObject cms, boolean excludeSystem, boolean excludeUnchanged, boolean exportUserdata) throws CmsException { if(isAdmin(currentUser, currentProject)) { new CmsExport(exportFile, exportPaths, cms, excludeSystem, excludeUnchanged, null, exportUserdata); } else { throw new CmsException("[" + this.getClass().getName() + "] exportResources", CmsException.C_NO_ACCESS); } } // now private stuff /** * This method is called, when a resource was changed. Currently it counts the * changes. */ protected void fileSystemChanged(boolean folderChanged) { // count only the changes - do nothing else! // in the future here will maybe a event-story be added m_fileSystemChanges++; if(folderChanged){ m_fileSystemFolderChanges++; } } /** * Forwards a task to a new user. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task to forward. * @param newRole The new Group for the task * @param newUser The new user who gets the task. if its "" the a new agent will automatic selected * * @exception CmsException Throws CmsException if something goes wrong. */ public void forwardTask(CmsUser currentUser, CmsProject currentProject, int taskid, String newRoleName, String newUserName) throws CmsException { CmsGroup newRole = m_dbAccess.readGroup(newRoleName); CmsUser newUser = null; if(newUserName.equals("")) { newUser = m_dbAccess.readUser(m_dbAccess.findAgent(newRole.getId())); } else { newUser = m_dbAccess.readUser(newUserName, C_USER_TYPE_SYSTEMUSER); } m_dbAccess.forwardTask(taskid, newRole.getId(), newUser.getId()); m_dbAccess.writeSystemTaskLog(taskid, "Task fowarded from " + currentUser.getFirstname() + " " + currentUser.getLastname() + " to " + newUser.getFirstname() + " " + newUser.getLastname() + "."); } /** * Returns all projects, which are owned by the user or which are accessible * for the group of the user. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * @return a Vector of projects. */ public Vector getAllAccessibleProjects(CmsUser currentUser, CmsProject currentProject) throws CmsException { // get all groups of the user Vector groups = getGroupsOfUser(currentUser, currentProject, currentUser.getName()); // get all projects which are owned by the user. Vector projects = m_dbAccess.getAllAccessibleProjectsByUser(currentUser); // get all projects, that the user can access with his groups. for(int i = 0; i < groups.size(); i++) { Vector projectsByGroup; // is this the admin-group? if( ((CmsGroup) groups.elementAt(i)).getName().equals(C_GROUP_ADMIN) ) { // yes - all unlocked projects are accessible for him projectsByGroup = m_dbAccess.getAllProjects(C_PROJECT_STATE_UNLOCKED); } else { // no - get all projects, which can be accessed by the current group projectsByGroup = m_dbAccess.getAllAccessibleProjectsByGroup((CmsGroup) groups.elementAt(i)); } // merge the projects to the vector for(int j = 0; j < projectsByGroup.size(); j++) { // add only projects, which are new if(!projects.contains(projectsByGroup.elementAt(j))) { projects.addElement(projectsByGroup.elementAt(j)); } } } // return the vector of projects return(projects); } /** * Returns all projects, which are owned by the user or which are manageable * for the group of the user. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * @return a Vector of projects. */ public Vector getAllManageableProjects(CmsUser currentUser, CmsProject currentProject) throws CmsException { // get all groups of the user Vector groups = getGroupsOfUser(currentUser, currentProject, currentUser.getName()); // get all projects which are owned by the user. Vector projects = m_dbAccess.getAllAccessibleProjectsByUser(currentUser); // get all projects, that the user can manage with his groups. for(int i = 0; i < groups.size(); i++) { // get all projects, which can be managed by the current group Vector projectsByGroup; // is this the admin-group? if( ((CmsGroup) groups.elementAt(i)).getName().equals(C_GROUP_ADMIN) ) { // yes - all unlocked projects are accessible for him projectsByGroup = m_dbAccess.getAllProjects(C_PROJECT_STATE_UNLOCKED); } else { // no - get all projects, which can be accessed by the current group projectsByGroup = m_dbAccess.getAllAccessibleProjectsByManagerGroup((CmsGroup)groups.elementAt(i)); } // merge the projects to the vector for(int j = 0; j < projectsByGroup.size(); j++) { // add only projects, which are new if(!projects.contains(projectsByGroup.elementAt(j))) { projects.addElement(projectsByGroup.elementAt(j)); } } } // remove the online-project, it is not manageable! projects.removeElement(onlineProject(currentUser, currentProject)); // return the vector of projects return(projects); } /** * Returns a Vector with all projects from history * * @return Vector with all projects from history. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getAllBackupProjects() throws CmsException{ Vector projects = new Vector(); projects = m_dbAccess.getAllBackupProjects(); return projects; } /** * Returns a Vector with all I_CmsResourceTypes. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * Returns a Hashtable with all I_CmsResourceTypes. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Hashtable getAllResourceTypes(CmsUser currentUser, CmsProject currentProject) throws CmsException { // check, if the resourceTypes were read bevore if(m_resourceTypes == null) { // get the resourceTypes from the registry m_resourceTypes = new Hashtable(); Vector resTypeNames = new Vector(); Vector launcherTypes = new Vector(); Vector launcherClass = new Vector(); Vector resourceClass = new Vector(); int resTypeCount = m_registry.getResourceTypes(resTypeNames, launcherTypes, launcherClass, resourceClass); for (int i = 0; i < resTypeCount; i++){ // add the resource-type try{ Class c = Class.forName((String)resourceClass.elementAt(i)); I_CmsResourceType resTypeClass = (I_CmsResourceType) c.newInstance(); resTypeClass.init(i, Integer.parseInt((String)launcherTypes.elementAt(i)), (String)resTypeNames.elementAt(i), (String)launcherClass.elementAt(i)); m_resourceTypes.put((String)resTypeNames.elementAt(i), resTypeClass); }catch(Exception e){ e.printStackTrace(); throw new CmsException("[" + this.getClass().getName() + "] Error while getting ResourceType: " + (String)resTypeNames.elementAt(i) + " from registry ", CmsException.C_UNKNOWN_EXCEPTION ); } } } // return the resource-types. return(m_resourceTypes); } /** * Returns informations about the cache<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @return A hashtable with informations about the cache. */ public Hashtable getCacheInfo() { Hashtable info = new Hashtable(); info.put("UserCache",""+m_userCache.size()); info.put("GroupCache",""+m_groupCache.size()); info.put("UserGroupCache",""+m_usergroupsCache.size()); info.put("ResourceCache",""+m_resourceCache.size()); info.put("SubResourceCache",""+m_subresCache.size()); info.put("ProjectCache",""+m_projectCache.size()); info.put("PropertyCache",""+m_propertyCache.size()); info.put("PropertyDefinitionCache",""+m_propertyDefCache.size()); info.put("PropertyDefinitionVectorCache",""+m_propertyDefVectorCache.size()); info.put("AccessCache",""+m_accessCache.size()); return info; } /** * Returns all child groups of a group<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param groupname The name of the group. * @return groups A Vector of all child groups or null. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getChild(CmsUser currentUser, CmsProject currentProject, String groupname) throws CmsException { // check security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { return m_dbAccess.getChild(groupname); } else { throw new CmsException("[" + this.getClass().getName() + "] " + groupname, CmsException.C_NO_ACCESS); } } /** * Returns all child groups of a group<P/> * This method also returns all sub-child groups of the current group. * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param groupname The name of the group. * @return groups A Vector of all child groups or null. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getChilds(CmsUser currentUser, CmsProject currentProject, String groupname) throws CmsException { // check security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { Vector childs=new Vector(); Vector allChilds=new Vector(); Vector subchilds=new Vector(); CmsGroup group=null; // get all child groups if the user group childs=m_dbAccess.getChild(groupname); if (childs!=null) { allChilds=childs; // now get all subchilds for each group Enumeration enu=childs.elements(); while (enu.hasMoreElements()) { group=(CmsGroup)enu.nextElement(); subchilds=getChilds(currentUser,currentProject,group.getName()); //add the subchilds to the already existing groups Enumeration enusub=subchilds.elements(); while (enusub.hasMoreElements()) { group=(CmsGroup)enusub.nextElement(); allChilds.addElement(group); } } } return allChilds; } else { throw new CmsException("[" + this.getClass().getName() + "] " + groupname, CmsException.C_NO_ACCESS); } } // Method to access the configuration /** * Method to access the configurations of the properties-file. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The Configurations of the properties-file. */ public Configurations getConfigurations(CmsUser currentUser, CmsProject currentProject) { return m_configuration; } /** * Returns the list of groups to which the user directly belongs to<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user. * @return Vector of groups * @exception CmsException Throws CmsException if operation was not succesful */ public Vector getDirectGroupsOfUser(CmsUser currentUser, CmsProject currentProject, String username) throws CmsException { return m_dbAccess.getGroupsOfUser(username); } /** * Returns a Vector with all files of a folder.<br> * * Files of a folder can be read from an offline Project and the online Project.<br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read this resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername the complete path to the folder. * * @return A Vector with all subfiles for the overgiven folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getFilesInFolder(CmsUser currentUser, CmsProject currentProject, String foldername) throws CmsException { return getFilesInFolder(currentUser, currentProject, foldername, false); } /** * Returns a Vector with all files of a folder.<br> * * Files of a folder can be read from an offline Project and the online Project.<br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read this resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername the complete path to the folder. * @param includeDeleted Include the folder if it is deleted * * @return A Vector with all subfiles for the overgiven folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getFilesInFolder(CmsUser currentUser, CmsProject currentProject, String foldername, boolean includeDeleted) throws CmsException { Vector files; // Todo: add caching for getFilesInFolder //files=(Vector)m_subresCache.get(C_FILE+currentProject.getId()+foldername); //if ((files==null) || (files.size()==0)) { // try to get the files in the current project try { files = helperGetFilesInFolder(currentUser, currentProject, foldername, includeDeleted); } catch (CmsException e) { //if access is denied to the folder, dont try to read them from the online project.) if (e.getType() == CmsException.C_ACCESS_DENIED) return new Vector(); //an empty vector. else //can't handle it here. throw e; } //} if (files == null) { //we are not allowed to read the folder (folder deleted) return new Vector(); } Vector onlineFiles = null; if (!currentProject.equals(onlineProject(currentUser, currentProject))) { // this is not the onlineproject, get the files // from the onlineproject, too try { onlineFiles = helperGetFilesInFolder(currentUser, onlineProject(currentUser, currentProject), foldername,includeDeleted); // merge the resources } catch (CmsException exc) { if (exc.getType() != CmsException.C_ACCESS_DENIED) //cant handle it. throw exc; else //access denied. return files; } } //m_subresCache.put(C_FILE+currentProject.getId()+foldername,files); if(onlineFiles == null) //if it was null, the folder was marked deleted -> no files in online project. return files; //m_subresCache.put(C_FILE+currentProject.getId()+foldername,files); return files = mergeResources(files, onlineFiles); } /** * Returns a Vector with all resource-names that have set the given property to the given value. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername the complete path to the folder. * @param propertydef, the name of the propertydefinition to check. * @param property, the value of the property for the resource. * * @return Vector with all names of resources. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getFilesWithProperty(CmsUser currentUser, CmsProject currentProject, String propertyDefinition, String propertyValue) throws CmsException { return m_dbAccess.getFilesWithProperty(currentProject.getId(), propertyDefinition, propertyValue); } /** * This method can be called, to determine if the file-system was changed * in the past. A module can compare its previosly stored number with this * returned number. If they differ, a change was made. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * @return the number of file-system-changes. */ public long getFileSystemChanges(CmsUser currentUser, CmsProject currentProject) { return m_fileSystemChanges; } /** * This method can be called, to determine if the file-system was changed * in the past. A module can compare its previosly stored number with this * returned number. If they differ, a change was made. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * @return the number of file-system-changes. */ public long getFileSystemFolderChanges(CmsUser currentUser, CmsProject currentProject) { return m_fileSystemFolderChanges; } /** * Returns a Vector with the complete folder-tree for this project.<br> * * Subfolders can be read from an offline project and the online project. <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read this resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param rootName The name of the root, e.g. /default/vfs * @return subfolders A Vector with the complete folder-tree for this project. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getFolderTree(CmsUser currentUser, CmsProject currentProject, String rootName) throws CmsException { Vector resources = m_dbAccess.getFolderTree(currentProject.getId(), rootName); Vector retValue = new Vector(resources.size()); String lastcheck = "#"; // just a char that is not valid in a filename //make sure that we have access to all these. for (Enumeration e = resources.elements(); e.hasMoreElements();) { CmsResource res = (CmsResource) e.nextElement(); if (!res.getAbsolutePath().startsWith(lastcheck)) { if (accessOther(currentUser, currentProject, res, C_ACCESS_PUBLIC_READ + C_ACCESS_PUBLIC_VISIBLE) || accessOwner(currentUser, currentProject, res, C_ACCESS_OWNER_READ + C_ACCESS_OWNER_VISIBLE) || accessGroup(currentUser, currentProject, res, C_ACCESS_GROUP_READ + C_ACCESS_GROUP_VISIBLE)) { retValue.addElement(res); } else { lastcheck = res.getAbsolutePath(); } } } return retValue; } /** * Returns all groups<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return users A Vector of all existing groups. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getGroups(CmsUser currentUser, CmsProject currentProject) throws CmsException { // check security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { return m_dbAccess.getGroups(); } else { throw new CmsException("[" + this.getClass().getName() + "] " + currentUser.getName(), CmsException.C_NO_ACCESS); } } /** * Returns a list of groups of a user.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user. * @return Vector of groups * @exception CmsException Throws CmsException if operation was not succesful */ public Vector getGroupsOfUser(CmsUser currentUser, CmsProject currentProject, String username) throws CmsException { Vector allGroups; allGroups=(Vector)m_usergroupsCache.get(C_USER+username); if ((allGroups==null) || (allGroups.size()==0)) { CmsGroup subGroup; CmsGroup group; // get all groups of the user Vector groups=m_dbAccess.getGroupsOfUser(username); allGroups=groups; // now get all childs of the groups Enumeration enu = groups.elements(); while (enu.hasMoreElements()) { group=(CmsGroup)enu.nextElement(); subGroup=getParent(currentUser, currentProject,group.getName()); while(subGroup != null) { // is the subGroup already in the vector? if(!allGroups.contains(subGroup)) { // no! add it allGroups.addElement(subGroup); } // read next sub group subGroup = getParent(currentUser, currentProject,subGroup.getName()); } } m_usergroupsCache.put(C_USER+username,allGroups); } return allGroups; } /** * Checks which Group can read the resource and all the parent folders. * * @param projectid the project to check the permission. * @param res The resource name to be checked. * @return The Group Id of the Group which can read the resource. * null for all Groups and * Admingroup for no Group. */ public String getReadingpermittedGroup(int projectId, String resource) throws CmsException { return m_dbAccess.getReadingpermittedGroup(projectId, resource); } /** * Returns the parent group of a group<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param groupname The name of the group. * @return group The parent group or null. * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsGroup getParent(CmsUser currentUser, CmsProject currentProject, String groupname) throws CmsException { CmsGroup group = readGroup(currentUser, currentProject, groupname); if (group.getParentId() == C_UNKNOWN_ID) { return null; } // try to read from cache CmsGroup parent = (CmsGroup) m_groupCache.get(group.getParentId()); if (parent == null) { parent = m_dbAccess.readGroup(group.getParentId()); m_groupCache.put(group.getParentId(), parent); } return parent; } /** * Returns the parent resource of a resouce. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsResource getParentResource(CmsUser currentUser, CmsProject currentProject, String resourcename) throws CmsException { // TODO: this can maybe done via the new parent id'd CmsResource theResource = readFileHeader(currentUser, currentProject, resourcename); String parentresourceName = theResource.getRootName()+theResource.getParent(); return readFileHeader(currentUser, currentProject, parentresourceName); } /** * Gets the Registry.<BR/> * * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param cms The actual CmsObject * @exception Throws CmsException if access is not allowed. */ public I_CmsRegistry getRegistry(CmsUser currentUser, CmsProject currentProject, CmsObject cms) throws CmsException { return m_registry.clone(cms); } /** * Returns a Vector with the subresources for a folder.<br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read and view this resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param folder The name of the folder to get the subresources from. * * @return subfolders A Vector with resources. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getResourcesInFolder(CmsUser currentUser, CmsProject currentProject, String folder) throws CmsException { CmsFolder offlineFolder = null; Vector resources = new Vector(); try { offlineFolder = readFolder(currentUser, currentProject, folder); if (offlineFolder.getState() == C_STATE_DELETED) { offlineFolder = null; } } catch (CmsException exc) { // ignore the exception - folder was not found in this project } if (offlineFolder == null) { // the folder is not existent throw new CmsException("[" + this.getClass().getName() + "] " + folder, CmsException.C_NOT_FOUND); } else resources = m_dbAccess.getResourcesInFolder(currentProject.getId(), offlineFolder); Vector retValue = new Vector(resources.size()); //make sure that we have access to all these. for (Enumeration e = resources.elements(); e.hasMoreElements();) { CmsResource res = (CmsResource) e.nextElement(); if (accessOther(currentUser, currentProject, res, C_ACCESS_PUBLIC_READ + C_ACCESS_PUBLIC_VISIBLE) || accessOwner(currentUser, currentProject, res, C_ACCESS_OWNER_READ + C_ACCESS_OWNER_VISIBLE) || accessGroup(currentUser, currentProject, res, C_ACCESS_GROUP_READ + C_ACCESS_GROUP_VISIBLE)) { retValue.addElement(res); } } return retValue; } /** * Returns a Vector with all resources of the given type that have set the given property to the given value. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param propertyDefinition, the name of the propertydefinition to check. * @param propertyValue, the value of the property for the resource. * @param resourceType The resource type of the resource * * @return Vector with all resources. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getResourcesWithProperty(CmsUser currentUser, CmsProject currentProject, String propertyDefinition, String propertyValue, int resourceType) throws CmsException { return m_dbAccess.getResourcesWithProperty(currentProject.getId(), propertyDefinition, propertyValue, resourceType); } /** * Returns a I_CmsResourceType. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resourceType the id of the resourceType to get. * * Returns a I_CmsResourceType. * * @exception CmsException Throws CmsException if operation was not succesful. */ public I_CmsResourceType getResourceType(CmsUser currentUser, CmsProject currentProject, int resourceType) throws CmsException { // try to get the resource-type Hashtable types = getAllResourceTypes(currentUser, currentProject); Enumeration keys = types.keys(); I_CmsResourceType currentType; while(keys.hasMoreElements()) { currentType = (I_CmsResourceType) types.get(keys.nextElement()); if(currentType.getResourceType() == resourceType) { return(currentType); } } // was not found - throw exception throw new CmsException("[" + this.getClass().getName() + "] " + resourceType, CmsException.C_NOT_FOUND); } /** * Returns a I_CmsResourceType. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resourceType the name of the resource to get. * * Returns a I_CmsResourceType. * * @exception CmsException Throws CmsException if operation was not succesful. */ public I_CmsResourceType getResourceType(CmsUser currentUser, CmsProject currentProject, String resourceType) throws CmsException { // try to get the resource-type try { I_CmsResourceType type = (I_CmsResourceType)getAllResourceTypes(currentUser, currentProject).get(resourceType); if(type == null) { throw new CmsException("[" + this.getClass().getName() + "] " + resourceType, CmsException.C_NOT_FOUND); } return type; } catch(NullPointerException exc) { // was not found - throw exception throw new CmsException("[" + this.getClass().getName() + "] " + resourceType, CmsException.C_NOT_FOUND); } } /** * Returns a Vector with all subfolders.<br> * * Subfolders can be read from an offline project and the online project. <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read this resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername the complete path to the folder. * * @return subfolders A Vector with all subfolders for the given folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getSubFolders(CmsUser currentUser, CmsProject currentProject, String foldername) throws CmsException { return getSubFolders(currentUser, currentProject, foldername, false); } /** * Returns a Vector with all subfolders.<br> * * Subfolders can be read from an offline project and the online project. <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read this resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername the complete path to the folder. * @param includeDeleted Include the folder if it is deleted * * @return subfolders A Vector with all subfolders for the given folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getSubFolders(CmsUser currentUser, CmsProject currentProject, String foldername, boolean includeDeleted) throws CmsException { Vector folders = new Vector(); // Todo: add caching for getSubFolders //folders=(Vector)m_subresCache.get(C_FOLDER+currentProject.getId()+foldername); if ((folders==null) || (folders.size()==0)){ folders=new Vector(); // try to get the folders in the current project try { folders = helperGetSubFolders(currentUser, currentProject, foldername); } catch (CmsException exc) { // no folders, ignoring them } if( !currentProject.equals(onlineProject(currentUser, currentProject))) { // this is not the onlineproject, get the files // from the onlineproject, too try { Vector onlineFolders = helperGetSubFolders(currentUser, onlineProject(currentUser, currentProject), foldername); // merge the resources folders = mergeResources(folders, onlineFolders); } catch(CmsException exc) { // no onlinefolders, ignoring them } } //m_subresCache.put(C_FOLDER+currentProject.getId()+foldername,folders); } // return the folders return(folders); } /** * Get a parameter value for a task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskId The Id of the task. * @param parName Name of the parameter. * * @exception CmsException Throws CmsException if something goes wrong. */ public String getTaskPar(CmsUser currentUser, CmsProject currentProject, int taskId, String parName) throws CmsException { return m_dbAccess.getTaskPar(taskId, parName); } /** * Get the template task id fo a given taskname. * * @param taskName Name of the Task * * @return id from the task template * * @exception CmsException Throws CmsException if something goes wrong. */ public int getTaskType(String taskName) throws CmsException { return m_dbAccess.getTaskType(taskName); } /** * Returns all users<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return users A Vector of all existing users. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getUsers(CmsUser currentUser, CmsProject currentProject) throws CmsException { // check security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { return m_dbAccess.getUsers(C_USER_TYPE_SYSTEMUSER); } else { throw new CmsException("[" + this.getClass().getName() + "] " + currentUser.getName(), CmsException.C_NO_ACCESS); } } /** * Returns all users from a given type<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param type The type of the users. * @return users A Vector of all existing users. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getUsers(CmsUser currentUser, CmsProject currentProject, int type) throws CmsException { // check security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { return m_dbAccess.getUsers(type); } else { throw new CmsException("[" + this.getClass().getName() + "] " + currentUser.getName(), CmsException.C_NO_ACCESS); } } /** * Returns all users from a given type that start with a specified string<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param type The type of the users. * @param namestart The filter for the username * @return users A Vector of all existing users. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getUsers(CmsUser currentUser, CmsProject currentProject, int type, String namestart) throws CmsException { // check security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { return m_dbAccess.getUsers(type,namestart); } else { throw new CmsException("[" + this.getClass().getName() + "] " + currentUser.getName(), CmsException.C_NO_ACCESS); } } /** * Returns a list of users in a group.<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param groupname The name of the group to list users from. * @return Vector of users. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getUsersOfGroup(CmsUser currentUser, CmsProject currentProject, String groupname) throws CmsException { // check the security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { return m_dbAccess.getUsersOfGroup(groupname, C_USER_TYPE_SYSTEMUSER); } else { throw new CmsException("[" + this.getClass().getName() + "] " + groupname, CmsException.C_NO_ACCESS); } } /** * Gets all users with a certain Lastname. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param Lastname the start of the users lastname * @param UserType webuser or systemuser * @param UserStatus enabled, disabled * @param wasLoggedIn was the user ever locked in? * @param nMax max number of results * * @return the users. * * @exception CmsException if operation was not successful. */ public Vector getUsersByLastname(CmsUser currentUser, CmsProject currentProject, String Lastname, int UserType, int UserStatus, int wasLoggedIn, int nMax) throws CmsException { // check security if( ! anonymousUser(currentUser, currentProject).equals( currentUser )){ return m_dbAccess.getUsersByLastname(Lastname, UserType, UserStatus, wasLoggedIn, nMax); } else { throw new CmsException( "[" + this.getClass().getName() + "] " + currentUser.getName(), CmsException.C_NO_ACCESS); } } /** * A helper method for this resource-broker. * Returns a Vector with all files of a folder. * The method does not read any files from the parrent folder, * and do also return deleted files. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername the complete path to the folder. * * @return subfiles A Vector with all subfiles for the overgiven folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ protected Vector helperGetFilesInFolder(CmsUser currentUser, CmsProject currentProject, String foldername, boolean includeDeleted) throws CmsException { // get the folder CmsFolder cmsFolder = null; try { cmsFolder = m_dbAccess.readFolder(currentProject.getId(), foldername); } catch(CmsException exc) { if(exc.getType() == exc.C_NOT_FOUND) { // ignore the exception - file dosen't exist in this project return new Vector(); //just an empty vector. } else { throw exc; } } if ((cmsFolder.getState() == I_CmsConstants.C_STATE_DELETED) && (!includeDeleted)) { //indicate that the folder was found, but deleted, and resources are not avaiable. return null; } Vector _files = m_dbAccess.getFilesInFolder(currentProject.getId(),cmsFolder); Vector files = new Vector(_files.size()); //make sure that we have access to all these. for (Enumeration e = _files.elements();e.hasMoreElements();) { CmsFile file = (CmsFile) e.nextElement(); if( accessOther(currentUser, currentProject, (CmsResource)file, C_ACCESS_PUBLIC_READ) || accessOwner(currentUser, currentProject, (CmsResource)file, C_ACCESS_OWNER_READ) || accessGroup(currentUser, currentProject, (CmsResource)file, C_ACCESS_GROUP_READ) ) { files.addElement(file); } } return files; } /** * A helper method for this resource-broker. * Returns a Hashtable with all subfolders.<br> * * Subfolders can be read from an offline project and the online project. <br> * * @param currentUser The user who requested this method. * @param currentProject The current project to read the folders from. * @param foldername the complete path to the folder. * * @return subfolders A Hashtable with all subfolders for the given folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ protected Vector helperGetSubFolders(CmsUser currentUser, CmsProject currentProject, String foldername) throws CmsException{ CmsFolder cmsFolder = m_dbAccess.readFolder(currentProject.getId(),foldername); if( accessRead(currentUser, currentProject, (CmsResource)cmsFolder) ) { // acces to all subfolders was granted - return the sub-folders. Vector folders = m_dbAccess.getSubFolders(currentProject.getId(),cmsFolder); CmsFolder folder; for(int z=0 ; z < folders.size() ; z++) { // read the current folder folder = (CmsFolder)folders.elementAt(z); // check the readability for the folder if( !( accessOther(currentUser, currentProject, (CmsResource)folder, C_ACCESS_PUBLIC_READ) || accessOwner(currentUser, currentProject, (CmsResource)folder, C_ACCESS_OWNER_READ) || accessGroup(currentUser, currentProject, (CmsResource)folder, C_ACCESS_GROUP_READ) ) ) { // access to the folder was not granted delete him folders.removeElementAt(z); // correct the index z--; } } return folders; } else { throw new CmsException("[" + this.getClass().getName() + "] " + foldername, CmsException.C_ACCESS_DENIED); } } /** * Imports a import-resource (folder or zipfile) to the cms. * * <B>Security:</B> * only Administrators can do this; * * @param currentUser user who requestd themethod * @param currentProject current project of the user * @param importFile the name (absolute Path) of the import resource (zip or folder) * @param importPath the name (absolute Path) of folder in which should be imported * @param cms the cms-object to use for the import. * * @exception Throws CmsException if something goes wrong. */ public void importFolder(CmsUser currentUser, CmsProject currentProject, String importFile, String importPath, CmsObject cms) throws CmsException { if(isAdmin(currentUser, currentProject)) { new CmsImportFolder(importFile, importPath, cms); } else { throw new CmsException("[" + this.getClass().getName() + "] importResources", CmsException.C_NO_ACCESS); } } // Methods working with database import and export /** * Imports a import-resource (folder or zipfile) to the cms. * * <B>Security:</B> * only Administrators can do this; * * @param currentUser user who requestd themethod * @param currentProject current project of the user * @param importFile the name (absolute Path) of the import resource (zip or folder) * @param importPath the name (absolute Path) of folder in which should be imported * @param cms the cms-object to use for the import. * * @exception Throws CmsException if something goes wrong. */ public void importResources(CmsUser currentUser, CmsProject currentProject, String importFile, String importPath, CmsObject cms) throws CmsException { if(isAdmin(currentUser, currentProject)) { CmsImport imp = new CmsImport(importFile, importPath, cms); imp.importResources(); } else { throw new CmsException("[" + this.getClass().getName() + "] importResources", CmsException.C_NO_ACCESS); } } // Internal ResourceBroker methods /** * Initializes the resource broker and sets up all required modules and connections. * @param config The OpenCms configuration. * @exception CmsException Throws CmsException if something goes wrong. */ public void init(Configurations config) throws CmsException { // Store the configuration. m_configuration = config; if (config.getString("history.enabled", "true").toLowerCase().equals("false")) { m_enableHistory = false; } // initialize the access-module. if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsResourceBroker] init the dbaccess-module."); } m_dbAccess = createDbAccess(config); // initalize the caches m_userCache=new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".user", 50)); m_groupCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".group", 50)); m_usergroupsCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".usergroups", 50)); m_projectCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".project", 50)); m_onlineProjectCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".onlineproject", 50)); //m_resourceCache=new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".resource", 1000)); m_resourceCache=new CmsResourceCache(config.getInteger(C_CONFIGURATION_CACHE + ".resource", 1000)); m_subresCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".subres", 100)); m_propertyCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".property", 1000)); m_propertyDefCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".propertydef", 100)); m_propertyDefVectorCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".propertyvectordef", 100)); m_accessCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".access", 1000)); m_cachelimit = config.getInteger(C_CONFIGURATION_CACHE + ".maxsize", 20000); m_refresh=config.getString(C_CONFIGURATION_CACHE + ".refresh", ""); // initialize the registry# if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsResourceBroker] init registry."); } try { m_registry= new CmsRegistry(CmsBase.getAbsolutePath(config.getString(C_CONFIGURATION_REGISTRY))); } catch (CmsException ex) { throw ex; } catch(Exception ex) { // init of registry failed - throw exception throw new CmsException("Init of registry failed", CmsException.C_REGISTRY_ERROR, ex); } } /** * Determines, if the users current group is the admin-group. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return true, if the users current group is the admin-group, * else it returns false. * @exception CmsException Throws CmsException if operation was not succesful. */ public boolean isAdmin(CmsUser currentUser, CmsProject currentProject) throws CmsException { return userInGroup(currentUser, currentProject,currentUser.getName(), C_GROUP_ADMIN); } /** * Determines, if the users may manage a project.<BR/> * Only the manager of a project may publish it. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return true, if the may manage this project. * @exception CmsException Throws CmsException if operation was not succesful. */ public boolean isManagerOfProject(CmsUser currentUser, CmsProject currentProject) throws CmsException { // is the user owner of the project? if( currentUser.getId() == currentProject.getOwnerId() ) { // YES return true; } if (isAdmin(currentUser, currentProject)){ return true; } // get all groups of the user Vector groups = getGroupsOfUser(currentUser, currentProject, currentUser.getName()); for(int i = 0; i < groups.size(); i++) { // is this a managergroup for this project? if( ((CmsGroup)groups.elementAt(i)).getId() == currentProject.getManagerGroupId() ) { // this group is manager of the project return true; } } // this user is not manager of this project return false; } /** * Determines, if the users current group is the projectleader-group.<BR/> * All projectleaders can create new projects, or close their own projects. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return true, if the users current group is the projectleader-group, * else it returns false. * @exception CmsException Throws CmsException if operation was not succesful. */ public boolean isProjectManager(CmsUser currentUser, CmsProject currentProject) throws CmsException { return userInGroup(currentUser, currentProject,currentUser.getName(), C_GROUP_PROJECTLEADER); } /** * Returns the user, who had locked the resource.<BR/> * * A user can lock a resource, so he is the only one who can write this * resource. This methods checks, if a resource was locked. * * @param user The user who wants to lock the file. * @param project The project in which the resource will be used. * @param resource The resource. * * @return the user, who had locked the resource. * * @exception CmsException will be thrown, if the user has not the rights * for this resource. */ public CmsUser lockedBy(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { return readUser(currentUser,currentProject,resource.isLockedBy() ) ; } /** * Returns the user, who had locked the resource.<BR/> * * A user can lock a resource, so he is the only one who can write this * resource. This methods checks, if a resource was locked. * * @param user The user who wants to lock the file. * @param project The project in which the resource will be used. * @param resource The complete path to the resource. * * @return the user, who had locked the resource. * * @exception CmsException will be thrown, if the user has not the rights * for this resource. */ public CmsUser lockedBy(CmsUser currentUser, CmsProject currentProject, String resource) throws CmsException { return readUser(currentUser,currentProject,readFileHeader(currentUser, currentProject, resource).isLockedBy() ) ; } /** * Locks a resource.<br> * * Only a resource in an offline project can be locked. The state of the resource * is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * A user can lock a resource, so he is the only one who can write this * resource. <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is not locked by another user</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The complete path to the resource to lock. * @param force If force is true, a existing locking will be oberwritten. * * @exception CmsException Throws CmsException if operation was not succesful. * It will also be thrown, if there is a existing lock * and force was set to false. */ public void lockResource(CmsUser currentUser, CmsProject currentProject, String resourcename, boolean force) throws CmsException { CmsResource cmsResource=null; // read the resource, that should be locked if (resourcename.endsWith("/")) { cmsResource = (CmsFolder)readFolder(currentUser,currentProject,resourcename); } else { cmsResource = (CmsFile)readFileHeader(currentUser,currentProject,resourcename); } // Can't lock what isn't there if (cmsResource == null) throw new CmsException(CmsException.C_NOT_FOUND); // check, if the resource is in the offline-project if(cmsResource.getProjectId() != currentProject.getId()) { // the resource is not in the current project and can't be locked - so ignore. return; } // check, if the user may lock the resource if( accessLock(currentUser, currentProject, cmsResource) ) { if(cmsResource.isLocked()) { // if the force switch is not set, throw an exception if (force==false) { throw new CmsException("["+this.getClass().getName()+"] "+resourcename,CmsException.C_LOCKED); } } // lock the resource cmsResource.setLocked(currentUser.getId()); cmsResource.setLockedInProject(currentProject.getId()); //update resource m_dbAccess.updateLockstate(cmsResource, currentProject.getId()); // update the cache if (resourcename.endsWith("/")) { m_resourceCache.remove(resourcename); } else { m_resourceCache.remove(resourcename); } m_subresCache.clear(); // if this resource is a folder -> lock all subresources, too if(cmsResource.isFolder()) { Vector files = getFilesInFolder(currentUser,currentProject, cmsResource.getResourceName()); Vector folders = getSubFolders(currentUser,currentProject, cmsResource.getResourceName()); CmsResource currentResource; // lock all files in this folder for(int i = 0; i < files.size(); i++ ) { currentResource = (CmsResource)files.elementAt(i); if (currentResource.getState() != C_STATE_DELETED) { lockResource(currentUser, currentProject, currentResource.getResourceName(), true); } } // lock all files in this folder for(int i = 0; i < folders.size(); i++) { currentResource = (CmsResource)folders.elementAt(i); if (currentResource.getState() != C_STATE_DELETED) { lockResource(currentUser, currentProject, currentResource.getResourceName(), true); } } } } else { throw new CmsException("[" + this.getClass().getName() + "] " + resourcename, CmsException.C_NO_ACCESS); } } // Methods working with user and groups /** * Logs a user into the Cms, if the password is correct. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user to be returned. * @param password The password of the user to be returned. * @return the logged in user. * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser loginUser(CmsUser currentUser, CmsProject currentProject, String username, String password) throws CmsException { // we must read the user from the dbAccess to avoid the cache CmsUser newUser = m_dbAccess.readUser(username, password, C_USER_TYPE_SYSTEMUSER); // is the user enabled? if( newUser.getFlags() == C_FLAG_ENABLED ) { // Yes - log him in! // first write the lastlogin-time. newUser.setLastlogin(new Date().getTime()); // write the user back to the cms. m_dbAccess.writeUser(newUser); // update cache m_userCache.put(newUser.getName()+newUser.getType(),newUser); return(newUser); } else { // No Access! throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS ); } } /** * Logs a web user into the Cms, if the password is correct. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user to be returned. * @param password The password of the user to be returned. * @return the logged in user. * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser loginWebUser(CmsUser currentUser, CmsProject currentProject, String username, String password) throws CmsException { // we must read the user from the dbAccess to avoid the cache CmsUser newUser = m_dbAccess.readUser(username, password, C_USER_TYPE_WEBUSER); // is the user enabled? if( newUser.getFlags() == C_FLAG_ENABLED ) { // Yes - log him in! // first write the lastlogin-time. newUser.setLastlogin(new Date().getTime()); // write the user back to the cms. m_dbAccess.writeUser(newUser); // update cache m_userCache.put(newUser.getName()+newUser.getType(),newUser); return(newUser); } else { // No Access! throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS ); } } /** * Merges two resource-vectors into one vector. * All offline-resources will be putted to the return-vector. All additional * online-resources will be putted to the return-vector, too. All online resources, * which are present in the offline-vector will be ignored. * * * @param offline The vector with the offline resources. * @param online The vector with the online resources. * @return The merged vector. */ protected Vector mergeResources(Vector offline, Vector online) { //dont do anything if any of the given vectors are empty or null. if ((offline == null) || (offline.size() == 0)) return (online!=null)?online:new Vector(); if ((online == null) || (online.size() == 0)) return (offline!=null)?offline:new Vector(); // create a vector for the merged offline //remove all objects in the online vector that are present in the offline vector. for (Enumeration e=offline.elements();e.hasMoreElements();) { CmsResource cr = (CmsResource) e.nextElement(); Resource r = new Resource(cr.getResourceName()); online.removeElement(r); } //merge the two vectors. If both vectors were sorted, the mereged vector will remain sorted. Vector merged = new Vector(offline.size() + online.size()); int offIndex = 0; int onIndex = 0; while ((offIndex < offline.size()) || (onIndex < online.size())) { if (offIndex >= offline.size()) { merged.addElement(online.elementAt(onIndex++)); continue; } if (onIndex >= online.size()) { merged.addElement(offline.elementAt(offIndex++)); continue; } String on = ((CmsResource)online.elementAt(onIndex)).getResourceName(); String off = ((CmsResource)offline.elementAt(offIndex)).getResourceName(); if (on.compareTo(off) < 0) merged.addElement(online.elementAt(onIndex++)); else merged.addElement(offline.elementAt(offIndex++)); } return(merged); } /** * Moves the file. * * This operation includes a copy and a delete operation. These operations * are done with their security-checks. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param source The complete path of the sourcefile. * @param destination The complete path of the destinationfile. * * @exception CmsException will be thrown, if the file couldn't be moved. * The CmsException will also be thrown, if the user has not the rights * for this resource. */ public void moveFile(CmsUser currentUser, CmsProject currentProject, String source, String destination) throws CmsException { // read the file to check access CmsResource file = readFileHeader(currentUser,currentProject, source); // has the user write-access? if (accessWrite(currentUser, currentProject, file)) { // first copy the file, this may ends with an exception copyFile(currentUser, currentProject, source, destination); // then delete the source-file, this may end with an exception // => the file was only copied, not moved! deleteFile(currentUser, currentProject, source); // inform about the file-system-change fileSystemChanged(file.isFolder()); } else { throw new CmsException("[" + this.getClass().getName() + "] " + source, CmsException.C_NO_ACCESS); } } /** * Returns the onlineproject. All anonymous * (CmsUser callingUser, or guest) users will see the resources of this project. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return the onlineproject object. * @exception CmsException Throws CmsException if something goes wrong. */ public CmsProject onlineProject(CmsUser currentUser, CmsProject currentProject) throws CmsException { CmsProject project = null; // try to get the online project for this offline project from cache project = (CmsProject) m_onlineProjectCache.get(currentProject.getId()); if (project == null) { // the project was not in the cache // lookup the currentProject in the CMS_SITE_PROJECT table, and in the same call return it. project = m_dbAccess.getOnlineProject(currentProject.getId()); // store the project into the cache m_onlineProjectCache.put(currentProject.getId(), project); } return project; } /** * Creates a static export of a Cmsresource in the filesystem * * @param currentUser user who requestd themethod * @param currentProject current project of the user * @param cms the cms-object to use for the export. * @param startpoints the startpoints for the export. * * @exception CmsException if operation was not successful. */ public void exportStaticResources(CmsUser currentUser, CmsProject currentProject, CmsObject cms, Vector startpoints) throws CmsException { if(isAdmin(currentUser, currentProject)) { new CmsStaticExport(cms, startpoints); } else { throw new CmsException("[" + this.getClass().getName() + "] exportResources", CmsException.C_NO_ACCESS); } } /** * Publishes a project. * * <B>Security</B> * Only the admin or the owner of the project can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id of the project to be published. * @return CmsPublishedResources The object includes the vectors of changed resources. * * @exception CmsException Throws CmsException if something goes wrong. */ public synchronized CmsPublishedResources publishProject(CmsObject cms, CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { CmsProject publishProject = readProject(currentUser, currentProject, id); CmsPublishedResources allChanged = new CmsPublishedResources(); Vector changedResources = new Vector(); Vector changedModuleMasters = new Vector(); // check the security if ((isAdmin(currentUser, currentProject) || isManagerOfProject(currentUser, publishProject)) && (publishProject.getFlags() == C_PROJECT_STATE_UNLOCKED) && (id != C_PROJECT_ONLINE_ID)) { // check, if we update class-files with this publishing ClassLoader loader = getClass().getClassLoader(); boolean shouldReload = false; // check if we are using our own classloader // e.g. the cms-shell uses the default classloader if(loader instanceof CmsClassLoader) { // yes we have our own classloader Vector classFiles = ((CmsClassLoader)loader).getFilenames(); shouldReload = shouldReloadClasses(id, classFiles); } try{ changedResources = m_dbAccess.publishProject(currentUser, id, onlineProject(currentUser, currentProject), m_enableHistory); // now publish the module masters Vector publishModules = new Vector(); cms.getRegistry().getModulePublishables(publishModules); int versionId = 0; long publishDate = System.currentTimeMillis(); if(m_enableHistory){ versionId = m_dbAccess.getBackupVersionId(); // get the version_id for the currently published version if(versionId > 1){ versionId--; } try{ publishDate = m_dbAccess.readBackupProject(versionId).getPublishingDate(); } catch (CmsException e){ // nothing to do } if(publishDate == 0){ publishDate = System.currentTimeMillis(); } } for(int i = 0; i < publishModules.size(); i++){ // call the publishProject method of the class with parameters: // cms, m_enableHistory, project_id, version_id, publishDate, subId, // the vector changedResources and the vector changedModuleMasters try{ // The changed masters are added to the vector changedModuleMasters, so after the last module // was published the vector contains the changed masters of all published modules Class.forName((String)publishModules.elementAt(i)).getMethod("publishProject", new Class[] {CmsObject.class, Boolean.class, Integer.class, Integer.class, Long.class, Vector.class, Vector.class}).invoke(null, new Object[] {cms, new Boolean(m_enableHistory), new Integer(id), new Integer(versionId), new Long(publishDate), changedResources, changedModuleMasters}); } catch(Exception ex){ ex.printStackTrace(); if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) { A_OpenCms.log(A_OpenCms.C_OPENCMS_INFO, "Error when publish data of module "+(String)publishModules.elementAt(i)+"!: "+ex.getMessage()); } } } } catch (CmsException e){ throw e; } finally { m_resourceCache.clear(); m_subresCache.clear(); // inform about the file-system-change fileSystemChanged(true); // the project was stored in the backuptables for history //new projectmechanism: the project can be still used after publishing // it will be deleted if the project_flag = C_PROJECT_STATE_TEMP if (publishProject.getType() == C_PROJECT_TYPE_TEMPORARY) { m_dbAccess.deleteProject(publishProject); try{ m_projectCache.remove(id); } catch (Exception e){ if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) { A_OpenCms.log(A_OpenCms.C_OPENCMS_CACHE,"Could not remove project "+id+" from cache"); } } //deleteProject(currentUser, currentProject, id); } // finally set the refrish signal to another server if nescessary if (m_refresh.length() > 0) { try { URL url = new URL(m_refresh); URLConnection con = url.openConnection(); con.connect(); InputStream in = con.getInputStream(); in.close(); //System.err.println(in.toString()); } catch (Exception ex) { throw new CmsException(0, ex); } } // inform about the reload classes if(loader instanceof CmsClassLoader) { ((CmsClassLoader)loader).setShouldReload(shouldReload); } } } else { throw new CmsException("[" + this.getClass().getName() + "] could not publish project " + id, CmsException.C_NO_ACCESS); } allChanged.setChangedResources(changedResources); allChanged.setChangedModuleMasters(changedModuleMasters); return allChanged; } /** * This method checks, if there is a classFile marked as changed or deleted. * If that is so, we have to reload all classes and instances to get rid of old versions. */ public boolean shouldReloadClasses(int projectId, Vector classFiles) { for(int i = 0; i < classFiles.size(); i++) { try { CmsFile file = m_dbAccess.readFileHeader(projectId, (String)classFiles.elementAt(i)); if( (file.getState() == C_STATE_CHANGED) || (file.getState() == C_STATE_DELETED) ) { // this class-file was changed or deleted - we have to reload return true; } } catch(CmsException exc) { // the file couldn't be read - it is not in our project - ignore this file } } // no modified class-files are found - we can use the old classes return false; } /** * Reads the agent of a task from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param task The task to read the agent from. * @return The owner of a task. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsUser readAgent(CmsUser currentUser, CmsProject currentProject, CmsTask task) throws CmsException { return readUser(currentUser,currentProject,task.getAgentUser()); } /** * Reads all file headers of a file in the OpenCms.<BR> * This method returns a vector with all file headers, i.e. * the file headers of a file, independent of the project they were attached to.<br> * * The reading excludes the filecontent. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The name of the file to be read. * * @return Vector of file headers read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector readAllFileHeaders(CmsUser currentUser, CmsProject currentProject, String filename) throws CmsException { CmsResource cmsFile = readFileHeader(currentUser,currentProject, filename); if( accessRead(currentUser, currentProject, cmsFile) ) { // access to all subfolders was granted - return the file-history. return(m_dbAccess.readAllFileHeaders(currentProject.getId(), filename)); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } /** * Reads all file headers of a file in the OpenCms.<BR> * This method returns a vector with the histroy of all file headers, i.e. * the file headers of a file, independent of the project they were attached to.<br> * * The reading excludes the filecontent. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The name of the file to be read. * * @return Vector of file headers read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector readAllFileHeadersForHist(CmsUser currentUser, CmsProject currentProject, String filename) throws CmsException { CmsResource cmsFile = readFileHeader(currentUser,currentProject, filename); if( accessRead(currentUser, currentProject, cmsFile) ) { // access to all subfolders was granted - return the file-history. return(m_dbAccess.readAllFileHeadersForHist(currentProject.getId(), filename)); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } /** * select all projectResources from an given project * * @param project The project in which the resource is used. * * * @exception CmsException Throws CmsException if operation was not succesful */ public Vector readAllProjectResources(int projectId) throws CmsException { return m_dbAccess.readAllProjectResources(projectId); } /** * Returns a list of all propertyinformations of a file or folder. * * <B>Security</B> * Only the user is granted, who has the right to view the resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource of which the propertyinformation has to be * read. * * @return Vector of propertyinformation as Strings. * * @exception CmsException Throws CmsException if operation was not succesful */ public Hashtable readAllProperties(CmsUser currentUser, CmsProject currentProject, String resource) throws CmsException { CmsResource res; // read the resource from the currentProject, or the online-project try { res = readFileHeader(currentUser,currentProject, resource); } catch(CmsException exc) { // the resource was not readable if(currentProject.equals(onlineProject(currentUser, currentProject))) { // this IS the onlineproject - throw the exception throw exc; } else { // try to read the resource in the onlineproject res = readFileHeader(currentUser,onlineProject(currentUser, currentProject), resource); } } // check the security if( ! accessRead(currentUser, currentProject, res) ) { throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_NO_ACCESS); } Hashtable returnValue = null; returnValue = (Hashtable)m_propertyCache.get(currentProject.getId()+"_"+Integer.toString(res.getResourceId()) +"_"+ Integer.toString(res.getType())); if (returnValue == null){ returnValue = m_dbAccess.readAllProperties(currentProject.getId(),res,res.getType()); m_propertyCache.put(currentProject.getId()+"_"+Integer.toString(res.getResourceId()) +"_"+ Integer.toString(res.getType()),returnValue); } return returnValue; } /** * Reads all propertydefinitions for the given resource type. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resourceType The resource type to read the propertydefinitions for. * * @return propertydefinitions A Vector with propertydefefinitions for the resource type. * The Vector is maybe empty. * * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readAllPropertydefinitions(CmsUser currentUser, CmsProject currentProject, int resourceType) throws CmsException { Vector returnValue = null; returnValue = (Vector) m_propertyDefVectorCache.get(Integer.toString(resourceType)); if (returnValue == null){ returnValue = m_dbAccess.readAllPropertydefinitions(resourceType); m_propertyDefVectorCache.put(Integer.toString(resourceType), returnValue); } return returnValue; } /** * Reads all propertydefinitions for the given resource type. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resourcetype The name of the resource type to read the propertydefinitions for. * * @return propertydefinitions A Vector with propertydefefinitions for the resource type. * The Vector is maybe empty. * * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readAllPropertydefinitions(CmsUser currentUser, CmsProject currentProject, String resourcetype) throws CmsException { Vector returnValue = null; I_CmsResourceType resType = getResourceType(currentUser, currentProject, resourcetype); returnValue = (Vector)m_propertyDefVectorCache.get(resType.getResourceTypeName()); if (returnValue == null){ returnValue = m_dbAccess.readAllPropertydefinitions(resType); m_propertyDefVectorCache.put(resType.getResourceTypeName(), returnValue); } return returnValue; } // Methods working with system properties /** * Reads the export-path for the system. * This path is used for db-export and db-import. * * <B>Security:</B> * All users are granted.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return the exportpath. */ public String readExportPath(CmsUser currentUser, CmsProject currentProject) throws CmsException { return (String) m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_EXPORTPATH); } /** * Reads a file from a previous project of the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the project to read the file from. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. * */ public CmsFile readFile(CmsUser currentUser, CmsProject currentProject, int projectId, String filename) throws CmsException { CmsFile cmsFile = null; // read the resource from the projectId, try { //cmsFile=(CmsFile)m_resourceCache.get(projectId+C_FILECONTENT+filename); if (cmsFile == null) { cmsFile = m_dbAccess.readFileInProject(projectId, onlineProject(currentUser, currentProject).getId(), filename); // only put it in thecache until the size is below the max site /*if (cmsFile.getContents().length <m_cachelimit) { m_resourceCache.put(projectId+C_FILECONTENT+filename,cmsFile); } else { }*/ } if (accessRead(currentUser, currentProject, (CmsResource) cmsFile)) { // acces to all subfolders was granted - return the file. return cmsFile; } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } catch (CmsException exc) { throw exc; } } /** * Reads a file from the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. * */ public CmsFile readFile(CmsUser currentUser, CmsProject currentProject, String filename) throws CmsException { CmsFile cmsFile = null; // read the resource from the currentProject, or the online-project try { //cmsFile=(CmsFile)m_resourceCache.get(currentProject.getId()+C_FILECONTENT+filename); if (cmsFile == null) { cmsFile = m_dbAccess.readFile(currentProject.getId(), onlineProject(currentUser, currentProject).getId(), filename); // only put it in thecache until the size is below the max site /*if (cmsFile.getContents().length <m_cachelimit) { m_resourceCache.put(currentProject.getId()+C_FILECONTENT+filename,cmsFile); } else { }*/ } } catch (CmsException exc) { // the resource was not readable throw exc; } if (accessRead(currentUser, currentProject, (CmsResource) cmsFile)) { // acces to all subfolders was granted - return the file. return cmsFile; } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } /** * Reads a file from the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. * */ public CmsFile readFile(CmsUser currentUser, CmsProject currentProject, String filename, boolean includeDeleted) throws CmsException { CmsFile cmsFile = null; // read the resource from the currentProject, or the online-project try { //cmsFile=(CmsFile)m_resourceCache.get(currentProject.getId()+C_FILECONTENT+filename); if (cmsFile == null) { cmsFile = m_dbAccess.readFile(currentProject.getId(), onlineProject(currentUser, currentProject).getId(), filename, includeDeleted); // only put it in thecache until the size is below the max site /*if (cmsFile.getContents().length <m_cachelimit) { m_resourceCache.put(currentProject.getId()+C_FILECONTENT+filename,cmsFile); } else { }*/ } } catch (CmsException exc) { // the resource was not readable throw exc; } if (accessRead(currentUser, currentProject, (CmsResource) cmsFile)) { // acces to all subfolders was granted - return the file. return cmsFile; } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } /** * Gets the known file extensions (=suffixes) * * <B>Security:</B> * All users are granted access<BR/> * * @param currentUser The user who requested this method, not used here * @param currentProject The current project of the user, not used here * * @return Hashtable with file extensions as Strings */ public Hashtable readFileExtensions(CmsUser currentUser, CmsProject currentProject) throws CmsException { Hashtable res=(Hashtable) m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS); return ( (res!=null)? res : new Hashtable()); } /** * Reads a file header a previous project of the Cms.<BR/> * The reading excludes the filecontent. <br> * * A file header can be read from an offline project or the online project. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the project to read the file from. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsResource readFileHeader(CmsUser currentUser, CmsProject currentProject, int projectId, String filename) throws CmsException { CmsResource cmsFile = null; // check if this method is misused to read a folder if (filename.endsWith("/")) { return (CmsResource) readFolder(currentUser, currentProject, projectId,filename); } // read the resource from the currentProject try { cmsFile=(CmsResource)m_resourceCache.get(filename, projectId); if (cmsFile==null) { cmsFile = m_dbAccess.readFileHeaderInProject(projectId, filename); m_resourceCache.put(filename,projectId,cmsFile); } if( accessRead(currentUser, currentProject, cmsFile) ) { // acces to all subfolders was granted - return the file-header. return cmsFile; } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } catch(CmsException exc) { throw exc; } } /** * Reads a file header from the Cms.<BR/> * The reading excludes the filecontent. <br> * * A file header can be read from an offline project or the online project. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsResource readFileHeader(CmsUser currentUser, CmsProject currentProject, String filename) throws CmsException { CmsResource cmsFile = null; // check if this method is misused to read a folder if (filename.endsWith("/")) { return (CmsResource) readFolder(currentUser,currentProject,filename); } // read the resource from the currentProject, or the online-project try { // try to read form cache first cmsFile=(CmsResource)m_resourceCache.get(filename, currentProject.getId()); if (cmsFile==null) { cmsFile = m_dbAccess.readFileHeader(currentProject.getId(), filename); m_resourceCache.put(filename,currentProject.getId(),cmsFile); } } catch(CmsException exc) { // the resource was not readable throw exc; } if( accessRead(currentUser, currentProject, cmsFile) ) { // acces to all subfolders was granted - return the file-header. return cmsFile; } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } /** * Reads a file header from the Cms.<BR/> * The reading excludes the filecontent. <br> * * A file header can be read from an offline project or the online project. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsResource readFileHeader(CmsUser currentUser, CmsProject currentProject, String filename, boolean includeDeleted) throws CmsException { CmsResource cmsFile = null; // check if this method is misused to read a folder if (filename.endsWith("/")) { return (CmsResource) readFolder(currentUser,currentProject,filename, includeDeleted); } // read the resource from the currentProject, or the online-project try { // try to read form cache first cmsFile=(CmsResource)m_resourceCache.get(filename,currentProject.getId()); if (cmsFile==null) { cmsFile = m_dbAccess.readFileHeader(currentProject.getId(), filename, includeDeleted); m_resourceCache.put(filename,currentProject.getId(),cmsFile); } } catch(CmsException exc) { // the resource was not readable throw exc; } if( accessRead(currentUser, currentProject, cmsFile) ) { // acces to all subfolders was granted - return the file-header. return cmsFile; } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } /** * Reads a file header from the history of the Cms.<BR/> * The reading excludes the filecontent. <br> * * A file header is read from the backup resources. * * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param versionId The id of the version of the file. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsBackupResource readFileHeaderForHist(CmsUser currentUser, CmsProject currentProject, int versionId, String filename) throws CmsException { CmsBackupResource resource; // read the resource from the backup resources try { resource = m_dbAccess.readFileHeaderForHist(versionId, filename); } catch(CmsException exc) { throw exc; } return resource; } /** * Reads a file from the history of the Cms.<BR/> * The reading includes the filecontent. <br> * * A file is read from the backup resources. * * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param versionId The id of the version of the file. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsBackupResource readFileForHist(CmsUser currentUser, CmsProject currentProject, int versionId, String filename) throws CmsException { CmsBackupResource resource; // read the resource from the backup resources try { resource = m_dbAccess.readFileForHist(versionId, filename); } catch(CmsException exc) { throw exc; } return resource; } /** * Reads all file headers for a project from the Cms.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the project to read the resources for. * * @return a Vector of resources. * * @exception CmsException will be thrown, if the file couldn't be read. * The CmsException will also be thrown, if the user has not the rights * for this resource. */ public Vector readFileHeaders(CmsUser currentUser, CmsProject currentProject, int projectId) throws CmsException { CmsProject project = readProject(currentUser, currentProject, projectId); Vector resources = m_dbAccess.readResources(project); Vector retValue = new Vector(); // check the security for(int i = 0; i < resources.size(); i++) { if( accessRead(currentUser, currentProject, (CmsResource) resources.elementAt(i)) ) { retValue.addElement(resources.elementAt(i)); } } return retValue; } /** * Reads a folder from the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param project the project to read the folder from. * @param foldername The complete path of the folder to be read. * * @return folder The read folder. * * @exception CmsException will be thrown, if the folder couldn't be read. * The CmsException will also be thrown, if the user has not the rights * for this resource */ protected CmsFolder readFolder(CmsUser currentUser, CmsProject currentProject, int project, String folder) throws CmsException { if (folder == null) return null; CmsFolder cmsFolder = (CmsFolder) m_resourceCache.get(folder,currentProject.getId()); if (cmsFolder == null) { cmsFolder = m_dbAccess.readFolderInProject(project, folder); if (cmsFolder != null){ m_resourceCache.put(folder, currentProject.getId(), (CmsFolder) cmsFolder); } } if (cmsFolder != null) { if (!accessRead(currentUser, currentProject, (CmsResource) cmsFolder)) throw new CmsException("[" + this.getClass().getName() + "] " + folder, CmsException.C_ACCESS_DENIED); } return cmsFolder; } /** * Reads a folder from the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername The complete path of the folder to be read. * * @return folder The read folder. * * @exception CmsException will be thrown, if the folder couldn't be read. * The CmsException will also be thrown, if the user has not the rights * for this resource. */ public CmsFolder readFolder(CmsUser currentUser, CmsProject currentProject, String folder) throws CmsException { return readFolder(currentUser, currentProject, folder, false); } /** * Reads a folder from the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername The complete path of the folder to be read. * @param includeDeleted Include the folder it it is marked as deleted * * @return folder The read folder. * * @exception CmsException will be thrown, if the folder couldn't be read. * The CmsException will also be thrown, if the user has not the rights * for this resource. */ public CmsFolder readFolder(CmsUser currentUser, CmsProject currentProject, String folder, boolean includeDeleted) throws CmsException { CmsFolder cmsFolder = null; // read the resource from the currentProject, or the online-project try { cmsFolder = (CmsFolder) m_resourceCache.get(folder, currentProject.getId()); if (cmsFolder == null) { cmsFolder = m_dbAccess.readFolder(currentProject.getId(), folder); if (cmsFolder.getState() != C_STATE_DELETED) { m_resourceCache.put(folder, currentProject.getId(), (CmsFolder) cmsFolder); } } } catch (CmsException exc) { throw exc; } if (accessRead(currentUser, currentProject, (CmsResource) cmsFolder)) { // acces to all subfolders was granted - return the folder. if ((cmsFolder.getState() == C_STATE_DELETED) && (!includeDeleted)) { throw new CmsException("[" + this.getClass().getName() + "]" + cmsFolder.getAbsolutePath(), CmsException.C_RESOURCE_DELETED); } else { return cmsFolder; } } else { throw new CmsException("[" + this.getClass().getName() + "] " + folder, CmsException.C_ACCESS_DENIED); } } /** * Reads a folder from the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param folder The complete path to the folder from which the folder will be * read. * @param foldername The name of the folder to be read. * * @return folder The read folder. * * @exception CmsException will be thrown, if the folder couldn't be read. * The CmsException will also be thrown, if the user has not the rights * for this resource. * * @see #readFolder(CmsUser, CmsProject, String) */ public CmsFolder readFolder(CmsUser currentUser, CmsProject currentProject, String folder, String folderName) throws CmsException { return readFolder(currentUser, currentProject, folder + folderName); } /** * Reads a folder from the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param folderid The id of the folder to be read. * @param includeDeleted Include the folder it it is marked as deleted * * @return folder The read folder. * * @exception CmsException will be thrown, if the folder couldn't be read. * The CmsException will also be thrown, if the user has not the rights * for this resource. */ public CmsFolder readFolder(CmsUser currentUser, CmsProject currentProject, int folderid, boolean includeDeleted) throws CmsException { CmsFolder cmsFolder = null; // read the resource from the currentProject, or the online-project try { if (cmsFolder == null) { cmsFolder = m_dbAccess.readFolder(currentProject.getId(), folderid); } } catch (CmsException exc) { throw exc; } if (accessRead(currentUser, currentProject, (CmsResource) cmsFolder)) { // acces to all subfolders was granted - return the folder. if ((cmsFolder.getState() == C_STATE_DELETED) && (!includeDeleted)) { throw new CmsException("[" + this.getClass().getName() + "]" + cmsFolder.getAbsolutePath(), CmsException.C_RESOURCE_DELETED); } else { return cmsFolder; } } else { throw new CmsException("[" + this.getClass().getName() + "] " + folderid, CmsException.C_ACCESS_DENIED); } } /** * Reads all given tasks from a user for a project. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the Project in which the tasks are defined. * @param owner Owner of the task. * @param tasktype Task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW. * @param orderBy Chooses, how to order the tasks. * * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readGivenTasks(CmsUser currentUser, CmsProject currentProject, int projectId, String ownerName, int taskType, String orderBy, String sort) throws CmsException { CmsProject project = null; CmsUser owner = null; if(ownerName != null) { owner = readUser(currentUser, currentProject, ownerName); } if(projectId != C_UNKNOWN_ID) { project = readProject(currentUser, currentProject, projectId); } return m_dbAccess.readTasks(project,null, owner, null, taskType, orderBy, sort); } /** * Reads the group of a project from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The group of a resource. * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsGroup readGroup(CmsUser currentUser, CmsProject currentProject, CmsProject project) throws CmsException { CmsGroup group=null; // try to read group form cache group=(CmsGroup)m_groupCache.get(project.getGroupId()); if (group== null) { try { group=m_dbAccess.readGroup(project.getGroupId()) ; } catch(CmsException exc) { if(exc.getType() == exc.C_NO_GROUP) { // the group does not exist any more - return a dummy-group return new CmsGroup(C_UNKNOWN_ID, C_UNKNOWN_ID, project.getGroupId() + "", "deleted group", 0); } } m_groupCache.put(project.getGroupId(),group); } return group; } /** * Reads the group of a resource from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The group of a resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsGroup readGroup(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { CmsGroup group=null; // try to read group form cache group=(CmsGroup)m_groupCache.get(resource.getGroupId()); if (group== null) { try { group=m_dbAccess.readGroup(resource.getGroupId()) ; } catch(CmsException exc) { if(exc.getType() == exc.C_NO_GROUP) { return new CmsGroup(C_UNKNOWN_ID, C_UNKNOWN_ID, resource.getGroupId() + "", "deleted group", 0); } } m_groupCache.put(resource.getGroupId(),group); } return group; } /** * Reads the group (role) of a task from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param task The task to read from. * @return The group of a resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsGroup readGroup(CmsUser currentUser, CmsProject currentProject, CmsTask task) throws CmsException { return m_dbAccess.readGroup(task.getRole()); } /** * Returns a group object.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param groupname The name of the group that is to be read. * @return Group. * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsGroup readGroup(CmsUser currentUser, CmsProject currentProject, String groupname) throws CmsException { CmsGroup group=null; // try to read group form cache group=(CmsGroup)m_groupCache.get(groupname); if (group== null) { group=m_dbAccess.readGroup(groupname) ; m_groupCache.put(groupname,group); } return group; } /** * Returns a group object.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param groupid The id of the group that is to be read. * @return Group. * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsGroup readGroup(CmsUser currentUser, CmsProject currentProject, int groupid) throws CmsException { return m_dbAccess.readGroup(groupid); } /** * Reads the managergroup of a project from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The group of a resource. * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsGroup readManagerGroup(CmsUser currentUser, CmsProject currentProject, CmsProject project) throws CmsException { CmsGroup group=null; // try to read group form cache group=(CmsGroup)m_groupCache.get(project.getManagerGroupId()); if (group== null) { try { group=m_dbAccess.readGroup(project.getManagerGroupId()) ; } catch(CmsException exc) { if(exc.getType() == exc.C_NO_GROUP) { // the group does not exist any more - return a dummy-group return new CmsGroup(C_UNKNOWN_ID, C_UNKNOWN_ID, project.getManagerGroupId() + "", "deleted group", 0); } } m_groupCache.put(project.getManagerGroupId(),group); } return group; } /** * Gets the MimeTypes. * The Mime-Types will be returned. * * <B>Security:</B> * All users are garnted<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * @return the mime-types. */ public Hashtable readMimeTypes(CmsUser currentUser, CmsProject currentProject) throws CmsException { // read the mimetype-properties as ressource from classloader and convert them // to hashtable Properties props = new Properties(); try { props.load(getClass().getClassLoader().getResourceAsStream("mimetypes.properties")); } catch(Exception exc) { if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[CmsResourceBroker] could not read mimetypes from properties. " + exc.getMessage()); } } return(Hashtable) props; } /** * Reads the original agent of a task from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param task The task to read the original agent from. * @return The owner of a task. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsUser readOriginalAgent(CmsUser currentUser, CmsProject currentProject, CmsTask task) throws CmsException { return readUser(currentUser,currentProject,task.getOriginalUser()); } /** * Reads the owner of a project from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The owner of a resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsUser readOwner(CmsUser currentUser, CmsProject currentProject, CmsProject project) throws CmsException { return readUser(currentUser,currentProject,project.getOwnerId()); } /** * Reads the owner of a resource from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The owner of a resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsUser readOwner(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { return readUser(currentUser,currentProject,resource.getOwnerId() ); } /** * Reads the owner (initiator) of a task from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param task The task to read the owner from. * @return The owner of a task. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsUser readOwner(CmsUser currentUser, CmsProject currentProject, CmsTask task) throws CmsException { return readUser(currentUser,currentProject,task.getInitiatorUser()); } /** * Reads the owner of a tasklog from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The owner of a resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsUser readOwner(CmsUser currentUser, CmsProject currentProject, CmsTaskLog log) throws CmsException { return readUser(currentUser,currentProject,log.getUser()); } /** * Reads a project from the Cms. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id of the project to read. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsProject readProject(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { CmsProject project=null; project=(CmsProject)m_projectCache.get(id); if (project==null) { project=m_dbAccess.readProject(id); m_projectCache.put(id,project); } return project; } /** * Reads a project from the Cms. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param res The resource to read the project of. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsProject readProject(CmsUser currentUser, CmsProject currentProject, CmsResource res) throws CmsException { return readProject(currentUser, currentProject, res.getProjectId()); } /** * Reads a project from the Cms. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param task The task to read the project of. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsProject readProject(CmsUser currentUser, CmsProject currentProject, CmsTask task) throws CmsException { // read the parent of the task, until it has no parents. task = this.readTask(currentUser, currentProject, task.getId()); while(task.getParent() != 0) { task = readTask(currentUser, currentProject, task.getParent()); } return m_dbAccess.readProject(task); } /** * Reads all file headers of a project from the Cms. * * @param projectId the id of the project to read the file headers for. * @param filter The filter for the resources (all, new, changed, deleted, locked) * * @return a Vector of resources. */ public Vector readProjectView(CmsUser currentUser, CmsProject currentProject, int projectId, String filter) throws CmsException { CmsProject project = readProject(currentUser, currentProject, projectId); Vector retValue = new Vector(); String whereClause = new String(); if("new".equalsIgnoreCase(filter)){ whereClause = " AND STATE="+C_STATE_NEW; } else if ("changed".equalsIgnoreCase(filter)){ whereClause = " AND STATE="+C_STATE_CHANGED; } else if ("deleted".equalsIgnoreCase(filter)){ whereClause = " AND STATE="+C_STATE_DELETED; } else if ("locked".equalsIgnoreCase(filter)){ whereClause = " AND LOCKED_BY != "+C_UNKNOWN_ID; } else { whereClause = " AND STATE != "+C_STATE_UNCHANGED; } Vector resources = m_dbAccess.readProjectView(currentProject.getId(), projectId, whereClause); // check the security for(int i = 0; i < resources.size(); i++) { if( accessRead(currentUser, project, (CmsResource) resources.elementAt(i)) ) { retValue.addElement(resources.elementAt(i)); } } return retValue; } /** * Reads the backupinformation of a project from the Cms. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param versionId The versionId of the project. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsBackupProject readBackupProject(CmsUser currentUser, CmsProject currentProject, int versionId) throws CmsException { return m_dbAccess.readBackupProject(versionId); } /** * Reads log entries for a project. * * @param projectId The id of the projec for tasklog to read. * @return A Vector of new TaskLog objects * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readProjectLogs(CmsUser currentUser, CmsProject currentProject, int projectid) throws CmsException { return m_dbAccess.readProjectLogs(projectid); } /** * Returns a propertyinformation of a file or folder. * * <B>Security</B> * Only the user is granted, who has the right to view the resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource of which the propertyinformation has * to be read. * @param property The propertydefinition-name of which the propertyinformation has to be read. * * @return propertyinfo The propertyinfo as string. * * @exception CmsException Throws CmsException if operation was not succesful */ public String readProperty(CmsUser currentUser, CmsProject currentProject, String resource, String property) throws CmsException { CmsResource res; // read the resource from the currentProject try { res = readFileHeader(currentUser,currentProject, resource, true); } catch(CmsException exc) { // the resource was not readable throw exc; } // check the security if( ! accessRead(currentUser, currentProject, res) ) { throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_NO_ACCESS); } String returnValue = null; returnValue = (String)m_propertyCache.get(currentProject.getId()+property + Integer.toString(res.getResourceId()) +","+ Integer.toString(res.getType())); if (returnValue == null){ returnValue = m_dbAccess.readProperty(property,currentProject.getId(),res,res.getType()); if (returnValue == null) { returnValue=""; } m_propertyCache.put(currentProject.getId()+property +Integer.toString(res.getResourceId()) + ","+ Integer.toString(res.getType()), returnValue); } if (returnValue.equals("")){returnValue=null;} return returnValue; } /** * Reads a definition for the given resource type. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name of the propertydefinition to read. * @param resourcetype The name of the resource type for which the propertydefinition * is valid. * * @return propertydefinition The propertydefinition that corresponds to the overgiven * arguments - or null if there is no valid propertydefinition. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsPropertydefinition readPropertydefinition(CmsUser currentUser, CmsProject currentProject, String name, String resourcetype) throws CmsException { I_CmsResourceType resType = getResourceType(currentUser,currentProject,resourcetype); CmsPropertydefinition returnValue = null; returnValue = (CmsPropertydefinition)m_propertyDefCache.get(name + resType.getResourceType()); if (returnValue == null){ returnValue = m_dbAccess.readPropertydefinition(name, resType); m_propertyDefCache.put(name + resType.getResourceType(), returnValue); } return returnValue; } /** * Insert the method's description here. * Creation date: (09-10-2000 09:29:45) * @return java.util.Vector * @param project com.opencms.file.CmsProject * @exception com.opencms.core.CmsException The exception description. */ public Vector readResources(CmsProject project) throws com.opencms.core.CmsException { return m_dbAccess.readResources(project); } /** * Read a task by id. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id for the task to read. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsTask readTask(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { return m_dbAccess.readTask(id); } /** * Reads log entries for a task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The task for the tasklog to read . * @return A Vector of new TaskLog objects * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readTaskLogs(CmsUser currentUser, CmsProject currentProject, int taskid) throws CmsException { return m_dbAccess.readTaskLogs(taskid);; } /** * Reads all tasks for a project. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the Project in which the tasks are defined. Can be null for all tasks * @tasktype Task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW * @param orderBy Chooses, how to order the tasks. * @param sort Sort order C_SORT_ASC, C_SORT_DESC, or null * * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readTasksForProject(CmsUser currentUser, CmsProject currentProject, int projectId, int tasktype, String orderBy, String sort) throws CmsException { CmsProject project = null; if(projectId != C_UNKNOWN_ID) { project = readProject(currentUser, currentProject, projectId); } return m_dbAccess.readTasks(project, null, null, null, tasktype, orderBy, sort); } /** * Reads all tasks for a role in a project. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the Project in which the tasks are defined. * @param user The user who has to process the task. * @param tasktype Task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW. * @param orderBy Chooses, how to order the tasks. * @param sort Sort order C_SORT_ASC, C_SORT_DESC, or null * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readTasksForRole(CmsUser currentUser, CmsProject currentProject, int projectId, String roleName, int tasktype, String orderBy, String sort) throws CmsException { CmsProject project = null; CmsGroup role = null; if(roleName != null) { role = readGroup(currentUser, currentProject, roleName); } if(projectId != C_UNKNOWN_ID) { project = readProject(currentUser, currentProject, projectId); } return m_dbAccess.readTasks(project, null, null, role, tasktype, orderBy, sort); } /** * Reads all tasks for a user in a project. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the Project in which the tasks are defined. * @param userName The user who has to process the task. * @param taskType Task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW. * @param orderBy Chooses, how to order the tasks. * @param sort Sort order C_SORT_ASC, C_SORT_DESC, or null * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readTasksForUser(CmsUser currentUser, CmsProject currentProject, int projectId, String userName, int taskType, String orderBy, String sort) throws CmsException { CmsUser user = m_dbAccess.readUser(userName, C_USER_TYPE_SYSTEMUSER); return m_dbAccess.readTasks(currentProject, user, null, null, taskType, orderBy, sort); } /** * Returns a user object.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id of the user that is to be read. * @return User * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser readUser(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { try { CmsUser user=null; // try to read the user from cache user=(CmsUser)m_userCache.get(id); if (user==null) { user=m_dbAccess.readUser(id); m_userCache.put(id,user); } return user; } catch (CmsException ex) { return new CmsUser(C_UNKNOWN_ID, id + "", "deleted user"); } } /** * Returns a user object.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user that is to be read. * @return User * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser readUser(CmsUser currentUser, CmsProject currentProject, String username) throws CmsException { CmsUser user = null; // try to read the user from cache user = (CmsUser)m_userCache.get(username+C_USER_TYPE_SYSTEMUSER); if (user == null) { user = m_dbAccess.readUser(username, C_USER_TYPE_SYSTEMUSER); m_userCache.put(username+C_USER_TYPE_SYSTEMUSER,user); } return user; } /** * Returns a user object.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user that is to be read. * @param type The type of the user. * @return User * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser readUser(CmsUser currentUser, CmsProject currentProject, String username,int type) throws CmsException { CmsUser user = null; // try to read the user from cache user = (CmsUser)m_userCache.get(username+type); if (user == null) { user = m_dbAccess.readUser(username, type); m_userCache.put(username+type,user); } return user; } /** * Returns a user object if the password for the user is correct.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The username of the user that is to be read. * @param password The password of the user that is to be read. * @return User * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser readUser(CmsUser currentUser, CmsProject currentProject, String username, String password) throws CmsException { CmsUser user = null; // ednfal: don't read user from cache because password may be changed //user = (CmsUser)m_userCache.get(username+C_USER_TYPE_SYSTEMUSER); // store user in cache if (user == null) { user = m_dbAccess.readUser(username, password, C_USER_TYPE_SYSTEMUSER); m_userCache.put(username+C_USER_TYPE_SYSTEMUSER, user); } return user; } /** * Returns a user object if the password for the user is correct.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The username of the user that is to be read. * @return User * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser readWebUser(CmsUser currentUser, CmsProject currentProject, String username) throws CmsException { CmsUser user = null; user = (CmsUser)m_userCache.get(username+C_USER_TYPE_WEBUSER); // store user in cache if (user == null) { user = m_dbAccess.readUser(username, C_USER_TYPE_WEBUSER); m_userCache.put(username+C_USER_TYPE_WEBUSER, user); } return user; } /** * Returns a user object if the password for the user is correct.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The username of the user that is to be read. * @param password The password of the user that is to be read. * @return User * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser readWebUser(CmsUser currentUser, CmsProject currentProject, String username, String password) throws CmsException { CmsUser user = null; // ednfal: don't read user from cache because password may be changed user = (CmsUser)m_userCache.get(username+C_USER_TYPE_WEBUSER); // store user in cache if (user == null) { user = m_dbAccess.readUser(username, password, C_USER_TYPE_WEBUSER); m_userCache.put(username+C_USER_TYPE_WEBUSER,user); } return user; } /** * Reaktivates a task from the Cms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task to accept. * * @exception CmsException Throws CmsException if something goes wrong. */ public void reaktivateTask(CmsUser currentUser, CmsProject currentProject, int taskId) throws CmsException { CmsTask task = m_dbAccess.readTask(taskId); task.setState(C_TASK_STATE_STARTED); task.setPercentage(0); task = m_dbAccess.writeTask(task); m_dbAccess.writeSystemTaskLog(taskId, "Task was reactivated from " + currentUser.getFirstname() + " " + currentUser.getLastname() + "."); } /** * Sets a new password only if the user knows his recovery-password. * * All users can do this if he knows the recovery-password.<P/> * * <B>Security:</B> * All users can do this if he knows the recovery-password.<P/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user. * @param recoveryPassword The recovery password. * @param newPassword The new password. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void recoverPassword(CmsUser currentUser, CmsProject currentProject, String username, String recoveryPassword, String newPassword) throws CmsException { // check the length of the new password. if(newPassword.length() < C_PASSWORD_MINIMUMSIZE) { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_SHORT_PASSWORD); } // check the length of the recovery password. if(recoveryPassword.length() < C_PASSWORD_MINIMUMSIZE) { throw new CmsException("[" + this.getClass().getName() + "] no recovery password."); } m_dbAccess.recoverPassword(username, recoveryPassword, newPassword); } /** * Removes a user from a group. * * Only the admin can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user that is to be removed from the group. * @param groupname The name of the group. * @exception CmsException Throws CmsException if operation was not succesful. */ public void removeUserFromGroup(CmsUser currentUser, CmsProject currentProject, String username, String groupname) throws CmsException { // test if this user is existing in the group if (!userInGroup(currentUser,currentProject,username,groupname)) { // user already there, throw exception throw new CmsException("[" + this.getClass().getName() + "] remove " + username+ " from " +groupname, CmsException.C_NO_USER); } if( isAdmin(currentUser, currentProject) ) { CmsUser user; CmsGroup group; user=readUser(currentUser,currentProject,username); //check if the user exists if (user != null) { group=readGroup(currentUser,currentProject,groupname); //check if group exists if (group != null){ // do not remmove the user from its default group if (user.getDefaultGroupId() != group.getId()) { //remove this user from the group m_dbAccess.removeUserFromGroup(user.getId(),group.getId()); m_usergroupsCache.clear(); } else { throw new CmsException("["+this.getClass().getName()+"]",CmsException.C_NO_DEFAULT_GROUP); } } else { throw new CmsException("["+this.getClass().getName()+"]"+groupname,CmsException.C_NO_GROUP); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS); } } } /** * Renames the file to a new name. <br> * * Rename can only be done in an offline project. To rename a file, the following * steps have to be done: * <ul> * <li> Copy the file with the oldname to a file with the new name, the state * of the new file is set to NEW (2). * <ul> * <li> If the state of the original file is UNCHANGED (0), the file content of the * file is read from the online project. </li> * <li> If the state of the original file is CHANGED (1) or NEW (2) the file content * of the file is read from the offline project. </li> * </ul> * </li> * <li> Set the state of the old file to DELETED (3). </li> * </ul> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param oldname The complete path to the resource which will be renamed. * @param newname The new name of the resource (CmsUser callingUser, No path information allowed). * * @exception CmsException Throws CmsException if operation was not succesful. */ public void renameFile(CmsUser currentUser, CmsProject currentProject, String oldname, String newname) throws CmsException { // read the old file CmsResource file = readFileHeader(currentUser, currentProject, oldname); // checks, if the newname is valid, if not it throws a exception validFilename(newname); // has the user write-access? if (accessWrite(currentUser, currentProject, file)) { String path = oldname.substring(0, oldname.lastIndexOf("/") + 1); copyFile(currentUser, currentProject, oldname, path + newname); deleteFile(currentUser, currentProject, oldname); } else { throw new CmsException("[" + this.getClass().getName() + "] " + oldname, CmsException.C_NO_ACCESS); } } /** * This method loads old sessiondata from the database. It is used * for sessionfailover. * * @param oldSessionId the id of the old session. * @return the old sessiondata. */ public Hashtable restoreSession(String oldSessionId) throws CmsException { return m_dbAccess.readSession(oldSessionId); } /** * Restores a file in the current project with a version in the backup * * @param currentUser The current user * @param currentProject The current project * @param versionId The version id of the resource * @param filename The name of the file to restore * * @exception CmsException Throws CmsException if operation was not succesful. */ public void restoreResource(CmsUser currentUser, CmsProject currentProject, int versionId, String filename) throws CmsException { CmsBackupResource backupFile = null; CmsFile offlineFile = null; int state = C_STATE_CHANGED; // read the backup file backupFile = readFileForHist(currentUser, currentProject, versionId, filename); // try to read the owner and the group int ownerId = currentUser.getId(); int groupId = currentUser.getDefaultGroupId(); try{ ownerId = readUser(currentUser, currentProject, backupFile.getOwnerName()).getId(); } catch(CmsException exc){ // user can not be read, set the userid of current user } try{ groupId = readGroup(currentUser, currentProject, backupFile.getGroupName()).getId(); } catch(CmsException exc){ // group can not be read, set the groupid of current user } offlineFile = readFile(currentUser, currentProject, filename); if(offlineFile.getState() == C_STATE_NEW){ state = C_STATE_NEW; } if (backupFile != null && offlineFile != null){ CmsFile newFile = new CmsFile(offlineFile.getResourceId(), offlineFile.getParentId(), offlineFile.getFileId(), offlineFile.getResourceName(), backupFile.getType(), backupFile.getFlags(), ownerId, groupId, currentProject.getId(), backupFile.getAccessFlags(), state, offlineFile.isLockedBy(), backupFile.getLauncherType(), backupFile.getLauncherClassname(), offlineFile.getDateCreated(), offlineFile.getDateLastModified(), currentUser.getId(), backupFile.getContents(), backupFile.getLength(), currentProject.getId()); writeFile(currentUser, currentProject, newFile); } } /** * Set a new name for a task * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task to set the percentage. * @param name The new name value * * @exception CmsException Throws CmsException if something goes wrong. */ public void setName(CmsUser currentUser, CmsProject currentProject, int taskId, String name) throws CmsException { if( (name == null) || name.length() == 0) { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME); } CmsTask task = m_dbAccess.readTask(taskId); task.setName(name); task = m_dbAccess.writeTask(task); m_dbAccess.writeSystemTaskLog(taskId, "Name was set to " + name + "% from " + currentUser.getFirstname() + " " + currentUser.getLastname() + "."); } /** * Sets a new parent-group for an already existing group in the Cms.<BR/> * * Only the admin can do this.<P/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param groupName The name of the group that should be written to the Cms. * @param parentGroupName The name of the parentGroup to set, or null if the parent * group should be deleted. * @exception CmsException Throws CmsException if operation was not succesfull. */ public void setParentGroup(CmsUser currentUser, CmsProject currentProject, String groupName, String parentGroupName) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) ) { CmsGroup group = readGroup(currentUser, currentProject, groupName); int parentGroupId = C_UNKNOWN_ID; // if the group exists, use its id, else set to unknown. if( parentGroupName != null ) { parentGroupId = readGroup(currentUser, currentProject, parentGroupName).getId(); } group.setParentId(parentGroupId); // write the changes to the cms writeGroup(currentUser,currentProject,group); } else { throw new CmsException("[" + this.getClass().getName() + "] " + groupName, CmsException.C_NO_ACCESS); } } /** * Sets the password for a user. * * Only a adminstrator can do this.<P/> * * <B>Security:</B> * Users, which are in the group "administrators" are granted.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user. * @param newPassword The new password. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void setPassword(CmsUser currentUser, CmsProject currentProject, String username, String newPassword) throws CmsException { // check the length of the new password. if(newPassword.length() < C_PASSWORD_MINIMUMSIZE) { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_SHORT_PASSWORD); } if( isAdmin(currentUser, currentProject) ) { m_dbAccess.setPassword(username, newPassword); } else { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS); } } /** * Sets the password for a user. * * Every user who knows the username and the password can do this.<P/> * * <B>Security:</B> * Users, who knows the username and the old password are granted.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user. * @param oldPassword The new password. * @param newPassword The new password. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void setPassword(CmsUser currentUser, CmsProject currentProject, String username, String oldPassword, String newPassword) throws CmsException { // check the length of the new password. if(newPassword.length() < C_PASSWORD_MINIMUMSIZE) { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_SHORT_PASSWORD); } // read the user CmsUser user; try { user = m_dbAccess.readUser(username, oldPassword, C_USER_TYPE_SYSTEMUSER); } catch(CmsException exc) { // this is no system-user - maybe a webuser? try{ user = m_dbAccess.readUser(username, oldPassword, C_USER_TYPE_WEBUSER); } catch(CmsException e) { throw exc; } } //if( !anonymousUser(currentUser, currentProject).equals( currentUser )) { m_dbAccess.setPassword(username, newPassword); //} else { // throw new CmsException("[" + this.getClass().getName() + "] " + username, // CmsException.C_NO_ACCESS); //} } /** * Set priority of a task * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task to set the percentage. * @param new priority value * * @exception CmsException Throws CmsException if something goes wrong. */ public void setPriority(CmsUser currentUser, CmsProject currentProject, int taskId, int priority) throws CmsException { CmsTask task = m_dbAccess.readTask(taskId); task.setPriority(priority); task = m_dbAccess.writeTask(task); m_dbAccess.writeSystemTaskLog(taskId, "Priority was set to " + priority + " from " + currentUser.getFirstname() + " " + currentUser.getLastname() + "."); } /** * Sets the recovery password for a user. * * Only a adminstrator or the curretuser can do this.<P/> * * <B>Security:</B> * Users, which are in the group "administrators" are granted.<BR/> * Current users can change their own password. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user. * @param password The password of the user. * @param newPassword The new recoveryPassword to be set. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void setRecoveryPassword(CmsUser currentUser, CmsProject currentProject, String username, String password, String newPassword) throws CmsException { // check the length of the new password. if(newPassword.length() < C_PASSWORD_MINIMUMSIZE) { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_SHORT_PASSWORD); } // read the user CmsUser user; try { user = readUser(currentUser, currentProject, username, password); } catch(CmsException exc) { // this is no system-user - maybe a webuser? user = readWebUser(currentUser, currentProject, username, password); } //if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) && // ( isAdmin(user, currentProject) || user.equals(currentUser)) ) { m_dbAccess.setRecoveryPassword(username, newPassword); //} else { // throw new CmsException("[" + this.getClass().getName() + "] " + username, // CmsException.C_NO_ACCESS); //} } /** * Set a Parameter for a task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskId The Id of the task. * @param parName Name of the parameter. * @param parValue Value if the parameter. * * @return The id of the inserted parameter or 0 if the parameter already exists for this task. * * @exception CmsException Throws CmsException if something goes wrong. */ public void setTaskPar(CmsUser currentUser, CmsProject currentProject, int taskId, String parName, String parValue) throws CmsException { m_dbAccess.setTaskPar(taskId, parName, parValue); } /** * Set timeout of a task * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task to set the percentage. * @param new timeout value * * @exception CmsException Throws CmsException if something goes wrong. */ public void setTimeout(CmsUser currentUser, CmsProject currentProject, int taskId, long timeout) throws CmsException { CmsTask task = m_dbAccess.readTask(taskId); java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout); task.setTimeOut(timestamp); task = m_dbAccess.writeTask(task); m_dbAccess.writeSystemTaskLog(taskId, "Timeout was set to " + timeout + " from " + currentUser.getFirstname() + " " + currentUser.getLastname() + "."); } /** * This method stores sessiondata into the database. It is used * for sessionfailover. * * @param sessionId the id of the session. * @param isNew determines, if the session is new or not. * @return data the sessionData. */ public void storeSession(String sessionId, Hashtable sessionData) throws CmsException { // update the session int rowCount = m_dbAccess.updateSession(sessionId, sessionData); if(rowCount != 1) { // the entry dosn't exists - create it m_dbAccess.createSession(sessionId, sessionData); } } /** * Undo all changes in the resource, restore the online file. * * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resourceName The name of the resource to be restored. * * @exception CmsException Throws CmsException if something goes wrong. */ public void undoChanges(CmsUser currentUser, CmsProject currentProject, String resourceName) throws CmsException { CmsProject onlineProject = readProject(currentUser, currentProject, C_PROJECT_ONLINE_ID); // change folder or file? if (resourceName.endsWith("/")){ // read the resource from the online project CmsFolder onlineFolder = readFolder(currentUser, onlineProject, resourceName); // read the resource from the offline project and change the data CmsFolder offlineFolder = readFolder(currentUser, currentProject, resourceName); CmsFolder restoredFolder = new CmsFolder(offlineFolder.getResourceId(), offlineFolder.getParentId(), offlineFolder.getFileId(), offlineFolder.getResourceName(), onlineFolder.getType(), onlineFolder.getFlags(), onlineFolder.getOwnerId(), onlineFolder.getGroupId(), currentProject.getId(), onlineFolder.getAccessFlags(), C_STATE_UNCHANGED, offlineFolder.isLockedBy(), offlineFolder.getDateCreated(), offlineFolder.getDateLastModified(), currentUser.getId(), currentProject.getId()); // write the file in the offline project // has the user write-access? if( accessWrite(currentUser, currentProject, (CmsResource)restoredFolder) ) { // write-access was granted - write the folder without setting state = changed m_dbAccess.writeFolder(currentProject, restoredFolder, false, currentUser.getId()); // restore the properties in the offline project m_dbAccess.deleteAllProperties(currentProject.getId(),restoredFolder); Hashtable propertyInfos = m_dbAccess.readAllProperties(onlineProject.getId(),onlineFolder,onlineFolder.getType()); m_dbAccess.writeProperties(propertyInfos,currentProject.getId(),restoredFolder,restoredFolder.getType()); m_propertyCache.clear(); // update the cache m_resourceCache.remove(restoredFolder.getResourceName()); m_subresCache.clear(); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + restoredFolder.getAbsolutePath(), CmsException.C_NO_ACCESS); } } else { // read the file from the online project CmsFile onlineFile = readFile(currentUser, onlineProject, resourceName); // read the file from the offline project and change the data CmsFile offlineFile = readFile(currentUser, currentProject, resourceName); CmsFile restoredFile = new CmsFile(offlineFile.getResourceId(), offlineFile.getParentId(), offlineFile.getFileId(), offlineFile.getResourceName(), onlineFile.getType(), onlineFile.getFlags(), onlineFile.getOwnerId(), onlineFile.getGroupId(), currentProject.getId(), onlineFile.getAccessFlags(), C_STATE_UNCHANGED, offlineFile.isLockedBy(), onlineFile.getLauncherType(), onlineFile.getLauncherClassname(), offlineFile.getDateCreated(), offlineFile.getDateLastModified(), currentUser.getId(), onlineFile.getContents(), onlineFile.getLength(), currentProject.getId()); // write the file in the offline project // has the user write-access? if( accessWrite(currentUser, currentProject, (CmsResource)restoredFile) ) { // write-acces was granted - write the file without setting state = changed m_dbAccess.writeFile(currentProject, onlineProject(currentUser, currentProject), restoredFile, false); // restore the properties in the offline project m_dbAccess.deleteAllProperties(currentProject.getId(),restoredFile); Hashtable propertyInfos = m_dbAccess.readAllProperties(onlineProject.getId(),onlineFile,onlineFile.getType()); m_dbAccess.writeProperties(propertyInfos,currentProject.getId(),restoredFile,restoredFile.getType()); m_propertyCache.clear(); // update the cache m_resourceCache.remove(restoredFile.getResourceName()); m_subresCache.clear(); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + restoredFile.getAbsolutePath(), CmsException.C_NO_ACCESS); } } } /** * Unlocks all resources in this project. * * <B>Security</B> * Only the admin or the owner of the project can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id of the project to be published. * * @exception CmsException Throws CmsException if something goes wrong. */ public void unlockProject(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { // read the project. CmsProject project = readProject(currentUser, currentProject, id); // check the security if( (isAdmin(currentUser, currentProject) || isManagerOfProject(currentUser, project) ) && (project.getFlags() == C_PROJECT_STATE_UNLOCKED )) { // unlock all resources in the project m_dbAccess.unlockProject(project); m_resourceCache.clear(); m_projectCache.clear(); } else { throw new CmsException("[" + this.getClass().getName() + "] " + id, CmsException.C_NO_ACCESS); } } /** * Unlocks a resource.<br> * * Only a resource in an offline project can be unlock. The state of the resource * is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * Only the user who locked a resource can unlock it. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user had locked the resource before</li> * </ul> * * @param user The user who wants to lock the file. * @param project The project in which the resource will be used. * @param resourcename The complete path to the resource to lock. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void unlockResource(CmsUser currentUser,CmsProject currentProject, String resourcename) throws CmsException { CmsResource cmsResource=null; // read the resource, that should be locked if (resourcename.endsWith("/")) { cmsResource = readFolder(currentUser,currentProject,resourcename); } else { cmsResource = (CmsFile)readFileHeader(currentUser,currentProject,resourcename); } // check, if the user may lock the resource if( accessUnlock(currentUser, currentProject, cmsResource) ) { // unlock the resource. if (cmsResource.isLocked()){ // check if the resource is locked by the actual user if (cmsResource.isLockedBy()==currentUser.getId()) { // unlock the resource cmsResource.setLocked(C_UNKNOWN_ID); //update resource m_dbAccess.updateLockstate(cmsResource, cmsResource.getLockedInProject()); if (resourcename.endsWith("/")) { // update the cache m_resourceCache.remove(resourcename); } else { // update the cache m_resourceCache.remove(resourcename); } m_subresCache.clear(); } else { throw new CmsException("[" + this.getClass().getName() + "] " + resourcename + CmsException.C_NO_ACCESS); } } // if this resource is a folder -> lock all subresources, too if(cmsResource.isFolder()) { Vector files = getFilesInFolder(currentUser,currentProject, cmsResource.getResourceName()); Vector folders = getSubFolders(currentUser,currentProject, cmsResource.getResourceName()); CmsResource currentResource; // lock all files in this folder for(int i = 0; i < files.size(); i++ ) { currentResource = (CmsResource)files.elementAt(i); if (currentResource.getState() != C_STATE_DELETED) { unlockResource(currentUser, currentProject, currentResource.getResourceName()); } } // lock all files in this folder for(int i = 0; i < folders.size(); i++) { currentResource = (CmsResource)folders.elementAt(i); if (currentResource.getState() != C_STATE_DELETED) { unlockResource(currentUser, currentProject, currentResource.getResourceName()); } } } } else { throw new CmsException("[" + this.getClass().getName() + "] " + resourcename, CmsException.C_NO_ACCESS); } } /** * Checks if a user is member of a group.<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param callingUser The user who wants to use this method. * @param nameuser The name of the user to check. * @param groupname The name of the group to check. * @return True or False * * @exception CmsException Throws CmsException if operation was not succesful */ public boolean userInGroup(CmsUser currentUser, CmsProject currentProject, String username, String groupname) throws CmsException { Vector groups = getGroupsOfUser(currentUser,currentProject,username); CmsGroup group; for(int z = 0; z < groups.size(); z++) { group = (CmsGroup) groups.elementAt(z); if(groupname.equals(group.getName())) { return true; } } return false; } /** * Checks ii characters in a String are allowed for filenames * * @param filename String to check * * @exception throws a exception, if the check fails. */ protected void validFilename( String filename ) throws CmsException { if (filename == null) { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_BAD_NAME); } int l = filename.trim().length(); if (l == 0 || filename.startsWith(".")) { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_BAD_NAME); } for (int i=0; i<l; i++) { char c = filename.charAt(i); if ( ((c < 'a') || (c > 'z')) && ((c < '0') || (c > '9')) && ((c < 'A') || (c > 'Z')) && (c != '-') && (c != '.') && (c != '_') && (c != '~') ) { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_BAD_NAME); } } } /** * Checks ii characters in a String are allowed for filenames * * @param filename String to check * * @exception throws a exception, if the check fails. */ protected void validTaskname( String taskname ) throws CmsException { if (taskname == null) { throw new CmsException("[" + this.getClass().getName() + "] " + taskname, CmsException.C_BAD_NAME); } int l = taskname.length(); if (l == 0) { throw new CmsException("[" + this.getClass().getName() + "] " + taskname, CmsException.C_BAD_NAME); } for (int i=0; i<l; i++) { char c = taskname.charAt(i); if ( ((c < '') || (c > '')) && ((c < '') || (c > '')) && ((c < 'a') || (c > 'z')) && ((c < '0') || (c > '9')) && ((c < 'A') || (c > 'Z')) && (c != '-') && (c != '.') && (c != '_') && (c != '~') && (c != ' ') && (c != '') ) { throw new CmsException("[" + this.getClass().getName() + "] " + taskname, CmsException.C_BAD_NAME); } } } /** * Checks ii characters in a String are allowed for names * * @param name String to check * * @exception throws a exception, if the check fails. */ protected void validName(String name, boolean blank) throws CmsException { if (name == null || name.length() == 0 || name.trim().length() == 0) { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME); } // throw exception if no blanks are allowed if (!blank) { int l = name.length(); for (int i = 0; i < l; i++) { char c = name.charAt(i); if (c == ' ') { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME); } } } /* for (int i=0; i<l; i++) { char c = name.charAt(i); if ( ((c < 'a') || (c > 'z')) && ((c < '0') || (c > '9')) && ((c < 'A') || (c > 'Z')) && (c != '-') && (c != '.') && (c != '_') && (c != '~') ) { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME); } } */ } /** * Writes the export-path for the system. * This path is used for db-export and db-import. * * <B>Security:</B> * Users, which are in the group "administrators" are granted.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param mountpoint The mount point in the Cms filesystem. */ public void writeExportPath(CmsUser currentUser, CmsProject currentProject, String path) throws CmsException { // check the security if( isAdmin(currentUser, currentProject) ) { // security is ok - write the exportpath. if(m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_EXPORTPATH) == null) { // the property wasn't set before. m_dbAccess.addSystemProperty(C_SYSTEMPROPERTY_EXPORTPATH, path); } else { // overwrite the property. m_dbAccess.writeSystemProperty(C_SYSTEMPROPERTY_EXPORTPATH, path); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + path, CmsException.C_NO_ACCESS); } } /** * Writes a file to the Cms.<br> * * A file can only be written to an offline project.<br> * The state of the resource is set to CHANGED (1). The file content of the file * is either updated (if it is already existing in the offline project), or created * in the offline project (if it is not available there).<br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who own this file. * @param currentProject The project in which the resource will be used. * @param file The name of the file to write. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void writeFile(CmsUser currentUser, CmsProject currentProject, CmsFile file) throws CmsException { // has the user write-access? if( accessWrite(currentUser, currentProject, (CmsResource)file) ) { // write-acces was granted - write the file. m_dbAccess.writeFile(currentProject, onlineProject(currentUser, currentProject), file, true, currentUser.getId()); if (file.getState()==C_STATE_UNCHANGED) { file.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.remove(file.getResourceName()); m_subresCache.clear(); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + file.getAbsolutePath(), CmsException.C_NO_ACCESS); } } /** * Writes the file extensions * * <B>Security:</B> * Users, which are in the group "Administrators" are authorized.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param extensions Holds extensions as keys and resourcetypes (Stings) as values */ public void writeFileExtensions(CmsUser currentUser, CmsProject currentProject, Hashtable extensions) throws CmsException { if (extensions != null) { if (isAdmin(currentUser, currentProject)) { Enumeration enu=extensions.keys(); while (enu.hasMoreElements()) { String key=(String)enu.nextElement(); validFilename(key); } if (m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS) == null) { // the property wasn't set before. m_dbAccess.addSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS, extensions); } else { // overwrite the property. m_dbAccess.writeSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS, extensions); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + extensions.size(), CmsException.C_NO_ACCESS); } } } /** * Writes a fileheader to the Cms.<br> * * A file can only be written to an offline project.<br> * The state of the resource is set to CHANGED (1). The file content of the file * is either updated (if it is already existing in the offline project), or created * in the offline project (if it is not available there).<br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who own this file. * @param currentProject The project in which the resource will be used. * @param file The file to write. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void writeFileHeader(CmsUser currentUser, CmsProject currentProject, CmsFile file) throws CmsException { // has the user write-access? if( accessWrite(currentUser, currentProject, (CmsResource)file) ) { // write-acces was granted - write the file. m_dbAccess.writeFileHeader(currentProject, file,true, currentUser.getId()); if (file.getState()==C_STATE_UNCHANGED) { file.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.remove(file.getResourceName()); // inform about the file-system-change m_subresCache.clear(); m_accessCache.clear(); fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + file.getAbsolutePath(), CmsException.C_NO_ACCESS); } } /** * Writes an already existing group in the Cms.<BR/> * * Only the admin can do this.<P/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param group The group that should be written to the Cms. * @exception CmsException Throws CmsException if operation was not succesfull. */ public void writeGroup(CmsUser currentUser, CmsProject currentProject, CmsGroup group) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) ) { m_dbAccess.writeGroup(group); m_groupCache.put(group.getName(),group); } else { throw new CmsException("[" + this.getClass().getName() + "] " + group.getName(), CmsException.C_NO_ACCESS); } } /** * Writes a couple of propertyinformation for a file or folder. * * <B>Security</B> * Only the user is granted, who has the right to write the resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource of which the propertyinformation * has to be read. * @param propertyinfos A Hashtable with propertydefinition- propertyinfo-pairs as strings. * * @exception CmsException Throws CmsException if operation was not succesful */ public void writeProperties(CmsUser currentUser, CmsProject currentProject, String resource, Hashtable propertyinfos) throws CmsException { // read the resource CmsResource res = readFileHeader(currentUser,currentProject, resource); // check the security if( ! accessWrite(currentUser, currentProject, res) ) { throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_NO_ACCESS); } m_dbAccess.writeProperties(propertyinfos,currentProject.getId(),res,res.getType()); m_propertyCache.clear(); if (res.getState()==C_STATE_UNCHANGED) { res.setState(C_STATE_CHANGED); } if(res.isFile()){ m_dbAccess.writeFileHeader(currentProject, (CmsFile) res, false, currentUser.getId()); // update the cache m_resourceCache.remove(resource); } else { m_dbAccess.writeFolder(currentProject, readFolder(currentUser,currentProject, resource), false, currentUser.getId()); // update the cache m_resourceCache.remove(resource); } m_subresCache.clear(); } /** * Writes a propertyinformation for a file or folder. * * <B>Security</B> * Only the user is granted, who has the right to write the resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource of which the propertyinformation has * to be read. * @param property The propertydefinition-name of which the propertyinformation has to be set. * @param value The value for the propertyinfo to be set. * * @exception CmsException Throws CmsException if operation was not succesful */ public void writeProperty(CmsUser currentUser, CmsProject currentProject, String resource, String property, String value) throws CmsException { // read the resource CmsResource res = readFileHeader(currentUser,currentProject, resource); // check the security if( ! accessWrite(currentUser, currentProject, res) ) { throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_NO_ACCESS); } m_dbAccess.writeProperty(property, currentProject.getId(),value, res,res.getType()); m_propertyCache.clear(); // set the file-state to changed if(res.isFile()){ m_dbAccess.writeFileHeader(currentProject, (CmsFile) res, true, currentUser.getId()); if (res.getState()==C_STATE_UNCHANGED) { res.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.remove(resource); } else { if (res.getState()==C_STATE_UNCHANGED) { res.setState(C_STATE_CHANGED); } m_dbAccess.writeFolder(currentProject, readFolder(currentUser,currentProject, resource), true, currentUser.getId()); // update the cache m_resourceCache.remove(resource); } m_subresCache.clear(); } /** * Updates the propertydefinition for the resource type.<BR/> * * <B>Security</B> * Only the admin can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param propertydef The propertydef to be deleted. * * @return The propertydefinition, that was written. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsPropertydefinition writePropertydefinition(CmsUser currentUser, CmsProject currentProject, CmsPropertydefinition propertydef) throws CmsException { // check the security if( isAdmin(currentUser, currentProject) ) { m_propertyDefVectorCache.clear(); return( m_dbAccess.writePropertydefinition(propertydef) ); } else { throw new CmsException("[" + this.getClass().getName() + "] " + propertydef.getName(), CmsException.C_NO_ACCESS); } } /** * Writes a new user tasklog for a task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task . * @param comment Description for the log * * @exception CmsException Throws CmsException if something goes wrong. */ public void writeTaskLog(CmsUser currentUser, CmsProject currentProject, int taskid, String comment) throws CmsException { m_dbAccess.writeTaskLog(taskid, currentUser.getId(), new java.sql.Timestamp(System.currentTimeMillis()), comment, C_TASKLOG_USER); } /** * Writes a new user tasklog for a task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task . * @param comment Description for the log * @param tasktype Type of the tasklog. User tasktypes must be greater then 100. * * @exception CmsException Throws CmsException if something goes wrong. */ public void writeTaskLog(CmsUser currentUser, CmsProject currentProject, int taskid, String comment, int type) throws CmsException { m_dbAccess.writeTaskLog(taskid, currentUser.getId(), new java.sql.Timestamp(System.currentTimeMillis()), comment, type); } /** * Updates the user information.<BR/> * * Only the administrator can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param user The user to be updated. * * @exception CmsException Throws CmsException if operation was not succesful */ public void writeUser(CmsUser currentUser, CmsProject currentProject, CmsUser user) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) || (currentUser.equals(user)) ) { // prevent the admin to be set disabled! if( isAdmin(user, currentProject) ) { user.setEnabled(); } m_dbAccess.writeUser(user); // update the cache m_userCache.put(user.getName()+user.getType(),user); } else { throw new CmsException("[" + this.getClass().getName() + "] " + user.getName(), CmsException.C_NO_ACCESS); } } /** * Updates the user information of a web user.<BR/> * * Only a web user can be updated this way.<P/> * * <B>Security:</B> * Only users of the user type webuser can be updated this way. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param user The user to be updated. * * @exception CmsException Throws CmsException if operation was not succesful */ public void writeWebUser(CmsUser currentUser, CmsProject currentProject, CmsUser user) throws CmsException { // Check the security if( user.getType() == C_USER_TYPE_WEBUSER) { m_dbAccess.writeUser(user); // update the cache m_userCache.put(user.getName()+user.getType(),user); } else { throw new CmsException("[" + this.getClass().getName() + "] " + user.getName(), CmsException.C_NO_ACCESS); } } /** * Changes the project-id of a resource to the new project * for publishing the resource directly * * @param newProjectId The new project-id * @param resourcename The name of the resource to change */ public void changeLockedInProject(int projectId, String resourcename) throws CmsException{ m_dbAccess.changeLockedInProject(projectId, resourcename); m_resourceCache.remove(resourcename); } /** * Check if the history is enabled * * @return boolean Is true if history is enabled */ public boolean isHistoryEnabled(){ return this.m_enableHistory; } /** * Get the next version id for the published backup resources * * @return int The new version id */ public int getBackupVersionId(){ return m_dbAccess.getBackupVersionId(); } /** * Creates a backup of the published project * * @param project The project in which the resource was published. * @param projectresources The resources of the project * @param versionId The version of the backup * @param publishDate The date of publishing * @param userId The id of the user who had published the project * * @exception CmsException Throws CmsException if operation was not succesful. */ public void backupProject(int projectId, int versionId, long publishDate, CmsUser currentUser) throws CmsException{ CmsProject project = m_dbAccess.readProject(projectId); m_dbAccess.backupProject(project, versionId, publishDate, currentUser); } /** * Checks if this is a valid group for webusers * * @param group The group to be checked * @return boolean If the group does not belong to Users, Administrators or Projectmanagers return true */ protected boolean isWebgroup(CmsGroup group){ try{ int user = m_dbAccess.readGroup(C_GROUP_USERS).getId(); int admin = m_dbAccess.readGroup(C_GROUP_ADMIN).getId(); int manager = m_dbAccess.readGroup(C_GROUP_PROJECTLEADER).getId(); if(group.getId() == user || group.getId() == admin || group.getId() == manager){ return false; } else { int parentId = group.getParentId(); // check if the group belongs to Users, Administrators or Projectmanager if (parentId != C_UNKNOWN_ID){ if(parentId == user || parentId == admin || parentId == manager){ // the parent return false; } else { // check is the parentgroup is a webgroup isWebgroup(m_dbAccess.readGroup(parentId)); } } } } catch (Exception e){ return false; } return true; } /** * Gets the Crontable. * * <B>Security:</B> * All users are garnted<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * @return the crontable. */ public String readCronTable(CmsUser currentUser, CmsProject currentProject) throws CmsException { String retValue = (String) m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_CRONTABLE); if(retValue == null) { return ""; } else { return retValue; } } /** * Writes the Crontable. * * <B>Security:</B> * Only a administrator can do this<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * @return the crontable. */ public void writeCronTable(CmsUser currentUser, CmsProject currentProject, String crontable) throws CmsException { if(isAdmin(currentUser, currentProject)) { if(m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_CRONTABLE) == null) { m_dbAccess.addSystemProperty(C_SYSTEMPROPERTY_CRONTABLE, crontable); } else { m_dbAccess.writeSystemProperty(C_SYSTEMPROPERTY_CRONTABLE, crontable); } } else { throw new CmsException("No access to write crontable", CmsException.C_NO_ACCESS); } } }
src/com/opencms/file/genericSql/CmsResourceBroker.java
/* * File : $Source: /alkacon/cvs/opencms/src/com/opencms/file/genericSql/Attic/CmsResourceBroker.java,v $ * Date : $Date: 2001/11/15 16:41:21 $ * Version: $Revision: 1.292 $ * * This library is part of OpenCms - * the Open Source Content Mananagement System * * Copyright (C) 2001 The OpenCms Group * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about OpenCms, please see the * OpenCms Website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.opencms.file.genericSql; import javax.servlet.http.*; import java.util.*; import java.net.*; import java.io.*; import source.org.apache.java.io.*; import source.org.apache.java.util.*; import com.opencms.boot.CmsClassLoader; import com.opencms.boot.CmsBase; import com.opencms.core.*; import com.opencms.file.*; import com.opencms.template.*; import java.sql.SQLException; /** * This is THE resource broker. It merges all resource broker * into one public class. The interface is local to package. <B>All</B> methods * get additional parameters (callingUser and currentproject) to check the security- * police. * * @author Andreas Schouten * @author Michaela Schleich * @author Michael Emmerich * @author Anders Fugmann * @version $Revision: 1.292 $ $Date: 2001/11/15 16:41:21 $ * */ public class CmsResourceBroker implements I_CmsResourceBroker, I_CmsConstants { //create a compare class to be used in the vector. class Resource { private String path = null; public Resource(String path) { this.path = path; } public boolean equals(Object obj) { return ( (obj instanceof CmsResource) && path.equals( ((CmsResource) obj).getResourceName() )); } } /** * Constant to count the file-system changes. */ protected long m_fileSystemChanges = 0; /** * Constant to count the file-system changes if Folders are involved. */ protected long m_fileSystemFolderChanges = 0; /** * Hashtable with resource-types. */ protected Hashtable m_resourceTypes = null; /** * The configuration of the property-file. */ protected Configurations m_configuration = null; /** * The access-module. */ protected CmsDbAccess m_dbAccess = null; /** * The Registry */ protected I_CmsRegistry m_registry = null; /** * Define the caches */ protected CmsCache m_userCache = null; protected CmsCache m_groupCache = null; protected CmsCache m_usergroupsCache = null; //protected CmsCache m_resourceCache = null; protected CmsResourceCache m_resourceCache = null; protected CmsCache m_subresCache = null; protected CmsCache m_projectCache = null; protected CmsCache m_onlineProjectCache = null; protected CmsCache m_propertyCache = null; protected CmsCache m_propertyDefCache = null; protected CmsCache m_propertyDefVectorCache = null; protected CmsCache m_accessCache = null; protected int m_cachelimit = 0; protected String m_refresh = null; /** * backup published resources for history */ protected boolean m_enableHistory = true; /** * Accept a task from the Cms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task to accept. * * @exception CmsException Throws CmsException if something goes wrong. */ public void acceptTask(CmsUser currentUser, CmsProject currentProject, int taskId) throws CmsException { CmsTask task = m_dbAccess.readTask(taskId); task.setPercentage(1); task = m_dbAccess.writeTask(task); m_dbAccess.writeSystemTaskLog(taskId, "Task was accepted from " + currentUser.getFirstname() + " " + currentUser.getLastname() + "."); } /** * Checks, if the user may create this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user has access, or not. */ public boolean accessCreate(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { // check, if this is the onlineproject if(onlineProject(currentUser, currentProject).equals(currentProject)){ // the online-project is not writeable! return(false); } // check the access to the project if( ! accessProject(currentUser, currentProject, currentProject.getId()) ) { // no access to the project! return(false); } // check if the resource belongs to the current project if(resource.getProjectId() != currentProject.getId()) { return false; } // is the resource locked? if( resource.isLocked() && (resource.isLockedBy() != currentUser.getId() || (resource.getLockedInProject() != currentProject.getId() && currentProject.getFlags() != C_PROJECT_STATE_INVISIBLE)) ) { // resource locked by anopther user, no creation allowed return(false); } // check the rights for the current resource if( ! ( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_WRITE) || accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_WRITE) || accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_WRITE) ) ) { // no write access to this resource! return false; } // read the parent folder if(resource.getParent() != null) { // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getRootName()+resource.getParent()); } else { // no parent folder! return true; } // check the rights and if the resource is not locked do { if( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_READ) || accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_READ) || accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_READ) ) { // is the resource locked? if( resource.isLocked() && resource.isLockedBy() != currentUser.getId() ) { // resource locked by anopther user, no creation allowed return(false); } // read next resource if(resource.getParent() != null) { // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getRootName()+resource.getParent()); } } else { // last check was negative return(false); } } while(resource.getParent() != null); // all checks are done positive return(true); } /** * Checks, if the user may create this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user has access, or not. */ public boolean accessCreate(CmsUser currentUser, CmsProject currentProject, String resourceName) throws CmsException { CmsResource resource = m_dbAccess.readFileHeader(currentProject.getId(), resourceName); return accessCreate(currentUser, currentProject, resource); } /** * Checks, if the group may access this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * @param flags The flags to check. * * @return wether the user has access, or not. */ protected boolean accessGroup(CmsUser currentUser, CmsProject currentProject, CmsResource resource, int flags) throws CmsException { // is the user in the group for the resource? if(userInGroup(currentUser, currentProject, currentUser.getName(), readGroup(currentUser, currentProject, resource).getName())) { if( (resource.getAccessFlags() & flags) == flags ) { return true; } } // the resource isn't accesible by the user. return false; } /** * Checks, if the user may lock this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user may lock this resource, or not. */ public boolean accessLock(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { // check, if this is the onlineproject if(onlineProject(currentUser, currentProject).equals(currentProject)){ // the online-project is not writeable! return(false); } // check the access to the project if( ! accessProject(currentUser, currentProject, currentProject.getId()) ) { // no access to the project! return(false); } // check if the resource belongs to the current project if(resource.getProjectId() != currentProject.getId()) { return false; } // read the parent folder if(resource.getParent() != null) { // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getRootName()+resource.getParent()); } else { // no parent folder! return true; } // check the rights and if the resource is not locked do { // is the resource locked? if( resource.isLocked() && (resource.isLockedBy() != currentUser.getId() || (resource.getLockedInProject() != currentProject.getId() && currentProject.getFlags() != C_PROJECT_STATE_INVISIBLE)) ) { // resource locked by anopther user, no creation allowed return(false); } // read next resource if(resource.getParent() != null) { // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getRootName()+resource.getParent()); } } while(resource.getParent() != null); // all checks are done positive return(true); } /** * Checks, if the user may lock this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user may lock this resource, or not. */ public boolean accessLock(CmsUser currentUser, CmsProject currentProject, String resourceName) throws CmsException { CmsResource resource = m_dbAccess.readFileHeader(currentProject.getId(), resourceName); return accessLock(currentUser,currentProject,resource); } /** * Checks, if others may access this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * @param flags The flags to check. * * @return wether the user has access, or not. */ protected boolean accessOther(CmsUser currentUser, CmsProject currentProject, CmsResource resource, int flags) throws CmsException { if ((resource.getAccessFlags() & flags) == flags) { return true; } else { return false; } } /** * Checks, if the owner may access this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * @param flags The flags to check. * * @return wether the user has access, or not. */ protected boolean accessOwner(CmsUser currentUser, CmsProject currentProject, CmsResource resource, int flags) throws CmsException { // The Admin has always access if( isAdmin(currentUser, currentProject) ) { return(true); } // is the resource owned by this user? if(resource.getOwnerId() == currentUser.getId()) { if( (resource.getAccessFlags() & flags) == flags ) { return true ; } } // the resource isn't accesible by the user. return false; } // Methods working with projects /** * Tests if the user can access the project. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId the id of the project. * @return true, if the user has access, else returns false. * @exception CmsException Throws CmsException if something goes wrong. */ public boolean accessProject(CmsUser currentUser, CmsProject currentProject, int projectId) throws CmsException { CmsProject testProject = readProject(currentUser, currentProject, projectId); if (projectId==C_PROJECT_ONLINE_ID) { return true; } // is the project unlocked? if( testProject.getFlags() != C_PROJECT_STATE_UNLOCKED && testProject.getFlags() != C_PROJECT_STATE_INVISIBLE) { return(false); } // is the current-user admin, or the owner of the project? if( (currentProject.getOwnerId() == currentUser.getId()) || isAdmin(currentUser, currentProject) ) { return(true); } // get all groups of the user Vector groups = getGroupsOfUser(currentUser, currentProject, currentUser.getName()); // test, if the user is in the same groups like the project. for(int i = 0; i < groups.size(); i++) { int groupId = ((CmsGroup) groups.elementAt(i)).getId(); if( ( groupId == testProject.getGroupId() ) || ( groupId == testProject.getManagerGroupId() ) ) { return( true ); } } return( false ); } /** * Checks, if the user may read this resource. * NOTE: If the ressource is in the project you never have to fallback. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return weather the user has access, or not. */ public boolean accessRead(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { Boolean access=(Boolean)m_accessCache.get(currentUser.getId()+":"+currentProject.getId()+":"+resource.getResourceName()); if (access != null) { return access.booleanValue(); } else { if ((resource == null) || !accessProject(currentUser, currentProject, resource.getProjectId()) || (!accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_READ) && !accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_READ) && !accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_READ))) { m_accessCache.put(currentUser.getId()+":"+currentProject.getId()+":"+resource.getResourceName(), new Boolean(false)); return false; } // check the rights for all CmsResource res = resource; // save the original resource name to be used if an error occurs. while (res.getParent() != null) { // readFolder without checking access res = m_dbAccess.readFolder(currentProject.getId(), res.getRootName()+res.getParent()); if (res == null) { if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(A_OpenCms.C_OPENCMS_DEBUG, "Resource has no parent: " + resource.getAbsolutePath()); } throw new CmsException(this.getClass().getName() + ".accessRead(): Cannot find \'" + resource.getName(), CmsException.C_NOT_FOUND); } if (!accessOther(currentUser, currentProject, res, C_ACCESS_PUBLIC_READ) && !accessOwner(currentUser, currentProject, res, C_ACCESS_OWNER_READ) && !accessGroup(currentUser, currentProject, res, C_ACCESS_GROUP_READ)) { m_accessCache.put(currentUser.getId()+":"+currentProject.getId()+":"+resource.getResourceName(), new Boolean(false)); return false; } } m_accessCache.put(currentUser.getId()+":"+currentProject.getId()+":"+resource.getResourceName(), new Boolean(true)); return true; } } /** * Checks, if the user may read this resource. * NOTE: If the ressource is in the project you never have to fallback. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return weather the user has access, or not. */ public boolean accessRead(CmsUser currentUser, CmsProject currentProject, String resourceName) throws CmsException { CmsResource resource = m_dbAccess.readFileHeader(currentProject.getId(), resourceName); return accessRead(currentUser, currentProject, resource); } /** * Checks, if the user may unlock this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user may unlock this resource, or not. */ public boolean accessUnlock(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { // check, if this is the onlineproject if(onlineProject(currentUser, currentProject).equals(currentProject)){ // the online-project is not writeable! return(false); } // check the access to the project if( ! accessProject(currentUser, currentProject, currentProject.getId()) ) { // no access to the project! return(false); } // check if the resource belongs to the current project if(resource.getProjectId() != currentProject.getId()) { return false; } // read the parent folder if(resource.getParent() != null) { // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getRootName()+resource.getParent()); } else { // no parent folder! return true; } // check if the resource is not locked do { // is the resource locked? if( resource.isLocked() ) { // resource locked by anopther user, no creation allowed return(false); } // read next resource if(resource.getParent() != null) { // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getRootName()+resource.getParent()); } } while(resource.getParent() != null); // all checks are done positive return(true); } /** * Checks, if the user may write this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user has access, or not. */ public boolean accessWrite(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { // check, if this is the onlineproject if(onlineProject(currentUser, currentProject).equals(currentProject)){ // the online-project is not writeable! return(false); } // check the access to the project if( ! accessProject(currentUser, currentProject, currentProject.getId()) ) { // no access to the project! return(false); } // check if the resource belongs to the current project if(resource.getProjectId() != currentProject.getId()) { return false; } // check, if the resource is locked by the current user if(resource.isLockedBy() != currentUser.getId()) { // resource is not locked by the current user, no writing allowed return(false); } else { //check if the project that has locked the resource is the current project if((resource.getLockedInProject() != currentProject.getId())){ return (false); } } // check the rights for the current resource if( ! ( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_WRITE) || accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_WRITE) || accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_WRITE) ) ) { // no write access to this resource! return false; } // read the parent folder if(resource.getParent() != null) { // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getRootName()+resource.getParent()); } else { // no parent folder! return true; } // check the rights and if the resource is not locked // for parent folders only read access is needed do { if( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_READ) || accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_READ) || accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_READ) ) { // is the resource locked? if( resource.isLocked() && (resource.isLockedBy() != currentUser.getId() ) ) { // resource locked by anopther user, no creation allowed return(false); } // read next resource if(resource.getParent() != null) { // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getRootName()+resource.getParent()); } } else { // last check was negative return(false); } } while(resource.getParent() != null); // all checks are done positive return(true); } /** * Checks, if the user may write this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user has access, or not. */ public boolean accessWrite(CmsUser currentUser, CmsProject currentProject, String resourceName) throws CmsException { CmsResource resource = m_dbAccess.readFileHeader(currentProject.getId(), resourceName); return accessWrite(currentUser,currentProject,resource); } /** * Checks, if the user may write the unlocked resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user has access, or not. */ public boolean accessWriteUnlocked(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { // check, if this is the onlineproject if(onlineProject(currentUser, currentProject).equals(currentProject)){ // the online-project is not writeable! return(false); } // check the access to the project if( ! accessProject(currentUser, currentProject, currentProject.getId()) ) { // no access to the project! return(false); } // check if the resource belongs to the current project if(resource.getProjectId() != currentProject.getId()) { return false; } // check the rights for the current resource if( ! ( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_WRITE) || accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_WRITE) || accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_WRITE) ) ) { // no write access to this resource! return false; } // read the parent folder if(resource.getParent() != null) { // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getRootName()+resource.getParent()); } else { // no parent folder! return true; } // check the rights and if the resource is not locked // for parent folders only read access is needed do { if( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_READ) || accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_READ) || accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_READ) ) { // is the resource locked? if( resource.isLocked() && (resource.isLockedBy() != currentUser.getId() ) ) { // resource locked by anopther user, no creation allowed return(false); } // read next resource if(resource.getParent() != null) { // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getRootName()+resource.getParent()); } } else { // last check was negative return(false); } } while(resource.getParent() != null); // all checks are done positive return(true); } /** * adds a file extension to the list of known file extensions * * <B>Security:</B> * Users, which are in the group "administrators" are granted.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param extension a file extension like 'html' * @param resTypeName name of the resource type associated to the extension */ public void addFileExtension(CmsUser currentUser, CmsProject currentProject, String extension, String resTypeName) throws CmsException { if (extension != null && resTypeName != null) { if (isAdmin(currentUser, currentProject)) { Hashtable suffixes=(Hashtable) m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS); if (suffixes == null) { suffixes = new Hashtable(); suffixes.put(extension, resTypeName); m_dbAccess.addSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS, suffixes); } else { suffixes.put(extension, resTypeName); m_dbAccess.writeSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS, suffixes); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + extension, CmsException.C_NO_ACCESS); } } } /** * Add a new group to the Cms.<BR/> * * Only the admin can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name of the new group. * @param description The description for the new group. * @int flags The flags for the new group. * @param name The name of the parent group (or null). * * @return Group * * @exception CmsException Throws CmsException if operation was not succesfull. */ public CmsGroup addGroup(CmsUser currentUser, CmsProject currentProject, String name, String description, int flags, String parent) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) ) { name = name.trim(); validFilename(name); // check the lenght of the groupname if(name.length() > 1) { return( m_dbAccess.createGroup(name, description, flags, parent) ); } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } /** * Adds a user to the Cms. * * Only a adminstrator can add users to the cms.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The new name for the user. * @param password The new password for the user. * @param group The default groupname for the user. * @param description The description for the user. * @param additionalInfos A Hashtable with additional infos for the user. These * Infos may be stored into the Usertables (depending on the implementation). * @param flags The flags for a user (e.g. C_FLAG_ENABLED) * * @return user The added user will be returned. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public CmsUser addUser(CmsUser currentUser, CmsProject currentProject, String name, String password, String group, String description, Hashtable additionalInfos, int flags) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) ) { // no space before or after the name name = name.trim(); // check the username validFilename(name); // check the password minimumsize if( (name.length() > 0) && (password.length() >= C_PASSWORD_MINIMUMSIZE) ) { CmsGroup defaultGroup = readGroup(currentUser, currentProject, group); CmsUser newUser = m_dbAccess.addUser(name, password, description, " ", " ", " ", 0, 0, C_FLAG_ENABLED, additionalInfos, defaultGroup, " ", " ", C_USER_TYPE_SYSTEMUSER); addUserToGroup(currentUser, currentProject, newUser.getName(),defaultGroup.getName()); return newUser; } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_SHORT_PASSWORD); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } /** * Adds a user to the Cms. * * Only a adminstrator can add users to the cms.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name for the user. * @param password The password for the user. * @param recoveryPassword The recoveryPassword for the user. * @param description The description for the user. * @param firstname The firstname of the user. * @param lastname The lastname of the user. * @param email The email of the user. * @param flags The flags for a user (e.g. C_FLAG_ENABLED) * @param additionalInfos A Hashtable with additional infos for the user. These * Infos may be stored into the Usertables (depending on the implementation). * @param defaultGroup The default groupname for the user. * @param address The address of the user * @param section The section of the user * @param type The type of the user * * @return user The added user will be returned. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public CmsUser addImportUser(CmsUser currentUser, CmsProject currentProject, String name, String password, String recoveryPassword, String description, String firstname, String lastname, String email, int flags, Hashtable additionalInfos, String defaultGroup, String address, String section, int type) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) ) { // no space before or after the name name = name.trim(); // check the username validFilename(name); CmsGroup group = readGroup(currentUser, currentProject, defaultGroup); CmsUser newUser = m_dbAccess.addImportUser(name, password, recoveryPassword, description, firstname, lastname, email, 0, 0, flags, additionalInfos, group, address, section, type); addUserToGroup(currentUser, currentProject, newUser.getName(), group.getName()); return newUser; } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } /** * Adds a user to a group.<BR/> * * Only the admin can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user that is to be added to the group. * @param groupname The name of the group. * @exception CmsException Throws CmsException if operation was not succesfull. */ public void addUserToGroup(CmsUser currentUser, CmsProject currentProject, String username, String groupname) throws CmsException { if (!userInGroup(currentUser, currentProject, username, groupname)) { // Check the security if (isAdmin(currentUser, currentProject)) { CmsUser user; CmsGroup group; try{ user = readUser(currentUser, currentProject, username); } catch (CmsException e){ if (e.getType() == CmsException.C_NO_USER){ user = readWebUser(currentUser, currentProject, username); } else { throw e; } } //check if the user exists if (user != null) { group = readGroup(currentUser, currentProject, groupname); //check if group exists if (group != null) { //add this user to the group m_dbAccess.addUserToGroup(user.getId(), group.getId()); // update the cache m_usergroupsCache.clear(); } else { throw new CmsException("[" + this.getClass().getName() + "]" + groupname, CmsException.C_NO_GROUP); } } else { throw new CmsException("[" + this.getClass().getName() + "]" + username, CmsException.C_NO_USER); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS); } } } /** * Adds a web user to the Cms. <br> * * A web user has no access to the workplace but is able to access personalized * functions controlled by the OpenCms. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The new name for the user. * @param password The new password for the user. * @param group The default groupname for the user. * @param description The description for the user. * @param additionalInfos A Hashtable with additional infos for the user. These * Infos may be stored into the Usertables (depending on the implementation). * @param flags The flags for a user (e.g. C_FLAG_ENABLED) * * @return user The added user will be returned. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public CmsUser addWebUser(CmsUser currentUser, CmsProject currentProject, String name, String password, String group, String description, Hashtable additionalInfos, int flags) throws CmsException { // no space before or after the name name = name.trim(); // check the username validFilename(name); // check the password minimumsize if( (name.length() > 0) && (password.length() >= C_PASSWORD_MINIMUMSIZE) ) { CmsGroup defaultGroup = readGroup(currentUser, currentProject, group); CmsUser newUser = m_dbAccess.addUser(name, password, description, " ", " ", " ", 0, 0, C_FLAG_ENABLED, additionalInfos, defaultGroup, " ", " ", C_USER_TYPE_WEBUSER); CmsUser user; CmsGroup usergroup; user=m_dbAccess.readUser(newUser.getName(),C_USER_TYPE_WEBUSER); //check if the user exists if (user != null) { usergroup=readGroup(currentUser,currentProject,group); //check if group exists if (usergroup != null){ //add this user to the group m_dbAccess.addUserToGroup(user.getId(),usergroup.getId()); // update the cache m_usergroupsCache.clear(); } else { throw new CmsException("["+this.getClass().getName()+"]"+group,CmsException.C_NO_GROUP); } } else { throw new CmsException("["+this.getClass().getName()+"]"+name,CmsException.C_NO_USER); } return newUser; } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_SHORT_PASSWORD); } } /** * Adds a web user to the Cms. <br> * * A web user has no access to the workplace but is able to access personalized * functions controlled by the OpenCms. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The new name for the user. * @param password The new password for the user. * @param group The default groupname for the user. * @param additionalGroup An additional group for the user. * @param description The description for the user. * @param additionalInfos A Hashtable with additional infos for the user. These * Infos may be stored into the Usertables (depending on the implementation). * @param flags The flags for a user (e.g. C_FLAG_ENABLED) * * @return user The added user will be returned. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public CmsUser addWebUser(CmsUser currentUser, CmsProject currentProject, String name, String password, String group, String additionalGroup, String description, Hashtable additionalInfos, int flags) throws CmsException { // no space before or after the name name = name.trim(); // check the username validFilename(name); // check the password minimumsize if( (name.length() > 0) && (password.length() >= C_PASSWORD_MINIMUMSIZE) ) { CmsGroup defaultGroup = readGroup(currentUser, currentProject, group); CmsUser newUser = m_dbAccess.addUser(name, password, description, " ", " ", " ", 0, 0, C_FLAG_ENABLED, additionalInfos, defaultGroup, " ", " ", C_USER_TYPE_WEBUSER); CmsUser user; CmsGroup usergroup; CmsGroup addGroup; user=m_dbAccess.readUser(newUser.getName(),C_USER_TYPE_WEBUSER); //check if the user exists if (user != null) { usergroup=readGroup(currentUser,currentProject,group); //check if group exists if (usergroup != null && isWebgroup(usergroup)){ //add this user to the group m_dbAccess.addUserToGroup(user.getId(),usergroup.getId()); // update the cache m_usergroupsCache.clear(); } else { throw new CmsException("["+this.getClass().getName()+"]"+group,CmsException.C_NO_GROUP); } // if an additional groupname is given and the group does not belong to // Users, Administrators or Projectmanager add the user to this group if (additionalGroup != null && !"".equals(additionalGroup)){ addGroup = readGroup(currentUser, currentProject, additionalGroup); if(addGroup != null && isWebgroup(addGroup)){ //add this user to the group m_dbAccess.addUserToGroup(user.getId(), addGroup.getId()); // update the cache m_usergroupsCache.clear(); } else { throw new CmsException("["+this.getClass().getName()+"]"+additionalGroup,CmsException.C_NO_GROUP); } } } else { throw new CmsException("["+this.getClass().getName()+"]"+name,CmsException.C_NO_USER); } return newUser; } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_SHORT_PASSWORD); } } /** * Returns the anonymous user object.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return the anonymous user object. * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser anonymousUser(CmsUser currentUser, CmsProject currentProject) throws CmsException { return readUser(currentUser, currentProject, C_USER_GUEST); } /** * Changes the group for this resource<br> * * Only the group of a resource in an offline project can be changed. The state * of the resource is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * The user may change this, if he is admin of the resource. <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user is owner of the resource or is admin</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The complete path to the resource. * @param newGroup The name of the new group for this resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void chgrp(CmsUser currentUser, CmsProject currentProject, String filename, String newGroup) throws CmsException { CmsResource resource=null; // read the resource to check the access if (filename.endsWith("/")) { resource = readFolder(currentUser,currentProject,filename); } else { resource = (CmsFile)readFileHeader(currentUser,currentProject,filename); } // has the user write-access? and is he owner or admin? if( accessWrite(currentUser, currentProject, resource) && ( (resource.getOwnerId() == currentUser.getId()) || isAdmin(currentUser, currentProject))) { CmsGroup group = readGroup(currentUser, currentProject, newGroup); resource.setGroupId(group.getId()); // write-acces was granted - write the file. if (filename.endsWith("/")) { if (resource.getState()==C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } m_dbAccess.writeFolder(currentProject,(CmsFolder)resource,true, currentUser.getId()); // update the cache m_resourceCache.remove(filename); } else { m_dbAccess.writeFileHeader(currentProject,(CmsFile)resource,true, currentUser.getId()); if (resource.getState()==C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.remove(filename); } m_subresCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS); } } /** * Changes the flags for this resource.<br> * * Only the flags of a resource in an offline project can be changed. The state * of the resource is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * The user may change the flags, if he is admin of the resource <br>. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The complete path to the resource. * @param flags The new accessflags for the resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void chmod(CmsUser currentUser, CmsProject currentProject, String filename, int flags) throws CmsException { CmsResource resource=null; // read the resource to check the access if (filename.endsWith("/")) { resource = readFolder(currentUser,currentProject,filename); } else { resource = (CmsFile)readFileHeader(currentUser,currentProject,filename); } // has the user write-access? if( accessWrite(currentUser, currentProject, resource)|| ((resource.isLockedBy() == currentUser.getId() && resource.getLockedInProject() == currentProject.getId()) && (resource.getOwnerId() == currentUser.getId()||isAdmin(currentUser, currentProject))) ) { // write-acces was granted - write the file. //set the flags resource.setAccessFlags(flags); //update file if (filename.endsWith("/")) { if (resource.getState()==C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } m_dbAccess.writeFolder(currentProject,(CmsFolder)resource,true, currentUser.getId()); // update the cache m_resourceCache.remove(filename); } else { m_dbAccess.writeFileHeader(currentProject,(CmsFile)resource,true, currentUser.getId()); if (resource.getState()==C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.remove(filename); } m_subresCache.clear(); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS); } } /** * Changes the owner for this resource.<br> * * Only the owner of a resource in an offline project can be changed. The state * of the resource is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * The user may change this, if he is admin of the resource. <br> * * <B>Security:</B> * Access is cranted, if: * <ul> * <li>the user has access to the project</li> * <li>the user is owner of the resource or the user is admin</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The complete path to the resource. * @param newOwner The name of the new owner for this resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void chown(CmsUser currentUser, CmsProject currentProject, String filename, String newOwner) throws CmsException { CmsResource resource = null; // read the resource to check the access if (filename.endsWith("/")) { resource = readFolder(currentUser, currentProject, filename); } else { resource = (CmsFile) readFileHeader(currentUser, currentProject, filename); } // has the user write-access? and is he owner or admin? if (((resource.getOwnerId() == currentUser.getId()) || isAdmin(currentUser, currentProject)) && (resource.isLockedBy() == currentUser.getId() && resource.getLockedInProject() == currentProject.getId())) { CmsUser owner = readUser(currentUser, currentProject, newOwner); resource.setUserId(owner.getId()); // write-acces was granted - write the file. if (filename.endsWith("/")) { if (resource.getState() == C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } m_dbAccess.writeFolder(currentProject, (CmsFolder) resource, true, currentUser.getId()); // update the cache m_resourceCache.remove(filename); } else { m_dbAccess.writeFileHeader(currentProject, (CmsFile) resource, true, currentUser.getId()); if (resource.getState() == C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.remove(filename); } m_subresCache.clear(); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS); } } /** * Changes the state for this resource<BR/> * * The user may change this, if he is admin of the resource. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user is owner of the resource or is admin</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param filename The complete path to the resource. * @param state The new state of this resource. * * @exception CmsException will be thrown, if the user has not the rights * for this resource. */ public void chstate(CmsUser currentUser, CmsProject currentProject, String filename, int state) throws CmsException { boolean isFolder=false; CmsResource resource=null; // read the resource to check the access if (filename.endsWith("/")) { isFolder=true; resource = readFolder(currentUser,currentProject,filename); } else { resource = (CmsFile)readFileHeader(currentUser,currentProject,filename); } // has the user write-access? if( accessWrite(currentUser, currentProject, resource)) { resource.setState(state); // write-acces was granted - write the file. if (filename.endsWith("/")) { m_dbAccess.writeFolder(currentProject,(CmsFolder)resource,false, currentUser.getId()); // update the cache m_resourceCache.remove(filename); } else { m_dbAccess.writeFileHeader(currentProject,(CmsFile)resource,false, currentUser.getId()); // update the cache m_resourceCache.remove(filename); } m_subresCache.clear(); // inform about the file-system-change fileSystemChanged(isFolder); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS); } } /** * Changes the resourcetype for this resource<br> * * Only the resourcetype of a resource in an offline project can be changed. The state * of the resource is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * The user may change this, if he is admin of the resource. <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user is owner of the resource or is admin</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The complete path to the resource. * @param newType The name of the new resourcetype for this resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void chtype(CmsUser currentUser, CmsProject currentProject, String filename, String newType) throws CmsException { I_CmsResourceType type = getResourceType(currentUser, currentProject, newType); // read the resource to check the access CmsResource resource = readFileHeader(currentUser,currentProject, filename); // has the user write-access? and is he owner or admin? if( accessWrite(currentUser, currentProject, resource) && ( (resource.getOwnerId() == currentUser.getId()) || isAdmin(currentUser, currentProject))) { // write-acces was granted - write the file. resource.setType(type.getResourceType()); resource.setLauncherType(type.getLauncherType()); m_dbAccess.writeFileHeader(currentProject, (CmsFile)resource,true, currentUser.getId()); if (resource.getState()==C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.remove(filename); m_subresCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS); } } /** * Clears all internal DB-Caches. */ public void clearcache() { m_userCache.clear(); m_groupCache.clear(); m_usergroupsCache.clear(); m_projectCache.clear(); m_resourceCache.clear(); m_subresCache.clear(); m_propertyCache.clear(); m_propertyDefCache.clear(); m_propertyDefVectorCache.clear(); m_onlineProjectCache.clear(); m_accessCache.clear(); CmsTemplateClassManager.clearCache(); } /** * Copies a file in the Cms. <br> * * <B>Security:</B> * Access is cranted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the sourceresource</li> * <li>the user can create the destinationresource</li> * <li>the destinationresource dosn't exists</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param source The complete path of the sourcefile. * @param destination The complete path to the destination. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void copyFile(CmsUser currentUser, CmsProject currentProject, String source, String destination) throws CmsException { // the name of the new file. String filename; // the name of the folder. String foldername; // checks, if the destinateion is valid, if not it throws a exception validFilename(destination.replace('/', 'a')); // read the source-file, to check readaccess CmsResource file = readFileHeader(currentUser, currentProject, source); // split the destination into file and foldername if (destination.endsWith("/")) { filename = file.getName(); foldername = destination; }else{ foldername = destination.substring(0, destination.lastIndexOf("/")+1); filename = destination.substring(destination.lastIndexOf("/")+1, destination.length()); } CmsFolder cmsFolder = readFolder(currentUser,currentProject, foldername); if( accessCreate(currentUser, currentProject, (CmsResource)cmsFolder) ) { if(( accessOther(currentUser, currentProject, file, C_ACCESS_PUBLIC_WRITE) || accessOwner(currentUser, currentProject, file, C_ACCESS_OWNER_WRITE) || accessGroup(currentUser, currentProject, file, C_ACCESS_GROUP_WRITE) )){ // write-acces was granted - copy the file and the metainfos m_dbAccess.copyFile(currentProject, onlineProject(currentUser, currentProject), currentUser.getId(),source,cmsFolder.getResourceId(), foldername + filename); // copy the metainfos lockResource(currentUser, currentProject, destination, true); writeProperties(currentUser,currentProject, destination, readAllProperties(currentUser,currentProject,file.getResourceName())); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(file.isFolder()); } else { throw new CmsException("[" + this.getClass().getName() + "] " + source, CmsException.C_NO_ACCESS); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + destination, CmsException.C_NO_ACCESS); } } /** * Copies a folder in the Cms. <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the sourceresource</li> * <li>the user can create the destinationresource</li> * <li>the destinationresource dosn't exists</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param source The complete path of the sourcefolder. * @param destination The complete path to the destination. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void copyFolder(CmsUser currentUser, CmsProject currentProject, String source, String destination) throws CmsException { // the name of the new file. String filename; // the name of the folder. String foldername; // checks, if the destinateion is valid, if not it throws a exception validFilename(destination.replace('/', 'a')); foldername = destination.substring(0, destination.substring(0,destination.length()-1).lastIndexOf("/")+1); CmsFolder cmsFolder = readFolder(currentUser,currentProject, foldername); if( accessCreate(currentUser, currentProject, (CmsResource)cmsFolder) ) { // write-acces was granted - copy the folder and the properties CmsFolder folder=readFolder(currentUser,currentProject,source); // check write access to the folder that has to be copied if(( accessOther(currentUser, currentProject, (CmsResource)folder, C_ACCESS_PUBLIC_WRITE) || accessOwner(currentUser, currentProject, (CmsResource)folder, C_ACCESS_OWNER_WRITE) || accessGroup(currentUser, currentProject, (CmsResource)folder, C_ACCESS_GROUP_WRITE) )){ m_dbAccess.createFolder(currentUser,currentProject,onlineProject(currentUser, currentProject),folder,cmsFolder.getResourceId(),destination); // copy the properties lockResource(currentUser, currentProject, destination, true); writeProperties(currentUser,currentProject, destination, readAllProperties(currentUser,currentProject,folder.getResourceName())); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(true); } else { throw new CmsException("[" + this.getClass().getName() + "] " + source, CmsException.C_ACCESS_DENIED); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + destination, CmsException.C_ACCESS_DENIED); } } /** * Copies a resource from the online project to a new, specified project.<br> * Copying a resource will copy the file header or folder into the specified * offline project and set its state to UNCHANGED. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user is the owner of the project</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource. * @exception CmsException Throws CmsException if operation was not succesful. */ public void copyResourceToProject(CmsUser currentUser, CmsProject currentProject, String resource) throws CmsException { // read the onlineproject CmsProject online = onlineProject(currentUser, currentProject); // is the current project the onlineproject? // and is the current user the owner of the project? // and is the current project state UNLOCKED? if ((!currentProject.equals(online)) && (isManagerOfProject(currentUser, currentProject)) && (currentProject.getFlags() == C_PROJECT_STATE_UNLOCKED)) { // is offlineproject and is owner // try to read the resource from the offline project, include deleted CmsResource offlineRes = null; try{ m_resourceCache.remove(resource); Vector subFiles = getFilesInFolder(currentUser, currentProject, resource, true); Vector subFolders = getSubFolders(currentUser, currentProject, resource, true); for(int i=0; i<subFolders.size(); i++){ String foldername = ((CmsResource)subFolders.elementAt(i)).getResourceName(); m_resourceCache.remove(foldername); } for(int i=0; i<subFiles.size(); i++){ String filename = ((CmsResource)subFiles.elementAt(i)).getResourceName(); m_resourceCache.remove(filename); } m_subresCache.clear(); m_accessCache.clear(); offlineRes = readFileHeader(currentUser, currentProject, currentProject.getId(),resource); } catch (CmsException exc){ // if the resource does not exist in the offlineProject - it's ok } // create the projectresource only if the resource is not in the current project if ((offlineRes == null) || (offlineRes.getProjectId() != currentProject.getId())){ // check if there are already any subfolders of this resource if(resource.endsWith("/")){ Vector projectResources = m_dbAccess.readAllProjectResources(currentProject.getId()); for(int i=0; i<projectResources.size(); i++){ String resname = (String)projectResources.elementAt(i); if(resname.startsWith(resource)){ // delete the existing project resource first m_dbAccess.deleteProjectResource(currentProject.getId(), resname); } } } try { m_dbAccess.createProjectResource(currentProject.getId(), resource); } catch (CmsException exc) { // if the subfolder exists already - all is ok } } } else { // no changes on the onlineproject! throw new CmsException("[" + this.getClass().getName() + "] " + currentProject.getName(), CmsException.C_NO_ACCESS); } } /** * Counts the locked resources in this project. * * <B>Security</B> * Only the admin or the owner of the project can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id of the project * @return the amount of locked resources in this project. * * @exception CmsException Throws CmsException if something goes wrong. */ public int countLockedResources(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { // read the project. CmsProject project = readProject(currentUser, currentProject, id); // check the security if( isAdmin(currentUser, currentProject) || isManagerOfProject(currentUser, project) || (project.getFlags() == C_PROJECT_STATE_UNLOCKED )) { // count locks return m_dbAccess.countLockedResources(project); } else { throw new CmsException("[" + this.getClass().getName() + "] " + id, CmsException.C_NO_ACCESS); } } /** * return the correct DbAccess class. * This method should be overloaded by all other Database Drivers * Creation date: (09/15/00 %r) * @return com.opencms.file.genericSql.CmsDbAccess * @param configurations source.org.apache.java.util.Configurations * @exception com.opencms.core.CmsException Thrown if CmsDbAccess class could not be instantiated. */ public com.opencms.file.genericSql.CmsDbAccess createDbAccess(Configurations configurations) throws CmsException { return new com.opencms.file.genericSql.CmsDbAccess(configurations); } /** * Creates a new file with the given content and resourcetype. <br> * * Files can only be created in an offline project, the state of the new file * is set to NEW (2). <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the folder-resource is not locked by another user</li> * <li>the file dosn't exists</li> * </ul> * * @param currentUser The user who owns this file. * @param currentGroup The group who owns this file. * @param currentProject The project in which the resource will be used. * @param folder The complete path to the folder in which the new folder will * be created. * @param file The name of the new file (No pathinformation allowed). * @param contents The contents of the new file. * @param type The name of the resourcetype of the new file. * @param propertyinfos A Hashtable of propertyinfos, that should be set for this folder. * The keys for this Hashtable are the names for propertydefinitions, the values are * the values for the propertyinfos. * @return file The created file. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsFile createFile(CmsUser currentUser, CmsGroup currentGroup, CmsProject currentProject, String folder, String filename, byte[] contents, String type, Hashtable propertyinfos) throws CmsException { // checks, if the filename is valid, if not it throws a exception validFilename(filename); CmsFolder cmsFolder = readFolder(currentUser,currentProject, folder); if( accessCreate(currentUser, currentProject, (CmsResource)cmsFolder) ) { // write-access was granted - create and return the file. CmsFile file = m_dbAccess.createFile(currentUser, currentProject, onlineProject(currentUser, currentProject), folder + filename, 0, cmsFolder.getResourceId(), contents, getResourceType(currentUser, currentProject, type)); // update the access flags Hashtable startSettings=null; Integer accessFlags=null; startSettings=(Hashtable)currentUser.getAdditionalInfo(C_ADDITIONAL_INFO_STARTSETTINGS); if (startSettings != null) { accessFlags=(Integer)startSettings.get(C_START_ACCESSFLAGS); if (accessFlags != null) { file.setAccessFlags(accessFlags.intValue()); } } if(currentGroup != null) { file.setGroupId(currentGroup.getId()); } m_dbAccess.writeFileHeader(currentProject, file,false); m_subresCache.clear(); // write the metainfos m_dbAccess.writeProperties(propertyinfos, currentProject.getId(),file, file.getType()); // inform about the file-system-change fileSystemChanged(false); return file ; } else { throw new CmsException("[" + this.getClass().getName() + "] " + folder + filename, CmsException.C_NO_ACCESS); } } /** * Creates a new folder. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is not locked by another user</li> * </ul> * * @param currentUser The user who requested this method. * @param currentGroup The group who requested this method. * @param currentProject The current project of the user. * @param folder The complete path to the folder in which the new folder will * be created. * @param newFolderName The name of the new folder (No pathinformation allowed). * @param propertyinfos A Hashtable of propertyinfos, that should be set for this folder. * The keys for this Hashtable are the names for propertydefinitions, the values are * the values for the propertyinfos. * * @return file The created file. * * @exception CmsException will be thrown for missing propertyinfos, for worng propertydefs * or if the filename is not valid. The CmsException will also be thrown, if the * user has not the rights for this resource. */ public CmsFolder createFolder(CmsUser currentUser, CmsGroup currentGroup, CmsProject currentProject, String folder, String newFolderName, Hashtable propertyinfos) throws CmsException { // checks, if the filename is valid, if not it throws a exception validFilename(newFolderName); CmsFolder cmsFolder = readFolder(currentUser,currentProject, folder); if( accessCreate(currentUser, currentProject, (CmsResource)cmsFolder) ) { // write-acces was granted - create the folder. CmsFolder newFolder = m_dbAccess.createFolder(currentUser, currentProject, cmsFolder.getResourceId(), C_UNKNOWN_ID, folder + newFolderName + C_FOLDER_SEPERATOR, 0); // update the access flags Hashtable startSettings=null; Integer accessFlags=null; startSettings=(Hashtable)currentUser.getAdditionalInfo(C_ADDITIONAL_INFO_STARTSETTINGS); if (startSettings != null) { accessFlags=(Integer)startSettings.get(C_START_ACCESSFLAGS); if (accessFlags != null) { newFolder.setAccessFlags(accessFlags.intValue()); } } if(currentGroup != null) { newFolder.setGroupId(currentGroup.getId()); } newFolder.setState(C_STATE_NEW); m_dbAccess.writeFolder(currentProject, newFolder, false); m_subresCache.clear(); // write metainfos for the folder m_dbAccess.writeProperties(propertyinfos, currentProject.getId(), newFolder, newFolder.getType()); // inform about the file-system-change fileSystemChanged(true); // return the folder return newFolder ; } else { throw new CmsException("[" + this.getClass().getName() + "] " + folder + newFolderName, CmsException.C_NO_ACCESS); } } /** * Creates a project. * * <B>Security</B> * Only the users which are in the admin or projectleader-group are granted. * * Changed: added the parent id * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name of the project to read. * @param description The description for the new project. * @param group the group to be set. * @param managergroup the managergroup to be set. * @param parentId the parent project * @exception CmsException Throws CmsException if something goes wrong. * @author Martin Langelund */ public CmsProject createProject(CmsUser currentUser, CmsProject currentProject, String name, String description, String groupname, String managergroupname) throws CmsException { if (isAdmin(currentUser, currentProject) || isProjectManager(currentUser, currentProject)) { if (C_PROJECT_ONLINE.equals(name)){ throw new CmsException ("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME); } // read the needed groups from the cms CmsGroup group = readGroup(currentUser, currentProject, groupname); CmsGroup managergroup = readGroup(currentUser, currentProject, managergroupname); // create a new task for the project CmsTask task = createProject(currentUser, name, 1, group.getName(), System.currentTimeMillis(), C_TASK_PRIORITY_NORMAL); return m_dbAccess.createProject(currentUser, group, managergroup, task, name, description, C_PROJECT_STATE_UNLOCKED, C_PROJECT_TYPE_NORMAL); } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } /** * Creates a project. * * <B>Security</B> * Only the users which are in the admin or projectleader-group are granted. * * Changed: added the project type * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name of the project to read. * @param description The description for the new project. * @param group the group to be set. * @param managergroup the managergroup to be set. * @param project type the type of the project * @exception CmsException Throws CmsException if something goes wrong. * @author Edna Falkenhan */ public CmsProject createProject(CmsUser currentUser, CmsProject currentProject, String name, String description, String groupname, String managergroupname, int projecttype) throws CmsException { if (isAdmin(currentUser, currentProject) || isProjectManager(currentUser, currentProject)) { if (C_PROJECT_ONLINE.equals(name)){ throw new CmsException ("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME); } // read the needed groups from the cms CmsGroup group = readGroup(currentUser, currentProject, groupname); CmsGroup managergroup = readGroup(currentUser, currentProject, managergroupname); // create a new task for the project CmsTask task = createProject(currentUser, name, 1, group.getName(), System.currentTimeMillis(), C_TASK_PRIORITY_NORMAL); return m_dbAccess.createProject(currentUser, group, managergroup, task, name, description, C_PROJECT_STATE_UNLOCKED, projecttype); } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } /** * Creates a project for the temporary files. * * <B>Security</B> * Only the users which are in the admin or projectleader-group are granted. * * Changed: added the project type * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @exception CmsException Throws CmsException if something goes wrong. * @author Edna Falkenhan */ public CmsProject createTempfileProject(CmsObject cms, CmsUser currentUser, CmsProject currentProject) throws CmsException { String name = "tempFileProject"; String description = "Project for temporary files"; if (isAdmin(currentUser, currentProject)) { // read the needed groups from the cms CmsGroup group = readGroup(currentUser, currentProject, "Users"); CmsGroup managergroup = readGroup(currentUser, currentProject, "Administrators"); // create a new task for the project CmsTask task = createProject(currentUser, name, 1, group.getName(), System.currentTimeMillis(), C_TASK_PRIORITY_NORMAL); CmsProject tempProject = m_dbAccess.createProject(currentUser, group, managergroup, task, name, description, C_PROJECT_STATE_INVISIBLE, C_PROJECT_STATE_INVISIBLE); m_dbAccess.createProjectResource(tempProject.getId(), "/"); cms.getRegistry().setSystemValue("tempfileproject",""+tempProject.getId()); return tempProject; } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } /** * Creates a new project for task handling. * * @param currentUser User who creates the project * @param projectName Name of the project * @param projectType Type of the Project * @param role Usergroup for the project * @param timeout Time when the Project must finished * @param priority Priority for the Project * * @return The new task project * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsTask createProject(CmsUser currentUser, String projectName, int projectType, String roleName, long timeout, int priority) throws CmsException { CmsGroup role = null; // read the role if(roleName!=null && !roleName.equals("")) { role = readGroup(currentUser, null, roleName); } // create the timestamp java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout); java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis()); return m_dbAccess.createTask(0,0, 1, // standart project type, currentUser.getId(), currentUser.getId(), role.getId(), projectName, now, timestamp, priority); } // Methods working with properties and propertydefinitions /** * Creates the propertydefinition for the resource type.<BR/> * * <B>Security</B> * Only the admin can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name of the propertydefinition to overwrite. * @param resourcetype The name of the resource-type for the propertydefinition. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsPropertydefinition createPropertydefinition(CmsUser currentUser, CmsProject currentProject, String name, String resourcetype) throws CmsException { // check the security if( isAdmin(currentUser, currentProject) ) { // no space before or after the name name = name.trim(); // check the name validFilename(name); m_propertyDefVectorCache.clear(); return( m_dbAccess.createPropertydefinition(name, getResourceType(currentUser, currentProject, resourcetype)) ); } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } /** * Creates a new task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param projectid The Id of the current project task of the user. * @param agentName User who will edit the task * @param roleName Usergroup for the task * @param taskName Name of the task * @param taskType Type of the task * @param taskComment Description of the task * @param timeout Time when the task must finished * @param priority Id for the priority * * @return A new Task Object * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsTask createTask(CmsUser currentUser, int projectid, String agentName, String roleName, String taskName, String taskComment, int taskType, long timeout, int priority) throws CmsException { CmsUser agent = m_dbAccess.readUser(agentName, C_USER_TYPE_SYSTEMUSER); CmsGroup role = m_dbAccess.readGroup(roleName); java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout); java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis()); validTaskname(taskName); // check for valid Filename CmsTask task = m_dbAccess.createTask(projectid, projectid, taskType, currentUser.getId(), agent.getId(), role.getId(), taskName, now, timestamp, priority); if(taskComment!=null && !taskComment.equals("")) { m_dbAccess.writeTaskLog(task.getId(), currentUser.getId(), new java.sql.Timestamp(System.currentTimeMillis()), taskComment, C_TASKLOG_USER); } return task; } /** * Creates a new task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param agent Username who will edit the task * @param role Usergroupname for the task * @param taskname Name of the task * @param taskcomment Description of the task. * @param timeout Time when the task must finished * @param priority Id for the priority * * @return A new Task Object * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsTask createTask(CmsUser currentUser, CmsProject currentProject, String agentName, String roleName, String taskname, String taskcomment, long timeout, int priority) throws CmsException { CmsGroup role = m_dbAccess.readGroup(roleName); java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout); java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis()); int agentId = C_UNKNOWN_ID; validTaskname(taskname); // check for valid Filename try { agentId = m_dbAccess.readUser(agentName, C_USER_TYPE_SYSTEMUSER).getId(); } catch (Exception e) { // ignore that this user doesn't exist and create a task for the role } return m_dbAccess.createTask(currentProject.getTaskId(), currentProject.getTaskId(), 1, // standart Task Type currentUser.getId(), agentId, role.getId(), taskname, now, timestamp, priority); } /** * Deletes all propertyinformation for a file or folder. * * <B>Security</B> * Only the user is granted, who has the right to write the resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource of which the propertyinformations * have to be deleted. * * @exception CmsException Throws CmsException if operation was not succesful */ public void deleteAllProperties(CmsUser currentUser, CmsProject currentProject, String resource) throws CmsException { // read the resource CmsResource res = readFileHeader(currentUser,currentProject, resource); // check the security if( ! accessWrite(currentUser, currentProject, res) ) { throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_NO_ACCESS); } //delete all Properties m_dbAccess.deleteAllProperties(currentProject.getId(),res); m_propertyCache.clear(); } /** * Deletes a file in the Cms.<br> * * A file can only be deleteed in an offline project. * A file is deleted by setting its state to DELETED (3). <br> * * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is locked by the callinUser</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The complete path of the file. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void deleteFile(CmsUser currentUser, CmsProject currentProject, String filename) throws CmsException { // read the file CmsResource onlineFile; CmsResource file = readFileHeader(currentUser,currentProject, filename); try { onlineFile = readFileHeader(currentUser,onlineProject(currentUser, currentProject), filename); } catch (CmsException exc) { // the file dosent exist onlineFile = null; } // has the user write-access? if( accessWrite(currentUser, currentProject, file) ) { // write-acces was granted - delete the file. // and the metainfos if(onlineFile == null) { // the onlinefile dosent exist => remove the file realy! deleteAllProperties(currentUser,currentProject,file.getResourceName()); m_dbAccess.removeFile(currentProject.getId(), filename); } else { m_dbAccess.deleteFile(currentProject, filename); } // update the cache m_resourceCache.remove(filename); m_subresCache.clear(); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { if(file.getState() == C_STATE_DELETED){ throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_RESOURCE_DELETED); } throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS); } } /** * Deletes a folder in the Cms.<br> * * Only folders in an offline Project can be deleted. A folder is deleted by * setting its state to DELETED (3). <br> * * In its current implmentation, this method can ONLY delete empty folders. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read and write this resource and all subresources</li> * <li>the resource is not locked</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername The complete path of the folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void deleteFolder(CmsUser currentUser, CmsProject currentProject, String foldername) throws CmsException { CmsResource onlineFolder; // read the folder, that shold be deleted CmsFolder cmsFolder = readFolder(currentUser,currentProject,foldername); try { onlineFolder = readFolder(currentUser,onlineProject(currentUser, currentProject), foldername); } catch (CmsException exc) { // the file dosent exist onlineFolder = null; } // check, if the user may delete the resource if( accessWrite(currentUser, currentProject, cmsFolder) ) { // write-acces was granted - delete the folder and metainfos. if(onlineFolder == null) { // the onlinefile dosent exist => remove the file realy! deleteAllProperties(currentUser,currentProject, cmsFolder.getResourceName()); m_dbAccess.removeFolder(currentProject.getId(),cmsFolder); } else { m_dbAccess.deleteFolder(currentProject,cmsFolder, false); } // update cache m_resourceCache.remove(foldername); m_subresCache.clear(); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(true); } else { throw new CmsException("[" + this.getClass().getName() + "] " + foldername, CmsException.C_NO_ACCESS); } } /** * Undeletes a file in the Cms.<br> * * A file can only be undeleted in an offline project. * A file is undeleted by setting its state to CHANGED (1). <br> * * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is locked by the callinUser</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The complete path of the file. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void undeleteResource(CmsUser currentUser, CmsProject currentProject, String filename) throws CmsException { boolean isFolder=false; CmsResource resource=null; int state = C_STATE_CHANGED; // read the resource to check the access if (filename.endsWith("/")) { isFolder=true; resource = m_dbAccess.readFolder(currentProject.getId(),filename); } else { resource = (CmsFile)m_dbAccess.readFileHeader(currentProject.getId(),filename, true); } // has the user write-access? if( accessWriteUnlocked(currentUser, currentProject, resource)) { resource.setState(state); resource.setLocked(currentUser.getId()); // write-access was granted - write the file. if (filename.endsWith("/")) { m_dbAccess.writeFolder(currentProject,(CmsFolder)resource,false, currentUser.getId()); // update the cache m_resourceCache.remove(filename); } else { m_dbAccess.writeFileHeader(currentProject,(CmsFile)resource,false, currentUser.getId()); // update the cache m_resourceCache.remove(filename); } m_subresCache.clear(); // inform about the file-system-change fileSystemChanged(isFolder); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS); } } /** * Delete a group from the Cms.<BR/> * Only groups that contain no subgroups can be deleted. * * Only the admin can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param delgroup The name of the group that is to be deleted. * @exception CmsException Throws CmsException if operation was not succesfull. */ public void deleteGroup(CmsUser currentUser, CmsProject currentProject, String delgroup) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) ) { Vector childs=null; Vector users=null; // get all child groups of the group childs=getChild(currentUser,currentProject,delgroup); // get all users in this group users=getUsersOfGroup(currentUser,currentProject,delgroup); // delete group only if it has no childs and there are no users in this group. if ((childs == null) && ((users == null) || (users.size() == 0))) { m_dbAccess.deleteGroup(delgroup); m_groupCache.remove(delgroup); } else { throw new CmsException(delgroup, CmsException.C_GROUP_NOT_EMPTY); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + delgroup, CmsException.C_NO_ACCESS); } } /** * Deletes a project. * * <B>Security</B> * Only the admin or the owner of the project can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id of the project to be published. * * @exception CmsException Throws CmsException if something goes wrong. */ public void deleteProject(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { Vector deletedFolders = new Vector(); // read the project that should be deleted. CmsProject deleteProject = readProject(currentUser, currentProject, id); if((isAdmin(currentUser, currentProject) || isManagerOfProject(currentUser, deleteProject)) && (id != C_PROJECT_ONLINE_ID)) { Vector allFiles = m_dbAccess.readFiles(deleteProject.getId(), false, true); Vector allFolders = m_dbAccess.readFolders(deleteProject.getId(), false, true); // first delete files or undo changes in files for(int i=0; i<allFiles.size();i++){ CmsFile currentFile = (CmsFile)allFiles.elementAt(i); if(currentFile.getState() == C_STATE_NEW){ // delete the properties m_dbAccess.deleteAllProperties(id, currentFile.getResourceId()); // delete the file m_dbAccess.removeFile(id, currentFile.getResourceName()); } else if (currentFile.getState() == C_STATE_CHANGED){ if(!currentFile.isLocked()){ // lock the resource lockResource(currentUser,deleteProject,currentFile.getResourceName(),true); } // undo all changes in the file undoChanges(currentUser, deleteProject, currentFile.getResourceName()); } else if (currentFile.getState() == C_STATE_DELETED){ // first undelete the file undeleteResource(currentUser, deleteProject, currentFile.getResourceName()); if(!currentFile.isLocked()){ // lock the resource lockResource(currentUser,deleteProject,currentFile.getResourceName(),true); } // then undo all changes in the file undoChanges(currentUser, deleteProject, currentFile.getResourceName()); } } // now delete folders or undo changes in folders for(int i=0; i<allFolders.size();i++){ CmsFolder currentFolder = (CmsFolder)allFolders.elementAt(i); if(currentFolder.getState() == C_STATE_NEW){ // delete the properties m_dbAccess.deleteAllProperties(id, currentFolder.getResourceId()); // add the folder to the vector of folders that has to be deleted deletedFolders.addElement(currentFolder); } else if (currentFolder.getState() == C_STATE_CHANGED){ if(!currentFolder.isLocked()){ // lock the resource lockResource(currentUser,deleteProject,currentFolder.getResourceName(),true); } // undo all changes in the folder undoChanges(currentUser, deleteProject, currentFolder.getResourceName()); } else if (currentFolder.getState() == C_STATE_DELETED){ // undelete the folder undeleteResource(currentUser, deleteProject, currentFolder.getResourceName()); if(!currentFolder.isLocked()){ // lock the resource lockResource(currentUser,deleteProject,currentFolder.getResourceName(),true); } // then undo all changes in the folder undoChanges(currentUser, deleteProject, currentFolder.getResourceName()); } } // now delete the folders in the vector for (int i = deletedFolders.size() - 1; i > -1; i--){ CmsFolder delFolder = ((CmsFolder) deletedFolders.elementAt(i)); m_dbAccess.removeFolder(id, delFolder); } // unlock all resources in the project m_dbAccess.unlockProject(deleteProject); m_resourceCache.clear(); //m_projectCache.clear(); // delete the project m_dbAccess.deleteProject(deleteProject); m_projectCache.remove(id); } else { throw new CmsException("[" + this.getClass().getName() + "] " + id, CmsException.C_NO_ACCESS); } } /** * Deletes a propertyinformation for a file or folder. * * <B>Security</B> * Only the user is granted, who has the right to write the resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource of which the propertyinformation * has to be read. * @param property The propertydefinition-name of which the propertyinformation has to be set. * * @exception CmsException Throws CmsException if operation was not succesful */ public void deleteProperty(CmsUser currentUser, CmsProject currentProject, String resource, String property) throws CmsException { // read the resource CmsResource res = readFileHeader(currentUser,currentProject, resource); // check the security if( ! accessWrite(currentUser, currentProject, res) ) { throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_NO_ACCESS); } // read the metadefinition I_CmsResourceType resType = getResourceType(currentUser,currentProject,res.getType()); CmsPropertydefinition metadef = readPropertydefinition(currentUser,currentProject,property, resType.getResourceTypeName()); if( (metadef != null) ) { m_dbAccess.deleteProperty(property,currentProject.getId(),res,res.getType()); // set the file-state to changed if(res.isFile()){ m_dbAccess.writeFileHeader(currentProject, (CmsFile) res, true, currentUser.getId()); if (res.getState()==C_STATE_UNCHANGED) { res.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.remove(resource); } else { if (res.getState()==C_STATE_UNCHANGED) { res.setState(C_STATE_CHANGED); } m_dbAccess.writeFolder(currentProject, readFolder(currentUser,currentProject, resource), true, currentUser.getId()); // update the cache m_resourceCache.remove(resource); } m_subresCache.clear(); m_propertyCache.clear(); } else { // yes - throw exception throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_UNKNOWN_EXCEPTION); } } /** * Delete the propertydefinition for the resource type.<BR/> * * <B>Security</B> * Only the admin can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name of the propertydefinition to read. * @param resourcetype The name of the resource type for which the * propertydefinition is valid. * * @exception CmsException Throws CmsException if something goes wrong. */ public void deletePropertydefinition(CmsUser currentUser, CmsProject currentProject, String name, String resourcetype) throws CmsException { // check the security if( isAdmin(currentUser, currentProject) ) { // first read and then delete the metadefinition. m_propertyDefVectorCache.clear(); m_propertyDefCache.remove(name + (getResourceType(currentUser,currentProject,resourcetype)).getResourceType()); m_dbAccess.deletePropertydefinition( readPropertydefinition(currentUser,currentProject,name,resourcetype)); } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } /** * Deletes a user from the Cms. * * Only a adminstrator can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param userId The Id of the user to be deleted. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void deleteUser(CmsUser currentUser, CmsProject currentProject, int userId) throws CmsException { CmsUser user = readUser(currentUser,currentProject,userId); deleteUser(currentUser,currentProject,user.getName()); } /** * Deletes a user from the Cms. * * Only a adminstrator can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name of the user to be deleted. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void deleteUser(CmsUser currentUser, CmsProject currentProject, String username) throws CmsException { // Test is this user is existing CmsUser user=readUser(currentUser,currentProject,username); // Check the security // Avoid to delete admin or guest-user if( isAdmin(currentUser, currentProject) && !(username.equals(C_USER_ADMIN) || username.equals(C_USER_GUEST))) { m_dbAccess.deleteUser(username); // delete user from cache m_userCache.remove(username+user.getType()); } else { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS); } } /** * Deletes a web user from the Cms. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param userId The Id of the user to be deleted. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void deleteWebUser(CmsUser currentUser, CmsProject currentProject, int userId) throws CmsException { CmsUser user = readUser(currentUser,currentProject,userId); m_dbAccess.deleteUser(user.getName()); // delete user from cache m_userCache.remove(user.getName()+user.getType()); } /** * Destroys the resource broker and required modules and connections. * @exception CmsException Throws CmsException if something goes wrong. */ public void destroy() throws CmsException { // destroy the db-access. m_dbAccess.destroy(); } /** * Ends a task from the Cms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The ID of the task to end. * * @exception CmsException Throws CmsException if something goes wrong. */ public void endTask(CmsUser currentUser, CmsProject currentProject, int taskid) throws CmsException { m_dbAccess.endTask(taskid); if(currentUser == null) { m_dbAccess.writeSystemTaskLog(taskid, "Task finished."); } else { m_dbAccess.writeSystemTaskLog(taskid, "Task finished by " + currentUser.getFirstname() + " " + currentUser.getLastname() + "."); } } /** * Exports cms-resources to zip. * * <B>Security:</B> * only Administrators can do this; * * @param currentUser user who requestd themethod * @param currentProject current project of the user * @param exportFile the name (absolute Path) of the export resource (zip) * @param exportPath the names (absolute Path) of folders and files which should be exported * @param cms the cms-object to use for the export. * * @exception Throws CmsException if something goes wrong. */ public void exportResources(CmsUser currentUser, CmsProject currentProject, String exportFile, String[] exportPaths, CmsObject cms) throws CmsException { if(isAdmin(currentUser, currentProject)) { new CmsExport(exportFile, exportPaths, cms); } else { throw new CmsException("[" + this.getClass().getName() + "] exportResources", CmsException.C_NO_ACCESS); } } /** * Exports cms-resources to zip. * * <B>Security:</B> * only Administrators can do this; * * @param currentUser user who requestd themethod * @param currentProject current project of the user * @param exportFile the name (absolute Path) of the export resource (zip) * @param exportPath the name (absolute Path) of folder from which should be exported * @param excludeSystem, decides whether to exclude the system * @param excludeUnchanged <code>true</code>, if unchanged files should be excluded. * @param cms the cms-object to use for the export. * * @exception Throws CmsException if something goes wrong. */ public void exportResources(CmsUser currentUser, CmsProject currentProject, String exportFile, String[] exportPaths, CmsObject cms, boolean excludeSystem, boolean excludeUnchanged) throws CmsException { if(isAdmin(currentUser, currentProject)) { new CmsExport(exportFile, exportPaths, cms, excludeSystem, excludeUnchanged); } else { throw new CmsException("[" + this.getClass().getName() + "] exportResources", CmsException.C_NO_ACCESS); } } /** * Exports cms-resources to zip. * * <B>Security:</B> * only Administrators can do this; * * @param currentUser user who requestd themethod * @param currentProject current project of the user * @param exportFile the name (absolute Path) of the export resource (zip) * @param exportPath the name (absolute Path) of folder from which should be exported * @param excludeSystem, decides whether to exclude the system * @param excludeUnchanged <code>true</code>, if unchanged files should be excluded. * @param cms the cms-object to use for the export. * * @exception Throws CmsException if something goes wrong. */ public void exportResources(CmsUser currentUser, CmsProject currentProject, String exportFile, String[] exportPaths, CmsObject cms, boolean excludeSystem, boolean excludeUnchanged, boolean exportUserdata) throws CmsException { if(isAdmin(currentUser, currentProject)) { new CmsExport(exportFile, exportPaths, cms, excludeSystem, excludeUnchanged, null, exportUserdata); } else { throw new CmsException("[" + this.getClass().getName() + "] exportResources", CmsException.C_NO_ACCESS); } } // now private stuff /** * This method is called, when a resource was changed. Currently it counts the * changes. */ protected void fileSystemChanged(boolean folderChanged) { // count only the changes - do nothing else! // in the future here will maybe a event-story be added m_fileSystemChanges++; if(folderChanged){ m_fileSystemFolderChanges++; } } /** * Forwards a task to a new user. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task to forward. * @param newRole The new Group for the task * @param newUser The new user who gets the task. if its "" the a new agent will automatic selected * * @exception CmsException Throws CmsException if something goes wrong. */ public void forwardTask(CmsUser currentUser, CmsProject currentProject, int taskid, String newRoleName, String newUserName) throws CmsException { CmsGroup newRole = m_dbAccess.readGroup(newRoleName); CmsUser newUser = null; if(newUserName.equals("")) { newUser = m_dbAccess.readUser(m_dbAccess.findAgent(newRole.getId())); } else { newUser = m_dbAccess.readUser(newUserName, C_USER_TYPE_SYSTEMUSER); } m_dbAccess.forwardTask(taskid, newRole.getId(), newUser.getId()); m_dbAccess.writeSystemTaskLog(taskid, "Task fowarded from " + currentUser.getFirstname() + " " + currentUser.getLastname() + " to " + newUser.getFirstname() + " " + newUser.getLastname() + "."); } /** * Returns all projects, which are owned by the user or which are accessible * for the group of the user. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * @return a Vector of projects. */ public Vector getAllAccessibleProjects(CmsUser currentUser, CmsProject currentProject) throws CmsException { // get all groups of the user Vector groups = getGroupsOfUser(currentUser, currentProject, currentUser.getName()); // get all projects which are owned by the user. Vector projects = m_dbAccess.getAllAccessibleProjectsByUser(currentUser); // get all projects, that the user can access with his groups. for(int i = 0; i < groups.size(); i++) { Vector projectsByGroup; // is this the admin-group? if( ((CmsGroup) groups.elementAt(i)).getName().equals(C_GROUP_ADMIN) ) { // yes - all unlocked projects are accessible for him projectsByGroup = m_dbAccess.getAllProjects(C_PROJECT_STATE_UNLOCKED); } else { // no - get all projects, which can be accessed by the current group projectsByGroup = m_dbAccess.getAllAccessibleProjectsByGroup((CmsGroup) groups.elementAt(i)); } // merge the projects to the vector for(int j = 0; j < projectsByGroup.size(); j++) { // add only projects, which are new if(!projects.contains(projectsByGroup.elementAt(j))) { projects.addElement(projectsByGroup.elementAt(j)); } } } // return the vector of projects return(projects); } /** * Returns all projects, which are owned by the user or which are manageable * for the group of the user. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * @return a Vector of projects. */ public Vector getAllManageableProjects(CmsUser currentUser, CmsProject currentProject) throws CmsException { // get all groups of the user Vector groups = getGroupsOfUser(currentUser, currentProject, currentUser.getName()); // get all projects which are owned by the user. Vector projects = m_dbAccess.getAllAccessibleProjectsByUser(currentUser); // get all projects, that the user can manage with his groups. for(int i = 0; i < groups.size(); i++) { // get all projects, which can be managed by the current group Vector projectsByGroup; // is this the admin-group? if( ((CmsGroup) groups.elementAt(i)).getName().equals(C_GROUP_ADMIN) ) { // yes - all unlocked projects are accessible for him projectsByGroup = m_dbAccess.getAllProjects(C_PROJECT_STATE_UNLOCKED); } else { // no - get all projects, which can be accessed by the current group projectsByGroup = m_dbAccess.getAllAccessibleProjectsByManagerGroup((CmsGroup)groups.elementAt(i)); } // merge the projects to the vector for(int j = 0; j < projectsByGroup.size(); j++) { // add only projects, which are new if(!projects.contains(projectsByGroup.elementAt(j))) { projects.addElement(projectsByGroup.elementAt(j)); } } } // remove the online-project, it is not manageable! projects.removeElement(onlineProject(currentUser, currentProject)); // return the vector of projects return(projects); } /** * Returns a Vector with all projects from history * * @return Vector with all projects from history. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getAllBackupProjects() throws CmsException{ Vector projects = new Vector(); projects = m_dbAccess.getAllBackupProjects(); return projects; } /** * Returns a Vector with all I_CmsResourceTypes. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * Returns a Hashtable with all I_CmsResourceTypes. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Hashtable getAllResourceTypes(CmsUser currentUser, CmsProject currentProject) throws CmsException { // check, if the resourceTypes were read bevore if(m_resourceTypes == null) { // get the resourceTypes from the registry m_resourceTypes = new Hashtable(); Vector resTypeNames = new Vector(); Vector launcherTypes = new Vector(); Vector launcherClass = new Vector(); Vector resourceClass = new Vector(); int resTypeCount = m_registry.getResourceTypes(resTypeNames, launcherTypes, launcherClass, resourceClass); for (int i = 0; i < resTypeCount; i++){ // add the resource-type try{ Class c = Class.forName((String)resourceClass.elementAt(i)); I_CmsResourceType resTypeClass = (I_CmsResourceType) c.newInstance(); resTypeClass.init(i, Integer.parseInt((String)launcherTypes.elementAt(i)), (String)resTypeNames.elementAt(i), (String)launcherClass.elementAt(i)); m_resourceTypes.put((String)resTypeNames.elementAt(i), resTypeClass); }catch(Exception e){ e.printStackTrace(); throw new CmsException("[" + this.getClass().getName() + "] Error while getting ResourceType: " + (String)resTypeNames.elementAt(i) + " from registry ", CmsException.C_UNKNOWN_EXCEPTION ); } } } // return the resource-types. return(m_resourceTypes); } /** * Returns informations about the cache<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @return A hashtable with informations about the cache. */ public Hashtable getCacheInfo() { Hashtable info = new Hashtable(); info.put("UserCache",""+m_userCache.size()); info.put("GroupCache",""+m_groupCache.size()); info.put("UserGroupCache",""+m_usergroupsCache.size()); info.put("ResourceCache",""+m_resourceCache.size()); info.put("SubResourceCache",""+m_subresCache.size()); info.put("ProjectCache",""+m_projectCache.size()); info.put("PropertyCache",""+m_propertyCache.size()); info.put("PropertyDefinitionCache",""+m_propertyDefCache.size()); info.put("PropertyDefinitionVectorCache",""+m_propertyDefVectorCache.size()); info.put("AccessCache",""+m_accessCache.size()); return info; } /** * Returns all child groups of a group<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param groupname The name of the group. * @return groups A Vector of all child groups or null. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getChild(CmsUser currentUser, CmsProject currentProject, String groupname) throws CmsException { // check security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { return m_dbAccess.getChild(groupname); } else { throw new CmsException("[" + this.getClass().getName() + "] " + groupname, CmsException.C_NO_ACCESS); } } /** * Returns all child groups of a group<P/> * This method also returns all sub-child groups of the current group. * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param groupname The name of the group. * @return groups A Vector of all child groups or null. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getChilds(CmsUser currentUser, CmsProject currentProject, String groupname) throws CmsException { // check security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { Vector childs=new Vector(); Vector allChilds=new Vector(); Vector subchilds=new Vector(); CmsGroup group=null; // get all child groups if the user group childs=m_dbAccess.getChild(groupname); if (childs!=null) { allChilds=childs; // now get all subchilds for each group Enumeration enu=childs.elements(); while (enu.hasMoreElements()) { group=(CmsGroup)enu.nextElement(); subchilds=getChilds(currentUser,currentProject,group.getName()); //add the subchilds to the already existing groups Enumeration enusub=subchilds.elements(); while (enusub.hasMoreElements()) { group=(CmsGroup)enusub.nextElement(); allChilds.addElement(group); } } } return allChilds; } else { throw new CmsException("[" + this.getClass().getName() + "] " + groupname, CmsException.C_NO_ACCESS); } } // Method to access the configuration /** * Method to access the configurations of the properties-file. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The Configurations of the properties-file. */ public Configurations getConfigurations(CmsUser currentUser, CmsProject currentProject) { return m_configuration; } /** * Returns the list of groups to which the user directly belongs to<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user. * @return Vector of groups * @exception CmsException Throws CmsException if operation was not succesful */ public Vector getDirectGroupsOfUser(CmsUser currentUser, CmsProject currentProject, String username) throws CmsException { return m_dbAccess.getGroupsOfUser(username); } /** * Returns a Vector with all files of a folder.<br> * * Files of a folder can be read from an offline Project and the online Project.<br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read this resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername the complete path to the folder. * * @return A Vector with all subfiles for the overgiven folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getFilesInFolder(CmsUser currentUser, CmsProject currentProject, String foldername) throws CmsException { return getFilesInFolder(currentUser, currentProject, foldername, false); } /** * Returns a Vector with all files of a folder.<br> * * Files of a folder can be read from an offline Project and the online Project.<br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read this resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername the complete path to the folder. * @param includeDeleted Include the folder if it is deleted * * @return A Vector with all subfiles for the overgiven folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getFilesInFolder(CmsUser currentUser, CmsProject currentProject, String foldername, boolean includeDeleted) throws CmsException { Vector files; // Todo: add caching for getFilesInFolder //files=(Vector)m_subresCache.get(C_FILE+currentProject.getId()+foldername); //if ((files==null) || (files.size()==0)) { // try to get the files in the current project try { files = helperGetFilesInFolder(currentUser, currentProject, foldername, includeDeleted); } catch (CmsException e) { //if access is denied to the folder, dont try to read them from the online project.) if (e.getType() == CmsException.C_ACCESS_DENIED) return new Vector(); //an empty vector. else //can't handle it here. throw e; } //} if (files == null) { //we are not allowed to read the folder (folder deleted) return new Vector(); } Vector onlineFiles = null; if (!currentProject.equals(onlineProject(currentUser, currentProject))) { // this is not the onlineproject, get the files // from the onlineproject, too try { onlineFiles = helperGetFilesInFolder(currentUser, onlineProject(currentUser, currentProject), foldername,includeDeleted); // merge the resources } catch (CmsException exc) { if (exc.getType() != CmsException.C_ACCESS_DENIED) //cant handle it. throw exc; else //access denied. return files; } } //m_subresCache.put(C_FILE+currentProject.getId()+foldername,files); if(onlineFiles == null) //if it was null, the folder was marked deleted -> no files in online project. return files; //m_subresCache.put(C_FILE+currentProject.getId()+foldername,files); return files = mergeResources(files, onlineFiles); } /** * Returns a Vector with all resource-names that have set the given property to the given value. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername the complete path to the folder. * @param propertydef, the name of the propertydefinition to check. * @param property, the value of the property for the resource. * * @return Vector with all names of resources. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getFilesWithProperty(CmsUser currentUser, CmsProject currentProject, String propertyDefinition, String propertyValue) throws CmsException { return m_dbAccess.getFilesWithProperty(currentProject.getId(), propertyDefinition, propertyValue); } /** * This method can be called, to determine if the file-system was changed * in the past. A module can compare its previosly stored number with this * returned number. If they differ, a change was made. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * @return the number of file-system-changes. */ public long getFileSystemChanges(CmsUser currentUser, CmsProject currentProject) { return m_fileSystemChanges; } /** * This method can be called, to determine if the file-system was changed * in the past. A module can compare its previosly stored number with this * returned number. If they differ, a change was made. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * @return the number of file-system-changes. */ public long getFileSystemFolderChanges(CmsUser currentUser, CmsProject currentProject) { return m_fileSystemFolderChanges; } /** * Returns a Vector with the complete folder-tree for this project.<br> * * Subfolders can be read from an offline project and the online project. <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read this resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param rootName The name of the root, e.g. /default/vfs * @return subfolders A Vector with the complete folder-tree for this project. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getFolderTree(CmsUser currentUser, CmsProject currentProject, String rootName) throws CmsException { Vector resources = m_dbAccess.getFolderTree(currentProject.getId(), rootName); Vector retValue = new Vector(resources.size()); String lastcheck = "#"; // just a char that is not valid in a filename //make sure that we have access to all these. for (Enumeration e = resources.elements(); e.hasMoreElements();) { CmsResource res = (CmsResource) e.nextElement(); if (!res.getAbsolutePath().startsWith(lastcheck)) { if (accessOther(currentUser, currentProject, res, C_ACCESS_PUBLIC_READ + C_ACCESS_PUBLIC_VISIBLE) || accessOwner(currentUser, currentProject, res, C_ACCESS_OWNER_READ + C_ACCESS_OWNER_VISIBLE) || accessGroup(currentUser, currentProject, res, C_ACCESS_GROUP_READ + C_ACCESS_GROUP_VISIBLE)) { retValue.addElement(res); } else { lastcheck = res.getAbsolutePath(); } } } return retValue; } /** * Returns all groups<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return users A Vector of all existing groups. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getGroups(CmsUser currentUser, CmsProject currentProject) throws CmsException { // check security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { return m_dbAccess.getGroups(); } else { throw new CmsException("[" + this.getClass().getName() + "] " + currentUser.getName(), CmsException.C_NO_ACCESS); } } /** * Returns a list of groups of a user.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user. * @return Vector of groups * @exception CmsException Throws CmsException if operation was not succesful */ public Vector getGroupsOfUser(CmsUser currentUser, CmsProject currentProject, String username) throws CmsException { Vector allGroups; allGroups=(Vector)m_usergroupsCache.get(C_USER+username); if ((allGroups==null) || (allGroups.size()==0)) { CmsGroup subGroup; CmsGroup group; // get all groups of the user Vector groups=m_dbAccess.getGroupsOfUser(username); allGroups=groups; // now get all childs of the groups Enumeration enu = groups.elements(); while (enu.hasMoreElements()) { group=(CmsGroup)enu.nextElement(); subGroup=getParent(currentUser, currentProject,group.getName()); while(subGroup != null) { // is the subGroup already in the vector? if(!allGroups.contains(subGroup)) { // no! add it allGroups.addElement(subGroup); } // read next sub group subGroup = getParent(currentUser, currentProject,subGroup.getName()); } } m_usergroupsCache.put(C_USER+username,allGroups); } return allGroups; } /** * Checks which Group can read the resource and all the parent folders. * * @param projectid the project to check the permission. * @param res The resource name to be checked. * @return The Group Id of the Group which can read the resource. * null for all Groups and * Admingroup for no Group. */ public String getReadingpermittedGroup(int projectId, String resource) throws CmsException { return m_dbAccess.getReadingpermittedGroup(projectId, resource); } /** * Returns the parent group of a group<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param groupname The name of the group. * @return group The parent group or null. * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsGroup getParent(CmsUser currentUser, CmsProject currentProject, String groupname) throws CmsException { CmsGroup group = readGroup(currentUser, currentProject, groupname); if (group.getParentId() == C_UNKNOWN_ID) { return null; } // try to read from cache CmsGroup parent = (CmsGroup) m_groupCache.get(group.getParentId()); if (parent == null) { parent = m_dbAccess.readGroup(group.getParentId()); m_groupCache.put(group.getParentId(), parent); } return parent; } /** * Returns the parent resource of a resouce. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsResource getParentResource(CmsUser currentUser, CmsProject currentProject, String resourcename) throws CmsException { // TODO: this can maybe done via the new parent id'd CmsResource theResource = readFileHeader(currentUser, currentProject, resourcename); String parentresourceName = theResource.getRootName()+theResource.getParent(); return readFileHeader(currentUser, currentProject, parentresourceName); } /** * Gets the Registry.<BR/> * * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param cms The actual CmsObject * @exception Throws CmsException if access is not allowed. */ public I_CmsRegistry getRegistry(CmsUser currentUser, CmsProject currentProject, CmsObject cms) throws CmsException { return m_registry.clone(cms); } /** * Returns a Vector with the subresources for a folder.<br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read and view this resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param folder The name of the folder to get the subresources from. * * @return subfolders A Vector with resources. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getResourcesInFolder(CmsUser currentUser, CmsProject currentProject, String folder) throws CmsException { CmsFolder offlineFolder = null; Vector resources = new Vector(); try { offlineFolder = readFolder(currentUser, currentProject, folder); if (offlineFolder.getState() == C_STATE_DELETED) { offlineFolder = null; } } catch (CmsException exc) { // ignore the exception - folder was not found in this project } if (offlineFolder == null) { // the folder is not existent throw new CmsException("[" + this.getClass().getName() + "] " + folder, CmsException.C_NOT_FOUND); } else resources = m_dbAccess.getResourcesInFolder(currentProject.getId(), offlineFolder); Vector retValue = new Vector(resources.size()); //make sure that we have access to all these. for (Enumeration e = resources.elements(); e.hasMoreElements();) { CmsResource res = (CmsResource) e.nextElement(); if (accessOther(currentUser, currentProject, res, C_ACCESS_PUBLIC_READ + C_ACCESS_PUBLIC_VISIBLE) || accessOwner(currentUser, currentProject, res, C_ACCESS_OWNER_READ + C_ACCESS_OWNER_VISIBLE) || accessGroup(currentUser, currentProject, res, C_ACCESS_GROUP_READ + C_ACCESS_GROUP_VISIBLE)) { retValue.addElement(res); } } return retValue; } /** * Returns a Vector with all resources of the given type that have set the given property to the given value. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param propertyDefinition, the name of the propertydefinition to check. * @param propertyValue, the value of the property for the resource. * @param resourceType The resource type of the resource * * @return Vector with all resources. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getResourcesWithProperty(CmsUser currentUser, CmsProject currentProject, String propertyDefinition, String propertyValue, int resourceType) throws CmsException { return m_dbAccess.getResourcesWithProperty(currentProject.getId(), propertyDefinition, propertyValue, resourceType); } /** * Returns a I_CmsResourceType. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resourceType the id of the resourceType to get. * * Returns a I_CmsResourceType. * * @exception CmsException Throws CmsException if operation was not succesful. */ public I_CmsResourceType getResourceType(CmsUser currentUser, CmsProject currentProject, int resourceType) throws CmsException { // try to get the resource-type Hashtable types = getAllResourceTypes(currentUser, currentProject); Enumeration keys = types.keys(); I_CmsResourceType currentType; while(keys.hasMoreElements()) { currentType = (I_CmsResourceType) types.get(keys.nextElement()); if(currentType.getResourceType() == resourceType) { return(currentType); } } // was not found - throw exception throw new CmsException("[" + this.getClass().getName() + "] " + resourceType, CmsException.C_NOT_FOUND); } /** * Returns a I_CmsResourceType. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resourceType the name of the resource to get. * * Returns a I_CmsResourceType. * * @exception CmsException Throws CmsException if operation was not succesful. */ public I_CmsResourceType getResourceType(CmsUser currentUser, CmsProject currentProject, String resourceType) throws CmsException { // try to get the resource-type try { I_CmsResourceType type = (I_CmsResourceType)getAllResourceTypes(currentUser, currentProject).get(resourceType); if(type == null) { throw new CmsException("[" + this.getClass().getName() + "] " + resourceType, CmsException.C_NOT_FOUND); } return type; } catch(NullPointerException exc) { // was not found - throw exception throw new CmsException("[" + this.getClass().getName() + "] " + resourceType, CmsException.C_NOT_FOUND); } } /** * Returns a Vector with all subfolders.<br> * * Subfolders can be read from an offline project and the online project. <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read this resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername the complete path to the folder. * * @return subfolders A Vector with all subfolders for the given folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getSubFolders(CmsUser currentUser, CmsProject currentProject, String foldername) throws CmsException { return getSubFolders(currentUser, currentProject, foldername, false); } /** * Returns a Vector with all subfolders.<br> * * Subfolders can be read from an offline project and the online project. <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read this resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername the complete path to the folder. * @param includeDeleted Include the folder if it is deleted * * @return subfolders A Vector with all subfolders for the given folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getSubFolders(CmsUser currentUser, CmsProject currentProject, String foldername, boolean includeDeleted) throws CmsException { Vector folders = new Vector(); // Todo: add caching for getSubFolders //folders=(Vector)m_subresCache.get(C_FOLDER+currentProject.getId()+foldername); if ((folders==null) || (folders.size()==0)){ folders=new Vector(); // try to get the folders in the current project try { folders = helperGetSubFolders(currentUser, currentProject, foldername); } catch (CmsException exc) { // no folders, ignoring them } if( !currentProject.equals(onlineProject(currentUser, currentProject))) { // this is not the onlineproject, get the files // from the onlineproject, too try { Vector onlineFolders = helperGetSubFolders(currentUser, onlineProject(currentUser, currentProject), foldername); // merge the resources folders = mergeResources(folders, onlineFolders); } catch(CmsException exc) { // no onlinefolders, ignoring them } } //m_subresCache.put(C_FOLDER+currentProject.getId()+foldername,folders); } // return the folders return(folders); } /** * Get a parameter value for a task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskId The Id of the task. * @param parName Name of the parameter. * * @exception CmsException Throws CmsException if something goes wrong. */ public String getTaskPar(CmsUser currentUser, CmsProject currentProject, int taskId, String parName) throws CmsException { return m_dbAccess.getTaskPar(taskId, parName); } /** * Get the template task id fo a given taskname. * * @param taskName Name of the Task * * @return id from the task template * * @exception CmsException Throws CmsException if something goes wrong. */ public int getTaskType(String taskName) throws CmsException { return m_dbAccess.getTaskType(taskName); } /** * Returns all users<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return users A Vector of all existing users. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getUsers(CmsUser currentUser, CmsProject currentProject) throws CmsException { // check security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { return m_dbAccess.getUsers(C_USER_TYPE_SYSTEMUSER); } else { throw new CmsException("[" + this.getClass().getName() + "] " + currentUser.getName(), CmsException.C_NO_ACCESS); } } /** * Returns all users from a given type<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param type The type of the users. * @return users A Vector of all existing users. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getUsers(CmsUser currentUser, CmsProject currentProject, int type) throws CmsException { // check security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { return m_dbAccess.getUsers(type); } else { throw new CmsException("[" + this.getClass().getName() + "] " + currentUser.getName(), CmsException.C_NO_ACCESS); } } /** * Returns all users from a given type that start with a specified string<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param type The type of the users. * @param namestart The filter for the username * @return users A Vector of all existing users. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getUsers(CmsUser currentUser, CmsProject currentProject, int type, String namestart) throws CmsException { // check security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { return m_dbAccess.getUsers(type,namestart); } else { throw new CmsException("[" + this.getClass().getName() + "] " + currentUser.getName(), CmsException.C_NO_ACCESS); } } /** * Returns a list of users in a group.<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param groupname The name of the group to list users from. * @return Vector of users. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getUsersOfGroup(CmsUser currentUser, CmsProject currentProject, String groupname) throws CmsException { // check the security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { return m_dbAccess.getUsersOfGroup(groupname, C_USER_TYPE_SYSTEMUSER); } else { throw new CmsException("[" + this.getClass().getName() + "] " + groupname, CmsException.C_NO_ACCESS); } } /** * Gets all users with a certain Lastname. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param Lastname the start of the users lastname * @param UserType webuser or systemuser * @param UserStatus enabled, disabled * @param wasLoggedIn was the user ever locked in? * @param nMax max number of results * * @return the users. * * @exception CmsException if operation was not successful. */ public Vector getUsersByLastname(CmsUser currentUser, CmsProject currentProject, String Lastname, int UserType, int UserStatus, int wasLoggedIn, int nMax) throws CmsException { // check security if( ! anonymousUser(currentUser, currentProject).equals( currentUser )){ return m_dbAccess.getUsersByLastname(Lastname, UserType, UserStatus, wasLoggedIn, nMax); } else { throw new CmsException( "[" + this.getClass().getName() + "] " + currentUser.getName(), CmsException.C_NO_ACCESS); } } /** * A helper method for this resource-broker. * Returns a Vector with all files of a folder. * The method does not read any files from the parrent folder, * and do also return deleted files. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername the complete path to the folder. * * @return subfiles A Vector with all subfiles for the overgiven folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ protected Vector helperGetFilesInFolder(CmsUser currentUser, CmsProject currentProject, String foldername, boolean includeDeleted) throws CmsException { // get the folder CmsFolder cmsFolder = null; try { cmsFolder = m_dbAccess.readFolder(currentProject.getId(), foldername); } catch(CmsException exc) { if(exc.getType() == exc.C_NOT_FOUND) { // ignore the exception - file dosen't exist in this project return new Vector(); //just an empty vector. } else { throw exc; } } if ((cmsFolder.getState() == I_CmsConstants.C_STATE_DELETED) && (!includeDeleted)) { //indicate that the folder was found, but deleted, and resources are not avaiable. return null; } Vector _files = m_dbAccess.getFilesInFolder(currentProject.getId(),cmsFolder); Vector files = new Vector(_files.size()); //make sure that we have access to all these. for (Enumeration e = _files.elements();e.hasMoreElements();) { CmsFile file = (CmsFile) e.nextElement(); if( accessOther(currentUser, currentProject, (CmsResource)file, C_ACCESS_PUBLIC_READ) || accessOwner(currentUser, currentProject, (CmsResource)file, C_ACCESS_OWNER_READ) || accessGroup(currentUser, currentProject, (CmsResource)file, C_ACCESS_GROUP_READ) ) { files.addElement(file); } } return files; } /** * A helper method for this resource-broker. * Returns a Hashtable with all subfolders.<br> * * Subfolders can be read from an offline project and the online project. <br> * * @param currentUser The user who requested this method. * @param currentProject The current project to read the folders from. * @param foldername the complete path to the folder. * * @return subfolders A Hashtable with all subfolders for the given folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ protected Vector helperGetSubFolders(CmsUser currentUser, CmsProject currentProject, String foldername) throws CmsException{ CmsFolder cmsFolder = m_dbAccess.readFolder(currentProject.getId(),foldername); if( accessRead(currentUser, currentProject, (CmsResource)cmsFolder) ) { // acces to all subfolders was granted - return the sub-folders. Vector folders = m_dbAccess.getSubFolders(currentProject.getId(),cmsFolder); CmsFolder folder; for(int z=0 ; z < folders.size() ; z++) { // read the current folder folder = (CmsFolder)folders.elementAt(z); // check the readability for the folder if( !( accessOther(currentUser, currentProject, (CmsResource)folder, C_ACCESS_PUBLIC_READ) || accessOwner(currentUser, currentProject, (CmsResource)folder, C_ACCESS_OWNER_READ) || accessGroup(currentUser, currentProject, (CmsResource)folder, C_ACCESS_GROUP_READ) ) ) { // access to the folder was not granted delete him folders.removeElementAt(z); // correct the index z--; } } return folders; } else { throw new CmsException("[" + this.getClass().getName() + "] " + foldername, CmsException.C_ACCESS_DENIED); } } /** * Imports a import-resource (folder or zipfile) to the cms. * * <B>Security:</B> * only Administrators can do this; * * @param currentUser user who requestd themethod * @param currentProject current project of the user * @param importFile the name (absolute Path) of the import resource (zip or folder) * @param importPath the name (absolute Path) of folder in which should be imported * @param cms the cms-object to use for the import. * * @exception Throws CmsException if something goes wrong. */ public void importFolder(CmsUser currentUser, CmsProject currentProject, String importFile, String importPath, CmsObject cms) throws CmsException { if(isAdmin(currentUser, currentProject)) { new CmsImportFolder(importFile, importPath, cms); } else { throw new CmsException("[" + this.getClass().getName() + "] importResources", CmsException.C_NO_ACCESS); } } // Methods working with database import and export /** * Imports a import-resource (folder or zipfile) to the cms. * * <B>Security:</B> * only Administrators can do this; * * @param currentUser user who requestd themethod * @param currentProject current project of the user * @param importFile the name (absolute Path) of the import resource (zip or folder) * @param importPath the name (absolute Path) of folder in which should be imported * @param cms the cms-object to use for the import. * * @exception Throws CmsException if something goes wrong. */ public void importResources(CmsUser currentUser, CmsProject currentProject, String importFile, String importPath, CmsObject cms) throws CmsException { if(isAdmin(currentUser, currentProject)) { CmsImport imp = new CmsImport(importFile, importPath, cms); imp.importResources(); } else { throw new CmsException("[" + this.getClass().getName() + "] importResources", CmsException.C_NO_ACCESS); } } // Internal ResourceBroker methods /** * Initializes the resource broker and sets up all required modules and connections. * @param config The OpenCms configuration. * @exception CmsException Throws CmsException if something goes wrong. */ public void init(Configurations config) throws CmsException { // Store the configuration. m_configuration = config; if (config.getString("history.enabled", "true").toLowerCase().equals("false")) { m_enableHistory = false; } // initialize the access-module. if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsResourceBroker] init the dbaccess-module."); } m_dbAccess = createDbAccess(config); // initalize the caches m_userCache=new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".user", 50)); m_groupCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".group", 50)); m_usergroupsCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".usergroups", 50)); m_projectCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".project", 50)); m_onlineProjectCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".onlineproject", 50)); //m_resourceCache=new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".resource", 1000)); m_resourceCache=new CmsResourceCache(config.getInteger(C_CONFIGURATION_CACHE + ".resource", 1000)); m_subresCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".subres", 100)); m_propertyCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".property", 1000)); m_propertyDefCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".propertydef", 100)); m_propertyDefVectorCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".propertyvectordef", 100)); m_accessCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".access", 1000)); m_cachelimit = config.getInteger(C_CONFIGURATION_CACHE + ".maxsize", 20000); m_refresh=config.getString(C_CONFIGURATION_CACHE + ".refresh", ""); // initialize the registry# if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsResourceBroker] init registry."); } try { m_registry= new CmsRegistry(CmsBase.getAbsolutePath(config.getString(C_CONFIGURATION_REGISTRY))); } catch (CmsException ex) { throw ex; } catch(Exception ex) { // init of registry failed - throw exception throw new CmsException("Init of registry failed", CmsException.C_REGISTRY_ERROR, ex); } } /** * Determines, if the users current group is the admin-group. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return true, if the users current group is the admin-group, * else it returns false. * @exception CmsException Throws CmsException if operation was not succesful. */ public boolean isAdmin(CmsUser currentUser, CmsProject currentProject) throws CmsException { return userInGroup(currentUser, currentProject,currentUser.getName(), C_GROUP_ADMIN); } /** * Determines, if the users may manage a project.<BR/> * Only the manager of a project may publish it. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return true, if the may manage this project. * @exception CmsException Throws CmsException if operation was not succesful. */ public boolean isManagerOfProject(CmsUser currentUser, CmsProject currentProject) throws CmsException { // is the user owner of the project? if( currentUser.getId() == currentProject.getOwnerId() ) { // YES return true; } if (isAdmin(currentUser, currentProject)){ return true; } // get all groups of the user Vector groups = getGroupsOfUser(currentUser, currentProject, currentUser.getName()); for(int i = 0; i < groups.size(); i++) { // is this a managergroup for this project? if( ((CmsGroup)groups.elementAt(i)).getId() == currentProject.getManagerGroupId() ) { // this group is manager of the project return true; } } // this user is not manager of this project return false; } /** * Determines, if the users current group is the projectleader-group.<BR/> * All projectleaders can create new projects, or close their own projects. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return true, if the users current group is the projectleader-group, * else it returns false. * @exception CmsException Throws CmsException if operation was not succesful. */ public boolean isProjectManager(CmsUser currentUser, CmsProject currentProject) throws CmsException { return userInGroup(currentUser, currentProject,currentUser.getName(), C_GROUP_PROJECTLEADER); } /** * Returns the user, who had locked the resource.<BR/> * * A user can lock a resource, so he is the only one who can write this * resource. This methods checks, if a resource was locked. * * @param user The user who wants to lock the file. * @param project The project in which the resource will be used. * @param resource The resource. * * @return the user, who had locked the resource. * * @exception CmsException will be thrown, if the user has not the rights * for this resource. */ public CmsUser lockedBy(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { return readUser(currentUser,currentProject,resource.isLockedBy() ) ; } /** * Returns the user, who had locked the resource.<BR/> * * A user can lock a resource, so he is the only one who can write this * resource. This methods checks, if a resource was locked. * * @param user The user who wants to lock the file. * @param project The project in which the resource will be used. * @param resource The complete path to the resource. * * @return the user, who had locked the resource. * * @exception CmsException will be thrown, if the user has not the rights * for this resource. */ public CmsUser lockedBy(CmsUser currentUser, CmsProject currentProject, String resource) throws CmsException { return readUser(currentUser,currentProject,readFileHeader(currentUser, currentProject, resource).isLockedBy() ) ; } /** * Locks a resource.<br> * * Only a resource in an offline project can be locked. The state of the resource * is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * A user can lock a resource, so he is the only one who can write this * resource. <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is not locked by another user</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The complete path to the resource to lock. * @param force If force is true, a existing locking will be oberwritten. * * @exception CmsException Throws CmsException if operation was not succesful. * It will also be thrown, if there is a existing lock * and force was set to false. */ public void lockResource(CmsUser currentUser, CmsProject currentProject, String resourcename, boolean force) throws CmsException { CmsResource cmsResource=null; // read the resource, that should be locked if (resourcename.endsWith("/")) { cmsResource = (CmsFolder)readFolder(currentUser,currentProject,resourcename); } else { cmsResource = (CmsFile)readFileHeader(currentUser,currentProject,resourcename); } // Can't lock what isn't there if (cmsResource == null) throw new CmsException(CmsException.C_NOT_FOUND); // check, if the resource is in the offline-project if(cmsResource.getProjectId() != currentProject.getId()) { // the resource is not in the current project and can't be locked - so ignore. return; } // check, if the user may lock the resource if( accessLock(currentUser, currentProject, cmsResource) ) { if(cmsResource.isLocked()) { // if the force switch is not set, throw an exception if (force==false) { throw new CmsException("["+this.getClass().getName()+"] "+resourcename,CmsException.C_LOCKED); } } // lock the resource cmsResource.setLocked(currentUser.getId()); cmsResource.setLockedInProject(currentProject.getId()); //update resource m_dbAccess.updateLockstate(cmsResource, currentProject.getId()); // update the cache if (resourcename.endsWith("/")) { m_resourceCache.remove(resourcename); } else { m_resourceCache.remove(resourcename); } m_subresCache.clear(); // if this resource is a folder -> lock all subresources, too if(cmsResource.isFolder()) { Vector files = getFilesInFolder(currentUser,currentProject, cmsResource.getResourceName()); Vector folders = getSubFolders(currentUser,currentProject, cmsResource.getResourceName()); CmsResource currentResource; // lock all files in this folder for(int i = 0; i < files.size(); i++ ) { currentResource = (CmsResource)files.elementAt(i); if (currentResource.getState() != C_STATE_DELETED) { lockResource(currentUser, currentProject, currentResource.getResourceName(), true); } } // lock all files in this folder for(int i = 0; i < folders.size(); i++) { currentResource = (CmsResource)folders.elementAt(i); if (currentResource.getState() != C_STATE_DELETED) { lockResource(currentUser, currentProject, currentResource.getResourceName(), true); } } } } else { throw new CmsException("[" + this.getClass().getName() + "] " + resourcename, CmsException.C_NO_ACCESS); } } // Methods working with user and groups /** * Logs a user into the Cms, if the password is correct. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user to be returned. * @param password The password of the user to be returned. * @return the logged in user. * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser loginUser(CmsUser currentUser, CmsProject currentProject, String username, String password) throws CmsException { // we must read the user from the dbAccess to avoid the cache CmsUser newUser = m_dbAccess.readUser(username, password, C_USER_TYPE_SYSTEMUSER); // is the user enabled? if( newUser.getFlags() == C_FLAG_ENABLED ) { // Yes - log him in! // first write the lastlogin-time. newUser.setLastlogin(new Date().getTime()); // write the user back to the cms. m_dbAccess.writeUser(newUser); // update cache m_userCache.put(newUser.getName()+newUser.getType(),newUser); return(newUser); } else { // No Access! throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS ); } } /** * Logs a web user into the Cms, if the password is correct. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user to be returned. * @param password The password of the user to be returned. * @return the logged in user. * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser loginWebUser(CmsUser currentUser, CmsProject currentProject, String username, String password) throws CmsException { // we must read the user from the dbAccess to avoid the cache CmsUser newUser = m_dbAccess.readUser(username, password, C_USER_TYPE_WEBUSER); // is the user enabled? if( newUser.getFlags() == C_FLAG_ENABLED ) { // Yes - log him in! // first write the lastlogin-time. newUser.setLastlogin(new Date().getTime()); // write the user back to the cms. m_dbAccess.writeUser(newUser); // update cache m_userCache.put(newUser.getName()+newUser.getType(),newUser); return(newUser); } else { // No Access! throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS ); } } /** * Merges two resource-vectors into one vector. * All offline-resources will be putted to the return-vector. All additional * online-resources will be putted to the return-vector, too. All online resources, * which are present in the offline-vector will be ignored. * * * @param offline The vector with the offline resources. * @param online The vector with the online resources. * @return The merged vector. */ protected Vector mergeResources(Vector offline, Vector online) { //dont do anything if any of the given vectors are empty or null. if ((offline == null) || (offline.size() == 0)) return (online!=null)?online:new Vector(); if ((online == null) || (online.size() == 0)) return (offline!=null)?offline:new Vector(); // create a vector for the merged offline //remove all objects in the online vector that are present in the offline vector. for (Enumeration e=offline.elements();e.hasMoreElements();) { CmsResource cr = (CmsResource) e.nextElement(); Resource r = new Resource(cr.getResourceName()); online.removeElement(r); } //merge the two vectors. If both vectors were sorted, the mereged vector will remain sorted. Vector merged = new Vector(offline.size() + online.size()); int offIndex = 0; int onIndex = 0; while ((offIndex < offline.size()) || (onIndex < online.size())) { if (offIndex >= offline.size()) { merged.addElement(online.elementAt(onIndex++)); continue; } if (onIndex >= online.size()) { merged.addElement(offline.elementAt(offIndex++)); continue; } String on = ((CmsResource)online.elementAt(onIndex)).getResourceName(); String off = ((CmsResource)offline.elementAt(offIndex)).getResourceName(); if (on.compareTo(off) < 0) merged.addElement(online.elementAt(onIndex++)); else merged.addElement(offline.elementAt(offIndex++)); } return(merged); } /** * Moves the file. * * This operation includes a copy and a delete operation. These operations * are done with their security-checks. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param source The complete path of the sourcefile. * @param destination The complete path of the destinationfile. * * @exception CmsException will be thrown, if the file couldn't be moved. * The CmsException will also be thrown, if the user has not the rights * for this resource. */ public void moveFile(CmsUser currentUser, CmsProject currentProject, String source, String destination) throws CmsException { // read the file to check access CmsResource file = readFileHeader(currentUser,currentProject, source); // has the user write-access? if (accessWrite(currentUser, currentProject, file)) { // first copy the file, this may ends with an exception copyFile(currentUser, currentProject, source, destination); // then delete the source-file, this may end with an exception // => the file was only copied, not moved! deleteFile(currentUser, currentProject, source); // inform about the file-system-change fileSystemChanged(file.isFolder()); } else { throw new CmsException("[" + this.getClass().getName() + "] " + source, CmsException.C_NO_ACCESS); } } /** * Returns the onlineproject. All anonymous * (CmsUser callingUser, or guest) users will see the resources of this project. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return the onlineproject object. * @exception CmsException Throws CmsException if something goes wrong. */ public CmsProject onlineProject(CmsUser currentUser, CmsProject currentProject) throws CmsException { CmsProject project = null; // try to get the online project for this offline project from cache project = (CmsProject) m_onlineProjectCache.get(currentProject.getId()); if (project == null) { // the project was not in the cache // lookup the currentProject in the CMS_SITE_PROJECT table, and in the same call return it. project = m_dbAccess.getOnlineProject(currentProject.getId()); // store the project into the cache m_onlineProjectCache.put(currentProject.getId(), project); } return project; } /** * Creates a static export of a Cmsresource in the filesystem * * @param currentUser user who requestd themethod * @param currentProject current project of the user * @param cms the cms-object to use for the export. * @param startpoints the startpoints for the export. * * @exception CmsException if operation was not successful. */ public void exportStaticResources(CmsUser currentUser, CmsProject currentProject, CmsObject cms, Vector startpoints) throws CmsException { if(isAdmin(currentUser, currentProject)) { new CmsStaticExport(cms, startpoints); } else { throw new CmsException("[" + this.getClass().getName() + "] exportResources", CmsException.C_NO_ACCESS); } } /** * Publishes a project. * * <B>Security</B> * Only the admin or the owner of the project can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id of the project to be published. * @return CmsPublishedResources The object includes the vectors of changed resources. * * @exception CmsException Throws CmsException if something goes wrong. */ public synchronized CmsPublishedResources publishProject(CmsObject cms, CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { CmsProject publishProject = readProject(currentUser, currentProject, id); CmsPublishedResources allChanged = new CmsPublishedResources(); Vector changedResources = new Vector(); Vector changedModuleMasters = new Vector(); // check the security if ((isAdmin(currentUser, currentProject) || isManagerOfProject(currentUser, publishProject)) && (publishProject.getFlags() == C_PROJECT_STATE_UNLOCKED) && (id != C_PROJECT_ONLINE_ID)) { // check, if we update class-files with this publishing ClassLoader loader = getClass().getClassLoader(); boolean shouldReload = false; // check if we are using our own classloader // e.g. the cms-shell uses the default classloader if(loader instanceof CmsClassLoader) { // yes we have our own classloader Vector classFiles = ((CmsClassLoader)loader).getFilenames(); shouldReload = shouldReloadClasses(id, classFiles); } try{ changedResources = m_dbAccess.publishProject(currentUser, id, onlineProject(currentUser, currentProject), m_enableHistory); // now publish the module masters Vector publishModules = new Vector(); cms.getRegistry().getModulePublishables(publishModules); int versionId = 0; long publishDate = System.currentTimeMillis(); if(m_enableHistory){ versionId = m_dbAccess.getBackupVersionId(); // get the version_id for the currently published version if(versionId > 1){ versionId--; } try{ publishDate = m_dbAccess.readBackupProject(versionId).getPublishingDate(); } catch (CmsException e){ // nothing to do } if(publishDate == 0){ publishDate = System.currentTimeMillis(); } } for(int i = 0; i < publishModules.size(); i++){ // call the publishProject method of the class with parameters: // cms, m_enableHistory, project_id, version_id, publishDate, subId, // the vector changedResources and the vector changedModuleMasters try{ // The changed masters are added to the vector changedModuleMasters, so after the last module // was published the vector contains the changed masters of all published modules Class.forName((String)publishModules.elementAt(i)).getMethod("publishProject", new Class[] {CmsObject.class, Boolean.class, Integer.class, Integer.class, Long.class, Vector.class, Vector.class}).invoke(null, new Object[] {cms, new Boolean(m_enableHistory), new Integer(id), new Integer(versionId), new Long(publishDate), changedResources, changedModuleMasters}); } catch(Exception ex){ ex.printStackTrace(); if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) { A_OpenCms.log(A_OpenCms.C_OPENCMS_INFO, "Error when publish data of module "+(String)publishModules.elementAt(i)+"!: "+ex.getMessage()); } } } } catch (CmsException e){ throw e; } finally { m_resourceCache.clear(); m_subresCache.clear(); // inform about the file-system-change fileSystemChanged(true); // the project was stored in the backuptables for history //new projectmechanism: the project can be still used after publishing // it will be deleted if the project_flag = C_PROJECT_STATE_TEMP if (publishProject.getType() == C_PROJECT_TYPE_TEMPORARY) { m_dbAccess.deleteProject(publishProject); try{ m_projectCache.remove(id); } catch (Exception e){ if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) { A_OpenCms.log(A_OpenCms.C_OPENCMS_CACHE,"Could not remove project "+id+" from cache"); } } //deleteProject(currentUser, currentProject, id); } // finally set the refrish signal to another server if nescessary if (m_refresh.length() > 0) { try { URL url = new URL(m_refresh); URLConnection con = url.openConnection(); con.connect(); InputStream in = con.getInputStream(); in.close(); //System.err.println(in.toString()); } catch (Exception ex) { throw new CmsException(0, ex); } } // inform about the reload classes if(loader instanceof CmsClassLoader) { ((CmsClassLoader)loader).setShouldReload(shouldReload); } } } else { throw new CmsException("[" + this.getClass().getName() + "] could not publish project " + id, CmsException.C_NO_ACCESS); } allChanged.setChangedResources(changedResources); allChanged.setChangedModuleMasters(changedModuleMasters); return allChanged; } /** * This method checks, if there is a classFile marked as changed or deleted. * If that is so, we have to reload all classes and instances to get rid of old versions. */ public boolean shouldReloadClasses(int projectId, Vector classFiles) { for(int i = 0; i < classFiles.size(); i++) { try { CmsFile file = m_dbAccess.readFileHeader(projectId, (String)classFiles.elementAt(i)); if( (file.getState() == C_STATE_CHANGED) || (file.getState() == C_STATE_DELETED) ) { // this class-file was changed or deleted - we have to reload return true; } } catch(CmsException exc) { // the file couldn't be read - it is not in our project - ignore this file } } // no modified class-files are found - we can use the old classes return false; } /** * Reads the agent of a task from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param task The task to read the agent from. * @return The owner of a task. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsUser readAgent(CmsUser currentUser, CmsProject currentProject, CmsTask task) throws CmsException { return readUser(currentUser,currentProject,task.getAgentUser()); } /** * Reads all file headers of a file in the OpenCms.<BR> * This method returns a vector with all file headers, i.e. * the file headers of a file, independent of the project they were attached to.<br> * * The reading excludes the filecontent. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The name of the file to be read. * * @return Vector of file headers read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector readAllFileHeaders(CmsUser currentUser, CmsProject currentProject, String filename) throws CmsException { CmsResource cmsFile = readFileHeader(currentUser,currentProject, filename); if( accessRead(currentUser, currentProject, cmsFile) ) { // access to all subfolders was granted - return the file-history. return(m_dbAccess.readAllFileHeaders(currentProject.getId(), filename)); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } /** * Reads all file headers of a file in the OpenCms.<BR> * This method returns a vector with the histroy of all file headers, i.e. * the file headers of a file, independent of the project they were attached to.<br> * * The reading excludes the filecontent. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The name of the file to be read. * * @return Vector of file headers read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector readAllFileHeadersForHist(CmsUser currentUser, CmsProject currentProject, String filename) throws CmsException { CmsResource cmsFile = readFileHeader(currentUser,currentProject, filename); if( accessRead(currentUser, currentProject, cmsFile) ) { // access to all subfolders was granted - return the file-history. return(m_dbAccess.readAllFileHeadersForHist(currentProject.getId(), filename)); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } /** * select all projectResources from an given project * * @param project The project in which the resource is used. * * * @exception CmsException Throws CmsException if operation was not succesful */ public Vector readAllProjectResources(int projectId) throws CmsException { return m_dbAccess.readAllProjectResources(projectId); } /** * Returns a list of all propertyinformations of a file or folder. * * <B>Security</B> * Only the user is granted, who has the right to view the resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource of which the propertyinformation has to be * read. * * @return Vector of propertyinformation as Strings. * * @exception CmsException Throws CmsException if operation was not succesful */ public Hashtable readAllProperties(CmsUser currentUser, CmsProject currentProject, String resource) throws CmsException { CmsResource res; // read the resource from the currentProject, or the online-project try { res = readFileHeader(currentUser,currentProject, resource); } catch(CmsException exc) { // the resource was not readable if(currentProject.equals(onlineProject(currentUser, currentProject))) { // this IS the onlineproject - throw the exception throw exc; } else { // try to read the resource in the onlineproject res = readFileHeader(currentUser,onlineProject(currentUser, currentProject), resource); } } // check the security if( ! accessRead(currentUser, currentProject, res) ) { throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_NO_ACCESS); } Hashtable returnValue = null; returnValue = (Hashtable)m_propertyCache.get(currentProject.getId()+"_"+Integer.toString(res.getResourceId()) +"_"+ Integer.toString(res.getType())); if (returnValue == null){ returnValue = m_dbAccess.readAllProperties(currentProject.getId(),res,res.getType()); m_propertyCache.put(currentProject.getId()+"_"+Integer.toString(res.getResourceId()) +"_"+ Integer.toString(res.getType()),returnValue); } return returnValue; } /** * Reads all propertydefinitions for the given resource type. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resourceType The resource type to read the propertydefinitions for. * * @return propertydefinitions A Vector with propertydefefinitions for the resource type. * The Vector is maybe empty. * * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readAllPropertydefinitions(CmsUser currentUser, CmsProject currentProject, int resourceType) throws CmsException { Vector returnValue = null; returnValue = (Vector) m_propertyDefVectorCache.get(Integer.toString(resourceType)); if (returnValue == null){ returnValue = m_dbAccess.readAllPropertydefinitions(resourceType); m_propertyDefVectorCache.put(Integer.toString(resourceType), returnValue); } return returnValue; } /** * Reads all propertydefinitions for the given resource type. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resourcetype The name of the resource type to read the propertydefinitions for. * * @return propertydefinitions A Vector with propertydefefinitions for the resource type. * The Vector is maybe empty. * * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readAllPropertydefinitions(CmsUser currentUser, CmsProject currentProject, String resourcetype) throws CmsException { Vector returnValue = null; I_CmsResourceType resType = getResourceType(currentUser, currentProject, resourcetype); returnValue = (Vector)m_propertyDefVectorCache.get(resType.getResourceTypeName()); if (returnValue == null){ returnValue = m_dbAccess.readAllPropertydefinitions(resType); m_propertyDefVectorCache.put(resType.getResourceTypeName(), returnValue); } return returnValue; } // Methods working with system properties /** * Reads the export-path for the system. * This path is used for db-export and db-import. * * <B>Security:</B> * All users are granted.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return the exportpath. */ public String readExportPath(CmsUser currentUser, CmsProject currentProject) throws CmsException { return (String) m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_EXPORTPATH); } /** * Reads a file from a previous project of the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the project to read the file from. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. * */ public CmsFile readFile(CmsUser currentUser, CmsProject currentProject, int projectId, String filename) throws CmsException { CmsFile cmsFile = null; // read the resource from the projectId, try { //cmsFile=(CmsFile)m_resourceCache.get(projectId+C_FILECONTENT+filename); if (cmsFile == null) { cmsFile = m_dbAccess.readFileInProject(projectId, onlineProject(currentUser, currentProject).getId(), filename); // only put it in thecache until the size is below the max site /*if (cmsFile.getContents().length <m_cachelimit) { m_resourceCache.put(projectId+C_FILECONTENT+filename,cmsFile); } else { }*/ } if (accessRead(currentUser, currentProject, (CmsResource) cmsFile)) { // acces to all subfolders was granted - return the file. return cmsFile; } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } catch (CmsException exc) { throw exc; } } /** * Reads a file from the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. * */ public CmsFile readFile(CmsUser currentUser, CmsProject currentProject, String filename) throws CmsException { CmsFile cmsFile = null; // read the resource from the currentProject, or the online-project try { //cmsFile=(CmsFile)m_resourceCache.get(currentProject.getId()+C_FILECONTENT+filename); if (cmsFile == null) { cmsFile = m_dbAccess.readFile(currentProject.getId(), onlineProject(currentUser, currentProject).getId(), filename); // only put it in thecache until the size is below the max site /*if (cmsFile.getContents().length <m_cachelimit) { m_resourceCache.put(currentProject.getId()+C_FILECONTENT+filename,cmsFile); } else { }*/ } } catch (CmsException exc) { // the resource was not readable throw exc; } if (accessRead(currentUser, currentProject, (CmsResource) cmsFile)) { // acces to all subfolders was granted - return the file. return cmsFile; } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } /** * Reads a file from the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. * */ public CmsFile readFile(CmsUser currentUser, CmsProject currentProject, String filename, boolean includeDeleted) throws CmsException { CmsFile cmsFile = null; // read the resource from the currentProject, or the online-project try { //cmsFile=(CmsFile)m_resourceCache.get(currentProject.getId()+C_FILECONTENT+filename); if (cmsFile == null) { cmsFile = m_dbAccess.readFile(currentProject.getId(), onlineProject(currentUser, currentProject).getId(), filename, includeDeleted); // only put it in thecache until the size is below the max site /*if (cmsFile.getContents().length <m_cachelimit) { m_resourceCache.put(currentProject.getId()+C_FILECONTENT+filename,cmsFile); } else { }*/ } } catch (CmsException exc) { // the resource was not readable throw exc; } if (accessRead(currentUser, currentProject, (CmsResource) cmsFile)) { // acces to all subfolders was granted - return the file. return cmsFile; } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } /** * Gets the known file extensions (=suffixes) * * <B>Security:</B> * All users are granted access<BR/> * * @param currentUser The user who requested this method, not used here * @param currentProject The current project of the user, not used here * * @return Hashtable with file extensions as Strings */ public Hashtable readFileExtensions(CmsUser currentUser, CmsProject currentProject) throws CmsException { Hashtable res=(Hashtable) m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS); return ( (res!=null)? res : new Hashtable()); } /** * Reads a file header a previous project of the Cms.<BR/> * The reading excludes the filecontent. <br> * * A file header can be read from an offline project or the online project. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the project to read the file from. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsResource readFileHeader(CmsUser currentUser, CmsProject currentProject, int projectId, String filename) throws CmsException { CmsResource cmsFile = null; // check if this method is misused to read a folder if (filename.endsWith("/")) { return (CmsResource) readFolder(currentUser, currentProject, projectId,filename); } // read the resource from the currentProject try { cmsFile=(CmsResource)m_resourceCache.get(filename, projectId); if (cmsFile==null) { cmsFile = m_dbAccess.readFileHeaderInProject(projectId, filename); m_resourceCache.put(filename,projectId,cmsFile); } if( accessRead(currentUser, currentProject, cmsFile) ) { // acces to all subfolders was granted - return the file-header. return cmsFile; } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } catch(CmsException exc) { throw exc; } } /** * Reads a file header from the Cms.<BR/> * The reading excludes the filecontent. <br> * * A file header can be read from an offline project or the online project. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsResource readFileHeader(CmsUser currentUser, CmsProject currentProject, String filename) throws CmsException { CmsResource cmsFile = null; // check if this method is misused to read a folder if (filename.endsWith("/")) { return (CmsResource) readFolder(currentUser,currentProject,filename); } // read the resource from the currentProject, or the online-project try { // try to read form cache first cmsFile=(CmsResource)m_resourceCache.get(filename, currentProject.getId()); if (cmsFile==null) { cmsFile = m_dbAccess.readFileHeader(currentProject.getId(), filename); m_resourceCache.put(filename,currentProject.getId(),cmsFile); } } catch(CmsException exc) { // the resource was not readable throw exc; } if( accessRead(currentUser, currentProject, cmsFile) ) { // acces to all subfolders was granted - return the file-header. return cmsFile; } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } /** * Reads a file header from the Cms.<BR/> * The reading excludes the filecontent. <br> * * A file header can be read from an offline project or the online project. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsResource readFileHeader(CmsUser currentUser, CmsProject currentProject, String filename, boolean includeDeleted) throws CmsException { CmsResource cmsFile = null; // check if this method is misused to read a folder if (filename.endsWith("/")) { return (CmsResource) readFolder(currentUser,currentProject,filename, includeDeleted); } // read the resource from the currentProject, or the online-project try { // try to read form cache first cmsFile=(CmsResource)m_resourceCache.get(filename,currentProject.getId()); if (cmsFile==null) { cmsFile = m_dbAccess.readFileHeader(currentProject.getId(), filename, includeDeleted); m_resourceCache.put(filename,currentProject.getId(),cmsFile); } } catch(CmsException exc) { // the resource was not readable throw exc; } if( accessRead(currentUser, currentProject, cmsFile) ) { // acces to all subfolders was granted - return the file-header. return cmsFile; } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } /** * Reads a file header from the history of the Cms.<BR/> * The reading excludes the filecontent. <br> * * A file header is read from the backup resources. * * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param versionId The id of the version of the file. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsBackupResource readFileHeaderForHist(CmsUser currentUser, CmsProject currentProject, int versionId, String filename) throws CmsException { CmsBackupResource resource; // read the resource from the backup resources try { resource = m_dbAccess.readFileHeaderForHist(versionId, filename); } catch(CmsException exc) { throw exc; } return resource; } /** * Reads a file from the history of the Cms.<BR/> * The reading includes the filecontent. <br> * * A file is read from the backup resources. * * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param versionId The id of the version of the file. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsBackupResource readFileForHist(CmsUser currentUser, CmsProject currentProject, int versionId, String filename) throws CmsException { CmsBackupResource resource; // read the resource from the backup resources try { resource = m_dbAccess.readFileForHist(versionId, filename); } catch(CmsException exc) { throw exc; } return resource; } /** * Reads all file headers for a project from the Cms.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the project to read the resources for. * * @return a Vector of resources. * * @exception CmsException will be thrown, if the file couldn't be read. * The CmsException will also be thrown, if the user has not the rights * for this resource. */ public Vector readFileHeaders(CmsUser currentUser, CmsProject currentProject, int projectId) throws CmsException { CmsProject project = readProject(currentUser, currentProject, projectId); Vector resources = m_dbAccess.readResources(project); Vector retValue = new Vector(); // check the security for(int i = 0; i < resources.size(); i++) { if( accessRead(currentUser, currentProject, (CmsResource) resources.elementAt(i)) ) { retValue.addElement(resources.elementAt(i)); } } return retValue; } /** * Reads a folder from the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param project the project to read the folder from. * @param foldername The complete path of the folder to be read. * * @return folder The read folder. * * @exception CmsException will be thrown, if the folder couldn't be read. * The CmsException will also be thrown, if the user has not the rights * for this resource */ protected CmsFolder readFolder(CmsUser currentUser, CmsProject currentProject, int project, String folder) throws CmsException { if (folder == null) return null; CmsFolder cmsFolder = (CmsFolder) m_resourceCache.get(folder,currentProject.getId()); if (cmsFolder == null) { cmsFolder = m_dbAccess.readFolderInProject(project, folder); if (cmsFolder != null){ m_resourceCache.put(folder, currentProject.getId(), (CmsFolder) cmsFolder); } } if (cmsFolder != null) { if (!accessRead(currentUser, currentProject, (CmsResource) cmsFolder)) throw new CmsException("[" + this.getClass().getName() + "] " + folder, CmsException.C_ACCESS_DENIED); } return cmsFolder; } /** * Reads a folder from the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername The complete path of the folder to be read. * * @return folder The read folder. * * @exception CmsException will be thrown, if the folder couldn't be read. * The CmsException will also be thrown, if the user has not the rights * for this resource. */ public CmsFolder readFolder(CmsUser currentUser, CmsProject currentProject, String folder) throws CmsException { return readFolder(currentUser, currentProject, folder, false); } /** * Reads a folder from the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername The complete path of the folder to be read. * @param includeDeleted Include the folder it it is marked as deleted * * @return folder The read folder. * * @exception CmsException will be thrown, if the folder couldn't be read. * The CmsException will also be thrown, if the user has not the rights * for this resource. */ public CmsFolder readFolder(CmsUser currentUser, CmsProject currentProject, String folder, boolean includeDeleted) throws CmsException { CmsFolder cmsFolder = null; // read the resource from the currentProject, or the online-project try { cmsFolder = (CmsFolder) m_resourceCache.get(folder, currentProject.getId()); if (cmsFolder == null) { cmsFolder = m_dbAccess.readFolder(currentProject.getId(), folder); if (cmsFolder.getState() != C_STATE_DELETED) { m_resourceCache.put(folder, currentProject.getId(), (CmsFolder) cmsFolder); } } } catch (CmsException exc) { throw exc; } if (accessRead(currentUser, currentProject, (CmsResource) cmsFolder)) { // acces to all subfolders was granted - return the folder. if ((cmsFolder.getState() == C_STATE_DELETED) && (!includeDeleted)) { throw new CmsException("[" + this.getClass().getName() + "]" + cmsFolder.getAbsolutePath(), CmsException.C_RESOURCE_DELETED); } else { return cmsFolder; } } else { throw new CmsException("[" + this.getClass().getName() + "] " + folder, CmsException.C_ACCESS_DENIED); } } /** * Reads a folder from the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param folder The complete path to the folder from which the folder will be * read. * @param foldername The name of the folder to be read. * * @return folder The read folder. * * @exception CmsException will be thrown, if the folder couldn't be read. * The CmsException will also be thrown, if the user has not the rights * for this resource. * * @see #readFolder(CmsUser, CmsProject, String) */ public CmsFolder readFolder(CmsUser currentUser, CmsProject currentProject, String folder, String folderName) throws CmsException { return readFolder(currentUser, currentProject, folder + folderName); } /** * Reads a folder from the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param folderid The id of the folder to be read. * @param includeDeleted Include the folder it it is marked as deleted * * @return folder The read folder. * * @exception CmsException will be thrown, if the folder couldn't be read. * The CmsException will also be thrown, if the user has not the rights * for this resource. */ public CmsFolder readFolder(CmsUser currentUser, CmsProject currentProject, int folderid, boolean includeDeleted) throws CmsException { CmsFolder cmsFolder = null; // read the resource from the currentProject, or the online-project try { if (cmsFolder == null) { cmsFolder = m_dbAccess.readFolder(currentProject.getId(), folderid); } } catch (CmsException exc) { throw exc; } if (accessRead(currentUser, currentProject, (CmsResource) cmsFolder)) { // acces to all subfolders was granted - return the folder. if ((cmsFolder.getState() == C_STATE_DELETED) && (!includeDeleted)) { throw new CmsException("[" + this.getClass().getName() + "]" + cmsFolder.getAbsolutePath(), CmsException.C_RESOURCE_DELETED); } else { return cmsFolder; } } else { throw new CmsException("[" + this.getClass().getName() + "] " + folderid, CmsException.C_ACCESS_DENIED); } } /** * Reads all given tasks from a user for a project. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the Project in which the tasks are defined. * @param owner Owner of the task. * @param tasktype Task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW. * @param orderBy Chooses, how to order the tasks. * * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readGivenTasks(CmsUser currentUser, CmsProject currentProject, int projectId, String ownerName, int taskType, String orderBy, String sort) throws CmsException { CmsProject project = null; CmsUser owner = null; if(ownerName != null) { owner = readUser(currentUser, currentProject, ownerName); } if(projectId != C_UNKNOWN_ID) { project = readProject(currentUser, currentProject, projectId); } return m_dbAccess.readTasks(project,null, owner, null, taskType, orderBy, sort); } /** * Reads the group of a project from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The group of a resource. * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsGroup readGroup(CmsUser currentUser, CmsProject currentProject, CmsProject project) throws CmsException { CmsGroup group=null; // try to read group form cache group=(CmsGroup)m_groupCache.get(project.getGroupId()); if (group== null) { try { group=m_dbAccess.readGroup(project.getGroupId()) ; } catch(CmsException exc) { if(exc.getType() == exc.C_NO_GROUP) { // the group does not exist any more - return a dummy-group return new CmsGroup(C_UNKNOWN_ID, C_UNKNOWN_ID, project.getGroupId() + "", "deleted group", 0); } } m_groupCache.put(project.getGroupId(),group); } return group; } /** * Reads the group of a resource from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The group of a resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsGroup readGroup(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { CmsGroup group=null; // try to read group form cache group=(CmsGroup)m_groupCache.get(resource.getGroupId()); if (group== null) { try { group=m_dbAccess.readGroup(resource.getGroupId()) ; } catch(CmsException exc) { if(exc.getType() == exc.C_NO_GROUP) { return new CmsGroup(C_UNKNOWN_ID, C_UNKNOWN_ID, resource.getGroupId() + "", "deleted group", 0); } } m_groupCache.put(resource.getGroupId(),group); } return group; } /** * Reads the group (role) of a task from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param task The task to read from. * @return The group of a resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsGroup readGroup(CmsUser currentUser, CmsProject currentProject, CmsTask task) throws CmsException { return m_dbAccess.readGroup(task.getRole()); } /** * Returns a group object.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param groupname The name of the group that is to be read. * @return Group. * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsGroup readGroup(CmsUser currentUser, CmsProject currentProject, String groupname) throws CmsException { CmsGroup group=null; // try to read group form cache group=(CmsGroup)m_groupCache.get(groupname); if (group== null) { group=m_dbAccess.readGroup(groupname) ; m_groupCache.put(groupname,group); } return group; } /** * Returns a group object.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param groupid The id of the group that is to be read. * @return Group. * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsGroup readGroup(CmsUser currentUser, CmsProject currentProject, int groupid) throws CmsException { return m_dbAccess.readGroup(groupid); } /** * Reads the managergroup of a project from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The group of a resource. * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsGroup readManagerGroup(CmsUser currentUser, CmsProject currentProject, CmsProject project) throws CmsException { CmsGroup group=null; // try to read group form cache group=(CmsGroup)m_groupCache.get(project.getManagerGroupId()); if (group== null) { try { group=m_dbAccess.readGroup(project.getManagerGroupId()) ; } catch(CmsException exc) { if(exc.getType() == exc.C_NO_GROUP) { // the group does not exist any more - return a dummy-group return new CmsGroup(C_UNKNOWN_ID, C_UNKNOWN_ID, project.getManagerGroupId() + "", "deleted group", 0); } } m_groupCache.put(project.getManagerGroupId(),group); } return group; } /** * Gets the MimeTypes. * The Mime-Types will be returned. * * <B>Security:</B> * All users are garnted<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * @return the mime-types. */ public Hashtable readMimeTypes(CmsUser currentUser, CmsProject currentProject) throws CmsException { // read the mimetype-properties as ressource from classloader and convert them // to hashtable Properties props = new Properties(); try { props.load(getClass().getClassLoader().getResourceAsStream("mimetypes.properties")); } catch(Exception exc) { if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[CmsResourceBroker] could not read mimetypes from properties. " + exc.getMessage()); } } return(Hashtable) props; } /** * Reads the original agent of a task from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param task The task to read the original agent from. * @return The owner of a task. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsUser readOriginalAgent(CmsUser currentUser, CmsProject currentProject, CmsTask task) throws CmsException { return readUser(currentUser,currentProject,task.getOriginalUser()); } /** * Reads the owner of a project from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The owner of a resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsUser readOwner(CmsUser currentUser, CmsProject currentProject, CmsProject project) throws CmsException { return readUser(currentUser,currentProject,project.getOwnerId()); } /** * Reads the owner of a resource from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The owner of a resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsUser readOwner(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { return readUser(currentUser,currentProject,resource.getOwnerId() ); } /** * Reads the owner (initiator) of a task from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param task The task to read the owner from. * @return The owner of a task. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsUser readOwner(CmsUser currentUser, CmsProject currentProject, CmsTask task) throws CmsException { return readUser(currentUser,currentProject,task.getInitiatorUser()); } /** * Reads the owner of a tasklog from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The owner of a resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsUser readOwner(CmsUser currentUser, CmsProject currentProject, CmsTaskLog log) throws CmsException { return readUser(currentUser,currentProject,log.getUser()); } /** * Reads a project from the Cms. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id of the project to read. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsProject readProject(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { CmsProject project=null; project=(CmsProject)m_projectCache.get(id); if (project==null) { project=m_dbAccess.readProject(id); m_projectCache.put(id,project); } return project; } /** * Reads a project from the Cms. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param res The resource to read the project of. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsProject readProject(CmsUser currentUser, CmsProject currentProject, CmsResource res) throws CmsException { return readProject(currentUser, currentProject, res.getProjectId()); } /** * Reads a project from the Cms. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param task The task to read the project of. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsProject readProject(CmsUser currentUser, CmsProject currentProject, CmsTask task) throws CmsException { // read the parent of the task, until it has no parents. task = this.readTask(currentUser, currentProject, task.getId()); while(task.getParent() != 0) { task = readTask(currentUser, currentProject, task.getParent()); } return m_dbAccess.readProject(task); } /** * Reads all file headers of a project from the Cms. * * @param projectId the id of the project to read the file headers for. * @param filter The filter for the resources (all, new, changed, deleted, locked) * * @return a Vector of resources. */ public Vector readProjectView(CmsUser currentUser, CmsProject currentProject, int projectId, String filter) throws CmsException { CmsProject project = readProject(currentUser, currentProject, projectId); Vector retValue = new Vector(); String whereClause = new String(); if("new".equalsIgnoreCase(filter)){ whereClause = " AND STATE="+C_STATE_NEW; } else if ("changed".equalsIgnoreCase(filter)){ whereClause = " AND STATE="+C_STATE_CHANGED; } else if ("deleted".equalsIgnoreCase(filter)){ whereClause = " AND STATE="+C_STATE_DELETED; } else if ("locked".equalsIgnoreCase(filter)){ whereClause = " AND LOCKED_BY != "+C_UNKNOWN_ID; } else { whereClause = " AND STATE != "+C_STATE_UNCHANGED; } Vector resources = m_dbAccess.readProjectView(currentProject.getId(), projectId, whereClause); // check the security for(int i = 0; i < resources.size(); i++) { if( accessRead(currentUser, project, (CmsResource) resources.elementAt(i)) ) { retValue.addElement(resources.elementAt(i)); } } return retValue; } /** * Reads the backupinformation of a project from the Cms. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param versionId The versionId of the project. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsBackupProject readBackupProject(CmsUser currentUser, CmsProject currentProject, int versionId) throws CmsException { return m_dbAccess.readBackupProject(versionId); } /** * Reads log entries for a project. * * @param projectId The id of the projec for tasklog to read. * @return A Vector of new TaskLog objects * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readProjectLogs(CmsUser currentUser, CmsProject currentProject, int projectid) throws CmsException { return m_dbAccess.readProjectLogs(projectid); } /** * Returns a propertyinformation of a file or folder. * * <B>Security</B> * Only the user is granted, who has the right to view the resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource of which the propertyinformation has * to be read. * @param property The propertydefinition-name of which the propertyinformation has to be read. * * @return propertyinfo The propertyinfo as string. * * @exception CmsException Throws CmsException if operation was not succesful */ public String readProperty(CmsUser currentUser, CmsProject currentProject, String resource, String property) throws CmsException { CmsResource res; // read the resource from the currentProject try { res = readFileHeader(currentUser,currentProject, resource, true); } catch(CmsException exc) { // the resource was not readable throw exc; } // check the security if( ! accessRead(currentUser, currentProject, res) ) { throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_NO_ACCESS); } String returnValue = null; returnValue = (String)m_propertyCache.get(currentProject.getId()+property + Integer.toString(res.getResourceId()) +","+ Integer.toString(res.getType())); if (returnValue == null){ returnValue = m_dbAccess.readProperty(property,currentProject.getId(),res,res.getType()); if (returnValue == null) { returnValue=""; } m_propertyCache.put(currentProject.getId()+property +Integer.toString(res.getResourceId()) + ","+ Integer.toString(res.getType()), returnValue); } if (returnValue.equals("")){returnValue=null;} return returnValue; } /** * Reads a definition for the given resource type. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name of the propertydefinition to read. * @param resourcetype The name of the resource type for which the propertydefinition * is valid. * * @return propertydefinition The propertydefinition that corresponds to the overgiven * arguments - or null if there is no valid propertydefinition. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsPropertydefinition readPropertydefinition(CmsUser currentUser, CmsProject currentProject, String name, String resourcetype) throws CmsException { I_CmsResourceType resType = getResourceType(currentUser,currentProject,resourcetype); CmsPropertydefinition returnValue = null; returnValue = (CmsPropertydefinition)m_propertyDefCache.get(name + resType.getResourceType()); if (returnValue == null){ returnValue = m_dbAccess.readPropertydefinition(name, resType); m_propertyDefCache.put(name + resType.getResourceType(), returnValue); } return returnValue; } /** * Insert the method's description here. * Creation date: (09-10-2000 09:29:45) * @return java.util.Vector * @param project com.opencms.file.CmsProject * @exception com.opencms.core.CmsException The exception description. */ public Vector readResources(CmsProject project) throws com.opencms.core.CmsException { return m_dbAccess.readResources(project); } /** * Read a task by id. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id for the task to read. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsTask readTask(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { return m_dbAccess.readTask(id); } /** * Reads log entries for a task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The task for the tasklog to read . * @return A Vector of new TaskLog objects * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readTaskLogs(CmsUser currentUser, CmsProject currentProject, int taskid) throws CmsException { return m_dbAccess.readTaskLogs(taskid);; } /** * Reads all tasks for a project. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the Project in which the tasks are defined. Can be null for all tasks * @tasktype Task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW * @param orderBy Chooses, how to order the tasks. * @param sort Sort order C_SORT_ASC, C_SORT_DESC, or null * * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readTasksForProject(CmsUser currentUser, CmsProject currentProject, int projectId, int tasktype, String orderBy, String sort) throws CmsException { CmsProject project = null; if(projectId != C_UNKNOWN_ID) { project = readProject(currentUser, currentProject, projectId); } return m_dbAccess.readTasks(project, null, null, null, tasktype, orderBy, sort); } /** * Reads all tasks for a role in a project. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the Project in which the tasks are defined. * @param user The user who has to process the task. * @param tasktype Task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW. * @param orderBy Chooses, how to order the tasks. * @param sort Sort order C_SORT_ASC, C_SORT_DESC, or null * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readTasksForRole(CmsUser currentUser, CmsProject currentProject, int projectId, String roleName, int tasktype, String orderBy, String sort) throws CmsException { CmsProject project = null; CmsGroup role = null; if(roleName != null) { role = readGroup(currentUser, currentProject, roleName); } if(projectId != C_UNKNOWN_ID) { project = readProject(currentUser, currentProject, projectId); } return m_dbAccess.readTasks(project, null, null, role, tasktype, orderBy, sort); } /** * Reads all tasks for a user in a project. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the Project in which the tasks are defined. * @param userName The user who has to process the task. * @param taskType Task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW. * @param orderBy Chooses, how to order the tasks. * @param sort Sort order C_SORT_ASC, C_SORT_DESC, or null * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readTasksForUser(CmsUser currentUser, CmsProject currentProject, int projectId, String userName, int taskType, String orderBy, String sort) throws CmsException { CmsUser user = m_dbAccess.readUser(userName, C_USER_TYPE_SYSTEMUSER); return m_dbAccess.readTasks(currentProject, user, null, null, taskType, orderBy, sort); } /** * Returns a user object.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id of the user that is to be read. * @return User * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser readUser(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { try { CmsUser user=null; // try to read the user from cache user=(CmsUser)m_userCache.get(id); if (user==null) { user=m_dbAccess.readUser(id); m_userCache.put(id,user); } return user; } catch (CmsException ex) { return new CmsUser(C_UNKNOWN_ID, id + "", "deleted user"); } } /** * Returns a user object.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user that is to be read. * @return User * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser readUser(CmsUser currentUser, CmsProject currentProject, String username) throws CmsException { CmsUser user = null; // try to read the user from cache user = (CmsUser)m_userCache.get(username+C_USER_TYPE_SYSTEMUSER); if (user == null) { user = m_dbAccess.readUser(username, C_USER_TYPE_SYSTEMUSER); m_userCache.put(username+C_USER_TYPE_SYSTEMUSER,user); } return user; } /** * Returns a user object.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user that is to be read. * @param type The type of the user. * @return User * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser readUser(CmsUser currentUser, CmsProject currentProject, String username,int type) throws CmsException { CmsUser user = null; // try to read the user from cache user = (CmsUser)m_userCache.get(username+type); if (user == null) { user = m_dbAccess.readUser(username, type); m_userCache.put(username+type,user); } return user; } /** * Returns a user object if the password for the user is correct.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The username of the user that is to be read. * @param password The password of the user that is to be read. * @return User * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser readUser(CmsUser currentUser, CmsProject currentProject, String username, String password) throws CmsException { CmsUser user = null; // ednfal: don't read user from cache because password may be changed //user = (CmsUser)m_userCache.get(username+C_USER_TYPE_SYSTEMUSER); // store user in cache if (user == null) { user = m_dbAccess.readUser(username, password, C_USER_TYPE_SYSTEMUSER); m_userCache.put(username+C_USER_TYPE_SYSTEMUSER, user); } return user; } /** * Returns a user object if the password for the user is correct.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The username of the user that is to be read. * @return User * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser readWebUser(CmsUser currentUser, CmsProject currentProject, String username) throws CmsException { CmsUser user = null; user = (CmsUser)m_userCache.get(username+C_USER_TYPE_WEBUSER); // store user in cache if (user == null) { user = m_dbAccess.readUser(username, C_USER_TYPE_WEBUSER); m_userCache.put(username+C_USER_TYPE_WEBUSER, user); } return user; } /** * Returns a user object if the password for the user is correct.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The username of the user that is to be read. * @param password The password of the user that is to be read. * @return User * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser readWebUser(CmsUser currentUser, CmsProject currentProject, String username, String password) throws CmsException { CmsUser user = null; // ednfal: don't read user from cache because password may be changed user = (CmsUser)m_userCache.get(username+C_USER_TYPE_WEBUSER); // store user in cache if (user == null) { user = m_dbAccess.readUser(username, password, C_USER_TYPE_WEBUSER); m_userCache.put(username+C_USER_TYPE_WEBUSER,user); } return user; } /** * Reaktivates a task from the Cms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task to accept. * * @exception CmsException Throws CmsException if something goes wrong. */ public void reaktivateTask(CmsUser currentUser, CmsProject currentProject, int taskId) throws CmsException { CmsTask task = m_dbAccess.readTask(taskId); task.setState(C_TASK_STATE_STARTED); task.setPercentage(0); task = m_dbAccess.writeTask(task); m_dbAccess.writeSystemTaskLog(taskId, "Task was reactivated from " + currentUser.getFirstname() + " " + currentUser.getLastname() + "."); } /** * Sets a new password only if the user knows his recovery-password. * * All users can do this if he knows the recovery-password.<P/> * * <B>Security:</B> * All users can do this if he knows the recovery-password.<P/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user. * @param recoveryPassword The recovery password. * @param newPassword The new password. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void recoverPassword(CmsUser currentUser, CmsProject currentProject, String username, String recoveryPassword, String newPassword) throws CmsException { // check the length of the new password. if(newPassword.length() < C_PASSWORD_MINIMUMSIZE) { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_SHORT_PASSWORD); } // check the length of the recovery password. if(recoveryPassword.length() < C_PASSWORD_MINIMUMSIZE) { throw new CmsException("[" + this.getClass().getName() + "] no recovery password."); } m_dbAccess.recoverPassword(username, recoveryPassword, newPassword); } /** * Removes a user from a group. * * Only the admin can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user that is to be removed from the group. * @param groupname The name of the group. * @exception CmsException Throws CmsException if operation was not succesful. */ public void removeUserFromGroup(CmsUser currentUser, CmsProject currentProject, String username, String groupname) throws CmsException { // test if this user is existing in the group if (!userInGroup(currentUser,currentProject,username,groupname)) { // user already there, throw exception throw new CmsException("[" + this.getClass().getName() + "] remove " + username+ " from " +groupname, CmsException.C_NO_USER); } if( isAdmin(currentUser, currentProject) ) { CmsUser user; CmsGroup group; user=readUser(currentUser,currentProject,username); //check if the user exists if (user != null) { group=readGroup(currentUser,currentProject,groupname); //check if group exists if (group != null){ // do not remmove the user from its default group if (user.getDefaultGroupId() != group.getId()) { //remove this user from the group m_dbAccess.removeUserFromGroup(user.getId(),group.getId()); m_usergroupsCache.clear(); } else { throw new CmsException("["+this.getClass().getName()+"]",CmsException.C_NO_DEFAULT_GROUP); } } else { throw new CmsException("["+this.getClass().getName()+"]"+groupname,CmsException.C_NO_GROUP); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS); } } } /** * Renames the file to a new name. <br> * * Rename can only be done in an offline project. To rename a file, the following * steps have to be done: * <ul> * <li> Copy the file with the oldname to a file with the new name, the state * of the new file is set to NEW (2). * <ul> * <li> If the state of the original file is UNCHANGED (0), the file content of the * file is read from the online project. </li> * <li> If the state of the original file is CHANGED (1) or NEW (2) the file content * of the file is read from the offline project. </li> * </ul> * </li> * <li> Set the state of the old file to DELETED (3). </li> * </ul> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param oldname The complete path to the resource which will be renamed. * @param newname The new name of the resource (CmsUser callingUser, No path information allowed). * * @exception CmsException Throws CmsException if operation was not succesful. */ public void renameFile(CmsUser currentUser, CmsProject currentProject, String oldname, String newname) throws CmsException { // read the old file CmsResource file = readFileHeader(currentUser, currentProject, oldname); // checks, if the newname is valid, if not it throws a exception validFilename(newname); // has the user write-access? if (accessWrite(currentUser, currentProject, file)) { String path = oldname.substring(0, oldname.lastIndexOf("/") + 1); copyFile(currentUser, currentProject, oldname, path + newname); deleteFile(currentUser, currentProject, oldname); } else { throw new CmsException("[" + this.getClass().getName() + "] " + oldname, CmsException.C_NO_ACCESS); } } /** * This method loads old sessiondata from the database. It is used * for sessionfailover. * * @param oldSessionId the id of the old session. * @return the old sessiondata. */ public Hashtable restoreSession(String oldSessionId) throws CmsException { return m_dbAccess.readSession(oldSessionId); } /** * Restores a file in the current project with a version in the backup * * @param currentUser The current user * @param currentProject The current project * @param versionId The version id of the resource * @param filename The name of the file to restore * * @exception CmsException Throws CmsException if operation was not succesful. */ public void restoreResource(CmsUser currentUser, CmsProject currentProject, int versionId, String filename) throws CmsException { CmsBackupResource backupFile = null; CmsFile offlineFile = null; int state = C_STATE_CHANGED; // read the backup file backupFile = readFileForHist(currentUser, currentProject, versionId, filename); // try to read the owner and the group int ownerId = currentUser.getId(); int groupId = currentUser.getDefaultGroupId(); try{ ownerId = readUser(currentUser, currentProject, backupFile.getOwnerName()).getId(); } catch(CmsException exc){ // user can not be read, set the userid of current user } try{ groupId = readGroup(currentUser, currentProject, backupFile.getGroupName()).getId(); } catch(CmsException exc){ // group can not be read, set the groupid of current user } offlineFile = readFile(currentUser, currentProject, filename); if(offlineFile.getState() == C_STATE_NEW){ state = C_STATE_NEW; } if (backupFile != null && offlineFile != null){ CmsFile newFile = new CmsFile(offlineFile.getResourceId(), offlineFile.getParentId(), offlineFile.getFileId(), offlineFile.getResourceName(), backupFile.getType(), backupFile.getFlags(), ownerId, groupId, currentProject.getId(), backupFile.getAccessFlags(), state, offlineFile.isLockedBy(), backupFile.getLauncherType(), backupFile.getLauncherClassname(), offlineFile.getDateCreated(), offlineFile.getDateLastModified(), currentUser.getId(), backupFile.getContents(), backupFile.getLength(), currentProject.getId()); writeFile(currentUser, currentProject, newFile); } } /** * Set a new name for a task * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task to set the percentage. * @param name The new name value * * @exception CmsException Throws CmsException if something goes wrong. */ public void setName(CmsUser currentUser, CmsProject currentProject, int taskId, String name) throws CmsException { if( (name == null) || name.length() == 0) { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME); } CmsTask task = m_dbAccess.readTask(taskId); task.setName(name); task = m_dbAccess.writeTask(task); m_dbAccess.writeSystemTaskLog(taskId, "Name was set to " + name + "% from " + currentUser.getFirstname() + " " + currentUser.getLastname() + "."); } /** * Sets a new parent-group for an already existing group in the Cms.<BR/> * * Only the admin can do this.<P/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param groupName The name of the group that should be written to the Cms. * @param parentGroupName The name of the parentGroup to set, or null if the parent * group should be deleted. * @exception CmsException Throws CmsException if operation was not succesfull. */ public void setParentGroup(CmsUser currentUser, CmsProject currentProject, String groupName, String parentGroupName) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) ) { CmsGroup group = readGroup(currentUser, currentProject, groupName); int parentGroupId = C_UNKNOWN_ID; // if the group exists, use its id, else set to unknown. if( parentGroupName != null ) { parentGroupId = readGroup(currentUser, currentProject, parentGroupName).getId(); } group.setParentId(parentGroupId); // write the changes to the cms writeGroup(currentUser,currentProject,group); } else { throw new CmsException("[" + this.getClass().getName() + "] " + groupName, CmsException.C_NO_ACCESS); } } /** * Sets the password for a user. * * Only a adminstrator can do this.<P/> * * <B>Security:</B> * Users, which are in the group "administrators" are granted.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user. * @param newPassword The new password. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void setPassword(CmsUser currentUser, CmsProject currentProject, String username, String newPassword) throws CmsException { // check the length of the new password. if(newPassword.length() < C_PASSWORD_MINIMUMSIZE) { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_SHORT_PASSWORD); } if( isAdmin(currentUser, currentProject) ) { m_dbAccess.setPassword(username, newPassword); } else { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS); } } /** * Sets the password for a user. * * Every user who knows the username and the password can do this.<P/> * * <B>Security:</B> * Users, who knows the username and the old password are granted.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user. * @param oldPassword The new password. * @param newPassword The new password. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void setPassword(CmsUser currentUser, CmsProject currentProject, String username, String oldPassword, String newPassword) throws CmsException { // check the length of the new password. if(newPassword.length() < C_PASSWORD_MINIMUMSIZE) { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_SHORT_PASSWORD); } // read the user CmsUser user; try { user = m_dbAccess.readUser(username, oldPassword, C_USER_TYPE_SYSTEMUSER); } catch(CmsException exc) { // this is no system-user - maybe a webuser? try{ user = m_dbAccess.readUser(username, oldPassword, C_USER_TYPE_WEBUSER); } catch(CmsException e) { throw exc; } } //if( !anonymousUser(currentUser, currentProject).equals( currentUser )) { m_dbAccess.setPassword(username, newPassword); //} else { // throw new CmsException("[" + this.getClass().getName() + "] " + username, // CmsException.C_NO_ACCESS); //} } /** * Set priority of a task * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task to set the percentage. * @param new priority value * * @exception CmsException Throws CmsException if something goes wrong. */ public void setPriority(CmsUser currentUser, CmsProject currentProject, int taskId, int priority) throws CmsException { CmsTask task = m_dbAccess.readTask(taskId); task.setPriority(priority); task = m_dbAccess.writeTask(task); m_dbAccess.writeSystemTaskLog(taskId, "Priority was set to " + priority + " from " + currentUser.getFirstname() + " " + currentUser.getLastname() + "."); } /** * Sets the recovery password for a user. * * Only a adminstrator or the curretuser can do this.<P/> * * <B>Security:</B> * Users, which are in the group "administrators" are granted.<BR/> * Current users can change their own password. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user. * @param password The password of the user. * @param newPassword The new recoveryPassword to be set. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void setRecoveryPassword(CmsUser currentUser, CmsProject currentProject, String username, String password, String newPassword) throws CmsException { // check the length of the new password. if(newPassword.length() < C_PASSWORD_MINIMUMSIZE) { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_SHORT_PASSWORD); } // read the user CmsUser user; try { user = readUser(currentUser, currentProject, username, password); } catch(CmsException exc) { // this is no system-user - maybe a webuser? user = readWebUser(currentUser, currentProject, username, password); } if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) && ( isAdmin(user, currentProject) || user.equals(currentUser)) ) { m_dbAccess.setRecoveryPassword(username, newPassword); } else { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS); } } /** * Set a Parameter for a task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskId The Id of the task. * @param parName Name of the parameter. * @param parValue Value if the parameter. * * @return The id of the inserted parameter or 0 if the parameter already exists for this task. * * @exception CmsException Throws CmsException if something goes wrong. */ public void setTaskPar(CmsUser currentUser, CmsProject currentProject, int taskId, String parName, String parValue) throws CmsException { m_dbAccess.setTaskPar(taskId, parName, parValue); } /** * Set timeout of a task * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task to set the percentage. * @param new timeout value * * @exception CmsException Throws CmsException if something goes wrong. */ public void setTimeout(CmsUser currentUser, CmsProject currentProject, int taskId, long timeout) throws CmsException { CmsTask task = m_dbAccess.readTask(taskId); java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout); task.setTimeOut(timestamp); task = m_dbAccess.writeTask(task); m_dbAccess.writeSystemTaskLog(taskId, "Timeout was set to " + timeout + " from " + currentUser.getFirstname() + " " + currentUser.getLastname() + "."); } /** * This method stores sessiondata into the database. It is used * for sessionfailover. * * @param sessionId the id of the session. * @param isNew determines, if the session is new or not. * @return data the sessionData. */ public void storeSession(String sessionId, Hashtable sessionData) throws CmsException { // update the session int rowCount = m_dbAccess.updateSession(sessionId, sessionData); if(rowCount != 1) { // the entry dosn't exists - create it m_dbAccess.createSession(sessionId, sessionData); } } /** * Undo all changes in the resource, restore the online file. * * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resourceName The name of the resource to be restored. * * @exception CmsException Throws CmsException if something goes wrong. */ public void undoChanges(CmsUser currentUser, CmsProject currentProject, String resourceName) throws CmsException { CmsProject onlineProject = readProject(currentUser, currentProject, C_PROJECT_ONLINE_ID); // change folder or file? if (resourceName.endsWith("/")){ // read the resource from the online project CmsFolder onlineFolder = readFolder(currentUser, onlineProject, resourceName); // read the resource from the offline project and change the data CmsFolder offlineFolder = readFolder(currentUser, currentProject, resourceName); CmsFolder restoredFolder = new CmsFolder(offlineFolder.getResourceId(), offlineFolder.getParentId(), offlineFolder.getFileId(), offlineFolder.getResourceName(), onlineFolder.getType(), onlineFolder.getFlags(), onlineFolder.getOwnerId(), onlineFolder.getGroupId(), currentProject.getId(), onlineFolder.getAccessFlags(), C_STATE_UNCHANGED, offlineFolder.isLockedBy(), offlineFolder.getDateCreated(), offlineFolder.getDateLastModified(), currentUser.getId(), currentProject.getId()); // write the file in the offline project // has the user write-access? if( accessWrite(currentUser, currentProject, (CmsResource)restoredFolder) ) { // write-access was granted - write the folder without setting state = changed m_dbAccess.writeFolder(currentProject, restoredFolder, false, currentUser.getId()); // restore the properties in the offline project m_dbAccess.deleteAllProperties(currentProject.getId(),restoredFolder); Hashtable propertyInfos = m_dbAccess.readAllProperties(onlineProject.getId(),onlineFolder,onlineFolder.getType()); m_dbAccess.writeProperties(propertyInfos,currentProject.getId(),restoredFolder,restoredFolder.getType()); m_propertyCache.clear(); // update the cache m_resourceCache.remove(restoredFolder.getResourceName()); m_subresCache.clear(); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + restoredFolder.getAbsolutePath(), CmsException.C_NO_ACCESS); } } else { // read the file from the online project CmsFile onlineFile = readFile(currentUser, onlineProject, resourceName); // read the file from the offline project and change the data CmsFile offlineFile = readFile(currentUser, currentProject, resourceName); CmsFile restoredFile = new CmsFile(offlineFile.getResourceId(), offlineFile.getParentId(), offlineFile.getFileId(), offlineFile.getResourceName(), onlineFile.getType(), onlineFile.getFlags(), onlineFile.getOwnerId(), onlineFile.getGroupId(), currentProject.getId(), onlineFile.getAccessFlags(), C_STATE_UNCHANGED, offlineFile.isLockedBy(), onlineFile.getLauncherType(), onlineFile.getLauncherClassname(), offlineFile.getDateCreated(), offlineFile.getDateLastModified(), currentUser.getId(), onlineFile.getContents(), onlineFile.getLength(), currentProject.getId()); // write the file in the offline project // has the user write-access? if( accessWrite(currentUser, currentProject, (CmsResource)restoredFile) ) { // write-acces was granted - write the file without setting state = changed m_dbAccess.writeFile(currentProject, onlineProject(currentUser, currentProject), restoredFile, false); // restore the properties in the offline project m_dbAccess.deleteAllProperties(currentProject.getId(),restoredFile); Hashtable propertyInfos = m_dbAccess.readAllProperties(onlineProject.getId(),onlineFile,onlineFile.getType()); m_dbAccess.writeProperties(propertyInfos,currentProject.getId(),restoredFile,restoredFile.getType()); m_propertyCache.clear(); // update the cache m_resourceCache.remove(restoredFile.getResourceName()); m_subresCache.clear(); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + restoredFile.getAbsolutePath(), CmsException.C_NO_ACCESS); } } } /** * Unlocks all resources in this project. * * <B>Security</B> * Only the admin or the owner of the project can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id of the project to be published. * * @exception CmsException Throws CmsException if something goes wrong. */ public void unlockProject(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { // read the project. CmsProject project = readProject(currentUser, currentProject, id); // check the security if( (isAdmin(currentUser, currentProject) || isManagerOfProject(currentUser, project) ) && (project.getFlags() == C_PROJECT_STATE_UNLOCKED )) { // unlock all resources in the project m_dbAccess.unlockProject(project); m_resourceCache.clear(); m_projectCache.clear(); } else { throw new CmsException("[" + this.getClass().getName() + "] " + id, CmsException.C_NO_ACCESS); } } /** * Unlocks a resource.<br> * * Only a resource in an offline project can be unlock. The state of the resource * is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * Only the user who locked a resource can unlock it. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user had locked the resource before</li> * </ul> * * @param user The user who wants to lock the file. * @param project The project in which the resource will be used. * @param resourcename The complete path to the resource to lock. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void unlockResource(CmsUser currentUser,CmsProject currentProject, String resourcename) throws CmsException { CmsResource cmsResource=null; // read the resource, that should be locked if (resourcename.endsWith("/")) { cmsResource = readFolder(currentUser,currentProject,resourcename); } else { cmsResource = (CmsFile)readFileHeader(currentUser,currentProject,resourcename); } // check, if the user may lock the resource if( accessUnlock(currentUser, currentProject, cmsResource) ) { // unlock the resource. if (cmsResource.isLocked()){ // check if the resource is locked by the actual user if (cmsResource.isLockedBy()==currentUser.getId()) { // unlock the resource cmsResource.setLocked(C_UNKNOWN_ID); //update resource m_dbAccess.updateLockstate(cmsResource, cmsResource.getLockedInProject()); if (resourcename.endsWith("/")) { // update the cache m_resourceCache.remove(resourcename); } else { // update the cache m_resourceCache.remove(resourcename); } m_subresCache.clear(); } else { throw new CmsException("[" + this.getClass().getName() + "] " + resourcename + CmsException.C_NO_ACCESS); } } // if this resource is a folder -> lock all subresources, too if(cmsResource.isFolder()) { Vector files = getFilesInFolder(currentUser,currentProject, cmsResource.getResourceName()); Vector folders = getSubFolders(currentUser,currentProject, cmsResource.getResourceName()); CmsResource currentResource; // lock all files in this folder for(int i = 0; i < files.size(); i++ ) { currentResource = (CmsResource)files.elementAt(i); if (currentResource.getState() != C_STATE_DELETED) { unlockResource(currentUser, currentProject, currentResource.getResourceName()); } } // lock all files in this folder for(int i = 0; i < folders.size(); i++) { currentResource = (CmsResource)folders.elementAt(i); if (currentResource.getState() != C_STATE_DELETED) { unlockResource(currentUser, currentProject, currentResource.getResourceName()); } } } } else { throw new CmsException("[" + this.getClass().getName() + "] " + resourcename, CmsException.C_NO_ACCESS); } } /** * Checks if a user is member of a group.<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param callingUser The user who wants to use this method. * @param nameuser The name of the user to check. * @param groupname The name of the group to check. * @return True or False * * @exception CmsException Throws CmsException if operation was not succesful */ public boolean userInGroup(CmsUser currentUser, CmsProject currentProject, String username, String groupname) throws CmsException { Vector groups = getGroupsOfUser(currentUser,currentProject,username); CmsGroup group; for(int z = 0; z < groups.size(); z++) { group = (CmsGroup) groups.elementAt(z); if(groupname.equals(group.getName())) { return true; } } return false; } /** * Checks ii characters in a String are allowed for filenames * * @param filename String to check * * @exception throws a exception, if the check fails. */ protected void validFilename( String filename ) throws CmsException { if (filename == null) { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_BAD_NAME); } int l = filename.trim().length(); if (l == 0 || filename.startsWith(".")) { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_BAD_NAME); } for (int i=0; i<l; i++) { char c = filename.charAt(i); if ( ((c < 'a') || (c > 'z')) && ((c < '0') || (c > '9')) && ((c < 'A') || (c > 'Z')) && (c != '-') && (c != '.') && (c != '_') && (c != '~') ) { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_BAD_NAME); } } } /** * Checks ii characters in a String are allowed for filenames * * @param filename String to check * * @exception throws a exception, if the check fails. */ protected void validTaskname( String taskname ) throws CmsException { if (taskname == null) { throw new CmsException("[" + this.getClass().getName() + "] " + taskname, CmsException.C_BAD_NAME); } int l = taskname.length(); if (l == 0) { throw new CmsException("[" + this.getClass().getName() + "] " + taskname, CmsException.C_BAD_NAME); } for (int i=0; i<l; i++) { char c = taskname.charAt(i); if ( ((c < '') || (c > '')) && ((c < '') || (c > '')) && ((c < 'a') || (c > 'z')) && ((c < '0') || (c > '9')) && ((c < 'A') || (c > 'Z')) && (c != '-') && (c != '.') && (c != '_') && (c != '~') && (c != ' ') && (c != '') ) { throw new CmsException("[" + this.getClass().getName() + "] " + taskname, CmsException.C_BAD_NAME); } } } /** * Checks ii characters in a String are allowed for names * * @param name String to check * * @exception throws a exception, if the check fails. */ protected void validName(String name, boolean blank) throws CmsException { if (name == null || name.length() == 0 || name.trim().length() == 0) { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME); } // throw exception if no blanks are allowed if (!blank) { int l = name.length(); for (int i = 0; i < l; i++) { char c = name.charAt(i); if (c == ' ') { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME); } } } /* for (int i=0; i<l; i++) { char c = name.charAt(i); if ( ((c < 'a') || (c > 'z')) && ((c < '0') || (c > '9')) && ((c < 'A') || (c > 'Z')) && (c != '-') && (c != '.') && (c != '_') && (c != '~') ) { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME); } } */ } /** * Writes the export-path for the system. * This path is used for db-export and db-import. * * <B>Security:</B> * Users, which are in the group "administrators" are granted.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param mountpoint The mount point in the Cms filesystem. */ public void writeExportPath(CmsUser currentUser, CmsProject currentProject, String path) throws CmsException { // check the security if( isAdmin(currentUser, currentProject) ) { // security is ok - write the exportpath. if(m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_EXPORTPATH) == null) { // the property wasn't set before. m_dbAccess.addSystemProperty(C_SYSTEMPROPERTY_EXPORTPATH, path); } else { // overwrite the property. m_dbAccess.writeSystemProperty(C_SYSTEMPROPERTY_EXPORTPATH, path); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + path, CmsException.C_NO_ACCESS); } } /** * Writes a file to the Cms.<br> * * A file can only be written to an offline project.<br> * The state of the resource is set to CHANGED (1). The file content of the file * is either updated (if it is already existing in the offline project), or created * in the offline project (if it is not available there).<br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who own this file. * @param currentProject The project in which the resource will be used. * @param file The name of the file to write. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void writeFile(CmsUser currentUser, CmsProject currentProject, CmsFile file) throws CmsException { // has the user write-access? if( accessWrite(currentUser, currentProject, (CmsResource)file) ) { // write-acces was granted - write the file. m_dbAccess.writeFile(currentProject, onlineProject(currentUser, currentProject), file, true, currentUser.getId()); if (file.getState()==C_STATE_UNCHANGED) { file.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.remove(file.getResourceName()); m_subresCache.clear(); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + file.getAbsolutePath(), CmsException.C_NO_ACCESS); } } /** * Writes the file extensions * * <B>Security:</B> * Users, which are in the group "Administrators" are authorized.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param extensions Holds extensions as keys and resourcetypes (Stings) as values */ public void writeFileExtensions(CmsUser currentUser, CmsProject currentProject, Hashtable extensions) throws CmsException { if (extensions != null) { if (isAdmin(currentUser, currentProject)) { Enumeration enu=extensions.keys(); while (enu.hasMoreElements()) { String key=(String)enu.nextElement(); validFilename(key); } if (m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS) == null) { // the property wasn't set before. m_dbAccess.addSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS, extensions); } else { // overwrite the property. m_dbAccess.writeSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS, extensions); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + extensions.size(), CmsException.C_NO_ACCESS); } } } /** * Writes a fileheader to the Cms.<br> * * A file can only be written to an offline project.<br> * The state of the resource is set to CHANGED (1). The file content of the file * is either updated (if it is already existing in the offline project), or created * in the offline project (if it is not available there).<br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who own this file. * @param currentProject The project in which the resource will be used. * @param file The file to write. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void writeFileHeader(CmsUser currentUser, CmsProject currentProject, CmsFile file) throws CmsException { // has the user write-access? if( accessWrite(currentUser, currentProject, (CmsResource)file) ) { // write-acces was granted - write the file. m_dbAccess.writeFileHeader(currentProject, file,true, currentUser.getId()); if (file.getState()==C_STATE_UNCHANGED) { file.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.remove(file.getResourceName()); // inform about the file-system-change m_subresCache.clear(); m_accessCache.clear(); fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + file.getAbsolutePath(), CmsException.C_NO_ACCESS); } } /** * Writes an already existing group in the Cms.<BR/> * * Only the admin can do this.<P/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param group The group that should be written to the Cms. * @exception CmsException Throws CmsException if operation was not succesfull. */ public void writeGroup(CmsUser currentUser, CmsProject currentProject, CmsGroup group) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) ) { m_dbAccess.writeGroup(group); m_groupCache.put(group.getName(),group); } else { throw new CmsException("[" + this.getClass().getName() + "] " + group.getName(), CmsException.C_NO_ACCESS); } } /** * Writes a couple of propertyinformation for a file or folder. * * <B>Security</B> * Only the user is granted, who has the right to write the resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource of which the propertyinformation * has to be read. * @param propertyinfos A Hashtable with propertydefinition- propertyinfo-pairs as strings. * * @exception CmsException Throws CmsException if operation was not succesful */ public void writeProperties(CmsUser currentUser, CmsProject currentProject, String resource, Hashtable propertyinfos) throws CmsException { // read the resource CmsResource res = readFileHeader(currentUser,currentProject, resource); // check the security if( ! accessWrite(currentUser, currentProject, res) ) { throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_NO_ACCESS); } m_dbAccess.writeProperties(propertyinfos,currentProject.getId(),res,res.getType()); m_propertyCache.clear(); if (res.getState()==C_STATE_UNCHANGED) { res.setState(C_STATE_CHANGED); } if(res.isFile()){ m_dbAccess.writeFileHeader(currentProject, (CmsFile) res, false, currentUser.getId()); // update the cache m_resourceCache.remove(resource); } else { m_dbAccess.writeFolder(currentProject, readFolder(currentUser,currentProject, resource), false, currentUser.getId()); // update the cache m_resourceCache.remove(resource); } m_subresCache.clear(); } /** * Writes a propertyinformation for a file or folder. * * <B>Security</B> * Only the user is granted, who has the right to write the resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource of which the propertyinformation has * to be read. * @param property The propertydefinition-name of which the propertyinformation has to be set. * @param value The value for the propertyinfo to be set. * * @exception CmsException Throws CmsException if operation was not succesful */ public void writeProperty(CmsUser currentUser, CmsProject currentProject, String resource, String property, String value) throws CmsException { // read the resource CmsResource res = readFileHeader(currentUser,currentProject, resource); // check the security if( ! accessWrite(currentUser, currentProject, res) ) { throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_NO_ACCESS); } m_dbAccess.writeProperty(property, currentProject.getId(),value, res,res.getType()); m_propertyCache.clear(); // set the file-state to changed if(res.isFile()){ m_dbAccess.writeFileHeader(currentProject, (CmsFile) res, true, currentUser.getId()); if (res.getState()==C_STATE_UNCHANGED) { res.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.remove(resource); } else { if (res.getState()==C_STATE_UNCHANGED) { res.setState(C_STATE_CHANGED); } m_dbAccess.writeFolder(currentProject, readFolder(currentUser,currentProject, resource), true, currentUser.getId()); // update the cache m_resourceCache.remove(resource); } m_subresCache.clear(); } /** * Updates the propertydefinition for the resource type.<BR/> * * <B>Security</B> * Only the admin can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param propertydef The propertydef to be deleted. * * @return The propertydefinition, that was written. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsPropertydefinition writePropertydefinition(CmsUser currentUser, CmsProject currentProject, CmsPropertydefinition propertydef) throws CmsException { // check the security if( isAdmin(currentUser, currentProject) ) { m_propertyDefVectorCache.clear(); return( m_dbAccess.writePropertydefinition(propertydef) ); } else { throw new CmsException("[" + this.getClass().getName() + "] " + propertydef.getName(), CmsException.C_NO_ACCESS); } } /** * Writes a new user tasklog for a task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task . * @param comment Description for the log * * @exception CmsException Throws CmsException if something goes wrong. */ public void writeTaskLog(CmsUser currentUser, CmsProject currentProject, int taskid, String comment) throws CmsException { m_dbAccess.writeTaskLog(taskid, currentUser.getId(), new java.sql.Timestamp(System.currentTimeMillis()), comment, C_TASKLOG_USER); } /** * Writes a new user tasklog for a task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task . * @param comment Description for the log * @param tasktype Type of the tasklog. User tasktypes must be greater then 100. * * @exception CmsException Throws CmsException if something goes wrong. */ public void writeTaskLog(CmsUser currentUser, CmsProject currentProject, int taskid, String comment, int type) throws CmsException { m_dbAccess.writeTaskLog(taskid, currentUser.getId(), new java.sql.Timestamp(System.currentTimeMillis()), comment, type); } /** * Updates the user information.<BR/> * * Only the administrator can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param user The user to be updated. * * @exception CmsException Throws CmsException if operation was not succesful */ public void writeUser(CmsUser currentUser, CmsProject currentProject, CmsUser user) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) || (currentUser.equals(user)) ) { // prevent the admin to be set disabled! if( isAdmin(user, currentProject) ) { user.setEnabled(); } m_dbAccess.writeUser(user); // update the cache m_userCache.put(user.getName()+user.getType(),user); } else { throw new CmsException("[" + this.getClass().getName() + "] " + user.getName(), CmsException.C_NO_ACCESS); } } /** * Updates the user information of a web user.<BR/> * * Only a web user can be updated this way.<P/> * * <B>Security:</B> * Only users of the user type webuser can be updated this way. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param user The user to be updated. * * @exception CmsException Throws CmsException if operation was not succesful */ public void writeWebUser(CmsUser currentUser, CmsProject currentProject, CmsUser user) throws CmsException { // Check the security if( user.getType() == C_USER_TYPE_WEBUSER) { m_dbAccess.writeUser(user); // update the cache m_userCache.put(user.getName()+user.getType(),user); } else { throw new CmsException("[" + this.getClass().getName() + "] " + user.getName(), CmsException.C_NO_ACCESS); } } /** * Changes the project-id of a resource to the new project * for publishing the resource directly * * @param newProjectId The new project-id * @param resourcename The name of the resource to change */ public void changeLockedInProject(int projectId, String resourcename) throws CmsException{ m_dbAccess.changeLockedInProject(projectId, resourcename); m_resourceCache.remove(resourcename); } /** * Check if the history is enabled * * @return boolean Is true if history is enabled */ public boolean isHistoryEnabled(){ return this.m_enableHistory; } /** * Get the next version id for the published backup resources * * @return int The new version id */ public int getBackupVersionId(){ return m_dbAccess.getBackupVersionId(); } /** * Creates a backup of the published project * * @param project The project in which the resource was published. * @param projectresources The resources of the project * @param versionId The version of the backup * @param publishDate The date of publishing * @param userId The id of the user who had published the project * * @exception CmsException Throws CmsException if operation was not succesful. */ public void backupProject(int projectId, int versionId, long publishDate, CmsUser currentUser) throws CmsException{ CmsProject project = m_dbAccess.readProject(projectId); m_dbAccess.backupProject(project, versionId, publishDate, currentUser); } /** * Checks if this is a valid group for webusers * * @param group The group to be checked * @return boolean If the group does not belong to Users, Administrators or Projectmanagers return true */ protected boolean isWebgroup(CmsGroup group){ try{ int user = m_dbAccess.readGroup(C_GROUP_USERS).getId(); int admin = m_dbAccess.readGroup(C_GROUP_ADMIN).getId(); int manager = m_dbAccess.readGroup(C_GROUP_PROJECTLEADER).getId(); if(group.getId() == user || group.getId() == admin || group.getId() == manager){ return false; } else { int parentId = group.getParentId(); // check if the group belongs to Users, Administrators or Projectmanager if (parentId != C_UNKNOWN_ID){ if(parentId == user || parentId == admin || parentId == manager){ // the parent return false; } else { // check is the parentgroup is a webgroup isWebgroup(m_dbAccess.readGroup(parentId)); } } } } catch (Exception e){ return false; } return true; } /** * Gets the Crontable. * * <B>Security:</B> * All users are garnted<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * @return the crontable. */ public String readCronTable(CmsUser currentUser, CmsProject currentProject) throws CmsException { String retValue = (String) m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_CRONTABLE); if(retValue == null) { return ""; } else { return retValue; } } /** * Writes the Crontable. * * <B>Security:</B> * Only a administrator can do this<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * @return the crontable. */ public void writeCronTable(CmsUser currentUser, CmsProject currentProject, String crontable) throws CmsException { if(isAdmin(currentUser, currentProject)) { if(m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_CRONTABLE) == null) { m_dbAccess.addSystemProperty(C_SYSTEMPROPERTY_CRONTABLE, crontable); } else { m_dbAccess.writeSystemProperty(C_SYSTEMPROPERTY_CRONTABLE, crontable); } } else { throw new CmsException("No access to write crontable", CmsException.C_NO_ACCESS); } } }
Recovery password can be set by any user who knows the users name and the users password
src/com/opencms/file/genericSql/CmsResourceBroker.java
Recovery password can be set by any user who knows the users name and the users password
<ide><path>rc/com/opencms/file/genericSql/CmsResourceBroker.java <ide> /* <ide> * File : $Source: /alkacon/cvs/opencms/src/com/opencms/file/genericSql/Attic/CmsResourceBroker.java,v $ <del>* Date : $Date: 2001/11/15 16:41:21 $ <del>* Version: $Revision: 1.292 $ <add>* Date : $Date: 2001/12/03 12:55:48 $ <add>* Version: $Revision: 1.293 $ <ide> * <ide> * This library is part of OpenCms - <ide> * the Open Source Content Mananagement System <ide> * @author Michaela Schleich <ide> * @author Michael Emmerich <ide> * @author Anders Fugmann <del> * @version $Revision: 1.292 $ $Date: 2001/11/15 16:41:21 $ <add> * @version $Revision: 1.293 $ $Date: 2001/12/03 12:55:48 $ <ide> * <ide> */ <ide> public class CmsResourceBroker implements I_CmsResourceBroker, I_CmsConstants { <ide> // this is no system-user - maybe a webuser? <ide> user = readWebUser(currentUser, currentProject, username, password); <ide> } <del> if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) && <del> ( isAdmin(user, currentProject) || user.equals(currentUser)) ) { <add> //if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) && <add> // ( isAdmin(user, currentProject) || user.equals(currentUser)) ) { <ide> m_dbAccess.setRecoveryPassword(username, newPassword); <del> } else { <del> throw new CmsException("[" + this.getClass().getName() + "] " + username, <del> CmsException.C_NO_ACCESS); <del> } <add> //} else { <add> // throw new CmsException("[" + this.getClass().getName() + "] " + username, <add> // CmsException.C_NO_ACCESS); <add> //} <ide> } <ide> /** <ide> * Set a Parameter for a task.
JavaScript
mit
f9500e954c3846c7e5ec4108318a211b00278b1c
0
silverbux/rsjs
0f4bac59-2e9d-11e5-b555-a45e60cdfd11
helloWorld.js
0f40ec47-2e9d-11e5-b895-a45e60cdfd11
0f4bac59-2e9d-11e5-b555-a45e60cdfd11
helloWorld.js
0f4bac59-2e9d-11e5-b555-a45e60cdfd11
<ide><path>elloWorld.js <del>0f40ec47-2e9d-11e5-b895-a45e60cdfd11 <add>0f4bac59-2e9d-11e5-b555-a45e60cdfd11
JavaScript
apache-2.0
4fae535be74e351c4097741b25aef04f8e77d743
0
tomorrowevening/fido
function getType(source) { var typeA = source.split("."); var type = typeA[ typeA.length-1 ]; // Image if(type === 'jpg' || type === 'jpeg' || type === 'png' || type === 'gif') { return 'image'; } // Audio else if(type === 'mp3' || type === 'wav') { return 'audio'; } // Video else if(type === 'mov' || type === 'mp4') { return 'video'; } return "noType"; } function sortObjArray(arr, value) { var newArr = [], i, total = arr.length; for(i = 0; i < total; ++i) { newArr.push( arr[i][value] ); } newArr.sort(); return newArr; } function ExportLayer(item, exportOptions) { exportOptions.name = item.name; var _retina = exportOptions.retina; ////////////////////////////////////////////////// // Export layer var transform = item.property("Transform"); var data = { "name": item.name.replace(" ", "_"), "type": "", "start": item.inPoint, "duration": item.outPoint - item.inPoint, "transform": ExportTransform( transform, exportOptions ), "content": [] }; if(item instanceof CameraLayer) { data.type = "camera"; data.content = ExportCamera( item, exportOptions ); } else { var effects = item.property("effect"); data.effects = ExportEffects( effects, exportOptions ); var masks = item.property("Masks"); if( masks.numProperties > 0 ) { data.masks = []; for(var i = 1; i <= masks.numProperties; ++i) { var prop = masks.property(i).property("Mask Path"); var path = prop.valueAtTime(0, false); var vertices = []; var inTangents = []; var outTangents= []; var n, total = path.vertices.length; for(n = 0; n < total; ++n) { vertices.push([ path.vertices[n][0] * _retina, path.vertices[n][1] * _retina ]); inTangents.push([ path.inTangents[n][0] * _retina, path.inTangents[n][1] * _retina ]); outTangents.push([ path.outTangents[n][0] * _retina, path.outTangents[n][1] * _retina ]); } var mask = { "name" : masks.property(i).name.replace(" ", "_"), "vertices" : vertices, "inTangents" : inTangents, "outTangents": outTangents, "timeline" : exportPathAni( prop, exportOptions ) }; data.masks.push( mask ); } } if( item instanceof ShapeLayer) { var content = item.property("content"); data.type = "shape"; data.content = exportShapeContent( content, exportOptions ); // data.content = sortObjArray(data.content, "type"); // for(var i = 1; i <= content.numProperties; ++i) { // var shape = ExportShape( content.property(i), exportOptions ); // if(shape !== undefined) data.content.push( shape ); // } } else if(item instanceof TextLayer) { data.type = "text"; data.content = ExportText( item, exportOptions ); } else if(item instanceof AVLayer) { if(item.hasTrackMatte) { var prevTransform = exportOptions.prevLayer.property("Transform"); data.matte = { src: getRelativeFilePath( exportOptions.prevLayer.source.mainSource.file.toString() ), type: 'none', transform: ExportTransform( prevTransform, exportOptions ) }; switch(item.trackMatteType) { case TrackMatteType.ALPHA: data.matte.type = 'alpha'; break; case TrackMatteType.ALPHA_INVERTED: data.matte.type = 'alphaInverted'; break; case TrackMatteType.LUMA: data.matte.type = 'luma'; break; case TrackMatteType.LUMA_INVERTED: data.matte.type = 'lumaInverted'; break; } } else if(item.isTrackMatte) { data.isTrackMatte = true; } if(item.adjustmentLayer) { data.type = "adjustment"; } else { if(item.source instanceof CompItem) { data.type = "composition"; data.content = item.source.name.replace(" ", "_"); } else if(item.source instanceof FootageItem) { if(item.source.mainSource instanceof SolidSource) { data.type = "shape"; data.content = { 'type': 'square', 'color': item.source.mainSource.color, 'width': item.source.width, 'height': item.source.height }; } else if(item.source.mainSource instanceof FileSource) { var source = getRelativeFilePath( item.source.mainSource.file.toString() ); data.type = getType( item.source.mainSource.file.toString() ); if(data.type === "audio") { if(!item.audioEnabled) return undefined; // layer isn't enabled data.content = ExportAudio( item, exportOptions ); data.effects = data.transform = undefined; } else if(data.type === "image") { data.content = ExportAVLayer( item, exportOptions ); } else if(data.type === "video") { data.content = ExportAVLayer( item, exportOptions ); } } else { // placeholder alert("placeholder!"); } } } } } return data; }; ////////////////////////////////////////////////// // Test functions function _isShape(p) { return p.property("Path") !== null; } function _isRect(p) { return p.property("Size") !== null && p.property("Position") !== null && p.property("Roundness") !== null; // return p.name.search("Rectangle Path") > -1; } function _isEllipse(p) { return p.property("Size") !== null && p.property("Position") !== null; // return p.name.search("Ellipse Path") > -1; } function _isPoly(p) { return p.property("Points") !== null; // return p.name.search("Polystar Path") > -1; } function getPropShape(prop, i, exportOptions) { // var content = prop.property("Contents"); var paths = []; var i, total = content.numProperties; for(i = 1; i <= total; ++i) { var sPath = content.property(i); if( sPath.active && sPath.enabled ) { if( _isRect(sPath) ) { // return ExportRectPath( sPath ); paths.push( ExportRectPath( sPath, exportOptions ) ); } else if( _isEllipse(sPath) ) { // return ExportEllipsePath( sPath ); paths.push( ExportEllipsePath( sPath, exportOptions ) ); } else if( _isPoly(sPath) ) { // return ExportPolygonPath( sPath ); paths.push( ExportPolygonPath( sPath, exportOptions ) ); } else if( _isShape(sPath) ) { // return ExportShapePath( sPath ); paths.push( ExportShapePath( sPath, exportOptions ) ); } } } return paths; } function exportShapeContent(content, exportOptions) { var _retina = exportOptions.retina; var layers = []; for(var i = 1; i <= content.numProperties; ++i) { var prop = content.property(i); if( prop.active && prop.enabled ) { var layer = { name : prop.name.replace(" ", "_"), type : "none" // value : {} }; // Stroke if( prop.property("Color") !== null && prop.property("Stroke Width") !== null ) { layer.type = "stroke"; layer.content = undefined; layer.value = { color: prop.property("Color").valueAtTime(0, false), opacity: prop.property("Opacity").valueAtTime(0, false) / 100, width: prop.property("Stroke Width").valueAtTime(0, false) * _retina, cap: "butt", corner: "miter" }; switch(prop.property("Line Cap").valueAtTime(0, false)) { case 1: layer.value.cap = "butt"; break; case 2: layer.value.cap = "round"; break; case 3: layer.value.cap = "bevel"; break; } switch(prop.property("Line Join").valueAtTime(0, false)) { case 1: layer.value.corner = "miter"; break; case 2: layer.value.corner = "round"; break; case 3: layer.value.corner = "bevel"; break; } layer.timeline = exportProps(prop, ["Color", "Opacity", "Stroke Width"], ["color", "opacity", "width"], exportOptions); if(layer.timeline.length > 0 && layer.timeline[0].name === "color") layer.timeline[0].name = "stroke"; var dashes = prop.property("Dashes"); layer.value.dashes = { dash : dashes.property("Dash").valueAtTime(0, false) * _retina, gap : dashes.property("Gap").valueAtTime(0, false) * _retina, offset: dashes.property("Offset").valueAtTime(0, false) * _retina }; if(!dashes.isModified) { layer.value.dashes = undefined; // delete, not actually added } if(layer.value.dashes !== undefined) { var dashedTL = exportProps(dashes, ["Dash", "Gap", "Offset"], ["dash", "gap", "offset"], exportOptions); if(dashedTL.length > 0) { layer.value.dashes.timeline = dashedTL; } } } // Fill else if( prop.property("Color") !== null && prop.property("Opacity") !== null ) { layer.type = "fill"; layer.content = undefined; layer.value = { color: prop.property("Color").valueAtTime(0, false), opacity: prop.property("Opacity").valueAtTime(0, false) / 100 }; layer.timeline = exportProps(prop, ["Color", "Opacity"], ["color", "opacity"], exportOptions); if(layer.timeline.length > 0 && layer.timeline[0].name === "color") layer.timeline[0].name = "fill"; } // Repeater else if( prop.property("Copies") !== null && prop.property("Offset") !== null && prop.property("Transform") !== null ) { var transform = prop.property("Transform"); layer.type = "repeater"; layer.value = { copies: prop.property("Copies").valueAtTime(0, false), offset: prop.property("Offset").valueAtTime(0, false), transform: { anchor : transform.property("Anchor Point").valueAtTime(0, false), position: transform.property("Position").valueAtTime(0, false), rotation: transform.property("Rotation").valueAtTime(0, false), scale : [ transform.property("Scale").valueAtTime(0, false)[0] / 100, transform.property("Scale").valueAtTime(0, false)[1] / 100 ] } }; layer.value.transform.anchor[0] *= _retina; layer.value.transform.anchor[1] *= _retina; layer.value.transform.position[0] *= _retina; layer.value.transform.position[1] *= _retina; layer.timeline = []; // Transform layer.timeline = layer.timeline.concat( exportProps(transform, [ "Anchor Point", "Position", "Scale", "Rotation" ], [ "anchor", "position", "scale", "rotationZ" ]) ); // Repeater layer.timeline = layer.timeline.concat( exportProps(prop, [ "Copies", "Offset" ], [ "copies", "offset" ]) ); } // Trim else if( prop.property("Start") !== null && prop.property("End") !== null && prop.property("Offset") !== null ) { layer.type = "trim"; layer.value = { start: prop.property("Start").valueAtTime(0, false), end: prop.property("End").valueAtTime(0, false), offset: prop.property("Offset").valueAtTime(0, false), }; // layer.value.start = prop.property("Start").valueAtTime(0, false) / 100; // layer.value.end = prop.property("End").valueAtTime(0, false); // layer.value.offset = prop.property("Offset").valueAtTime(0, false) / 100; layer.timeline = exportProps(prop, ["Start", "End", "Offset"], ["start", "end", "offset"], exportOptions); normalizeAnimation("start", layer); normalizeAnimation("end", layer); normalizeAnimation("offset", layer, 360); } // Offset else if( prop.property("Amount") !== null && prop.property("Line Join") !== null && prop.property("Miter Limit") !== null ) { layer.type = "offset"; layer.value = { amount: prop.property("Amount").valueAtTime(0, false) }; // layer.value.amount = prop.property("Amount").valueAtTime(0, false); layer.timeline = exportProps(prop, ["Amount"], ["amount"], exportOptions); } // Wiggle else if( prop.property("Size") !== null && prop.property("Detail") !== null && prop.property("Temporal Phase") !== null ) { layer.type = "wiggle"; layer.value = { size: prop.property("Size").valueAtTime(0, false), detail: prop.property("Detail").valueAtTime(0, false) }; // layer.value.size = prop.property("Size").valueAtTime(0, false); // layer.value.detail = prop.property("Detail").valueAtTime(0, false); } // Twist else if( prop.property("Angle") !== null && prop.property("Center") !== null ) { layer.type = "twist"; layer.value = { angle: prop.property("Angle").valueAtTime(0, false), center: prop.property("Center").valueAtTime(0, false) }; // layer.value.angle = prop.property("Angle").valueAtTime(0, false); // layer.value.center = prop.property("Center").valueAtTime(0, false); } // Zig Zag else if( prop.property("Size") !== null && prop.property("Points") !== null && prop.property("Ridges per segment") !== null ) { layer.type = "zigzag"; layer.value = { size: prop.property("Size").valueAtTime(0, false), ridges: prop.property("Ridges per segment").valueAtTime(0, false) }; // layer.value.size = prop.property("Size").valueAtTime(0, false); // layer.value.ridges = prop.property("Ridges per segment").valueAtTime(0, false); } // Shape else if( prop.property("Contents") !== null ) { layer.type = "shape"; layer.content = exportShapeContent( prop.property("Contents"), exportOptions ); var isGroup = layer.name.toLowerCase().search("group"); if(isGroup > -1) { layer.type = "group"; } else { layer.paths = getPropShape( prop, i, exportOptions ); var transform = ExportTransform2D( prop.property("Transform"), exportOptions ); transform.type = "transform"; layer.content.push( transform ); // Sort by type layer.content.sort(function(a,b) { if (a.type < b.type) return -1; if (a.type > b.type) return 1; return 0; }); } } // Path else if( prop.property("Path") !== null ) { layer = undefined; } else { layer = undefined; } if(layer !== undefined) layers.push( layer ); } } return layers; } ////////////////////////////////////////////////// // Layer calls function ExportEffects(effects, exportOptions) { var a = []; var i, effect, total = effects.numProperties; for(i = 1; i <= total; ++i) { effect = effects.property(i); var obj = { 'name': effect.name, 'timeline': {} }; for(var n = 1; n < effect.numProperties; ++n) { var prop = effect.property(n); if(prop !== undefined && prop !== null && prop.name.length > 0 && prop.value !== undefined) { if(prop.isTimeVarying) { obj[ prop.name ] = prop.keyValue(1); obj.timeline[ prop.name ] = exportPropAni( effect, prop.name, prop.name.toLowerCase(), exportOptions )[0]; } else { obj[ prop.name ] = prop.value; } } } a.push( obj ); } return cleanEffects(a); } function cleanEffects(effects) { var i, total = effects.length, newEffects = [], effect, timeline; for(i = 0; i < total; ++i) { effect = effects[i]; if(effect.name === "Gaussian Blur") { timeline = {}; if(effect.timeline.Blurriness !== undefined) { timeline.blurriness = effect.timeline.Blurriness; } var direction = [1, 1]; var dimensions = effect["Blur Dimensions"]; if(dimensions === 2) direction[1] = 0; else if(dimensions === 3) direction[0] = 0; newEffects.push({ name: 'Gaussian Blur', timeline: timeline, blurriness: effect.Blurriness, direction: direction }) } } return newEffects; }
src/fido/ExportLayer.js
function getType(source) { var typeA = source.split("."); var type = typeA[ typeA.length-1 ]; // Image if(type === 'jpg' || type === 'jpeg' || type === 'png' || type === 'gif') { return 'image'; } // Audio else if(type === 'mp3' || type === 'wav') { return 'audio'; } // Video else if(type === 'mov' || type === 'mp4') { return 'video'; } return "noType"; } function sortObjArray(arr, value) { var newArr = [], i, total = arr.length; for(i = 0; i < total; ++i) { newArr.push( arr[i][value] ); } newArr.sort(); return newArr; } function ExportLayer(item, exportOptions) { exportOptions.name = item.name; var _retina = exportOptions.retina; ////////////////////////////////////////////////// // Export layer var transform = item.property("Transform"); var data = { "name": item.name.replace(" ", "_"), "type": "", "start": item.inPoint, "duration": item.outPoint - item.inPoint, "transform": ExportTransform( transform, exportOptions ), "content": [] }; if(item instanceof CameraLayer) { data.type = "camera"; data.content = ExportCamera( item, exportOptions ); } else { var effects = item.property("effect"); data.effects = ExportEffects( effects, exportOptions ); var masks = item.property("Masks"); if( masks.numProperties > 0 ) { data.masks = []; for(var i = 1; i <= masks.numProperties; ++i) { var prop = masks.property(i).property("Mask Path"); var path = prop.valueAtTime(0, false); var vertices = []; var inTangents = []; var outTangents= []; var n, total = path.vertices.length; for(n = 0; n < total; ++n) { vertices.push([ path.vertices[n][0] * _retina, path.vertices[n][1] * _retina ]); inTangents.push([ path.inTangents[n][0] * _retina, path.inTangents[n][1] * _retina ]); outTangents.push([ path.outTangents[n][0] * _retina, path.outTangents[n][1] * _retina ]); } var mask = { "name" : masks.property(i).name.replace(" ", "_"), "vertices" : vertices, "inTangents" : inTangents, "outTangents": outTangents, "timeline" : exportPathAni( prop, exportOptions ) }; data.masks.push( mask ); } } if( item instanceof ShapeLayer) { var content = item.property("content"); data.type = "shape"; data.content = exportShapeContent( content, exportOptions ); // data.content = sortObjArray(data.content, "type"); // for(var i = 1; i <= content.numProperties; ++i) { // var shape = ExportShape( content.property(i), exportOptions ); // if(shape !== undefined) data.content.push( shape ); // } } else if(item instanceof TextLayer) { data.type = "text"; data.content = ExportText( item, exportOptions ); } else if(item instanceof AVLayer) { if(item.adjustmentLayer) { data.type = "adjustment"; } else { if(item.source instanceof CompItem) { data.type = "composition"; data.content = item.source.name.replace(" ", "_"); } else if(item.source instanceof FootageItem) { if(item.source.mainSource instanceof SolidSource) { data.type = "shape"; data.content = { 'type': 'square', 'color': item.source.mainSource.color, 'width': item.source.width, 'height': item.source.height }; } else if(item.source.mainSource instanceof FileSource) { var source = getRelativeFilePath( item.source.mainSource.file.toString() ); data.type = getType( item.source.mainSource.file.toString() ); if(data.type === "audio") { if(!item.audioEnabled) return undefined; // layer isn't enabled data.content = ExportAudio( item, exportOptions ); data.effects = data.transform = undefined; } else if(data.type === "image") { data.content = ExportAVLayer( item, exportOptions ); } else if(data.type === "video") { data.content = ExportAVLayer( item, exportOptions ); } } else { // placeholder alert("placeholder!"); } } } } } return data; }; ////////////////////////////////////////////////// // Test functions function _isShape(p) { return p.property("Path") !== null; } function _isRect(p) { return p.property("Size") !== null && p.property("Position") !== null && p.property("Roundness") !== null; // return p.name.search("Rectangle Path") > -1; } function _isEllipse(p) { return p.property("Size") !== null && p.property("Position") !== null; // return p.name.search("Ellipse Path") > -1; } function _isPoly(p) { return p.property("Points") !== null; // return p.name.search("Polystar Path") > -1; } function getPropShape(prop, i, exportOptions) { // var content = prop.property("Contents"); var paths = []; var i, total = content.numProperties; for(i = 1; i <= total; ++i) { var sPath = content.property(i); if( sPath.active && sPath.enabled ) { if( _isRect(sPath) ) { // return ExportRectPath( sPath ); paths.push( ExportRectPath( sPath, exportOptions ) ); } else if( _isEllipse(sPath) ) { // return ExportEllipsePath( sPath ); paths.push( ExportEllipsePath( sPath, exportOptions ) ); } else if( _isPoly(sPath) ) { // return ExportPolygonPath( sPath ); paths.push( ExportPolygonPath( sPath, exportOptions ) ); } else if( _isShape(sPath) ) { // return ExportShapePath( sPath ); paths.push( ExportShapePath( sPath, exportOptions ) ); } } } return paths; } function exportShapeContent(content, exportOptions) { var _retina = exportOptions.retina; var layers = []; for(var i = 1; i <= content.numProperties; ++i) { var prop = content.property(i); if( prop.active && prop.enabled ) { var layer = { name : prop.name.replace(" ", "_"), type : "none" // value : {} }; // Stroke if( prop.property("Color") !== null && prop.property("Stroke Width") !== null ) { layer.type = "stroke"; layer.content = undefined; layer.value = { color: prop.property("Color").valueAtTime(0, false), opacity: prop.property("Opacity").valueAtTime(0, false) / 100, width: prop.property("Stroke Width").valueAtTime(0, false) * _retina, cap: "butt", corner: "miter" }; switch(prop.property("Line Cap").valueAtTime(0, false)) { case 1: layer.value.cap = "butt"; break; case 2: layer.value.cap = "round"; break; case 3: layer.value.cap = "bevel"; break; } switch(prop.property("Line Join").valueAtTime(0, false)) { case 1: layer.value.corner = "miter"; break; case 2: layer.value.corner = "round"; break; case 3: layer.value.corner = "bevel"; break; } layer.timeline = exportProps(prop, ["Color", "Opacity", "Stroke Width"], ["color", "opacity", "width"], exportOptions); if(layer.timeline.length > 0 && layer.timeline[0].name === "color") layer.timeline[0].name = "stroke"; var dashes = prop.property("Dashes"); layer.value.dashes = { dash : dashes.property("Dash").valueAtTime(0, false) * _retina, gap : dashes.property("Gap").valueAtTime(0, false) * _retina, offset: dashes.property("Offset").valueAtTime(0, false) * _retina }; if(!dashes.isModified) { layer.value.dashes = undefined; // delete, not actually added } if(layer.value.dashes !== undefined) { var dashedTL = exportProps(dashes, ["Dash", "Gap", "Offset"], ["dash", "gap", "offset"], exportOptions); if(dashedTL.length > 0) { layer.value.dashes.timeline = dashedTL; } } } // Fill else if( prop.property("Color") !== null && prop.property("Opacity") !== null ) { layer.type = "fill"; layer.content = undefined; layer.value = { color: prop.property("Color").valueAtTime(0, false), opacity: prop.property("Opacity").valueAtTime(0, false) / 100 }; layer.timeline = exportProps(prop, ["Color", "Opacity"], ["color", "opacity"], exportOptions); if(layer.timeline.length > 0 && layer.timeline[0].name === "color") layer.timeline[0].name = "fill"; } // Repeater else if( prop.property("Copies") !== null && prop.property("Offset") !== null && prop.property("Transform") !== null ) { var transform = prop.property("Transform"); layer.type = "repeater"; layer.value = { copies: prop.property("Copies").valueAtTime(0, false), offset: prop.property("Offset").valueAtTime(0, false), transform: { anchor : transform.property("Anchor Point").valueAtTime(0, false), position: transform.property("Position").valueAtTime(0, false), rotation: transform.property("Rotation").valueAtTime(0, false), scale : [ transform.property("Scale").valueAtTime(0, false)[0] / 100, transform.property("Scale").valueAtTime(0, false)[1] / 100 ] } }; layer.value.transform.anchor[0] *= _retina; layer.value.transform.anchor[1] *= _retina; layer.value.transform.position[0] *= _retina; layer.value.transform.position[1] *= _retina; layer.timeline = []; // Transform layer.timeline = layer.timeline.concat( exportProps(transform, [ "Anchor Point", "Position", "Scale", "Rotation" ], [ "anchor", "position", "scale", "rotationZ" ]) ); // Repeater layer.timeline = layer.timeline.concat( exportProps(prop, [ "Copies", "Offset" ], [ "copies", "offset" ]) ); } // Trim else if( prop.property("Start") !== null && prop.property("End") !== null && prop.property("Offset") !== null ) { layer.type = "trim"; layer.value = { start: prop.property("Start").valueAtTime(0, false), end: prop.property("End").valueAtTime(0, false), offset: prop.property("Offset").valueAtTime(0, false), }; // layer.value.start = prop.property("Start").valueAtTime(0, false) / 100; // layer.value.end = prop.property("End").valueAtTime(0, false); // layer.value.offset = prop.property("Offset").valueAtTime(0, false) / 100; layer.timeline = exportProps(prop, ["Start", "End", "Offset"], ["start", "end", "offset"], exportOptions); normalizeAnimation("start", layer); normalizeAnimation("end", layer); normalizeAnimation("offset", layer, 360 * _retina); } // Offset else if( prop.property("Amount") !== null && prop.property("Line Join") !== null && prop.property("Miter Limit") !== null ) { layer.type = "offset"; layer.value = { amount: prop.property("Amount").valueAtTime(0, false) }; // layer.value.amount = prop.property("Amount").valueAtTime(0, false); layer.timeline = exportProps(prop, ["Amount"], ["amount"], exportOptions); } // Wiggle else if( prop.property("Size") !== null && prop.property("Detail") !== null && prop.property("Temporal Phase") !== null ) { layer.type = "wiggle"; layer.value = { size: prop.property("Size").valueAtTime(0, false), detail: prop.property("Detail").valueAtTime(0, false) }; // layer.value.size = prop.property("Size").valueAtTime(0, false); // layer.value.detail = prop.property("Detail").valueAtTime(0, false); } // Twist else if( prop.property("Angle") !== null && prop.property("Center") !== null ) { layer.type = "twist"; layer.value = { angle: prop.property("Angle").valueAtTime(0, false), center: prop.property("Center").valueAtTime(0, false) }; // layer.value.angle = prop.property("Angle").valueAtTime(0, false); // layer.value.center = prop.property("Center").valueAtTime(0, false); } // Zig Zag else if( prop.property("Size") !== null && prop.property("Points") !== null && prop.property("Ridges per segment") !== null ) { layer.type = "zigzag"; layer.value = { size: prop.property("Size").valueAtTime(0, false), ridges: prop.property("Ridges per segment").valueAtTime(0, false) }; // layer.value.size = prop.property("Size").valueAtTime(0, false); // layer.value.ridges = prop.property("Ridges per segment").valueAtTime(0, false); } // Shape else if( prop.property("Contents") !== null ) { layer.type = "shape"; layer.content = exportShapeContent( prop.property("Contents"), exportOptions ); var isGroup = layer.name.toLowerCase().search("group"); if(isGroup > -1) { layer.type = "group"; } else { layer.paths = getPropShape( prop, i, exportOptions ); var transform = ExportTransform2D( prop.property("Transform"), exportOptions ); transform.type = "transform"; layer.content.push( transform ); // Sort by type layer.content.sort(function(a,b) { if (a.type < b.type) return -1; if (a.type > b.type) return 1; return 0; }); } } // Path else if( prop.property("Path") !== null ) { layer = undefined; } else { layer = undefined; } if(layer !== undefined) layers.push( layer ); } } return layers; } //is something: Rectangle Path 1 //Error exporting: Rectangle Path 1, Size :: undefined is not an object //Error exporting: Rectangle Path 1, Position ////////////////////////////////////////////////// // Layer calls function ExportEffects(effects, exportOptions) { var a = []; var i, effect, total = effects.numProperties; for(i = 1; i <= total; ++i) { effect = effects.property(i); var obj = { 'name': effect.name, 'timeline': {} // 'keys': effect.numKeys }; for(var n = 1; n < effect.numProperties; ++n) { var prop = effect.property(n); if(prop !== undefined && prop !== null && prop.name.length > 0 && prop.value !== undefined) { // obj[ prop.name ] = prop.valueAtTime(1); if(prop.isTimeVarying) { obj[ prop.name ] = prop.keyValue(1); obj.timeline[ prop.name ] = exportPropAni( effect, prop.name, prop.name.toLowerCase(), exportOptions )[0]; // obj[ prop.name ].start = prop.keyValue(1); // obj[ prop.name ].end = prop.keyValue(prop.numKeys); } else { obj[ prop.name ] = prop.value; } } } // if(effect.isTimeVarying) { // obj['start'] = effect.keyValue(1); // obj['end'] = effect.keyValue(effect.numKeys); // // obj['keyframes'] = ExportKeyframes( effect ); // } a.push( obj ); } return a; }
effects/trackMatte added, trim fix
src/fido/ExportLayer.js
effects/trackMatte added, trim fix
<ide><path>rc/fido/ExportLayer.js <ide> data.type = "text"; <ide> data.content = ExportText( item, exportOptions ); <ide> } else if(item instanceof AVLayer) { <add> if(item.hasTrackMatte) { <add> var prevTransform = exportOptions.prevLayer.property("Transform"); <add> data.matte = { <add> src: getRelativeFilePath( exportOptions.prevLayer.source.mainSource.file.toString() ), <add> type: 'none', <add> transform: ExportTransform( prevTransform, exportOptions ) <add> }; <add> <add> switch(item.trackMatteType) { <add> case TrackMatteType.ALPHA: <add> data.matte.type = 'alpha'; <add> break; <add> case TrackMatteType.ALPHA_INVERTED: <add> data.matte.type = 'alphaInverted'; <add> break; <add> case TrackMatteType.LUMA: <add> data.matte.type = 'luma'; <add> break; <add> case TrackMatteType.LUMA_INVERTED: <add> data.matte.type = 'lumaInverted'; <add> break; <add> } <add> } else if(item.isTrackMatte) { <add> data.isTrackMatte = true; <add> } <ide> if(item.adjustmentLayer) { <ide> data.type = "adjustment"; <ide> } else { <ide> layer.timeline = exportProps(prop, ["Start", "End", "Offset"], ["start", "end", "offset"], exportOptions); <ide> normalizeAnimation("start", layer); <ide> normalizeAnimation("end", layer); <del> normalizeAnimation("offset", layer, 360 * _retina); <add> normalizeAnimation("offset", layer, 360); <ide> } <ide> // Offset <ide> else if( prop.property("Amount") !== null && prop.property("Line Join") !== null && prop.property("Miter Limit") !== null ) { <ide> return layers; <ide> } <ide> <del>//is something: Rectangle Path 1 <del>//Error exporting: Rectangle Path 1, Size :: undefined is not an object <del>//Error exporting: Rectangle Path 1, Position <del> <ide> ////////////////////////////////////////////////// <ide> // Layer calls <ide> <ide> var obj = { <ide> 'name': effect.name, <ide> 'timeline': {} <del> // 'keys': effect.numKeys <ide> }; <ide> for(var n = 1; n < effect.numProperties; ++n) { <ide> var prop = effect.property(n); <ide> if(prop !== undefined && prop !== null && prop.name.length > 0 && prop.value !== undefined) { <del> <del> // obj[ prop.name ] = prop.valueAtTime(1); <ide> if(prop.isTimeVarying) { <ide> obj[ prop.name ] = prop.keyValue(1); <ide> obj.timeline[ prop.name ] = exportPropAni( effect, prop.name, prop.name.toLowerCase(), exportOptions )[0]; <del> // obj[ prop.name ].start = prop.keyValue(1); <del> // obj[ prop.name ].end = prop.keyValue(prop.numKeys); <ide> } else { <ide> obj[ prop.name ] = prop.value; <ide> } <ide> } <ide> } <del> // if(effect.isTimeVarying) { <del> // obj['start'] = effect.keyValue(1); <del> // obj['end'] = effect.keyValue(effect.numKeys); <del> // // obj['keyframes'] = ExportKeyframes( effect ); <del> // } <ide> a.push( obj ); <ide> } <del> return a; <del>} <add> return cleanEffects(a); <add>} <add> <add>function cleanEffects(effects) { <add> var i, total = effects.length, newEffects = [], effect, timeline; <add> for(i = 0; i < total; ++i) { <add> effect = effects[i]; <add> if(effect.name === "Gaussian Blur") { <add> timeline = {}; <add> if(effect.timeline.Blurriness !== undefined) { <add> timeline.blurriness = effect.timeline.Blurriness; <add> } <add> <add> var direction = [1, 1]; <add> var dimensions = effect["Blur Dimensions"]; <add> if(dimensions === 2) direction[1] = 0; <add> else if(dimensions === 3) direction[0] = 0; <add> newEffects.push({ <add> name: 'Gaussian Blur', <add> timeline: timeline, <add> blurriness: effect.Blurriness, <add> direction: direction <add> }) <add> } <add> } <add> return newEffects; <add>}
Java
mit
error: pathspec 'cp-book/ch4/mf/_11380_DownWentTheTitanic.java' did not match any file(s) known to git
135865948375ae463012be8077504066f573059b
1
andrey-yemelyanov/competitive-programming,andrey-yemelyanov/competitive-programming
import java.util.*; import static java.lang.Math.*; import java.util.stream.*; /* Problem name: 11380 Down Went The Titanic Problem url: https://uva.onlinejudge.org/external/113/11380.pdf Author: Andrey Yemelyanov */ public class _11380_DownWentTheTitanic { public static void main(String[] args){ Scanner s = new Scanner(System.in); while(s.hasNext()){ int X = s.nextInt(); int Y = s.nextInt(); int P = s.nextInt(); char[][] grid = new char[X][Y]; for(int i = 0; i < grid.length; i++){ String line = s.next(); for(int j = 0; j < grid[i].length; j++){ grid[i][j] = line.charAt(j); } } int[][] res = buildResidualMatrix(buildIncidentMatrix(grid), grid, P); int source = res.length - 2; int sink = res.length - 1; System.out.println(maxFlow(res, source, sink)); } } static final int UNDEF = -1; static final int INF = 100000000; static int f; static void augment(int v, int source, int minEdge, int[][] res, int[] p){ if(v == source){ f = minEdge; return; }else if(p[v] != UNDEF){ augment(p[v], source, min(minEdge, res[p[v]][v]), res, p); res[p[v]][v] -= f; res[v][p[v]] += f; } } static int maxFlow(int[][] res, int source, int sink){ int V = res.length; int maxFlow = 0; while(true){ f = 0; boolean[] visited = new boolean[V]; visited[source] = true; Queue<Integer> q = new LinkedList<>(); q.add(source); int[] p = new int[V]; for(int i = 0; i < V; i++) p[i] = UNDEF; while(!q.isEmpty()){ int u = q.remove(); if(u == sink) break; for(int v = 0; v < V; v++){ if(res[u][v] > 0 && !visited[v]){ visited[v] = true; q.add(v); p[v] = u; } } } augment(sink, source, INF, res, p); if(f == 0) break; maxFlow += f; } return maxFlow; } static final char PERSON = '*'; static final char WATER = '~'; static final char ICE = '.'; static final char ICEBERG = '@'; static final char WOOD = '#'; static final int LARGE = 1000; static int[][] buildIncidentMatrix(char[][] grid){ int V = grid.length * grid[0].length; int[][] matrix = new int[V][V]; for(int i = 0; i < V; i++){ for(int j = 0; j < V; j++){ int row1 = i / grid[0].length; int row2 = j / grid[0].length; if((abs(i - j) == 1 && row1 == row2) || abs(i - j) == grid[0].length){ // i and j are immediate neighbors along NWES directions int col1 = i % grid[0].length; int col2 = j % grid[0].length; if(grid[row1][col1] != WATER && grid[row2][col2] != WATER){ matrix[i][j] = LARGE; } } } } return matrix; } static int out(int v){ return v * 2 + 1; } static int in(int v){ return v * 2; } static int vertexCapacity(int v, char[][] grid){ int row = v / grid[0].length; int col = v % grid[0].length; char c = grid[row][col]; if(c == PERSON || c == ICE) return 1; if(c == ICEBERG || c == WOOD) return LARGE; return 0; } static int[][] buildResidualMatrix(int[][] incidentMatrix, char[][] grid, int P){ int V = incidentMatrix.length * 2 + 2; int[][] res = new int[V][V]; for(int i = 0; i < incidentMatrix.length; i++){ for(int j = 0; j < incidentMatrix.length; j++){ if(incidentMatrix[i][j] == LARGE){ // edge exists res[out(i)][in(j)] = LARGE; // edge weight res[in(j)][out(j)] = vertexCapacity(j, grid); // vertex capacity } } } int source = V - 2; int sink = V - 1; for(int i = 0; i < V - 2; i += 2){ int row = (i / 2) / grid[0].length; int col = (i / 2) % grid[0].length; if(grid[row][col] == PERSON) res[source][i] = 1; if(grid[row][col] == WOOD) res[i + 1][sink] = P; } return res; } }
cp-book/ch4/mf/_11380_DownWentTheTitanic.java
UVA 11380 Down Went The Titanic
cp-book/ch4/mf/_11380_DownWentTheTitanic.java
UVA 11380 Down Went The Titanic
<ide><path>p-book/ch4/mf/_11380_DownWentTheTitanic.java <add>import java.util.*; <add>import static java.lang.Math.*; <add>import java.util.stream.*; <add> <add>/* <add>Problem name: 11380 Down Went The Titanic <add>Problem url: https://uva.onlinejudge.org/external/113/11380.pdf <add>Author: Andrey Yemelyanov <add>*/ <add>public class _11380_DownWentTheTitanic { <add> public static void main(String[] args){ <add> Scanner s = new Scanner(System.in); <add> while(s.hasNext()){ <add> int X = s.nextInt(); int Y = s.nextInt(); int P = s.nextInt(); <add> char[][] grid = new char[X][Y]; <add> for(int i = 0; i < grid.length; i++){ <add> String line = s.next(); <add> for(int j = 0; j < grid[i].length; j++){ <add> grid[i][j] = line.charAt(j); <add> } <add> } <add> int[][] res = buildResidualMatrix(buildIncidentMatrix(grid), grid, P); <add> int source = res.length - 2; <add> int sink = res.length - 1; <add> System.out.println(maxFlow(res, source, sink)); <add> } <add> } <add> <add> static final int UNDEF = -1; <add> static final int INF = 100000000; <add> static int f; <add> static void augment(int v, int source, int minEdge, int[][] res, int[] p){ <add> if(v == source){ <add> f = minEdge; <add> return; <add> }else if(p[v] != UNDEF){ <add> augment(p[v], source, min(minEdge, res[p[v]][v]), res, p); <add> res[p[v]][v] -= f; <add> res[v][p[v]] += f; <add> } <add> } <add> <add> static int maxFlow(int[][] res, int source, int sink){ <add> int V = res.length; <add> int maxFlow = 0; <add> while(true){ <add> f = 0; <add> boolean[] visited = new boolean[V]; <add> visited[source] = true; <add> Queue<Integer> q = new LinkedList<>(); <add> q.add(source); <add> int[] p = new int[V]; for(int i = 0; i < V; i++) p[i] = UNDEF; <add> while(!q.isEmpty()){ <add> int u = q.remove(); <add> if(u == sink) break; <add> for(int v = 0; v < V; v++){ <add> if(res[u][v] > 0 && !visited[v]){ <add> visited[v] = true; <add> q.add(v); <add> p[v] = u; <add> } <add> } <add> } <add> augment(sink, source, INF, res, p); <add> if(f == 0) break; <add> maxFlow += f; <add> } <add> return maxFlow; <add> } <add> <add> static final char PERSON = '*'; <add> static final char WATER = '~'; <add> static final char ICE = '.'; <add> static final char ICEBERG = '@'; <add> static final char WOOD = '#'; <add> static final int LARGE = 1000; <add> static int[][] buildIncidentMatrix(char[][] grid){ <add> int V = grid.length * grid[0].length; <add> int[][] matrix = new int[V][V]; <add> for(int i = 0; i < V; i++){ <add> for(int j = 0; j < V; j++){ <add> int row1 = i / grid[0].length; int row2 = j / grid[0].length; <add> if((abs(i - j) == 1 && row1 == row2) || abs(i - j) == grid[0].length){ // i and j are immediate neighbors along NWES directions <add> int col1 = i % grid[0].length; int col2 = j % grid[0].length; <add> if(grid[row1][col1] != WATER && grid[row2][col2] != WATER){ <add> matrix[i][j] = LARGE; <add> } <add> } <add> } <add> } <add> return matrix; <add> } <add> <add> static int out(int v){ return v * 2 + 1; } <add> static int in(int v){ return v * 2; } <add> <add> static int vertexCapacity(int v, char[][] grid){ <add> int row = v / grid[0].length; int col = v % grid[0].length; <add> char c = grid[row][col]; <add> if(c == PERSON || c == ICE) return 1; <add> if(c == ICEBERG || c == WOOD) return LARGE; <add> return 0; <add> } <add> <add> static int[][] buildResidualMatrix(int[][] incidentMatrix, char[][] grid, int P){ <add> int V = incidentMatrix.length * 2 + 2; <add> int[][] res = new int[V][V]; <add> for(int i = 0; i < incidentMatrix.length; i++){ <add> for(int j = 0; j < incidentMatrix.length; j++){ <add> if(incidentMatrix[i][j] == LARGE){ // edge exists <add> res[out(i)][in(j)] = LARGE; // edge weight <add> res[in(j)][out(j)] = vertexCapacity(j, grid); // vertex capacity <add> } <add> } <add> } <add> int source = V - 2; <add> int sink = V - 1; <add> for(int i = 0; i < V - 2; i += 2){ <add> int row = (i / 2) / grid[0].length; int col = (i / 2) % grid[0].length; <add> if(grid[row][col] == PERSON) res[source][i] = 1; <add> if(grid[row][col] == WOOD) res[i + 1][sink] = P; <add> } <add> return res; <add> } <add>}
Java
apache-2.0
3ad321fcb20230d5d5655527e44846f6981b1151
0
baishuo/elasticsearch_v2.1.0-baishuo,ThalaivaStars/OrgRepo1,heng4fun/elasticsearch,jsgao0/elasticsearch,alexbrasetvik/elasticsearch,milodky/elasticsearch,slavau/elasticsearch,btiernay/elasticsearch,acchen97/elasticsearch,luiseduardohdbackup/elasticsearch,javachengwc/elasticsearch,Asimov4/elasticsearch,queirozfcom/elasticsearch,liweinan0423/elasticsearch,trangvh/elasticsearch,wenpos/elasticsearch,trangvh/elasticsearch,yongminxia/elasticsearch,fooljohnny/elasticsearch,yuy168/elasticsearch,ThalaivaStars/OrgRepo1,GlenRSmith/elasticsearch,masaruh/elasticsearch,ZTE-PaaS/elasticsearch,TonyChai24/ESSource,acchen97/elasticsearch,elasticdog/elasticsearch,slavau/elasticsearch,yuy168/elasticsearch,mapr/elasticsearch,petmit/elasticsearch,ZTE-PaaS/elasticsearch,anti-social/elasticsearch,sc0ttkclark/elasticsearch,Liziyao/elasticsearch,ydsakyclguozi/elasticsearch,iamjakob/elasticsearch,mgalushka/elasticsearch,vvcephei/elasticsearch,mute/elasticsearch,wayeast/elasticsearch,marcuswr/elasticsearch-dateline,rajanm/elasticsearch,scottsom/elasticsearch,scottsom/elasticsearch,jeteve/elasticsearch,Asimov4/elasticsearch,gmarz/elasticsearch,Helen-Zhao/elasticsearch,infusionsoft/elasticsearch,aglne/elasticsearch,mm0/elasticsearch,TonyChai24/ESSource,lightslife/elasticsearch,wimvds/elasticsearch,szroland/elasticsearch,episerver/elasticsearch,Widen/elasticsearch,kimimj/elasticsearch,yanjunh/elasticsearch,nezirus/elasticsearch,jw0201/elastic,phani546/elasticsearch,JSCooke/elasticsearch,hanst/elasticsearch,huypx1292/elasticsearch,MaineC/elasticsearch,qwerty4030/elasticsearch,pozhidaevak/elasticsearch,nrkkalyan/elasticsearch,opendatasoft/elasticsearch,achow/elasticsearch,PhaedrusTheGreek/elasticsearch,alexbrasetvik/elasticsearch,heng4fun/elasticsearch,liweinan0423/elasticsearch,pablocastro/elasticsearch,Ansh90/elasticsearch,MichaelLiZhou/elasticsearch,hirdesh2008/elasticsearch,lightslife/elasticsearch,Microsoft/elasticsearch,vroyer/elassandra,caengcjd/elasticsearch,Shekharrajak/elasticsearch,kenshin233/elasticsearch,Stacey-Gammon/elasticsearch,geidies/elasticsearch,hafkensite/elasticsearch,KimTaehee/elasticsearch,ckclark/elasticsearch,himanshuag/elasticsearch,pritishppai/elasticsearch,pritishppai/elasticsearch,raishiv/elasticsearch,luiseduardohdbackup/elasticsearch,kingaj/elasticsearch,kimimj/elasticsearch,snikch/elasticsearch,ouyangkongtong/elasticsearch,thecocce/elasticsearch,ESamir/elasticsearch,abibell/elasticsearch,sdauletau/elasticsearch,KimTaehee/elasticsearch,bestwpw/elasticsearch,a2lin/elasticsearch,iantruslove/elasticsearch,jw0201/elastic,YosuaMichael/elasticsearch,nazarewk/elasticsearch,queirozfcom/elasticsearch,masaruh/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,elasticdog/elasticsearch,mbrukman/elasticsearch,pritishppai/elasticsearch,mortonsykes/elasticsearch,bestwpw/elasticsearch,mjhennig/elasticsearch,thecocce/elasticsearch,martinstuga/elasticsearch,strapdata/elassandra-test,xingguang2013/elasticsearch,strapdata/elassandra-test,palecur/elasticsearch,ouyangkongtong/elasticsearch,Rygbee/elasticsearch,kubum/elasticsearch,drewr/elasticsearch,schonfeld/elasticsearch,javachengwc/elasticsearch,sdauletau/elasticsearch,lchennup/elasticsearch,jsgao0/elasticsearch,slavau/elasticsearch,Siddartha07/elasticsearch,rajanm/elasticsearch,tahaemin/elasticsearch,mikemccand/elasticsearch,lydonchandra/elasticsearch,nazarewk/elasticsearch,Fsero/elasticsearch,episerver/elasticsearch,fekaputra/elasticsearch,zhiqinghuang/elasticsearch,wbowling/elasticsearch,hirdesh2008/elasticsearch,sarwarbhuiyan/elasticsearch,xpandan/elasticsearch,janmejay/elasticsearch,elasticdog/elasticsearch,hirdesh2008/elasticsearch,kkirsche/elasticsearch,jchampion/elasticsearch,artnowo/elasticsearch,vrkansagara/elasticsearch,socialrank/elasticsearch,Siddartha07/elasticsearch,mute/elasticsearch,khiraiwa/elasticsearch,ivansun1010/elasticsearch,KimTaehee/elasticsearch,mgalushka/elasticsearch,wimvds/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,humandb/elasticsearch,himanshuag/elasticsearch,umeshdangat/elasticsearch,salyh/elasticsearch,zhiqinghuang/elasticsearch,TonyChai24/ESSource,Liziyao/elasticsearch,koxa29/elasticsearch,phani546/elasticsearch,janmejay/elasticsearch,hydro2k/elasticsearch,MichaelLiZhou/elasticsearch,overcome/elasticsearch,likaiwalkman/elasticsearch,lmtwga/elasticsearch,micpalmia/elasticsearch,winstonewert/elasticsearch,mcku/elasticsearch,caengcjd/elasticsearch,PhaedrusTheGreek/elasticsearch,ouyangkongtong/elasticsearch,kkirsche/elasticsearch,zhaocloud/elasticsearch,geidies/elasticsearch,skearns64/elasticsearch,sarwarbhuiyan/elasticsearch,zhaocloud/elasticsearch,phani546/elasticsearch,jimczi/elasticsearch,tsohil/elasticsearch,smflorentino/elasticsearch,kingaj/elasticsearch,petmit/elasticsearch,wuranbo/elasticsearch,MetSystem/elasticsearch,henakamaMSFT/elasticsearch,apepper/elasticsearch,hafkensite/elasticsearch,JervyShi/elasticsearch,franklanganke/elasticsearch,franklanganke/elasticsearch,vietlq/elasticsearch,VukDukic/elasticsearch,kalimatas/elasticsearch,bawse/elasticsearch,jw0201/elastic,pablocastro/elasticsearch,springning/elasticsearch,jaynblue/elasticsearch,fooljohnny/elasticsearch,jchampion/elasticsearch,nellicus/elasticsearch,zhaocloud/elasticsearch,Chhunlong/elasticsearch,camilojd/elasticsearch,Shekharrajak/elasticsearch,nezirus/elasticsearch,nomoa/elasticsearch,cnfire/elasticsearch-1,zkidkid/elasticsearch,jchampion/elasticsearch,anti-social/elasticsearch,coding0011/elasticsearch,fooljohnny/elasticsearch,mjhennig/elasticsearch,nomoa/elasticsearch,ThiagoGarciaAlves/elasticsearch,kingaj/elasticsearch,elancom/elasticsearch,AshishThakur/elasticsearch,ESamir/elasticsearch,kalimatas/elasticsearch,wbowling/elasticsearch,cwurm/elasticsearch,MjAbuz/elasticsearch,infusionsoft/elasticsearch,vietlq/elasticsearch,HarishAtGitHub/elasticsearch,snikch/elasticsearch,caengcjd/elasticsearch,mnylen/elasticsearch,GlenRSmith/elasticsearch,lmtwga/elasticsearch,aglne/elasticsearch,hanswang/elasticsearch,ESamir/elasticsearch,masaruh/elasticsearch,dongjoon-hyun/elasticsearch,fooljohnny/elasticsearch,fooljohnny/elasticsearch,loconsolutions/elasticsearch,yongminxia/elasticsearch,golubev/elasticsearch,sneivandt/elasticsearch,mortonsykes/elasticsearch,TonyChai24/ESSource,mgalushka/elasticsearch,qwerty4030/elasticsearch,SergVro/elasticsearch,Collaborne/elasticsearch,rhoml/elasticsearch,easonC/elasticsearch,jpountz/elasticsearch,awislowski/elasticsearch,zkidkid/elasticsearch,cwurm/elasticsearch,rlugojr/elasticsearch,wangtuo/elasticsearch,PhaedrusTheGreek/elasticsearch,markllama/elasticsearch,hanst/elasticsearch,tsohil/elasticsearch,yongminxia/elasticsearch,ThiagoGarciaAlves/elasticsearch,sreeramjayan/elasticsearch,huanzhong/elasticsearch,kaneshin/elasticsearch,apepper/elasticsearch,alexshadow007/elasticsearch,franklanganke/elasticsearch,beiske/elasticsearch,petabytedata/elasticsearch,nellicus/elasticsearch,dantuffery/elasticsearch,dongjoon-hyun/elasticsearch,xingguang2013/elasticsearch,yynil/elasticsearch,tebriel/elasticsearch,btiernay/elasticsearch,abibell/elasticsearch,humandb/elasticsearch,abibell/elasticsearch,obourgain/elasticsearch,zhiqinghuang/elasticsearch,amit-shar/elasticsearch,chrismwendt/elasticsearch,mute/elasticsearch,diendt/elasticsearch,awislowski/elasticsearch,EasonYi/elasticsearch,StefanGor/elasticsearch,spiegela/elasticsearch,jango2015/elasticsearch,JackyMai/elasticsearch,uschindler/elasticsearch,fekaputra/elasticsearch,abibell/elasticsearch,LeoYao/elasticsearch,JSCooke/elasticsearch,ImpressTV/elasticsearch,achow/elasticsearch,s1monw/elasticsearch,mkis-/elasticsearch,AndreKR/elasticsearch,dongjoon-hyun/elasticsearch,MaineC/elasticsearch,wittyameta/elasticsearch,luiseduardohdbackup/elasticsearch,winstonewert/elasticsearch,mikemccand/elasticsearch,skearns64/elasticsearch,markharwood/elasticsearch,Brijeshrpatel9/elasticsearch,nrkkalyan/elasticsearch,achow/elasticsearch,lmtwga/elasticsearch,andrestc/elasticsearch,pritishppai/elasticsearch,weipinghe/elasticsearch,javachengwc/elasticsearch,infusionsoft/elasticsearch,VukDukic/elasticsearch,lmtwga/elasticsearch,areek/elasticsearch,loconsolutions/elasticsearch,kubum/elasticsearch,mute/elasticsearch,ouyangkongtong/elasticsearch,lchennup/elasticsearch,ulkas/elasticsearch,ckclark/elasticsearch,chrismwendt/elasticsearch,wittyameta/elasticsearch,tahaemin/elasticsearch,dataduke/elasticsearch,wangtuo/elasticsearch,geidies/elasticsearch,mjason3/elasticsearch,kenshin233/elasticsearch,obourgain/elasticsearch,Siddartha07/elasticsearch,huanzhong/elasticsearch,EasonYi/elasticsearch,pranavraman/elasticsearch,MjAbuz/elasticsearch,strapdata/elassandra5-rc,boliza/elasticsearch,Shepard1212/elasticsearch,mgalushka/elasticsearch,yanjunh/elasticsearch,jimczi/elasticsearch,qwerty4030/elasticsearch,codebunt/elasticsearch,marcuswr/elasticsearch-dateline,JSCooke/elasticsearch,knight1128/elasticsearch,hydro2k/elasticsearch,socialrank/elasticsearch,weipinghe/elasticsearch,robin13/elasticsearch,jeteve/elasticsearch,djschny/elasticsearch,scottsom/elasticsearch,rlugojr/elasticsearch,JackyMai/elasticsearch,brwe/elasticsearch,nezirus/elasticsearch,franklanganke/elasticsearch,Shepard1212/elasticsearch,huanzhong/elasticsearch,chirilo/elasticsearch,vingupta3/elasticsearch,wayeast/elasticsearch,codebunt/elasticsearch,wangyuxue/elasticsearch,lightslife/elasticsearch,yuy168/elasticsearch,mbrukman/elasticsearch,alexkuk/elasticsearch,mjason3/elasticsearch,amit-shar/elasticsearch,Kakakakakku/elasticsearch,fforbeck/elasticsearch,kenshin233/elasticsearch,karthikjaps/elasticsearch,wuranbo/elasticsearch,areek/elasticsearch,pranavraman/elasticsearch,obourgain/elasticsearch,smflorentino/elasticsearch,naveenhooda2000/elasticsearch,petabytedata/elasticsearch,achow/elasticsearch,MetSystem/elasticsearch,ZTE-PaaS/elasticsearch,Microsoft/elasticsearch,hirdesh2008/elasticsearch,feiqitian/elasticsearch,jango2015/elasticsearch,kcompher/elasticsearch,wayeast/elasticsearch,onegambler/elasticsearch,Rygbee/elasticsearch,SergVro/elasticsearch,mcku/elasticsearch,maddin2016/elasticsearch,adrianbk/elasticsearch,iamjakob/elasticsearch,liweinan0423/elasticsearch,dylan8902/elasticsearch,IanvsPoplicola/elasticsearch,schonfeld/elasticsearch,tcucchietti/elasticsearch,achow/elasticsearch,dataduke/elasticsearch,achow/elasticsearch,shreejay/elasticsearch,mcku/elasticsearch,jeteve/elasticsearch,gmarz/elasticsearch,chirilo/elasticsearch,SergVro/elasticsearch,hechunwen/elasticsearch,episerver/elasticsearch,wuranbo/elasticsearch,kevinkluge/elasticsearch,overcome/elasticsearch,davidvgalbraith/elasticsearch,fred84/elasticsearch,girirajsharma/elasticsearch,gingerwizard/elasticsearch,pozhidaevak/elasticsearch,hafkensite/elasticsearch,codebunt/elasticsearch,luiseduardohdbackup/elasticsearch,gingerwizard/elasticsearch,njlawton/elasticsearch,mapr/elasticsearch,peschlowp/elasticsearch,markharwood/elasticsearch,jaynblue/elasticsearch,djschny/elasticsearch,andrejserafim/elasticsearch,hechunwen/elasticsearch,marcuswr/elasticsearch-dateline,hechunwen/elasticsearch,bestwpw/elasticsearch,jbertouch/elasticsearch,rajanm/elasticsearch,strapdata/elassandra-test,markharwood/elasticsearch,nezirus/elasticsearch,lightslife/elasticsearch,spiegela/elasticsearch,ydsakyclguozi/elasticsearch,IanvsPoplicola/elasticsearch,camilojd/elasticsearch,knight1128/elasticsearch,obourgain/elasticsearch,overcome/elasticsearch,mortonsykes/elasticsearch,kalburgimanjunath/elasticsearch,C-Bish/elasticsearch,sjohnr/elasticsearch,humandb/elasticsearch,chrismwendt/elasticsearch,xuzha/elasticsearch,JervyShi/elasticsearch,jeteve/elasticsearch,rajanm/elasticsearch,szroland/elasticsearch,djschny/elasticsearch,mjhennig/elasticsearch,likaiwalkman/elasticsearch,umeshdangat/elasticsearch,javachengwc/elasticsearch,kaneshin/elasticsearch,Asimov4/elasticsearch,ricardocerq/elasticsearch,jimczi/elasticsearch,andrejserafim/elasticsearch,cnfire/elasticsearch-1,kalburgimanjunath/elasticsearch,drewr/elasticsearch,JervyShi/elasticsearch,sposam/elasticsearch,naveenhooda2000/elasticsearch,kubum/elasticsearch,fekaputra/elasticsearch,feiqitian/elasticsearch,dantuffery/elasticsearch,MichaelLiZhou/elasticsearch,mrorii/elasticsearch,petabytedata/elasticsearch,vingupta3/elasticsearch,mrorii/elasticsearch,zhiqinghuang/elasticsearch,likaiwalkman/elasticsearch,jimhooker2002/elasticsearch,ThiagoGarciaAlves/elasticsearch,davidvgalbraith/elasticsearch,avikurapati/elasticsearch,18098924759/elasticsearch,kaneshin/elasticsearch,coding0011/elasticsearch,myelin/elasticsearch,strapdata/elassandra,polyfractal/elasticsearch,GlenRSmith/elasticsearch,queirozfcom/elasticsearch,mjason3/elasticsearch,brandonkearby/elasticsearch,dataduke/elasticsearch,TonyChai24/ESSource,AndreKR/elasticsearch,Asimov4/elasticsearch,Siddartha07/elasticsearch,opendatasoft/elasticsearch,ThiagoGarciaAlves/elasticsearch,tsohil/elasticsearch,18098924759/elasticsearch,HarishAtGitHub/elasticsearch,scorpionvicky/elasticsearch,wimvds/elasticsearch,codebunt/elasticsearch,awislowski/elasticsearch,sauravmondallive/elasticsearch,brandonkearby/elasticsearch,jeteve/elasticsearch,tebriel/elasticsearch,cnfire/elasticsearch-1,himanshuag/elasticsearch,mute/elasticsearch,YosuaMichael/elasticsearch,wayeast/elasticsearch,vroyer/elassandra,liweinan0423/elasticsearch,MjAbuz/elasticsearch,EasonYi/elasticsearch,nomoa/elasticsearch,nilabhsagar/elasticsearch,uschindler/elasticsearch,strapdata/elassandra,Shekharrajak/elasticsearch,pritishppai/elasticsearch,myelin/elasticsearch,mcku/elasticsearch,alexshadow007/elasticsearch,weipinghe/elasticsearch,achow/elasticsearch,ImpressTV/elasticsearch,MisterAndersen/elasticsearch,MaineC/elasticsearch,pablocastro/elasticsearch,sreeramjayan/elasticsearch,alexkuk/elasticsearch,Ansh90/elasticsearch,tcucchietti/elasticsearch,ivansun1010/elasticsearch,i-am-Nathan/elasticsearch,thecocce/elasticsearch,uschindler/elasticsearch,18098924759/elasticsearch,Charlesdong/elasticsearch,ThalaivaStars/OrgRepo1,overcome/elasticsearch,ESamir/elasticsearch,kevinkluge/elasticsearch,brwe/elasticsearch,vietlq/elasticsearch,rmuir/elasticsearch,cwurm/elasticsearch,sc0ttkclark/elasticsearch,luiseduardohdbackup/elasticsearch,likaiwalkman/elasticsearch,sreeramjayan/elasticsearch,rento19962/elasticsearch,adrianbk/elasticsearch,iantruslove/elasticsearch,raishiv/elasticsearch,AshishThakur/elasticsearch,queirozfcom/elasticsearch,ckclark/elasticsearch,IanvsPoplicola/elasticsearch,JSCooke/elasticsearch,LewayneNaidoo/elasticsearch,iamjakob/elasticsearch,sjohnr/elasticsearch,hydro2k/elasticsearch,golubev/elasticsearch,jsgao0/elasticsearch,StefanGor/elasticsearch,sarwarbhuiyan/elasticsearch,Uiho/elasticsearch,chirilo/elasticsearch,jbertouch/elasticsearch,YosuaMichael/elasticsearch,artnowo/elasticsearch,hanswang/elasticsearch,lzo/elasticsearch-1,tsohil/elasticsearch,mkis-/elasticsearch,combinatorist/elasticsearch,knight1128/elasticsearch,himanshuag/elasticsearch,davidvgalbraith/elasticsearch,MetSystem/elasticsearch,Shepard1212/elasticsearch,sposam/elasticsearch,ydsakyclguozi/elasticsearch,mgalushka/elasticsearch,nellicus/elasticsearch,nilabhsagar/elasticsearch,artnowo/elasticsearch,ydsakyclguozi/elasticsearch,tahaemin/elasticsearch,SergVro/elasticsearch,Uiho/elasticsearch,petabytedata/elasticsearch,awislowski/elasticsearch,tahaemin/elasticsearch,sposam/elasticsearch,shreejay/elasticsearch,umeshdangat/elasticsearch,kubum/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,nilabhsagar/elasticsearch,drewr/elasticsearch,franklanganke/elasticsearch,kunallimaye/elasticsearch,brwe/elasticsearch,mortonsykes/elasticsearch,avikurapati/elasticsearch,Uiho/elasticsearch,petabytedata/elasticsearch,strapdata/elassandra5-rc,LewayneNaidoo/elasticsearch,abhijitiitr/es,GlenRSmith/elasticsearch,btiernay/elasticsearch,lzo/elasticsearch-1,trangvh/elasticsearch,HarishAtGitHub/elasticsearch,alexbrasetvik/elasticsearch,wbowling/elasticsearch,diendt/elasticsearch,infusionsoft/elasticsearch,kimimj/elasticsearch,Clairebi/ElasticsearchClone,obourgain/elasticsearch,knight1128/elasticsearch,a2lin/elasticsearch,ESamir/elasticsearch,hafkensite/elasticsearch,szroland/elasticsearch,markllama/elasticsearch,mohit/elasticsearch,huypx1292/elasticsearch,areek/elasticsearch,dylan8902/elasticsearch,iantruslove/elasticsearch,LeoYao/elasticsearch,camilojd/elasticsearch,linglaiyao1314/elasticsearch,djschny/elasticsearch,nazarewk/elasticsearch,acchen97/elasticsearch,diendt/elasticsearch,lks21c/elasticsearch,cnfire/elasticsearch-1,andrestc/elasticsearch,ckclark/elasticsearch,schonfeld/elasticsearch,sjohnr/elasticsearch,Fsero/elasticsearch,mkis-/elasticsearch,nknize/elasticsearch,MetSystem/elasticsearch,truemped/elasticsearch,MisterAndersen/elasticsearch,dpursehouse/elasticsearch,jbertouch/elasticsearch,wimvds/elasticsearch,btiernay/elasticsearch,markwalkom/elasticsearch,markllama/elasticsearch,queirozfcom/elasticsearch,abhijitiitr/es,Widen/elasticsearch,sdauletau/elasticsearch,MisterAndersen/elasticsearch,fred84/elasticsearch,khiraiwa/elasticsearch,markllama/elasticsearch,kunallimaye/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,wbowling/elasticsearch,chirilo/elasticsearch,amaliujia/elasticsearch,geidies/elasticsearch,coding0011/elasticsearch,glefloch/elasticsearch,Liziyao/elasticsearch,markharwood/elasticsearch,btiernay/elasticsearch,iantruslove/elasticsearch,SergVro/elasticsearch,andrestc/elasticsearch,glefloch/elasticsearch,VukDukic/elasticsearch,weipinghe/elasticsearch,tkssharma/elasticsearch,mortonsykes/elasticsearch,weipinghe/elasticsearch,likaiwalkman/elasticsearch,MetSystem/elasticsearch,yongminxia/elasticsearch,petabytedata/elasticsearch,knight1128/elasticsearch,micpalmia/elasticsearch,jango2015/elasticsearch,fekaputra/elasticsearch,masterweb121/elasticsearch,peschlowp/elasticsearch,Shekharrajak/elasticsearch,LewayneNaidoo/elasticsearch,mohit/elasticsearch,codebunt/elasticsearch,cwurm/elasticsearch,kcompher/elasticsearch,vingupta3/elasticsearch,wenpos/elasticsearch,wimvds/elasticsearch,opendatasoft/elasticsearch,lks21c/elasticsearch,StefanGor/elasticsearch,KimTaehee/elasticsearch,khiraiwa/elasticsearch,gfyoung/elasticsearch,humandb/elasticsearch,YosuaMichael/elasticsearch,abibell/elasticsearch,mm0/elasticsearch,yongminxia/elasticsearch,nazarewk/elasticsearch,gingerwizard/elasticsearch,VukDukic/elasticsearch,ThiagoGarciaAlves/elasticsearch,KimTaehee/elasticsearch,kimimj/elasticsearch,mmaracic/elasticsearch,F0lha/elasticsearch,geidies/elasticsearch,polyfractal/elasticsearch,Shekharrajak/elasticsearch,rmuir/elasticsearch,njlawton/elasticsearch,Ansh90/elasticsearch,Helen-Zhao/elasticsearch,onegambler/elasticsearch,njlawton/elasticsearch,markllama/elasticsearch,ouyangkongtong/elasticsearch,Collaborne/elasticsearch,HonzaKral/elasticsearch,mrorii/elasticsearch,martinstuga/elasticsearch,naveenhooda2000/elasticsearch,hafkensite/elasticsearch,wangyuxue/elasticsearch,overcome/elasticsearch,sscarduzio/elasticsearch,bawse/elasticsearch,masterweb121/elasticsearch,mcku/elasticsearch,areek/elasticsearch,MisterAndersen/elasticsearch,kevinkluge/elasticsearch,jango2015/elasticsearch,hechunwen/elasticsearch,hanst/elasticsearch,petmit/elasticsearch,glefloch/elasticsearch,hanst/elasticsearch,jaynblue/elasticsearch,huanzhong/elasticsearch,HarishAtGitHub/elasticsearch,yanjunh/elasticsearch,markwalkom/elasticsearch,sauravmondallive/elasticsearch,adrianbk/elasticsearch,xingguang2013/elasticsearch,kunallimaye/elasticsearch,xpandan/elasticsearch,umeshdangat/elasticsearch,feiqitian/elasticsearch,PhaedrusTheGreek/elasticsearch,khiraiwa/elasticsearch,mrorii/elasticsearch,scottsom/elasticsearch,Fsero/elasticsearch,sreeramjayan/elasticsearch,clintongormley/elasticsearch,yongminxia/elasticsearch,lzo/elasticsearch-1,sauravmondallive/elasticsearch,girirajsharma/elasticsearch,jbertouch/elasticsearch,ivansun1010/elasticsearch,cnfire/elasticsearch-1,markwalkom/elasticsearch,skearns64/elasticsearch,s1monw/elasticsearch,tsohil/elasticsearch,kkirsche/elasticsearch,wangyuxue/elasticsearch,cwurm/elasticsearch,pranavraman/elasticsearch,ajhalani/elasticsearch,mm0/elasticsearch,mnylen/elasticsearch,davidvgalbraith/elasticsearch,rajanm/elasticsearch,milodky/elasticsearch,StefanGor/elasticsearch,ouyangkongtong/elasticsearch,tcucchietti/elasticsearch,vrkansagara/elasticsearch,Brijeshrpatel9/elasticsearch,andrejserafim/elasticsearch,mkis-/elasticsearch,hanswang/elasticsearch,sneivandt/elasticsearch,beiske/elasticsearch,linglaiyao1314/elasticsearch,lchennup/elasticsearch,elasticdog/elasticsearch,mapr/elasticsearch,opendatasoft/elasticsearch,LeoYao/elasticsearch,geidies/elasticsearch,Charlesdong/elasticsearch,coding0011/elasticsearch,masterweb121/elasticsearch,mkis-/elasticsearch,jsgao0/elasticsearch,infusionsoft/elasticsearch,vvcephei/elasticsearch,mjhennig/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,Chhunlong/elasticsearch,easonC/elasticsearch,overcome/elasticsearch,shreejay/elasticsearch,iantruslove/elasticsearch,lchennup/elasticsearch,EasonYi/elasticsearch,winstonewert/elasticsearch,slavau/elasticsearch,LeoYao/elasticsearch,hydro2k/elasticsearch,tcucchietti/elasticsearch,acchen97/elasticsearch,MichaelLiZhou/elasticsearch,micpalmia/elasticsearch,loconsolutions/elasticsearch,luiseduardohdbackup/elasticsearch,mbrukman/elasticsearch,ThalaivaStars/OrgRepo1,wangtuo/elasticsearch,AleksKochev/elasticsearch,boliza/elasticsearch,mapr/elasticsearch,mnylen/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,masterweb121/elasticsearch,palecur/elasticsearch,ckclark/elasticsearch,wittyameta/elasticsearch,Siddartha07/elasticsearch,spiegela/elasticsearch,kevinkluge/elasticsearch,jchampion/elasticsearch,dpursehouse/elasticsearch,18098924759/elasticsearch,fernandozhu/elasticsearch,bestwpw/elasticsearch,sposam/elasticsearch,jimhooker2002/elasticsearch,tahaemin/elasticsearch,vvcephei/elasticsearch,tkssharma/elasticsearch,phani546/elasticsearch,alexshadow007/elasticsearch,henakamaMSFT/elasticsearch,aglne/elasticsearch,lchennup/elasticsearch,lzo/elasticsearch-1,mute/elasticsearch,strapdata/elassandra5-rc,dylan8902/elasticsearch,ESamir/elasticsearch,micpalmia/elasticsearch,Liziyao/elasticsearch,sdauletau/elasticsearch,adrianbk/elasticsearch,mm0/elasticsearch,caengcjd/elasticsearch,jimhooker2002/elasticsearch,mrorii/elasticsearch,springning/elasticsearch,ajhalani/elasticsearch,davidvgalbraith/elasticsearch,ImpressTV/elasticsearch,raishiv/elasticsearch,kenshin233/elasticsearch,robin13/elasticsearch,elancom/elasticsearch,girirajsharma/elasticsearch,strapdata/elassandra-test,fred84/elasticsearch,Kakakakakku/elasticsearch,sreeramjayan/elasticsearch,alexkuk/elasticsearch,zkidkid/elasticsearch,xuzha/elasticsearch,kubum/elasticsearch,Ansh90/elasticsearch,mikemccand/elasticsearch,glefloch/elasticsearch,socialrank/elasticsearch,lzo/elasticsearch-1,gingerwizard/elasticsearch,JervyShi/elasticsearch,Collaborne/elasticsearch,rento19962/elasticsearch,xuzha/elasticsearch,sc0ttkclark/elasticsearch,golubev/elasticsearch,linglaiyao1314/elasticsearch,humandb/elasticsearch,nrkkalyan/elasticsearch,YosuaMichael/elasticsearch,Flipkart/elasticsearch,btiernay/elasticsearch,clintongormley/elasticsearch,mcku/elasticsearch,naveenhooda2000/elasticsearch,Siddartha07/elasticsearch,janmejay/elasticsearch,huanzhong/elasticsearch,rhoml/elasticsearch,Brijeshrpatel9/elasticsearch,nellicus/elasticsearch,elancom/elasticsearch,aglne/elasticsearch,Shekharrajak/elasticsearch,schonfeld/elasticsearch,Fsero/elasticsearch,vrkansagara/elasticsearch,chrismwendt/elasticsearch,vvcephei/elasticsearch,pozhidaevak/elasticsearch,amaliujia/elasticsearch,clintongormley/elasticsearch,markwalkom/elasticsearch,milodky/elasticsearch,vroyer/elasticassandra,myelin/elasticsearch,ricardocerq/elasticsearch,mohit/elasticsearch,opendatasoft/elasticsearch,vvcephei/elasticsearch,ulkas/elasticsearch,Microsoft/elasticsearch,mjhennig/elasticsearch,shreejay/elasticsearch,ImpressTV/elasticsearch,acchen97/elasticsearch,nrkkalyan/elasticsearch,yuy168/elasticsearch,sjohnr/elasticsearch,fernandozhu/elasticsearch,winstonewert/elasticsearch,hanswang/elasticsearch,AshishThakur/elasticsearch,jprante/elasticsearch,jimczi/elasticsearch,bestwpw/elasticsearch,areek/elasticsearch,i-am-Nathan/elasticsearch,tkssharma/elasticsearch,lightslife/elasticsearch,salyh/elasticsearch,raishiv/elasticsearch,vietlq/elasticsearch,hydro2k/elasticsearch,hechunwen/elasticsearch,wenpos/elasticsearch,koxa29/elasticsearch,Fsero/elasticsearch,heng4fun/elasticsearch,zeroctu/elasticsearch,robin13/elasticsearch,JackyMai/elasticsearch,slavau/elasticsearch,tebriel/elasticsearch,tkssharma/elasticsearch,jimczi/elasticsearch,easonC/elasticsearch,abhijitiitr/es,NBSW/elasticsearch,kingaj/elasticsearch,artnowo/elasticsearch,ThalaivaStars/OrgRepo1,jchampion/elasticsearch,yynil/elasticsearch,jeteve/elasticsearch,likaiwalkman/elasticsearch,iantruslove/elasticsearch,tkssharma/elasticsearch,chirilo/elasticsearch,zhaocloud/elasticsearch,jbertouch/elasticsearch,marcuswr/elasticsearch-dateline,sauravmondallive/elasticsearch,zeroctu/elasticsearch,lightslife/elasticsearch,dongjoon-hyun/elasticsearch,rmuir/elasticsearch,sneivandt/elasticsearch,wimvds/elasticsearch,PhaedrusTheGreek/elasticsearch,chrismwendt/elasticsearch,kalimatas/elasticsearch,acchen97/elasticsearch,onegambler/elasticsearch,sscarduzio/elasticsearch,karthikjaps/elasticsearch,vvcephei/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,camilojd/elasticsearch,sc0ttkclark/elasticsearch,kenshin233/elasticsearch,Clairebi/ElasticsearchClone,MaineC/elasticsearch,peschlowp/elasticsearch,lks21c/elasticsearch,AshishThakur/elasticsearch,kingaj/elasticsearch,AshishThakur/elasticsearch,C-Bish/elasticsearch,lydonchandra/elasticsearch,lmtwga/elasticsearch,scottsom/elasticsearch,anti-social/elasticsearch,markllama/elasticsearch,szroland/elasticsearch,AleksKochev/elasticsearch,girirajsharma/elasticsearch,KimTaehee/elasticsearch,mmaracic/elasticsearch,clintongormley/elasticsearch,Rygbee/elasticsearch,ZTE-PaaS/elasticsearch,andrestc/elasticsearch,robin13/elasticsearch,yynil/elasticsearch,18098924759/elasticsearch,jimhooker2002/elasticsearch,karthikjaps/elasticsearch,Stacey-Gammon/elasticsearch,amit-shar/elasticsearch,feiqitian/elasticsearch,karthikjaps/elasticsearch,luiseduardohdbackup/elasticsearch,xingguang2013/elasticsearch,ajhalani/elasticsearch,xingguang2013/elasticsearch,Stacey-Gammon/elasticsearch,feiqitian/elasticsearch,gfyoung/elasticsearch,HarishAtGitHub/elasticsearch,andrestc/elasticsearch,lmtwga/elasticsearch,vrkansagara/elasticsearch,kevinkluge/elasticsearch,sc0ttkclark/elasticsearch,MichaelLiZhou/elasticsearch,boliza/elasticsearch,dataduke/elasticsearch,martinstuga/elasticsearch,vroyer/elasticassandra,markharwood/elasticsearch,sarwarbhuiyan/elasticsearch,mmaracic/elasticsearch,alexbrasetvik/elasticsearch,Chhunlong/elasticsearch,iacdingping/elasticsearch,MetSystem/elasticsearch,rlugojr/elasticsearch,a2lin/elasticsearch,LewayneNaidoo/elasticsearch,yynil/elasticsearch,kkirsche/elasticsearch,AndreKR/elasticsearch,javachengwc/elasticsearch,himanshuag/elasticsearch,njlawton/elasticsearch,brandonkearby/elasticsearch,VukDukic/elasticsearch,ricardocerq/elasticsearch,ckclark/elasticsearch,masterweb121/elasticsearch,combinatorist/elasticsearch,ivansun1010/elasticsearch,apepper/elasticsearch,lzo/elasticsearch-1,kevinkluge/elasticsearch,skearns64/elasticsearch,nrkkalyan/elasticsearch,ulkas/elasticsearch,naveenhooda2000/elasticsearch,abhijitiitr/es,mjhennig/elasticsearch,kenshin233/elasticsearch,Widen/elasticsearch,yynil/elasticsearch,anti-social/elasticsearch,avikurapati/elasticsearch,fekaputra/elasticsearch,onegambler/elasticsearch,kenshin233/elasticsearch,Microsoft/elasticsearch,jw0201/elastic,hanswang/elasticsearch,Chhunlong/elasticsearch,girirajsharma/elasticsearch,trangvh/elasticsearch,jango2015/elasticsearch,khiraiwa/elasticsearch,slavau/elasticsearch,phani546/elasticsearch,sarwarbhuiyan/elasticsearch,iamjakob/elasticsearch,glefloch/elasticsearch,ulkas/elasticsearch,huypx1292/elasticsearch,gfyoung/elasticsearch,tebriel/elasticsearch,martinstuga/elasticsearch,kevinkluge/elasticsearch,HonzaKral/elasticsearch,ivansun1010/elasticsearch,petmit/elasticsearch,vietlq/elasticsearch,jprante/elasticsearch,milodky/elasticsearch,beiske/elasticsearch,Clairebi/ElasticsearchClone,lydonchandra/elasticsearch,IanvsPoplicola/elasticsearch,gingerwizard/elasticsearch,koxa29/elasticsearch,zeroctu/elasticsearch,andrestc/elasticsearch,koxa29/elasticsearch,Uiho/elasticsearch,xpandan/elasticsearch,gingerwizard/elasticsearch,alexshadow007/elasticsearch,pranavraman/elasticsearch,fernandozhu/elasticsearch,s1monw/elasticsearch,apepper/elasticsearch,xuzha/elasticsearch,pablocastro/elasticsearch,cnfire/elasticsearch-1,lightslife/elasticsearch,TonyChai24/ESSource,alexshadow007/elasticsearch,rhoml/elasticsearch,petabytedata/elasticsearch,wayeast/elasticsearch,thecocce/elasticsearch,amaliujia/elasticsearch,jpountz/elasticsearch,PhaedrusTheGreek/elasticsearch,smflorentino/elasticsearch,humandb/elasticsearch,ricardocerq/elasticsearch,Ansh90/elasticsearch,iacdingping/elasticsearch,MjAbuz/elasticsearch,scorpionvicky/elasticsearch,Clairebi/ElasticsearchClone,henakamaMSFT/elasticsearch,martinstuga/elasticsearch,kkirsche/elasticsearch,infusionsoft/elasticsearch,springning/elasticsearch,koxa29/elasticsearch,Widen/elasticsearch,Flipkart/elasticsearch,loconsolutions/elasticsearch,i-am-Nathan/elasticsearch,yanjunh/elasticsearch,pablocastro/elasticsearch,schonfeld/elasticsearch,markwalkom/elasticsearch,Uiho/elasticsearch,Rygbee/elasticsearch,lks21c/elasticsearch,sneivandt/elasticsearch,ajhalani/elasticsearch,skearns64/elasticsearch,hafkensite/elasticsearch,HarishAtGitHub/elasticsearch,golubev/elasticsearch,zhiqinghuang/elasticsearch,golubev/elasticsearch,fforbeck/elasticsearch,micpalmia/elasticsearch,kimimj/elasticsearch,henakamaMSFT/elasticsearch,easonC/elasticsearch,gmarz/elasticsearch,loconsolutions/elasticsearch,Asimov4/elasticsearch,lchennup/elasticsearch,nknize/elasticsearch,awislowski/elasticsearch,trangvh/elasticsearch,Siddartha07/elasticsearch,kalburgimanjunath/elasticsearch,nellicus/elasticsearch,diendt/elasticsearch,henakamaMSFT/elasticsearch,szroland/elasticsearch,Collaborne/elasticsearch,ImpressTV/elasticsearch,girirajsharma/elasticsearch,camilojd/elasticsearch,jango2015/elasticsearch,truemped/elasticsearch,Shepard1212/elasticsearch,tsohil/elasticsearch,raishiv/elasticsearch,iacdingping/elasticsearch,liweinan0423/elasticsearch,thecocce/elasticsearch,andrestc/elasticsearch,s1monw/elasticsearch,Kakakakakku/elasticsearch,C-Bish/elasticsearch,xingguang2013/elasticsearch,mmaracic/elasticsearch,karthikjaps/elasticsearch,apepper/elasticsearch,Liziyao/elasticsearch,myelin/elasticsearch,easonC/elasticsearch,Helen-Zhao/elasticsearch,lydonchandra/elasticsearch,beiske/elasticsearch,weipinghe/elasticsearch,amaliujia/elasticsearch,vingupta3/elasticsearch,drewr/elasticsearch,tebriel/elasticsearch,kcompher/elasticsearch,springning/elasticsearch,nezirus/elasticsearch,cnfire/elasticsearch-1,smflorentino/elasticsearch,qwerty4030/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,YosuaMichael/elasticsearch,MichaelLiZhou/elasticsearch,nomoa/elasticsearch,nrkkalyan/elasticsearch,ImpressTV/elasticsearch,kingaj/elasticsearch,strapdata/elassandra-test,elancom/elasticsearch,spiegela/elasticsearch,iamjakob/elasticsearch,AshishThakur/elasticsearch,JackyMai/elasticsearch,brandonkearby/elasticsearch,gmarz/elasticsearch,linglaiyao1314/elasticsearch,smflorentino/elasticsearch,Fsero/elasticsearch,loconsolutions/elasticsearch,vingupta3/elasticsearch,wittyameta/elasticsearch,yuy168/elasticsearch,huypx1292/elasticsearch,iacdingping/elasticsearch,vingupta3/elasticsearch,pranavraman/elasticsearch,uschindler/elasticsearch,caengcjd/elasticsearch,LeoYao/elasticsearch,vroyer/elassandra,Stacey-Gammon/elasticsearch,djschny/elasticsearch,salyh/elasticsearch,winstonewert/elasticsearch,YosuaMichael/elasticsearch,Ansh90/elasticsearch,mrorii/elasticsearch,jeteve/elasticsearch,drewr/elasticsearch,wenpos/elasticsearch,btiernay/elasticsearch,elasticdog/elasticsearch,socialrank/elasticsearch,Flipkart/elasticsearch,abhijitiitr/es,jw0201/elastic,Helen-Zhao/elasticsearch,ckclark/elasticsearch,dataduke/elasticsearch,zeroctu/elasticsearch,jango2015/elasticsearch,Charlesdong/elasticsearch,peschlowp/elasticsearch,xpandan/elasticsearch,F0lha/elasticsearch,Charlesdong/elasticsearch,alexbrasetvik/elasticsearch,JackyMai/elasticsearch,pranavraman/elasticsearch,sc0ttkclark/elasticsearch,dpursehouse/elasticsearch,sarwarbhuiyan/elasticsearch,jimhooker2002/elasticsearch,szroland/elasticsearch,wuranbo/elasticsearch,thecocce/elasticsearch,rento19962/elasticsearch,hafkensite/elasticsearch,fforbeck/elasticsearch,fforbeck/elasticsearch,lmtwga/elasticsearch,truemped/elasticsearch,rmuir/elasticsearch,kaneshin/elasticsearch,kcompher/elasticsearch,anti-social/elasticsearch,LewayneNaidoo/elasticsearch,Uiho/elasticsearch,linglaiyao1314/elasticsearch,boliza/elasticsearch,knight1128/elasticsearch,nknize/elasticsearch,hydro2k/elasticsearch,springning/elasticsearch,Brijeshrpatel9/elasticsearch,shreejay/elasticsearch,polyfractal/elasticsearch,vingupta3/elasticsearch,mgalushka/elasticsearch,AleksKochev/elasticsearch,huanzhong/elasticsearch,Charlesdong/elasticsearch,markllama/elasticsearch,ajhalani/elasticsearch,kunallimaye/elasticsearch,vroyer/elasticassandra,tebriel/elasticsearch,socialrank/elasticsearch,diendt/elasticsearch,Widen/elasticsearch,zhaocloud/elasticsearch,gmarz/elasticsearch,lks21c/elasticsearch,ulkas/elasticsearch,combinatorist/elasticsearch,andrejserafim/elasticsearch,rhoml/elasticsearch,amaliujia/elasticsearch,sdauletau/elasticsearch,lydonchandra/elasticsearch,janmejay/elasticsearch,springning/elasticsearch,rhoml/elasticsearch,golubev/elasticsearch,iamjakob/elasticsearch,Collaborne/elasticsearch,nomoa/elasticsearch,sposam/elasticsearch,Brijeshrpatel9/elasticsearch,Liziyao/elasticsearch,truemped/elasticsearch,strapdata/elassandra5-rc,rlugojr/elasticsearch,JervyShi/elasticsearch,tkssharma/elasticsearch,heng4fun/elasticsearch,kalburgimanjunath/elasticsearch,masaruh/elasticsearch,caengcjd/elasticsearch,tahaemin/elasticsearch,hanswang/elasticsearch,onegambler/elasticsearch,JSCooke/elasticsearch,areek/elasticsearch,NBSW/elasticsearch,bestwpw/elasticsearch,rhoml/elasticsearch,JervyShi/elasticsearch,iacdingping/elasticsearch,dataduke/elasticsearch,mm0/elasticsearch,zeroctu/elasticsearch,markwalkom/elasticsearch,hirdesh2008/elasticsearch,ydsakyclguozi/elasticsearch,F0lha/elasticsearch,sposam/elasticsearch,polyfractal/elasticsearch,pozhidaevak/elasticsearch,rento19962/elasticsearch,njlawton/elasticsearch,mikemccand/elasticsearch,StefanGor/elasticsearch,pritishppai/elasticsearch,sc0ttkclark/elasticsearch,sreeramjayan/elasticsearch,gfyoung/elasticsearch,springning/elasticsearch,lydonchandra/elasticsearch,kunallimaye/elasticsearch,rmuir/elasticsearch,Kakakakakku/elasticsearch,mnylen/elasticsearch,AleksKochev/elasticsearch,mapr/elasticsearch,s1monw/elasticsearch,pritishppai/elasticsearch,mgalushka/elasticsearch,maddin2016/elasticsearch,Collaborne/elasticsearch,LeoYao/elasticsearch,mmaracic/elasticsearch,tahaemin/elasticsearch,linglaiyao1314/elasticsearch,Clairebi/ElasticsearchClone,18098924759/elasticsearch,vietlq/elasticsearch,jaynblue/elasticsearch,18098924759/elasticsearch,mikemccand/elasticsearch,snikch/elasticsearch,xuzha/elasticsearch,pablocastro/elasticsearch,iacdingping/elasticsearch,queirozfcom/elasticsearch,lydonchandra/elasticsearch,wbowling/elasticsearch,zkidkid/elasticsearch,Charlesdong/elasticsearch,episerver/elasticsearch,kingaj/elasticsearch,skearns64/elasticsearch,nilabhsagar/elasticsearch,Ansh90/elasticsearch,scorpionvicky/elasticsearch,ulkas/elasticsearch,jimhooker2002/elasticsearch,fooljohnny/elasticsearch,ulkas/elasticsearch,Helen-Zhao/elasticsearch,pranavraman/elasticsearch,jchampion/elasticsearch,fred84/elasticsearch,martinstuga/elasticsearch,kalburgimanjunath/elasticsearch,mm0/elasticsearch,bawse/elasticsearch,alexkuk/elasticsearch,feiqitian/elasticsearch,weipinghe/elasticsearch,beiske/elasticsearch,masterweb121/elasticsearch,zhaocloud/elasticsearch,jaynblue/elasticsearch,amit-shar/elasticsearch,F0lha/elasticsearch,phani546/elasticsearch,huanzhong/elasticsearch,jpountz/elasticsearch,yuy168/elasticsearch,palecur/elasticsearch,palecur/elasticsearch,wbowling/elasticsearch,amit-shar/elasticsearch,salyh/elasticsearch,Rygbee/elasticsearch,wbowling/elasticsearch,clintongormley/elasticsearch,areek/elasticsearch,Kakakakakku/elasticsearch,adrianbk/elasticsearch,nellicus/elasticsearch,myelin/elasticsearch,ouyangkongtong/elasticsearch,EasonYi/elasticsearch,gfyoung/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,NBSW/elasticsearch,ZTE-PaaS/elasticsearch,mnylen/elasticsearch,hanst/elasticsearch,amit-shar/elasticsearch,onegambler/elasticsearch,strapdata/elassandra,sarwarbhuiyan/elasticsearch,artnowo/elasticsearch,umeshdangat/elasticsearch,xuzha/elasticsearch,kcompher/elasticsearch,jsgao0/elasticsearch,combinatorist/elasticsearch,milodky/elasticsearch,mbrukman/elasticsearch,xpandan/elasticsearch,IanvsPoplicola/elasticsearch,brwe/elasticsearch,fforbeck/elasticsearch,nazarewk/elasticsearch,ImpressTV/elasticsearch,polyfractal/elasticsearch,avikurapati/elasticsearch,khiraiwa/elasticsearch,zkidkid/elasticsearch,mbrukman/elasticsearch,dantuffery/elasticsearch,petmit/elasticsearch,beiske/elasticsearch,Flipkart/elasticsearch,LeoYao/elasticsearch,janmejay/elasticsearch,AleksKochev/elasticsearch,Flipkart/elasticsearch,jpountz/elasticsearch,pablocastro/elasticsearch,strapdata/elassandra,lchennup/elasticsearch,socialrank/elasticsearch,a2lin/elasticsearch,HonzaKral/elasticsearch,jpountz/elasticsearch,Chhunlong/elasticsearch,peschlowp/elasticsearch,mohit/elasticsearch,opendatasoft/elasticsearch,truemped/elasticsearch,palecur/elasticsearch,vrkansagara/elasticsearch,dylan8902/elasticsearch,xpandan/elasticsearch,MjAbuz/elasticsearch,jaynblue/elasticsearch,sauravmondallive/elasticsearch,sscarduzio/elasticsearch,kimimj/elasticsearch,dpursehouse/elasticsearch,mkis-/elasticsearch,milodky/elasticsearch,xingguang2013/elasticsearch,abibell/elasticsearch,jprante/elasticsearch,brwe/elasticsearch,sjohnr/elasticsearch,wenpos/elasticsearch,nellicus/elasticsearch,GlenRSmith/elasticsearch,Fsero/elasticsearch,huypx1292/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,dylan8902/elasticsearch,episerver/elasticsearch,markharwood/elasticsearch,rento19962/elasticsearch,fekaputra/elasticsearch,kubum/elasticsearch,sscarduzio/elasticsearch,heng4fun/elasticsearch,andrejserafim/elasticsearch,karthikjaps/elasticsearch,dantuffery/elasticsearch,snikch/elasticsearch,bestwpw/elasticsearch,AndreKR/elasticsearch,tcucchietti/elasticsearch,fernandozhu/elasticsearch,PhaedrusTheGreek/elasticsearch,rento19962/elasticsearch,iacdingping/elasticsearch,davidvgalbraith/elasticsearch,HarishAtGitHub/elasticsearch,Brijeshrpatel9/elasticsearch,wittyameta/elasticsearch,hanswang/elasticsearch,alexkuk/elasticsearch,hanst/elasticsearch,nrkkalyan/elasticsearch,NBSW/elasticsearch,Collaborne/elasticsearch,Uiho/elasticsearch,Chhunlong/elasticsearch,caengcjd/elasticsearch,dpursehouse/elasticsearch,a2lin/elasticsearch,tkssharma/elasticsearch,franklanganke/elasticsearch,linglaiyao1314/elasticsearch,dantuffery/elasticsearch,ThiagoGarciaAlves/elasticsearch,jprante/elasticsearch,himanshuag/elasticsearch,F0lha/elasticsearch,gingerwizard/elasticsearch,Microsoft/elasticsearch,Shekharrajak/elasticsearch,adrianbk/elasticsearch,elancom/elasticsearch,dataduke/elasticsearch,sdauletau/elasticsearch,abibell/elasticsearch,socialrank/elasticsearch,djschny/elasticsearch,hirdesh2008/elasticsearch,MjAbuz/elasticsearch,Brijeshrpatel9/elasticsearch,combinatorist/elasticsearch,humandb/elasticsearch,wayeast/elasticsearch,kubum/elasticsearch,bawse/elasticsearch,C-Bish/elasticsearch,sdauletau/elasticsearch,elancom/elasticsearch,ThalaivaStars/OrgRepo1,MaineC/elasticsearch,salyh/elasticsearch,ydsakyclguozi/elasticsearch,jimhooker2002/elasticsearch,qwerty4030/elasticsearch,kalimatas/elasticsearch,fekaputra/elasticsearch,yynil/elasticsearch,kalburgimanjunath/elasticsearch,Widen/elasticsearch,boliza/elasticsearch,mmaracic/elasticsearch,F0lha/elasticsearch,hirdesh2008/elasticsearch,wuranbo/elasticsearch,drewr/elasticsearch,HonzaKral/elasticsearch,likaiwalkman/elasticsearch,i-am-Nathan/elasticsearch,yanjunh/elasticsearch,polyfractal/elasticsearch,Rygbee/elasticsearch,marcuswr/elasticsearch-dateline,pozhidaevak/elasticsearch,maddin2016/elasticsearch,strapdata/elassandra5-rc,fernandozhu/elasticsearch,sneivandt/elasticsearch,koxa29/elasticsearch,apepper/elasticsearch,maddin2016/elasticsearch,easonC/elasticsearch,jprante/elasticsearch,kunallimaye/elasticsearch,strapdata/elassandra-test,truemped/elasticsearch,scorpionvicky/elasticsearch,smflorentino/elasticsearch,vietlq/elasticsearch,snikch/elasticsearch,anti-social/elasticsearch,karthikjaps/elasticsearch,queirozfcom/elasticsearch,avikurapati/elasticsearch,MisterAndersen/elasticsearch,jbertouch/elasticsearch,Shepard1212/elasticsearch,mcku/elasticsearch,rlugojr/elasticsearch,dylan8902/elasticsearch,himanshuag/elasticsearch,yuy168/elasticsearch,wittyameta/elasticsearch,schonfeld/elasticsearch,hechunwen/elasticsearch,kaneshin/elasticsearch,andrejserafim/elasticsearch,zeroctu/elasticsearch,acchen97/elasticsearch,rmuir/elasticsearch,schonfeld/elasticsearch,TonyChai24/ESSource,bawse/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,kalimatas/elasticsearch,drewr/elasticsearch,NBSW/elasticsearch,Asimov4/elasticsearch,Flipkart/elasticsearch,Rygbee/elasticsearch,aglne/elasticsearch,MjAbuz/elasticsearch,adrianbk/elasticsearch,lzo/elasticsearch-1,AndreKR/elasticsearch,C-Bish/elasticsearch,djschny/elasticsearch,wangtuo/elasticsearch,dylan8902/elasticsearch,zhiqinghuang/elasticsearch,mute/elasticsearch,chirilo/elasticsearch,wimvds/elasticsearch,NBSW/elasticsearch,KimTaehee/elasticsearch,beiske/elasticsearch,Chhunlong/elasticsearch,fred84/elasticsearch,ivansun1010/elasticsearch,tsohil/elasticsearch,yongminxia/elasticsearch,knight1128/elasticsearch,iamjakob/elasticsearch,snikch/elasticsearch,EasonYi/elasticsearch,masterweb121/elasticsearch,mjason3/elasticsearch,Clairebi/ElasticsearchClone,sscarduzio/elasticsearch,jpountz/elasticsearch,elancom/elasticsearch,zeroctu/elasticsearch,Widen/elasticsearch,strapdata/elassandra,robin13/elasticsearch,EasonYi/elasticsearch,kaneshin/elasticsearch,zhiqinghuang/elasticsearch,rajanm/elasticsearch,kcompher/elasticsearch,janmejay/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,slavau/elasticsearch,MetSystem/elasticsearch,mnylen/elasticsearch,kimimj/elasticsearch,mapr/elasticsearch,mm0/elasticsearch,mbrukman/elasticsearch,AndreKR/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,i-am-Nathan/elasticsearch,nilabhsagar/elasticsearch,SergVro/elasticsearch,nknize/elasticsearch,mohit/elasticsearch,sjohnr/elasticsearch,amit-shar/elasticsearch,spiegela/elasticsearch,infusionsoft/elasticsearch,Stacey-Gammon/elasticsearch,Liziyao/elasticsearch,camilojd/elasticsearch,wangtuo/elasticsearch,brandonkearby/elasticsearch,jw0201/elastic,ricardocerq/elasticsearch,NBSW/elasticsearch,clintongormley/elasticsearch,rento19962/elasticsearch,strapdata/elassandra-test,alexbrasetvik/elasticsearch,coding0011/elasticsearch,mjason3/elasticsearch,diendt/elasticsearch,mjhennig/elasticsearch,huypx1292/elasticsearch,sauravmondallive/elasticsearch,uschindler/elasticsearch,nknize/elasticsearch,jsgao0/elasticsearch,MichaelLiZhou/elasticsearch,iantruslove/elasticsearch,masaruh/elasticsearch,Kakakakakku/elasticsearch,amaliujia/elasticsearch,javachengwc/elasticsearch,wayeast/elasticsearch,mnylen/elasticsearch,kalburgimanjunath/elasticsearch,scorpionvicky/elasticsearch,onegambler/elasticsearch,aglne/elasticsearch,maddin2016/elasticsearch,truemped/elasticsearch,kunallimaye/elasticsearch,dongjoon-hyun/elasticsearch,franklanganke/elasticsearch,Charlesdong/elasticsearch,kcompher/elasticsearch,codebunt/elasticsearch,sposam/elasticsearch,hydro2k/elasticsearch,vrkansagara/elasticsearch,kkirsche/elasticsearch,apepper/elasticsearch,alexkuk/elasticsearch,wittyameta/elasticsearch,mbrukman/elasticsearch
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.transport.netty; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchIllegalArgumentException; import org.elasticsearch.ElasticsearchIllegalStateException; import org.elasticsearch.Version; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.ReleasableBytesReference; import org.elasticsearch.common.component.AbstractLifecycleComponent; import org.elasticsearch.common.compress.CompressorFactory; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.io.stream.HandlesStreamOutput; import org.elasticsearch.common.io.stream.ReleasableBytesStreamOutput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.lease.Releasables; import org.elasticsearch.common.math.MathUtils; import org.elasticsearch.common.netty.NettyStaticSetup; import org.elasticsearch.common.netty.OpenChannelsHandler; import org.elasticsearch.common.netty.ReleaseChannelFutureListener; import org.elasticsearch.common.network.NetworkService; import org.elasticsearch.common.network.NetworkUtils; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.BoundTransportAddress; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.transport.PortsRange; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.BigArrays; import org.elasticsearch.common.util.concurrent.EsExecutors; import org.elasticsearch.common.util.concurrent.KeyedLock; import org.elasticsearch.monitor.jvm.JvmInfo; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.*; import org.elasticsearch.transport.support.TransportStatus; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.CompositeChannelBuffer; import org.jboss.netty.channel.*; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioWorkerPool; import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; import org.jboss.netty.util.HashedWheelTimer; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.channels.CancelledKeyException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import static org.elasticsearch.common.network.NetworkService.TcpSettings.*; import static org.elasticsearch.common.transport.NetworkExceptionHelper.isCloseConnectionException; import static org.elasticsearch.common.transport.NetworkExceptionHelper.isConnectException; import static org.elasticsearch.common.util.concurrent.ConcurrentCollections.newConcurrentMap; import static org.elasticsearch.common.util.concurrent.EsExecutors.daemonThreadFactory; /** * There are 4 types of connections per node, low/med/high/ping. Low if for batch oriented APIs (like recovery or * batch) with high payload that will cause regular request. (like search or single index) to take * longer. Med is for the typical search / single doc index. And High for things like cluster state. Ping is reserved for * sending out ping requests to other nodes. */ public class NettyTransport extends AbstractLifecycleComponent<Transport> implements Transport { static { NettyStaticSetup.setup(); } private final NetworkService networkService; final Version version; final int workerCount; final int bossCount; final boolean blockingServer; final boolean blockingClient; final String port; final String bindHost; final String publishHost; final int publishPort; final boolean compress; final TimeValue connectTimeout; final Boolean tcpNoDelay; final Boolean tcpKeepAlive; final Boolean reuseAddress; final ByteSizeValue tcpSendBufferSize; final ByteSizeValue tcpReceiveBufferSize; final ReceiveBufferSizePredictorFactory receiveBufferSizePredictorFactory; final int connectionsPerNodeRecovery; final int connectionsPerNodeBulk; final int connectionsPerNodeReg; final int connectionsPerNodeState; final int connectionsPerNodePing; final ByteSizeValue maxCumulationBufferCapacity; final int maxCompositeBufferComponents; final BigArrays bigArrays; private final ThreadPool threadPool; private volatile OpenChannelsHandler serverOpenChannels; private volatile ClientBootstrap clientBootstrap; private volatile ServerBootstrap serverBootstrap; // node id to actual channel final ConcurrentMap<DiscoveryNode, NodeChannels> connectedNodes = newConcurrentMap(); private volatile Channel serverChannel; private volatile TransportServiceAdapter transportServiceAdapter; private volatile BoundTransportAddress boundAddress; private final KeyedLock<String> connectionLock = new KeyedLock<>(); // this lock is here to make sure we close this transport and disconnect all the client nodes // connections while no connect operations is going on... (this might help with 100% CPU when stopping the transport?) private final ReadWriteLock globalLock = new ReentrantReadWriteLock(); @Inject public NettyTransport(Settings settings, ThreadPool threadPool, NetworkService networkService, BigArrays bigArrays, Version version) { super(settings); this.threadPool = threadPool; this.networkService = networkService; this.bigArrays = bigArrays; this.version = version; if (settings.getAsBoolean("netty.epollBugWorkaround", false)) { System.setProperty("org.jboss.netty.epollBugWorkaround", "true"); } this.workerCount = componentSettings.getAsInt("worker_count", EsExecutors.boundedNumberOfProcessors(settings) * 2); this.bossCount = componentSettings.getAsInt("boss_count", 1); this.blockingServer = settings.getAsBoolean("transport.tcp.blocking_server", settings.getAsBoolean(TCP_BLOCKING_SERVER, settings.getAsBoolean(TCP_BLOCKING, false))); this.blockingClient = settings.getAsBoolean("transport.tcp.blocking_client", settings.getAsBoolean(TCP_BLOCKING_CLIENT, settings.getAsBoolean(TCP_BLOCKING, false))); this.port = componentSettings.get("port", settings.get("transport.tcp.port", "9300-9400")); this.bindHost = componentSettings.get("bind_host", settings.get("transport.bind_host", settings.get("transport.host"))); this.publishHost = componentSettings.get("publish_host", settings.get("transport.publish_host", settings.get("transport.host"))); this.publishPort = componentSettings.getAsInt("publish_port", settings.getAsInt("transport.publish_port", 0)); this.compress = settings.getAsBoolean(TransportSettings.TRANSPORT_TCP_COMPRESS, false); this.connectTimeout = componentSettings.getAsTime("connect_timeout", settings.getAsTime("transport.tcp.connect_timeout", settings.getAsTime(TCP_CONNECT_TIMEOUT, TCP_DEFAULT_CONNECT_TIMEOUT))); this.tcpNoDelay = componentSettings.getAsBoolean("tcp_no_delay", settings.getAsBoolean(TCP_NO_DELAY, true)); this.tcpKeepAlive = componentSettings.getAsBoolean("tcp_keep_alive", settings.getAsBoolean(TCP_KEEP_ALIVE, true)); this.reuseAddress = componentSettings.getAsBoolean("reuse_address", settings.getAsBoolean(TCP_REUSE_ADDRESS, NetworkUtils.defaultReuseAddress())); this.tcpSendBufferSize = componentSettings.getAsBytesSize("tcp_send_buffer_size", settings.getAsBytesSize(TCP_SEND_BUFFER_SIZE, TCP_DEFAULT_SEND_BUFFER_SIZE)); this.tcpReceiveBufferSize = componentSettings.getAsBytesSize("tcp_receive_buffer_size", settings.getAsBytesSize(TCP_RECEIVE_BUFFER_SIZE, TCP_DEFAULT_RECEIVE_BUFFER_SIZE)); this.connectionsPerNodeRecovery = componentSettings.getAsInt("connections_per_node.recovery", settings.getAsInt("transport.connections_per_node.recovery", 2)); this.connectionsPerNodeBulk = componentSettings.getAsInt("connections_per_node.bulk", settings.getAsInt("transport.connections_per_node.bulk", 3)); this.connectionsPerNodeReg = componentSettings.getAsInt("connections_per_node.reg", settings.getAsInt("transport.connections_per_node.reg", 6)); this.connectionsPerNodeState = componentSettings.getAsInt("connections_per_node.high", settings.getAsInt("transport.connections_per_node.state", 1)); this.connectionsPerNodePing = componentSettings.getAsInt("connections_per_node.ping", settings.getAsInt("transport.connections_per_node.ping", 1)); // we want to have at least 1 for reg/state/ping if (this.connectionsPerNodeReg == 0) { throw new ElasticsearchIllegalArgumentException("can't set [connection_per_node.reg] to 0"); } if (this.connectionsPerNodePing == 0) { throw new ElasticsearchIllegalArgumentException("can't set [connection_per_node.ping] to 0"); } if (this.connectionsPerNodeState == 0) { throw new ElasticsearchIllegalArgumentException("can't set [connection_per_node.state] to 0"); } this.maxCumulationBufferCapacity = componentSettings.getAsBytesSize("max_cumulation_buffer_capacity", null); this.maxCompositeBufferComponents = componentSettings.getAsInt("max_composite_buffer_components", -1); long defaultReceiverPredictor = 512 * 1024; if (JvmInfo.jvmInfo().mem().directMemoryMax().bytes() > 0) { // we can guess a better default... long l = (long) ((0.3 * JvmInfo.jvmInfo().mem().directMemoryMax().bytes()) / workerCount); defaultReceiverPredictor = Math.min(defaultReceiverPredictor, Math.max(l, 64 * 1024)); } // See AdaptiveReceiveBufferSizePredictor#DEFAULT_XXX for default values in netty..., we can use higher ones for us, even fixed one ByteSizeValue receivePredictorMin = componentSettings.getAsBytesSize("receive_predictor_min", componentSettings.getAsBytesSize("receive_predictor_size", new ByteSizeValue(defaultReceiverPredictor))); ByteSizeValue receivePredictorMax = componentSettings.getAsBytesSize("receive_predictor_max", componentSettings.getAsBytesSize("receive_predictor_size", new ByteSizeValue(defaultReceiverPredictor))); if (receivePredictorMax.bytes() == receivePredictorMin.bytes()) { receiveBufferSizePredictorFactory = new FixedReceiveBufferSizePredictorFactory((int) receivePredictorMax.bytes()); } else { receiveBufferSizePredictorFactory = new AdaptiveReceiveBufferSizePredictorFactory((int) receivePredictorMin.bytes(), (int) receivePredictorMin.bytes(), (int) receivePredictorMax.bytes()); } logger.debug("using worker_count[{}], port[{}], bind_host[{}], publish_host[{}], compress[{}], connect_timeout[{}], connections_per_node[{}/{}/{}/{}/{}], receive_predictor[{}->{}]", workerCount, port, bindHost, publishHost, compress, connectTimeout, connectionsPerNodeRecovery, connectionsPerNodeBulk, connectionsPerNodeReg, connectionsPerNodeState, connectionsPerNodePing, receivePredictorMin, receivePredictorMax); } public Settings settings() { return this.settings; } @Override public void transportServiceAdapter(TransportServiceAdapter service) { this.transportServiceAdapter = service; } TransportServiceAdapter transportServiceAdapter() { return transportServiceAdapter; } ThreadPool threadPool() { return threadPool; } @Override protected void doStart() throws ElasticsearchException { if (blockingClient) { clientBootstrap = new ClientBootstrap(new OioClientSocketChannelFactory(Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_client_worker")))); } else { clientBootstrap = new ClientBootstrap(new NioClientSocketChannelFactory( Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_client_boss")), bossCount, new NioWorkerPool(Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_client_worker")), workerCount), new HashedWheelTimer(daemonThreadFactory(settings, "transport_client_timer")))); } ChannelPipelineFactory clientPipelineFactory = new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); SizeHeaderFrameDecoder sizeHeader = new SizeHeaderFrameDecoder(); if (maxCumulationBufferCapacity != null) { if (maxCumulationBufferCapacity.bytes() > Integer.MAX_VALUE) { sizeHeader.setMaxCumulationBufferCapacity(Integer.MAX_VALUE); } else { sizeHeader.setMaxCumulationBufferCapacity((int) maxCumulationBufferCapacity.bytes()); } } if (maxCompositeBufferComponents != -1) { sizeHeader.setMaxCumulationBufferComponents(maxCompositeBufferComponents); } pipeline.addLast("size", sizeHeader); pipeline.addLast("dispatcher", new MessageChannelHandler(NettyTransport.this, logger)); return pipeline; } }; clientBootstrap.setPipelineFactory(clientPipelineFactory); clientBootstrap.setOption("connectTimeoutMillis", connectTimeout.millis()); if (tcpNoDelay != null) { clientBootstrap.setOption("tcpNoDelay", tcpNoDelay); } if (tcpKeepAlive != null) { clientBootstrap.setOption("keepAlive", tcpKeepAlive); } if (tcpSendBufferSize != null && tcpSendBufferSize.bytes() > 0) { clientBootstrap.setOption("sendBufferSize", tcpSendBufferSize.bytes()); } if (tcpReceiveBufferSize != null && tcpReceiveBufferSize.bytes() > 0) { clientBootstrap.setOption("receiveBufferSize", tcpReceiveBufferSize.bytes()); } clientBootstrap.setOption("receiveBufferSizePredictorFactory", receiveBufferSizePredictorFactory); if (reuseAddress != null) { clientBootstrap.setOption("reuseAddress", reuseAddress); } if (!settings.getAsBoolean("network.server", true)) { return; } final OpenChannelsHandler openChannels = new OpenChannelsHandler(logger); this.serverOpenChannels = openChannels; if (blockingServer) { serverBootstrap = new ServerBootstrap(new OioServerSocketChannelFactory( Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_server_boss")), Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_server_worker")) )); } else { serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory( Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_server_boss")), Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_server_worker")), workerCount)); } ChannelPipelineFactory serverPipelineFactory = new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("openChannels", openChannels); SizeHeaderFrameDecoder sizeHeader = new SizeHeaderFrameDecoder(); if (maxCumulationBufferCapacity != null) { if (maxCumulationBufferCapacity.bytes() > Integer.MAX_VALUE) { sizeHeader.setMaxCumulationBufferCapacity(Integer.MAX_VALUE); } else { sizeHeader.setMaxCumulationBufferCapacity((int) maxCumulationBufferCapacity.bytes()); } } if (maxCompositeBufferComponents != -1) { sizeHeader.setMaxCumulationBufferComponents(maxCompositeBufferComponents); } pipeline.addLast("size", sizeHeader); pipeline.addLast("dispatcher", new MessageChannelHandler(NettyTransport.this, logger)); return pipeline; } }; serverBootstrap.setPipelineFactory(serverPipelineFactory); if (tcpNoDelay != null) { serverBootstrap.setOption("child.tcpNoDelay", tcpNoDelay); } if (tcpKeepAlive != null) { serverBootstrap.setOption("child.keepAlive", tcpKeepAlive); } if (tcpSendBufferSize != null && tcpSendBufferSize.bytes() > 0) { serverBootstrap.setOption("child.sendBufferSize", tcpSendBufferSize.bytes()); } if (tcpReceiveBufferSize != null && tcpReceiveBufferSize.bytes() > 0) { serverBootstrap.setOption("child.receiveBufferSize", tcpReceiveBufferSize.bytes()); } serverBootstrap.setOption("receiveBufferSizePredictorFactory", receiveBufferSizePredictorFactory); serverBootstrap.setOption("child.receiveBufferSizePredictorFactory", receiveBufferSizePredictorFactory); if (reuseAddress != null) { serverBootstrap.setOption("reuseAddress", reuseAddress); serverBootstrap.setOption("child.reuseAddress", reuseAddress); } // Bind and start to accept incoming connections. InetAddress hostAddressX; try { hostAddressX = networkService.resolveBindHostAddress(bindHost); } catch (IOException e) { throw new BindTransportException("Failed to resolve host [" + bindHost + "]", e); } final InetAddress hostAddress = hostAddressX; PortsRange portsRange = new PortsRange(port); final AtomicReference<Exception> lastException = new AtomicReference<>(); boolean success = portsRange.iterate(new PortsRange.PortCallback() { @Override public boolean onPortNumber(int portNumber) { try { serverChannel = serverBootstrap.bind(new InetSocketAddress(hostAddress, portNumber)); } catch (Exception e) { lastException.set(e); return false; } return true; } }); if (!success) { throw new BindTransportException("Failed to bind to [" + port + "]", lastException.get()); } logger.debug("Bound to address [{}]", serverChannel.getLocalAddress()); InetSocketAddress boundAddress = (InetSocketAddress) serverChannel.getLocalAddress(); InetSocketAddress publishAddress; int publishPort = this.publishPort; if (0 == publishPort) { publishPort = boundAddress.getPort(); } try { publishAddress = new InetSocketAddress(networkService.resolvePublishHostAddress(publishHost), publishPort); } catch (Exception e) { throw new BindTransportException("Failed to resolve publish address", e); } this.boundAddress = new BoundTransportAddress(new InetSocketTransportAddress(boundAddress), new InetSocketTransportAddress(publishAddress)); } @Override protected void doStop() throws ElasticsearchException { final CountDownLatch latch = new CountDownLatch(1); // make sure we run it on another thread than a possible IO handler thread threadPool.generic().execute(new Runnable() { @Override public void run() { globalLock.writeLock().lock(); try { for (Iterator<NodeChannels> it = connectedNodes.values().iterator(); it.hasNext(); ) { NodeChannels nodeChannels = it.next(); it.remove(); nodeChannels.close(); } if (serverChannel != null) { try { serverChannel.close().awaitUninterruptibly(); } finally { serverChannel = null; } } if (serverOpenChannels != null) { serverOpenChannels.close(); serverOpenChannels = null; } if (serverBootstrap != null) { serverBootstrap.releaseExternalResources(); serverBootstrap = null; } for (Iterator<NodeChannels> it = connectedNodes.values().iterator(); it.hasNext(); ) { NodeChannels nodeChannels = it.next(); it.remove(); nodeChannels.close(); } if (clientBootstrap != null) { clientBootstrap.releaseExternalResources(); clientBootstrap = null; } } finally { globalLock.writeLock().unlock(); latch.countDown(); } } }); try { latch.await(30, TimeUnit.SECONDS); } catch (InterruptedException e) { // ignore } } @Override protected void doClose() throws ElasticsearchException { } @Override public TransportAddress[] addressesFromString(String address) throws Exception { int index = address.indexOf('['); if (index != -1) { String host = address.substring(0, index); Set<String> ports = Strings.commaDelimitedListToSet(address.substring(index + 1, address.indexOf(']'))); List<TransportAddress> addresses = Lists.newArrayList(); for (String port : ports) { int[] iPorts = new PortsRange(port).ports(); for (int iPort : iPorts) { addresses.add(new InetSocketTransportAddress(host, iPort)); } } return addresses.toArray(new TransportAddress[addresses.size()]); } else { index = address.lastIndexOf(':'); if (index == -1) { List<TransportAddress> addresses = Lists.newArrayList(); int[] iPorts = new PortsRange(this.port).ports(); for (int iPort : iPorts) { addresses.add(new InetSocketTransportAddress(address, iPort)); } return addresses.toArray(new TransportAddress[addresses.size()]); } else { String host = address.substring(0, index); int port = Integer.parseInt(address.substring(index + 1)); return new TransportAddress[]{new InetSocketTransportAddress(host, port)}; } } } @Override public boolean addressSupported(Class<? extends TransportAddress> address) { return InetSocketTransportAddress.class.equals(address); } @Override public BoundTransportAddress boundAddress() { return this.boundAddress; } void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { if (!lifecycle.started()) { // ignore } if (isCloseConnectionException(e.getCause())) { logger.trace("close connection exception caught on transport layer [{}], disconnecting from relevant node", e.getCause(), ctx.getChannel()); // close the channel, which will cause a node to be disconnected if relevant ctx.getChannel().close(); disconnectFromNodeChannel(ctx.getChannel(), e.getCause()); } else if (isConnectException(e.getCause())) { logger.trace("connect exception caught on transport layer [{}]", e.getCause(), ctx.getChannel()); // close the channel as safe measure, which will cause a node to be disconnected if relevant ctx.getChannel().close(); disconnectFromNodeChannel(ctx.getChannel(), e.getCause()); } else if (e.getCause() instanceof CancelledKeyException) { logger.trace("cancelled key exception caught on transport layer [{}], disconnecting from relevant node", e.getCause(), ctx.getChannel()); // close the channel as safe measure, which will cause a node to be disconnected if relevant ctx.getChannel().close(); disconnectFromNodeChannel(ctx.getChannel(), e.getCause()); } else { logger.warn("exception caught on transport layer [{}], closing connection", e.getCause(), ctx.getChannel()); // close the channel, which will cause a node to be disconnected if relevant ctx.getChannel().close(); disconnectFromNodeChannel(ctx.getChannel(), e.getCause()); } } TransportAddress wrapAddress(SocketAddress socketAddress) { return new InetSocketTransportAddress((InetSocketAddress) socketAddress); } @Override public long serverOpen() { OpenChannelsHandler channels = serverOpenChannels; return channels == null ? 0 : channels.numberOfOpenChannels(); } @Override public void sendRequest(final DiscoveryNode node, final long requestId, final String action, final TransportRequest request, TransportRequestOptions options) throws IOException, TransportException { Channel targetChannel = nodeChannel(node, options); if (compress) { options.withCompress(true); } byte status = 0; status = TransportStatus.setRequest(status); ReleasableBytesStreamOutput bStream = new ReleasableBytesStreamOutput(bigArrays); boolean addedReleaseListener = false; try { bStream.skip(NettyHeader.HEADER_SIZE); StreamOutput stream = bStream; // only compress if asked, and, the request is not bytes, since then only // the header part is compressed, and the "body" can't be extracted as compressed if (options.compress() && (!(request instanceof BytesTransportRequest))) { status = TransportStatus.setCompress(status); stream = CompressorFactory.defaultCompressor().streamOutput(stream); } stream = new HandlesStreamOutput(stream); // we pick the smallest of the 2, to support both backward and forward compatibility // note, this is the only place we need to do this, since from here on, we use the serialized version // as the version to use also when the node receiving this request will send the response with Version version = Version.smallest(this.version, node.version()); stream.setVersion(version); stream.writeString(action); ReleasableBytesReference bytes; ChannelBuffer buffer; // it might be nice to somehow generalize this optimization, maybe a smart "paged" bytes output // that create paged channel buffers, but its tricky to know when to do it (where this option is // more explicit). if (request instanceof BytesTransportRequest) { BytesTransportRequest bRequest = (BytesTransportRequest) request; assert node.version().equals(bRequest.version()); bRequest.writeThin(stream); stream.close(); bytes = bStream.bytes(); ChannelBuffer headerBuffer = bytes.toChannelBuffer(); ChannelBuffer contentBuffer = bRequest.bytes().toChannelBuffer(); // false on gathering, cause gathering causes the NIO layer to combine the buffers into a single direct buffer.... buffer = new CompositeChannelBuffer(headerBuffer.order(), ImmutableList.<ChannelBuffer>of(headerBuffer, contentBuffer), false); } else { request.writeTo(stream); stream.close(); bytes = bStream.bytes(); buffer = bytes.toChannelBuffer(); } NettyHeader.writeHeader(buffer, requestId, status, version); ChannelFuture future = targetChannel.write(buffer); ReleaseChannelFutureListener listener = new ReleaseChannelFutureListener(bytes); future.addListener(listener); addedReleaseListener = true; } finally { if (!addedReleaseListener) { Releasables.close(bStream.bytes()); } } } @Override public boolean nodeConnected(DiscoveryNode node) { return connectedNodes.containsKey(node); } @Override public void connectToNodeLight(DiscoveryNode node) throws ConnectTransportException { connectToNode(node, true); } @Override public void connectToNode(DiscoveryNode node) { connectToNode(node, false); } public void connectToNode(DiscoveryNode node, boolean light) { if (!lifecycle.started()) { throw new ElasticsearchIllegalStateException("can't add nodes to a stopped transport"); } if (node == null) { throw new ConnectTransportException(null, "can't connect to a null node"); } globalLock.readLock().lock(); try { if (!lifecycle.started()) { throw new ElasticsearchIllegalStateException("can't add nodes to a stopped transport"); } NodeChannels nodeChannels = connectedNodes.get(node); if (nodeChannels != null) { return; } connectionLock.acquire(node.id()); try { if (!lifecycle.started()) { throw new ElasticsearchIllegalStateException("can't add nodes to a stopped transport"); } try { if (light) { nodeChannels = connectToChannelsLight(node); } else { nodeChannels = new NodeChannels(new Channel[connectionsPerNodeRecovery], new Channel[connectionsPerNodeBulk], new Channel[connectionsPerNodeReg], new Channel[connectionsPerNodeState], new Channel[connectionsPerNodePing]); try { connectToChannels(nodeChannels, node); } catch (Exception e) { nodeChannels.close(); throw e; } } NodeChannels existing = connectedNodes.putIfAbsent(node, nodeChannels); if (existing != null) { // we are already connected to a node, close this ones nodeChannels.close(); } else { if (logger.isDebugEnabled()) { logger.debug("connected to node [{}]", node); } transportServiceAdapter.raiseNodeConnected(node); } } catch (ConnectTransportException e) { throw e; } catch (Exception e) { throw new ConnectTransportException(node, "General node connection failure", e); } } finally { connectionLock.release(node.id()); } } finally { globalLock.readLock().unlock(); } } private NodeChannels connectToChannelsLight(DiscoveryNode node) { InetSocketAddress address = ((InetSocketTransportAddress) node.address()).address(); ChannelFuture connect = clientBootstrap.connect(address); connect.awaitUninterruptibly((long) (connectTimeout.millis() * 1.5)); if (!connect.isSuccess()) { throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connect.getCause()); } Channel[] channels = new Channel[1]; channels[0] = connect.getChannel(); channels[0].getCloseFuture().addListener(new ChannelCloseListener(node)); return new NodeChannels(channels, channels, channels, channels, channels); } private void connectToChannels(NodeChannels nodeChannels, DiscoveryNode node) { ChannelFuture[] connectRecovery = new ChannelFuture[nodeChannels.recovery.length]; ChannelFuture[] connectBulk = new ChannelFuture[nodeChannels.bulk.length]; ChannelFuture[] connectReg = new ChannelFuture[nodeChannels.reg.length]; ChannelFuture[] connectState = new ChannelFuture[nodeChannels.state.length]; ChannelFuture[] connectPing = new ChannelFuture[nodeChannels.ping.length]; InetSocketAddress address = ((InetSocketTransportAddress) node.address()).address(); for (int i = 0; i < connectRecovery.length; i++) { connectRecovery[i] = clientBootstrap.connect(address); } for (int i = 0; i < connectBulk.length; i++) { connectBulk[i] = clientBootstrap.connect(address); } for (int i = 0; i < connectReg.length; i++) { connectReg[i] = clientBootstrap.connect(address); } for (int i = 0; i < connectState.length; i++) { connectState[i] = clientBootstrap.connect(address); } for (int i = 0; i < connectPing.length; i++) { connectPing[i] = clientBootstrap.connect(address); } try { for (int i = 0; i < connectRecovery.length; i++) { connectRecovery[i].awaitUninterruptibly((long) (connectTimeout.millis() * 1.5)); if (!connectRecovery[i].isSuccess()) { throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connectRecovery[i].getCause()); } nodeChannels.recovery[i] = connectRecovery[i].getChannel(); nodeChannels.recovery[i].getCloseFuture().addListener(new ChannelCloseListener(node)); } for (int i = 0; i < connectBulk.length; i++) { connectBulk[i].awaitUninterruptibly((long) (connectTimeout.millis() * 1.5)); if (!connectBulk[i].isSuccess()) { throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connectBulk[i].getCause()); } nodeChannels.bulk[i] = connectBulk[i].getChannel(); nodeChannels.bulk[i].getCloseFuture().addListener(new ChannelCloseListener(node)); } for (int i = 0; i < connectReg.length; i++) { connectReg[i].awaitUninterruptibly((long) (connectTimeout.millis() * 1.5)); if (!connectReg[i].isSuccess()) { throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connectReg[i].getCause()); } nodeChannels.reg[i] = connectReg[i].getChannel(); nodeChannels.reg[i].getCloseFuture().addListener(new ChannelCloseListener(node)); } for (int i = 0; i < connectState.length; i++) { connectState[i].awaitUninterruptibly((long) (connectTimeout.millis() * 1.5)); if (!connectState[i].isSuccess()) { throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connectState[i].getCause()); } nodeChannels.state[i] = connectState[i].getChannel(); nodeChannels.state[i].getCloseFuture().addListener(new ChannelCloseListener(node)); } for (int i = 0; i < connectPing.length; i++) { connectPing[i].awaitUninterruptibly((long) (connectTimeout.millis() * 1.5)); if (!connectPing[i].isSuccess()) { throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connectPing[i].getCause()); } nodeChannels.ping[i] = connectPing[i].getChannel(); nodeChannels.ping[i].getCloseFuture().addListener(new ChannelCloseListener(node)); } if (nodeChannels.recovery.length == 0) { if (nodeChannels.bulk.length > 0) { nodeChannels.recovery = nodeChannels.bulk; } else { nodeChannels.recovery = nodeChannels.reg; } } if (nodeChannels.bulk.length == 0) { nodeChannels.bulk = nodeChannels.reg; } } catch (RuntimeException e) { // clean the futures for (ChannelFuture future : ImmutableList.<ChannelFuture>builder().add(connectRecovery).add(connectBulk).add(connectReg).add(connectState).add(connectPing).build()) { future.cancel(); if (future.getChannel() != null && future.getChannel().isOpen()) { try { future.getChannel().close(); } catch (Exception e1) { // ignore } } } throw e; } } @Override public void disconnectFromNode(DiscoveryNode node) { NodeChannels nodeChannels = connectedNodes.remove(node); if (nodeChannels != null) { connectionLock.acquire(node.id()); try { try { nodeChannels.close(); } finally { logger.debug("disconnected from [{}]", node); transportServiceAdapter.raiseNodeDisconnected(node); } } finally { connectionLock.release(node.id()); } } } /** * Disconnects from a node, only if the relevant channel is found to be part of the node channels. */ private void disconnectFromNode(DiscoveryNode node, Channel channel, String reason) { NodeChannels nodeChannels = connectedNodes.get(node); if (nodeChannels != null && nodeChannels.hasChannel(channel)) { connectionLock.acquire(node.id()); if (!nodeChannels.hasChannel(channel)) { //might have been removed in the meanwhile, safety check assert !connectedNodes.containsKey(node); } else { try { connectedNodes.remove(node); try { nodeChannels.close(); } finally { logger.debug("disconnected from [{}], {}", node, reason); transportServiceAdapter.raiseNodeDisconnected(node); } } finally { connectionLock.release(node.id()); } } } } /** * Disconnects from a node if a channel is found as part of that nodes channels. */ private void disconnectFromNodeChannel(Channel channel, Throwable failure) { for (DiscoveryNode node : connectedNodes.keySet()) { NodeChannels nodeChannels = connectedNodes.get(node); if (nodeChannels != null && nodeChannels.hasChannel(channel)) { connectionLock.acquire(node.id()); if (!nodeChannels.hasChannel(channel)) { //might have been removed in the meanwhile, safety check assert !connectedNodes.containsKey(node); } else { try { connectedNodes.remove(node); try { nodeChannels.close(); } finally { logger.debug("disconnected from [{}] on channel failure", failure, node); transportServiceAdapter.raiseNodeDisconnected(node); } } finally { connectionLock.release(node.id()); } } } } } private Channel nodeChannel(DiscoveryNode node, TransportRequestOptions options) throws ConnectTransportException { NodeChannels nodeChannels = connectedNodes.get(node); if (nodeChannels == null) { throw new NodeNotConnectedException(node, "Node not connected"); } return nodeChannels.channel(options.type()); } private class ChannelCloseListener implements ChannelFutureListener { private final DiscoveryNode node; private ChannelCloseListener(DiscoveryNode node) { this.node = node; } @Override public void operationComplete(ChannelFuture future) throws Exception { disconnectFromNode(node, future.getChannel(), "channel closed event"); } } public static class NodeChannels { private Channel[] recovery; private final AtomicInteger recoveryCounter = new AtomicInteger(); private Channel[] bulk; private final AtomicInteger bulkCounter = new AtomicInteger(); private Channel[] reg; private final AtomicInteger regCounter = new AtomicInteger(); private Channel[] state; private final AtomicInteger stateCounter = new AtomicInteger(); private Channel[] ping; private final AtomicInteger pingCounter = new AtomicInteger(); public NodeChannels(Channel[] recovery, Channel[] bulk, Channel[] reg, Channel[] state, Channel[] ping) { this.recovery = recovery; this.bulk = bulk; this.reg = reg; this.state = state; this.ping = ping; } public boolean hasChannel(Channel channel) { return hasChannel(channel, recovery) || hasChannel(channel, bulk) || hasChannel(channel, reg) || hasChannel(channel, state) || hasChannel(channel, ping); } private boolean hasChannel(Channel channel, Channel[] channels) { for (Channel channel1 : channels) { if (channel.equals(channel1)) { return true; } } return false; } public Channel channel(TransportRequestOptions.Type type) { if (type == TransportRequestOptions.Type.REG) { return reg[MathUtils.mod(regCounter.incrementAndGet(), reg.length)]; } else if (type == TransportRequestOptions.Type.STATE) { return state[MathUtils.mod(stateCounter.incrementAndGet(), state.length)]; } else if (type == TransportRequestOptions.Type.PING) { return ping[MathUtils.mod(pingCounter.incrementAndGet(), ping.length)]; } else if (type == TransportRequestOptions.Type.BULK) { return bulk[MathUtils.mod(bulkCounter.incrementAndGet(), bulk.length)]; } else if (type == TransportRequestOptions.Type.RECOVERY) { return recovery[MathUtils.mod(recoveryCounter.incrementAndGet(), recovery.length)]; } else { throw new ElasticsearchIllegalArgumentException("no type channel for [" + type + "]"); } } public synchronized void close() { List<ChannelFuture> futures = new ArrayList<>(); closeChannelsAndWait(recovery, futures); closeChannelsAndWait(bulk, futures); closeChannelsAndWait(reg, futures); closeChannelsAndWait(state, futures); closeChannelsAndWait(ping, futures); for (ChannelFuture future : futures) { future.awaitUninterruptibly(); } } private void closeChannelsAndWait(Channel[] channels, List<ChannelFuture> futures) { for (Channel channel : channels) { try { if (channel != null && channel.isOpen()) { futures.add(channel.close()); } } catch (Exception e) { //ignore } } } } }
src/main/java/org/elasticsearch/transport/netty/NettyTransport.java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.transport.netty; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchIllegalArgumentException; import org.elasticsearch.ElasticsearchIllegalStateException; import org.elasticsearch.Version; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.ReleasableBytesReference; import org.elasticsearch.common.component.AbstractLifecycleComponent; import org.elasticsearch.common.compress.CompressorFactory; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.io.stream.HandlesStreamOutput; import org.elasticsearch.common.io.stream.ReleasableBytesStreamOutput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.lease.Releasables; import org.elasticsearch.common.math.MathUtils; import org.elasticsearch.common.netty.NettyStaticSetup; import org.elasticsearch.common.netty.OpenChannelsHandler; import org.elasticsearch.common.netty.ReleaseChannelFutureListener; import org.elasticsearch.common.network.NetworkService; import org.elasticsearch.common.network.NetworkUtils; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.BoundTransportAddress; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.transport.PortsRange; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.BigArrays; import org.elasticsearch.common.util.concurrent.EsExecutors; import org.elasticsearch.common.util.concurrent.KeyedLock; import org.elasticsearch.monitor.jvm.JvmInfo; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.*; import org.elasticsearch.transport.support.TransportStatus; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.CompositeChannelBuffer; import org.jboss.netty.channel.*; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioWorkerPool; import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; import org.jboss.netty.util.HashedWheelTimer; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.channels.CancelledKeyException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import static org.elasticsearch.common.network.NetworkService.TcpSettings.*; import static org.elasticsearch.common.transport.NetworkExceptionHelper.isCloseConnectionException; import static org.elasticsearch.common.transport.NetworkExceptionHelper.isConnectException; import static org.elasticsearch.common.util.concurrent.ConcurrentCollections.newConcurrentMap; import static org.elasticsearch.common.util.concurrent.EsExecutors.daemonThreadFactory; /** * There are 4 types of connections per node, low/med/high/ping. Low if for batch oriented APIs (like recovery or * batch) with high payload that will cause regular request. (like search or single index) to take * longer. Med is for the typical search / single doc index. And High for things like cluster state. Ping is reserved for * sending out ping requests to other nodes. */ public class NettyTransport extends AbstractLifecycleComponent<Transport> implements Transport { static { NettyStaticSetup.setup(); } private final NetworkService networkService; final Version version; final int workerCount; final int bossCount; final boolean blockingServer; final boolean blockingClient; final String port; final String bindHost; final String publishHost; final int publishPort; final boolean compress; final TimeValue connectTimeout; final Boolean tcpNoDelay; final Boolean tcpKeepAlive; final Boolean reuseAddress; final ByteSizeValue tcpSendBufferSize; final ByteSizeValue tcpReceiveBufferSize; final ReceiveBufferSizePredictorFactory receiveBufferSizePredictorFactory; final int connectionsPerNodeRecovery; final int connectionsPerNodeBulk; final int connectionsPerNodeReg; final int connectionsPerNodeState; final int connectionsPerNodePing; final ByteSizeValue maxCumulationBufferCapacity; final int maxCompositeBufferComponents; final BigArrays bigArrays; private final ThreadPool threadPool; private volatile OpenChannelsHandler serverOpenChannels; private volatile ClientBootstrap clientBootstrap; private volatile ServerBootstrap serverBootstrap; // node id to actual channel final ConcurrentMap<DiscoveryNode, NodeChannels> connectedNodes = newConcurrentMap(); private volatile Channel serverChannel; private volatile TransportServiceAdapter transportServiceAdapter; private volatile BoundTransportAddress boundAddress; private final KeyedLock<String> connectionLock = new KeyedLock<>(); // this lock is here to make sure we close this transport and disconnect all the client nodes // connections while no connect operations is going on... (this might help with 100% CPU when stopping the transport?) private final ReadWriteLock globalLock = new ReentrantReadWriteLock(); @Inject public NettyTransport(Settings settings, ThreadPool threadPool, NetworkService networkService, BigArrays bigArrays, Version version) { super(settings); this.threadPool = threadPool; this.networkService = networkService; this.bigArrays = bigArrays; this.version = version; if (settings.getAsBoolean("netty.epollBugWorkaround", false)) { System.setProperty("org.jboss.netty.epollBugWorkaround", "true"); } this.workerCount = componentSettings.getAsInt("worker_count", EsExecutors.boundedNumberOfProcessors(settings) * 2); this.bossCount = componentSettings.getAsInt("boss_count", 1); this.blockingServer = settings.getAsBoolean("transport.tcp.blocking_server", settings.getAsBoolean(TCP_BLOCKING_SERVER, settings.getAsBoolean(TCP_BLOCKING, false))); this.blockingClient = settings.getAsBoolean("transport.tcp.blocking_client", settings.getAsBoolean(TCP_BLOCKING_CLIENT, settings.getAsBoolean(TCP_BLOCKING, false))); this.port = componentSettings.get("port", settings.get("transport.tcp.port", "9300-9400")); this.bindHost = componentSettings.get("bind_host", settings.get("transport.bind_host", settings.get("transport.host"))); this.publishHost = componentSettings.get("publish_host", settings.get("transport.publish_host", settings.get("transport.host"))); this.publishPort = componentSettings.getAsInt("publish_port", settings.getAsInt("transport.publish_port", 0)); this.compress = settings.getAsBoolean(TransportSettings.TRANSPORT_TCP_COMPRESS, false); this.connectTimeout = componentSettings.getAsTime("connect_timeout", settings.getAsTime("transport.tcp.connect_timeout", settings.getAsTime(TCP_CONNECT_TIMEOUT, TCP_DEFAULT_CONNECT_TIMEOUT))); this.tcpNoDelay = componentSettings.getAsBoolean("tcp_no_delay", settings.getAsBoolean(TCP_NO_DELAY, true)); this.tcpKeepAlive = componentSettings.getAsBoolean("tcp_keep_alive", settings.getAsBoolean(TCP_KEEP_ALIVE, true)); this.reuseAddress = componentSettings.getAsBoolean("reuse_address", settings.getAsBoolean(TCP_REUSE_ADDRESS, NetworkUtils.defaultReuseAddress())); this.tcpSendBufferSize = componentSettings.getAsBytesSize("tcp_send_buffer_size", settings.getAsBytesSize(TCP_SEND_BUFFER_SIZE, TCP_DEFAULT_SEND_BUFFER_SIZE)); this.tcpReceiveBufferSize = componentSettings.getAsBytesSize("tcp_receive_buffer_size", settings.getAsBytesSize(TCP_RECEIVE_BUFFER_SIZE, TCP_DEFAULT_RECEIVE_BUFFER_SIZE)); this.connectionsPerNodeRecovery = componentSettings.getAsInt("connections_per_node.recovery", settings.getAsInt("transport.connections_per_node.recovery", 2)); this.connectionsPerNodeBulk = componentSettings.getAsInt("connections_per_node.bulk", settings.getAsInt("transport.connections_per_node.bulk", 3)); this.connectionsPerNodeReg = componentSettings.getAsInt("connections_per_node.reg", settings.getAsInt("transport.connections_per_node.reg", 6)); this.connectionsPerNodeState = componentSettings.getAsInt("connections_per_node.high", settings.getAsInt("transport.connections_per_node.state", 1)); this.connectionsPerNodePing = componentSettings.getAsInt("connections_per_node.ping", settings.getAsInt("transport.connections_per_node.ping", 1)); // we want to have at least 1 for reg/state/ping if (this.connectionsPerNodeReg == 0) { throw new ElasticsearchIllegalArgumentException("can't set [connection_per_node.reg] to 0"); } if (this.connectionsPerNodePing == 0) { throw new ElasticsearchIllegalArgumentException("can't set [connection_per_node.ping] to 0"); } if (this.connectionsPerNodeState == 0) { throw new ElasticsearchIllegalArgumentException("can't set [connection_per_node.state] to 0"); } this.maxCumulationBufferCapacity = componentSettings.getAsBytesSize("max_cumulation_buffer_capacity", null); this.maxCompositeBufferComponents = componentSettings.getAsInt("max_composite_buffer_components", -1); long defaultReceiverPredictor = 512 * 1024; if (JvmInfo.jvmInfo().mem().directMemoryMax().bytes() > 0) { // we can guess a better default... long l = (long) ((0.3 * JvmInfo.jvmInfo().mem().directMemoryMax().bytes()) / workerCount); defaultReceiverPredictor = Math.min(defaultReceiverPredictor, Math.max(l, 64 * 1024)); } // See AdaptiveReceiveBufferSizePredictor#DEFAULT_XXX for default values in netty..., we can use higher ones for us, even fixed one ByteSizeValue receivePredictorMin = componentSettings.getAsBytesSize("receive_predictor_min", componentSettings.getAsBytesSize("receive_predictor_size", new ByteSizeValue(defaultReceiverPredictor))); ByteSizeValue receivePredictorMax = componentSettings.getAsBytesSize("receive_predictor_max", componentSettings.getAsBytesSize("receive_predictor_size", new ByteSizeValue(defaultReceiverPredictor))); if (receivePredictorMax.bytes() == receivePredictorMin.bytes()) { receiveBufferSizePredictorFactory = new FixedReceiveBufferSizePredictorFactory((int) receivePredictorMax.bytes()); } else { receiveBufferSizePredictorFactory = new AdaptiveReceiveBufferSizePredictorFactory((int) receivePredictorMin.bytes(), (int) receivePredictorMin.bytes(), (int) receivePredictorMax.bytes()); } logger.debug("using worker_count[{}], port[{}], bind_host[{}], publish_host[{}], compress[{}], connect_timeout[{}], connections_per_node[{}/{}/{}/{}/{}], receive_predictor[{}->{}]", workerCount, port, bindHost, publishHost, compress, connectTimeout, connectionsPerNodeRecovery, connectionsPerNodeBulk, connectionsPerNodeReg, connectionsPerNodeState, connectionsPerNodePing, receivePredictorMin, receivePredictorMax); } public Settings settings() { return this.settings; } @Override public void transportServiceAdapter(TransportServiceAdapter service) { this.transportServiceAdapter = service; } TransportServiceAdapter transportServiceAdapter() { return transportServiceAdapter; } ThreadPool threadPool() { return threadPool; } @Override protected void doStart() throws ElasticsearchException { if (blockingClient) { clientBootstrap = new ClientBootstrap(new OioClientSocketChannelFactory(Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_client_worker")))); } else { clientBootstrap = new ClientBootstrap(new NioClientSocketChannelFactory( Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_client_boss")), bossCount, new NioWorkerPool(Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_client_worker")), workerCount), new HashedWheelTimer(daemonThreadFactory(settings, "transport_client_timer")))); } ChannelPipelineFactory clientPipelineFactory = new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); SizeHeaderFrameDecoder sizeHeader = new SizeHeaderFrameDecoder(); if (maxCumulationBufferCapacity != null) { if (maxCumulationBufferCapacity.bytes() > Integer.MAX_VALUE) { sizeHeader.setMaxCumulationBufferCapacity(Integer.MAX_VALUE); } else { sizeHeader.setMaxCumulationBufferCapacity((int) maxCumulationBufferCapacity.bytes()); } } if (maxCompositeBufferComponents != -1) { sizeHeader.setMaxCumulationBufferComponents(maxCompositeBufferComponents); } pipeline.addLast("size", sizeHeader); pipeline.addLast("dispatcher", new MessageChannelHandler(NettyTransport.this, logger)); return pipeline; } }; clientBootstrap.setPipelineFactory(clientPipelineFactory); clientBootstrap.setOption("connectTimeoutMillis", connectTimeout.millis()); if (tcpNoDelay != null) { clientBootstrap.setOption("tcpNoDelay", tcpNoDelay); } if (tcpKeepAlive != null) { clientBootstrap.setOption("keepAlive", tcpKeepAlive); } if (tcpSendBufferSize != null && tcpSendBufferSize.bytes() > 0) { clientBootstrap.setOption("sendBufferSize", tcpSendBufferSize.bytes()); } if (tcpReceiveBufferSize != null && tcpReceiveBufferSize.bytes() > 0) { clientBootstrap.setOption("receiveBufferSize", tcpReceiveBufferSize.bytes()); } clientBootstrap.setOption("receiveBufferSizePredictorFactory", receiveBufferSizePredictorFactory); if (reuseAddress != null) { clientBootstrap.setOption("reuseAddress", reuseAddress); } if (!settings.getAsBoolean("network.server", true)) { return; } serverOpenChannels = new OpenChannelsHandler(logger); if (blockingServer) { serverBootstrap = new ServerBootstrap(new OioServerSocketChannelFactory( Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_server_boss")), Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_server_worker")) )); } else { serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory( Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_server_boss")), Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_server_worker")), workerCount)); } ChannelPipelineFactory serverPipelineFactory = new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("openChannels", serverOpenChannels); SizeHeaderFrameDecoder sizeHeader = new SizeHeaderFrameDecoder(); if (maxCumulationBufferCapacity != null) { if (maxCumulationBufferCapacity.bytes() > Integer.MAX_VALUE) { sizeHeader.setMaxCumulationBufferCapacity(Integer.MAX_VALUE); } else { sizeHeader.setMaxCumulationBufferCapacity((int) maxCumulationBufferCapacity.bytes()); } } if (maxCompositeBufferComponents != -1) { sizeHeader.setMaxCumulationBufferComponents(maxCompositeBufferComponents); } pipeline.addLast("size", sizeHeader); pipeline.addLast("dispatcher", new MessageChannelHandler(NettyTransport.this, logger)); return pipeline; } }; serverBootstrap.setPipelineFactory(serverPipelineFactory); if (tcpNoDelay != null) { serverBootstrap.setOption("child.tcpNoDelay", tcpNoDelay); } if (tcpKeepAlive != null) { serverBootstrap.setOption("child.keepAlive", tcpKeepAlive); } if (tcpSendBufferSize != null && tcpSendBufferSize.bytes() > 0) { serverBootstrap.setOption("child.sendBufferSize", tcpSendBufferSize.bytes()); } if (tcpReceiveBufferSize != null && tcpReceiveBufferSize.bytes() > 0) { serverBootstrap.setOption("child.receiveBufferSize", tcpReceiveBufferSize.bytes()); } serverBootstrap.setOption("receiveBufferSizePredictorFactory", receiveBufferSizePredictorFactory); serverBootstrap.setOption("child.receiveBufferSizePredictorFactory", receiveBufferSizePredictorFactory); if (reuseAddress != null) { serverBootstrap.setOption("reuseAddress", reuseAddress); serverBootstrap.setOption("child.reuseAddress", reuseAddress); } // Bind and start to accept incoming connections. InetAddress hostAddressX; try { hostAddressX = networkService.resolveBindHostAddress(bindHost); } catch (IOException e) { throw new BindTransportException("Failed to resolve host [" + bindHost + "]", e); } final InetAddress hostAddress = hostAddressX; PortsRange portsRange = new PortsRange(port); final AtomicReference<Exception> lastException = new AtomicReference<>(); boolean success = portsRange.iterate(new PortsRange.PortCallback() { @Override public boolean onPortNumber(int portNumber) { try { serverChannel = serverBootstrap.bind(new InetSocketAddress(hostAddress, portNumber)); } catch (Exception e) { lastException.set(e); return false; } return true; } }); if (!success) { throw new BindTransportException("Failed to bind to [" + port + "]", lastException.get()); } logger.debug("Bound to address [{}]", serverChannel.getLocalAddress()); InetSocketAddress boundAddress = (InetSocketAddress) serverChannel.getLocalAddress(); InetSocketAddress publishAddress; int publishPort = this.publishPort; if (0 == publishPort) { publishPort = boundAddress.getPort(); } try { publishAddress = new InetSocketAddress(networkService.resolvePublishHostAddress(publishHost), publishPort); } catch (Exception e) { throw new BindTransportException("Failed to resolve publish address", e); } this.boundAddress = new BoundTransportAddress(new InetSocketTransportAddress(boundAddress), new InetSocketTransportAddress(publishAddress)); } @Override protected void doStop() throws ElasticsearchException { final CountDownLatch latch = new CountDownLatch(1); // make sure we run it on another thread than a possible IO handler thread threadPool.generic().execute(new Runnable() { @Override public void run() { globalLock.writeLock().lock(); try { for (Iterator<NodeChannels> it = connectedNodes.values().iterator(); it.hasNext(); ) { NodeChannels nodeChannels = it.next(); it.remove(); nodeChannels.close(); } if (serverChannel != null) { try { serverChannel.close().awaitUninterruptibly(); } finally { serverChannel = null; } } if (serverOpenChannels != null) { serverOpenChannels.close(); serverOpenChannels = null; } if (serverBootstrap != null) { serverBootstrap.releaseExternalResources(); serverBootstrap = null; } for (Iterator<NodeChannels> it = connectedNodes.values().iterator(); it.hasNext(); ) { NodeChannels nodeChannels = it.next(); it.remove(); nodeChannels.close(); } if (clientBootstrap != null) { clientBootstrap.releaseExternalResources(); clientBootstrap = null; } } finally { globalLock.writeLock().unlock(); latch.countDown(); } } }); try { latch.await(30, TimeUnit.SECONDS); } catch (InterruptedException e) { // ignore } } @Override protected void doClose() throws ElasticsearchException { } @Override public TransportAddress[] addressesFromString(String address) throws Exception { int index = address.indexOf('['); if (index != -1) { String host = address.substring(0, index); Set<String> ports = Strings.commaDelimitedListToSet(address.substring(index + 1, address.indexOf(']'))); List<TransportAddress> addresses = Lists.newArrayList(); for (String port : ports) { int[] iPorts = new PortsRange(port).ports(); for (int iPort : iPorts) { addresses.add(new InetSocketTransportAddress(host, iPort)); } } return addresses.toArray(new TransportAddress[addresses.size()]); } else { index = address.lastIndexOf(':'); if (index == -1) { List<TransportAddress> addresses = Lists.newArrayList(); int[] iPorts = new PortsRange(this.port).ports(); for (int iPort : iPorts) { addresses.add(new InetSocketTransportAddress(address, iPort)); } return addresses.toArray(new TransportAddress[addresses.size()]); } else { String host = address.substring(0, index); int port = Integer.parseInt(address.substring(index + 1)); return new TransportAddress[]{new InetSocketTransportAddress(host, port)}; } } } @Override public boolean addressSupported(Class<? extends TransportAddress> address) { return InetSocketTransportAddress.class.equals(address); } @Override public BoundTransportAddress boundAddress() { return this.boundAddress; } void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { if (!lifecycle.started()) { // ignore } if (isCloseConnectionException(e.getCause())) { logger.trace("close connection exception caught on transport layer [{}], disconnecting from relevant node", e.getCause(), ctx.getChannel()); // close the channel, which will cause a node to be disconnected if relevant ctx.getChannel().close(); disconnectFromNodeChannel(ctx.getChannel(), e.getCause()); } else if (isConnectException(e.getCause())) { logger.trace("connect exception caught on transport layer [{}]", e.getCause(), ctx.getChannel()); // close the channel as safe measure, which will cause a node to be disconnected if relevant ctx.getChannel().close(); disconnectFromNodeChannel(ctx.getChannel(), e.getCause()); } else if (e.getCause() instanceof CancelledKeyException) { logger.trace("cancelled key exception caught on transport layer [{}], disconnecting from relevant node", e.getCause(), ctx.getChannel()); // close the channel as safe measure, which will cause a node to be disconnected if relevant ctx.getChannel().close(); disconnectFromNodeChannel(ctx.getChannel(), e.getCause()); } else { logger.warn("exception caught on transport layer [{}], closing connection", e.getCause(), ctx.getChannel()); // close the channel, which will cause a node to be disconnected if relevant ctx.getChannel().close(); disconnectFromNodeChannel(ctx.getChannel(), e.getCause()); } } TransportAddress wrapAddress(SocketAddress socketAddress) { return new InetSocketTransportAddress((InetSocketAddress) socketAddress); } @Override public long serverOpen() { OpenChannelsHandler channels = serverOpenChannels; return channels == null ? 0 : channels.numberOfOpenChannels(); } @Override public void sendRequest(final DiscoveryNode node, final long requestId, final String action, final TransportRequest request, TransportRequestOptions options) throws IOException, TransportException { Channel targetChannel = nodeChannel(node, options); if (compress) { options.withCompress(true); } byte status = 0; status = TransportStatus.setRequest(status); ReleasableBytesStreamOutput bStream = new ReleasableBytesStreamOutput(bigArrays); boolean addedReleaseListener = false; try { bStream.skip(NettyHeader.HEADER_SIZE); StreamOutput stream = bStream; // only compress if asked, and, the request is not bytes, since then only // the header part is compressed, and the "body" can't be extracted as compressed if (options.compress() && (!(request instanceof BytesTransportRequest))) { status = TransportStatus.setCompress(status); stream = CompressorFactory.defaultCompressor().streamOutput(stream); } stream = new HandlesStreamOutput(stream); // we pick the smallest of the 2, to support both backward and forward compatibility // note, this is the only place we need to do this, since from here on, we use the serialized version // as the version to use also when the node receiving this request will send the response with Version version = Version.smallest(this.version, node.version()); stream.setVersion(version); stream.writeString(action); ReleasableBytesReference bytes; ChannelBuffer buffer; // it might be nice to somehow generalize this optimization, maybe a smart "paged" bytes output // that create paged channel buffers, but its tricky to know when to do it (where this option is // more explicit). if (request instanceof BytesTransportRequest) { BytesTransportRequest bRequest = (BytesTransportRequest) request; assert node.version().equals(bRequest.version()); bRequest.writeThin(stream); stream.close(); bytes = bStream.bytes(); ChannelBuffer headerBuffer = bytes.toChannelBuffer(); ChannelBuffer contentBuffer = bRequest.bytes().toChannelBuffer(); // false on gathering, cause gathering causes the NIO layer to combine the buffers into a single direct buffer.... buffer = new CompositeChannelBuffer(headerBuffer.order(), ImmutableList.<ChannelBuffer>of(headerBuffer, contentBuffer), false); } else { request.writeTo(stream); stream.close(); bytes = bStream.bytes(); buffer = bytes.toChannelBuffer(); } NettyHeader.writeHeader(buffer, requestId, status, version); ChannelFuture future = targetChannel.write(buffer); ReleaseChannelFutureListener listener = new ReleaseChannelFutureListener(bytes); future.addListener(listener); addedReleaseListener = true; } finally { if (!addedReleaseListener) { Releasables.close(bStream.bytes()); } } } @Override public boolean nodeConnected(DiscoveryNode node) { return connectedNodes.containsKey(node); } @Override public void connectToNodeLight(DiscoveryNode node) throws ConnectTransportException { connectToNode(node, true); } @Override public void connectToNode(DiscoveryNode node) { connectToNode(node, false); } public void connectToNode(DiscoveryNode node, boolean light) { if (!lifecycle.started()) { throw new ElasticsearchIllegalStateException("can't add nodes to a stopped transport"); } if (node == null) { throw new ConnectTransportException(null, "can't connect to a null node"); } globalLock.readLock().lock(); try { if (!lifecycle.started()) { throw new ElasticsearchIllegalStateException("can't add nodes to a stopped transport"); } NodeChannels nodeChannels = connectedNodes.get(node); if (nodeChannels != null) { return; } connectionLock.acquire(node.id()); try { if (!lifecycle.started()) { throw new ElasticsearchIllegalStateException("can't add nodes to a stopped transport"); } try { if (light) { nodeChannels = connectToChannelsLight(node); } else { nodeChannels = new NodeChannels(new Channel[connectionsPerNodeRecovery], new Channel[connectionsPerNodeBulk], new Channel[connectionsPerNodeReg], new Channel[connectionsPerNodeState], new Channel[connectionsPerNodePing]); try { connectToChannels(nodeChannels, node); } catch (Exception e) { nodeChannels.close(); throw e; } } NodeChannels existing = connectedNodes.putIfAbsent(node, nodeChannels); if (existing != null) { // we are already connected to a node, close this ones nodeChannels.close(); } else { if (logger.isDebugEnabled()) { logger.debug("connected to node [{}]", node); } transportServiceAdapter.raiseNodeConnected(node); } } catch (ConnectTransportException e) { throw e; } catch (Exception e) { throw new ConnectTransportException(node, "General node connection failure", e); } } finally { connectionLock.release(node.id()); } } finally { globalLock.readLock().unlock(); } } private NodeChannels connectToChannelsLight(DiscoveryNode node) { InetSocketAddress address = ((InetSocketTransportAddress) node.address()).address(); ChannelFuture connect = clientBootstrap.connect(address); connect.awaitUninterruptibly((long) (connectTimeout.millis() * 1.5)); if (!connect.isSuccess()) { throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connect.getCause()); } Channel[] channels = new Channel[1]; channels[0] = connect.getChannel(); channels[0].getCloseFuture().addListener(new ChannelCloseListener(node)); return new NodeChannels(channels, channels, channels, channels, channels); } private void connectToChannels(NodeChannels nodeChannels, DiscoveryNode node) { ChannelFuture[] connectRecovery = new ChannelFuture[nodeChannels.recovery.length]; ChannelFuture[] connectBulk = new ChannelFuture[nodeChannels.bulk.length]; ChannelFuture[] connectReg = new ChannelFuture[nodeChannels.reg.length]; ChannelFuture[] connectState = new ChannelFuture[nodeChannels.state.length]; ChannelFuture[] connectPing = new ChannelFuture[nodeChannels.ping.length]; InetSocketAddress address = ((InetSocketTransportAddress) node.address()).address(); for (int i = 0; i < connectRecovery.length; i++) { connectRecovery[i] = clientBootstrap.connect(address); } for (int i = 0; i < connectBulk.length; i++) { connectBulk[i] = clientBootstrap.connect(address); } for (int i = 0; i < connectReg.length; i++) { connectReg[i] = clientBootstrap.connect(address); } for (int i = 0; i < connectState.length; i++) { connectState[i] = clientBootstrap.connect(address); } for (int i = 0; i < connectPing.length; i++) { connectPing[i] = clientBootstrap.connect(address); } try { for (int i = 0; i < connectRecovery.length; i++) { connectRecovery[i].awaitUninterruptibly((long) (connectTimeout.millis() * 1.5)); if (!connectRecovery[i].isSuccess()) { throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connectRecovery[i].getCause()); } nodeChannels.recovery[i] = connectRecovery[i].getChannel(); nodeChannels.recovery[i].getCloseFuture().addListener(new ChannelCloseListener(node)); } for (int i = 0; i < connectBulk.length; i++) { connectBulk[i].awaitUninterruptibly((long) (connectTimeout.millis() * 1.5)); if (!connectBulk[i].isSuccess()) { throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connectBulk[i].getCause()); } nodeChannels.bulk[i] = connectBulk[i].getChannel(); nodeChannels.bulk[i].getCloseFuture().addListener(new ChannelCloseListener(node)); } for (int i = 0; i < connectReg.length; i++) { connectReg[i].awaitUninterruptibly((long) (connectTimeout.millis() * 1.5)); if (!connectReg[i].isSuccess()) { throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connectReg[i].getCause()); } nodeChannels.reg[i] = connectReg[i].getChannel(); nodeChannels.reg[i].getCloseFuture().addListener(new ChannelCloseListener(node)); } for (int i = 0; i < connectState.length; i++) { connectState[i].awaitUninterruptibly((long) (connectTimeout.millis() * 1.5)); if (!connectState[i].isSuccess()) { throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connectState[i].getCause()); } nodeChannels.state[i] = connectState[i].getChannel(); nodeChannels.state[i].getCloseFuture().addListener(new ChannelCloseListener(node)); } for (int i = 0; i < connectPing.length; i++) { connectPing[i].awaitUninterruptibly((long) (connectTimeout.millis() * 1.5)); if (!connectPing[i].isSuccess()) { throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connectPing[i].getCause()); } nodeChannels.ping[i] = connectPing[i].getChannel(); nodeChannels.ping[i].getCloseFuture().addListener(new ChannelCloseListener(node)); } if (nodeChannels.recovery.length == 0) { if (nodeChannels.bulk.length > 0) { nodeChannels.recovery = nodeChannels.bulk; } else { nodeChannels.recovery = nodeChannels.reg; } } if (nodeChannels.bulk.length == 0) { nodeChannels.bulk = nodeChannels.reg; } } catch (RuntimeException e) { // clean the futures for (ChannelFuture future : ImmutableList.<ChannelFuture>builder().add(connectRecovery).add(connectBulk).add(connectReg).add(connectState).add(connectPing).build()) { future.cancel(); if (future.getChannel() != null && future.getChannel().isOpen()) { try { future.getChannel().close(); } catch (Exception e1) { // ignore } } } throw e; } } @Override public void disconnectFromNode(DiscoveryNode node) { NodeChannels nodeChannels = connectedNodes.remove(node); if (nodeChannels != null) { connectionLock.acquire(node.id()); try { try { nodeChannels.close(); } finally { logger.debug("disconnected from [{}]", node); transportServiceAdapter.raiseNodeDisconnected(node); } } finally { connectionLock.release(node.id()); } } } /** * Disconnects from a node, only if the relevant channel is found to be part of the node channels. */ private void disconnectFromNode(DiscoveryNode node, Channel channel, String reason) { NodeChannels nodeChannels = connectedNodes.get(node); if (nodeChannels != null && nodeChannels.hasChannel(channel)) { connectionLock.acquire(node.id()); if (!nodeChannels.hasChannel(channel)) { //might have been removed in the meanwhile, safety check assert !connectedNodes.containsKey(node); } else { try { connectedNodes.remove(node); try { nodeChannels.close(); } finally { logger.debug("disconnected from [{}], {}", node, reason); transportServiceAdapter.raiseNodeDisconnected(node); } } finally { connectionLock.release(node.id()); } } } } /** * Disconnects from a node if a channel is found as part of that nodes channels. */ private void disconnectFromNodeChannel(Channel channel, Throwable failure) { for (DiscoveryNode node : connectedNodes.keySet()) { NodeChannels nodeChannels = connectedNodes.get(node); if (nodeChannels != null && nodeChannels.hasChannel(channel)) { connectionLock.acquire(node.id()); if (!nodeChannels.hasChannel(channel)) { //might have been removed in the meanwhile, safety check assert !connectedNodes.containsKey(node); } else { try { connectedNodes.remove(node); try { nodeChannels.close(); } finally { logger.debug("disconnected from [{}] on channel failure", failure, node); transportServiceAdapter.raiseNodeDisconnected(node); } } finally { connectionLock.release(node.id()); } } } } } private Channel nodeChannel(DiscoveryNode node, TransportRequestOptions options) throws ConnectTransportException { NodeChannels nodeChannels = connectedNodes.get(node); if (nodeChannels == null) { throw new NodeNotConnectedException(node, "Node not connected"); } return nodeChannels.channel(options.type()); } private class ChannelCloseListener implements ChannelFutureListener { private final DiscoveryNode node; private ChannelCloseListener(DiscoveryNode node) { this.node = node; } @Override public void operationComplete(ChannelFuture future) throws Exception { disconnectFromNode(node, future.getChannel(), "channel closed event"); } } public static class NodeChannels { private Channel[] recovery; private final AtomicInteger recoveryCounter = new AtomicInteger(); private Channel[] bulk; private final AtomicInteger bulkCounter = new AtomicInteger(); private Channel[] reg; private final AtomicInteger regCounter = new AtomicInteger(); private Channel[] state; private final AtomicInteger stateCounter = new AtomicInteger(); private Channel[] ping; private final AtomicInteger pingCounter = new AtomicInteger(); public NodeChannels(Channel[] recovery, Channel[] bulk, Channel[] reg, Channel[] state, Channel[] ping) { this.recovery = recovery; this.bulk = bulk; this.reg = reg; this.state = state; this.ping = ping; } public boolean hasChannel(Channel channel) { return hasChannel(channel, recovery) || hasChannel(channel, bulk) || hasChannel(channel, reg) || hasChannel(channel, state) || hasChannel(channel, ping); } private boolean hasChannel(Channel channel, Channel[] channels) { for (Channel channel1 : channels) { if (channel.equals(channel1)) { return true; } } return false; } public Channel channel(TransportRequestOptions.Type type) { if (type == TransportRequestOptions.Type.REG) { return reg[MathUtils.mod(regCounter.incrementAndGet(), reg.length)]; } else if (type == TransportRequestOptions.Type.STATE) { return state[MathUtils.mod(stateCounter.incrementAndGet(), state.length)]; } else if (type == TransportRequestOptions.Type.PING) { return ping[MathUtils.mod(pingCounter.incrementAndGet(), ping.length)]; } else if (type == TransportRequestOptions.Type.BULK) { return bulk[MathUtils.mod(bulkCounter.incrementAndGet(), bulk.length)]; } else if (type == TransportRequestOptions.Type.RECOVERY) { return recovery[MathUtils.mod(recoveryCounter.incrementAndGet(), recovery.length)]; } else { throw new ElasticsearchIllegalArgumentException("no type channel for [" + type + "]"); } } public synchronized void close() { List<ChannelFuture> futures = new ArrayList<>(); closeChannelsAndWait(recovery, futures); closeChannelsAndWait(bulk, futures); closeChannelsAndWait(reg, futures); closeChannelsAndWait(state, futures); closeChannelsAndWait(ping, futures); for (ChannelFuture future : futures) { future.awaitUninterruptibly(); } } private void closeChannelsAndWait(Channel[] channels, List<ChannelFuture> futures) { for (Channel channel : channels) { try { if (channel != null && channel.isOpen()) { futures.add(channel.close()); } } catch (Exception e) { //ignore } } } } }
Fix NPE when initializing an accepted socket in NettyTransport. NettyTransport's ChannelPipelineFactory uses the instance variable serverOpenChannels in order to create sockets. However, this instance variable is set to null when stoping the netty transport, so if the transport tries to stop and to initialize a socket at the same time you might hit the following NullPointerException: [2014-05-13 07:33:47,616][WARN ][netty.channel.socket.nio.AbstractNioSelector] Failed to initialize an accepted socket. java.lang.NullPointerException: handler at org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.<init>(DefaultChannelPipeline.java:725) at org.jboss.netty.channel.DefaultChannelPipeline.init(DefaultChannelPipeline.java:667) at org.jboss.netty.channel.DefaultChannelPipeline.addLast(DefaultChannelPipeline.java:96) at org.elasticsearch.transport.netty.NettyTransport$2.getPipeline(NettyTransport.java:327) at org.jboss.netty.channel.socket.nio.NioServerBoss.registerAcceptedChannel(NioServerBoss.java:134) at org.jboss.netty.channel.socket.nio.NioServerBoss.process(NioServerBoss.java:104) at org.jboss.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:318) at org.jboss.netty.channel.socket.nio.NioServerBoss.run(NioServerBoss.java:42) at org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108) at org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) This fix ensures that the ChannelPipelineFactory always uses the channels that have been used upon start, even if a stop request is issued concurrently. Close #6144
src/main/java/org/elasticsearch/transport/netty/NettyTransport.java
Fix NPE when initializing an accepted socket in NettyTransport.
<ide><path>rc/main/java/org/elasticsearch/transport/netty/NettyTransport.java <ide> return; <ide> } <ide> <del> serverOpenChannels = new OpenChannelsHandler(logger); <add> final OpenChannelsHandler openChannels = new OpenChannelsHandler(logger); <add> this.serverOpenChannels = openChannels; <ide> if (blockingServer) { <ide> serverBootstrap = new ServerBootstrap(new OioServerSocketChannelFactory( <ide> Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_server_boss")), <ide> @Override <ide> public ChannelPipeline getPipeline() throws Exception { <ide> ChannelPipeline pipeline = Channels.pipeline(); <del> pipeline.addLast("openChannels", serverOpenChannels); <add> pipeline.addLast("openChannels", openChannels); <ide> SizeHeaderFrameDecoder sizeHeader = new SizeHeaderFrameDecoder(); <ide> if (maxCumulationBufferCapacity != null) { <ide> if (maxCumulationBufferCapacity.bytes() > Integer.MAX_VALUE) {
Java
bsd-3-clause
9ad9527a34872f263bc7569cfcdd4fa461de0983
0
JayKingsFrc/abcd,JayKingsFrc/abcd
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.SimpleRobot; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the SimpleRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class RobotTemplate extends SimpleRobot { /** * This function is called once each time the robot enters autonomous mode. */ public void autonomous() { //.....some more code // no not what to do with this so I am commeting meaningless comments for comment sake ersfesfasf } /** * This function is called once each time the robot enters operator control. */ public void operatorControl() { } /** * This function is called once each time the robot enters test mode. */ public void test() { } }
src/edu/wpi/first/wpilibj/templates/RobotTemplate.java
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.SimpleRobot; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the SimpleRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class RobotTemplate extends SimpleRobot { /** * This function is called once each time the robot enters autonomous mode. */ public void autonomous() { // no not what to do with this so I am commeting meaningless comments for comment sake ersfesfasf } /** * This function is called once each time the robot enters operator control. */ public void operatorControl() { } /** * This function is called once each time the robot enters test mode. */ public void test() { } }
added more code some more
src/edu/wpi/first/wpilibj/templates/RobotTemplate.java
added more code
<ide><path>rc/edu/wpi/first/wpilibj/templates/RobotTemplate.java <ide> * This function is called once each time the robot enters autonomous mode. <ide> */ <ide> public void autonomous() { <del> <add> //.....some more code <ide> <ide> // no not what to do with this so I am commeting meaningless comments for comment sake ersfesfasf <ide> }
Java
apache-2.0
44fe77f4b5540571afc8f60be0a14a8936b4037a
0
AVnetWS/Hentoid,AVnetWS/Hentoid,AVnetWS/Hentoid
package me.devsaki.hentoid.core; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.webkit.WebView; import androidx.annotation.NonNull; import com.google.firebase.analytics.FirebaseAnalytics; import com.google.firebase.crashlytics.FirebaseCrashlytics; import com.thin.downloadmanager.util.Log; import org.greenrobot.eventbus.EventBus; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.functions.BiConsumer; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import me.devsaki.hentoid.BuildConfig; import me.devsaki.hentoid.R; import me.devsaki.hentoid.database.DatabaseMaintenance; import me.devsaki.hentoid.enums.Site; import me.devsaki.hentoid.events.AppUpdatedEvent; import me.devsaki.hentoid.json.JsonSiteSettings; import me.devsaki.hentoid.notification.download.DownloadNotificationChannel; import me.devsaki.hentoid.notification.update.UpdateNotificationChannel; import me.devsaki.hentoid.services.UpdateCheckService; import me.devsaki.hentoid.util.FileHelper; import me.devsaki.hentoid.util.Helper; import me.devsaki.hentoid.util.JsonHelper; import me.devsaki.hentoid.util.Preferences; import me.devsaki.hentoid.util.network.HttpHelper; import me.devsaki.hentoid.views.NestedScrollWebView; import timber.log.Timber; public class AppStartup { private List<Observable<Float>> launchTasks; private Disposable launchDisposable = null; private static boolean isInitialized = false; public void initApp( @NonNull final Context context, @NonNull Consumer<Float> onMainProgress, @NonNull Consumer<Float> onSecondaryProgress, @NonNull Runnable onComplete ) { if (isInitialized) onComplete.run(); // Wait until launch tasks are completed launchTasks = getPreLaunchTasks(context); launchTasks.addAll(DatabaseMaintenance.getPreLaunchCleanupTasks(context)); // TODO execute post-launch tasks in another runner (background worker ?) launchTasks.addAll(getPostLaunchTasks(context)); launchTasks.addAll(DatabaseMaintenance.getPostLaunchCleanupTasks(context)); // TODO switch from a recursive function to a full RxJava-powered chain + clear the disposable elsewhere (as the chain will finish in a worker) doRunTask(0, onMainProgress, onSecondaryProgress, onComplete); } private void doRunTask( int taskIndex, @NonNull Consumer<Float> onMainProgress, @NonNull Consumer<Float> onSecondaryProgress, @NonNull Runnable onComplete ) { if (launchDisposable != null) launchDisposable.dispose(); try { onMainProgress.accept(taskIndex * 1f / launchTasks.size()); } catch (Exception e) { Timber.w(e); } // Continue executing launch tasks if (taskIndex < launchTasks.size()) { Timber.i("Splash / Launch task %s/%s", taskIndex + 1, launchTasks.size()); launchDisposable = launchTasks.get(taskIndex) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( onSecondaryProgress, Timber::e, () -> doRunTask(taskIndex + 1, onMainProgress, onSecondaryProgress, onComplete) ); } else { if (launchDisposable != null) launchDisposable.dispose(); isInitialized = true; onComplete.run(); } } /** * Application initialization tasks * NB : Heavy operations; must be performed in the background to avoid ANR at startup */ public static List<Observable<Float>> getPreLaunchTasks(@NonNull final Context context) { List<Observable<Float>> result = new ArrayList<>(); result.add(createObservableFrom(context, AppStartup::processAppUpdate)); result.add(createObservableFrom(context, AppStartup::loadSiteProperties)); result.add(createObservableFrom(context, AppStartup::initUtils)); return result; } public static List<Observable<Float>> getPostLaunchTasks(@NonNull final Context context) { List<Observable<Float>> result = new ArrayList<>(); result.add(createObservableFrom(context, AppStartup::searchForUpdates)); result.add(createObservableFrom(context, AppStartup::sendFirebaseStats)); return result; } private static Observable<Float> createObservableFrom(@NonNull final Context context, BiConsumer<Context, ObservableEmitter<Float>> function) { return Observable.create(emitter -> function.accept(context, emitter)); } private static void loadSiteProperties(@NonNull final Context context, ObservableEmitter<Float> emitter) { try (InputStream is = context.getResources().openRawResource(R.raw.sites)) { String siteSettingsStr = FileHelper.readStreamAsString(is); JsonSiteSettings siteSettings = JsonHelper.jsonToObject(siteSettingsStr, JsonSiteSettings.class); for (Map.Entry<String, JsonSiteSettings.JsonSite> entry : siteSettings.sites.entrySet()) { for (Site site : Site.values()) { if (site.name().equalsIgnoreCase(entry.getKey())) { site.updateFrom(entry.getValue()); break; } } } } catch (IOException e) { Timber.e(e); } finally { emitter.onComplete(); } } private static void initUtils(@NonNull final Context context, ObservableEmitter<Float> emitter) { try { Timber.i("Init user agents : start"); HttpHelper.initUserAgents(context); Timber.i("Init user agents : done"); Timber.i("Init notifications : start"); // Init notification channels UpdateNotificationChannel.init(context); DownloadNotificationChannel.init(context); // Clears all previous notifications NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (manager != null) manager.cancelAll(); Timber.i("Init notifications : done"); } finally { emitter.onComplete(); } } private static void processAppUpdate(@NonNull final Context context, ObservableEmitter<Float> emitter) { Timber.i("Process app update : start"); try { if (Preferences.getLastKnownAppVersionCode() < BuildConfig.VERSION_CODE) { Timber.d("Process app update : update detected from %s to %s", Preferences.getLastKnownAppVersionCode(), BuildConfig.VERSION_CODE); // Clear webview cache (needs to execute inside the activity's Looper) Timber.d("Process app update : Clearing webview cache"); Handler h = new Handler(Looper.getMainLooper()); h.post(() -> { WebView webView; try { webView = new NestedScrollWebView(context); } catch (Resources.NotFoundException e) { // Some older devices can crash when instantiating a WebView, due to a Resources$NotFoundException // Creating with the application Context fixes this, but is not generally recommended for view creation webView = new NestedScrollWebView(Helper.getFixedContext(context)); } webView.clearCache(true); }); // Clear app cache Timber.d("Process app update : Clearing app cache"); try { File dir = context.getCacheDir(); FileHelper.removeFile(dir); } catch (Exception e) { Timber.e(e, "Error when clearing app cache upon update"); } EventBus.getDefault().postSticky(new AppUpdatedEvent()); Preferences.setLastKnownAppVersionCode(BuildConfig.VERSION_CODE); } } finally { emitter.onComplete(); } Timber.i("Process app update : done"); } private static void searchForUpdates(@NonNull final Context context, ObservableEmitter<Float> emitter) { Timber.i("Run app update : start"); try { if (Preferences.isAutomaticUpdateEnabled()) { Timber.i("Run app update : auto-check is enabled"); Intent intent = UpdateCheckService.makeIntent(context, false); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(intent); } else { context.startService(intent); } } } finally { emitter.onComplete(); } Timber.i("Run app update : done"); } private static void sendFirebaseStats(@NonNull final Context context, ObservableEmitter<Float> emitter) { Timber.i("Send Firebase stats : start"); try { FirebaseAnalytics.getInstance(context).setUserProperty("color_theme", Integer.toString(Preferences.getColorTheme())); FirebaseAnalytics.getInstance(context).setUserProperty("endless", Boolean.toString(Preferences.getEndlessScroll())); FirebaseCrashlytics.getInstance().setCustomKey("Library display mode", Preferences.getEndlessScroll() ? "endless" : "paged"); } catch (IllegalStateException e) { // Happens during unit tests Log.e("fail@init Crashlytics", e); } finally { emitter.onComplete(); } Timber.i("Send Firebase stats : done"); } }
app/src/main/java/me/devsaki/hentoid/core/AppStartup.java
package me.devsaki.hentoid.core; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.webkit.WebView; import androidx.annotation.NonNull; import com.google.firebase.analytics.FirebaseAnalytics; import com.google.firebase.crashlytics.FirebaseCrashlytics; import com.thin.downloadmanager.util.Log; import org.greenrobot.eventbus.EventBus; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.functions.BiConsumer; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import me.devsaki.hentoid.BuildConfig; import me.devsaki.hentoid.R; import me.devsaki.hentoid.database.DatabaseMaintenance; import me.devsaki.hentoid.enums.Site; import me.devsaki.hentoid.events.AppUpdatedEvent; import me.devsaki.hentoid.json.JsonSiteSettings; import me.devsaki.hentoid.notification.download.DownloadNotificationChannel; import me.devsaki.hentoid.notification.update.UpdateNotificationChannel; import me.devsaki.hentoid.services.UpdateCheckService; import me.devsaki.hentoid.util.FileHelper; import me.devsaki.hentoid.util.Helper; import me.devsaki.hentoid.util.JsonHelper; import me.devsaki.hentoid.util.Preferences; import me.devsaki.hentoid.util.network.HttpHelper; import me.devsaki.hentoid.views.NestedScrollWebView; import timber.log.Timber; public class AppStartup { private List<Observable<Float>> launchTasks; private Disposable launchDisposable = null; public void initApp( @NonNull final Context context, @NonNull Consumer<Float> onMainProgress, @NonNull Consumer<Float> onSecondaryProgress, @NonNull Runnable onComplete ) { // Wait until launch tasks are completed launchTasks = getPreLaunchTasks(context); launchTasks.addAll(DatabaseMaintenance.getPreLaunchCleanupTasks(context)); // TODO execute post-launch tasks in another runner (background worker ?) launchTasks.addAll(getPostLaunchTasks(context)); launchTasks.addAll(DatabaseMaintenance.getPostLaunchCleanupTasks(context)); // TODO switch from a recursive function to a full RxJava-powered chain + clear the disposable elsewhere (as the chain will finish in a worker) doRunTask(0, onMainProgress, onSecondaryProgress, onComplete); } private void doRunTask( int taskIndex, @NonNull Consumer<Float> onMainProgress, @NonNull Consumer<Float> onSecondaryProgress, @NonNull Runnable onComplete ) { if (launchDisposable != null) launchDisposable.dispose(); try { onMainProgress.accept(taskIndex * 1f / launchTasks.size()); } catch (Exception e) { Timber.w(e); } // Continue executing launch tasks if (taskIndex < launchTasks.size()) { Timber.i("Splash / Launch task %s/%s", taskIndex + 1, launchTasks.size()); launchDisposable = launchTasks.get(taskIndex) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( onSecondaryProgress, Timber::e, () -> doRunTask(taskIndex + 1, onMainProgress, onSecondaryProgress, onComplete) ); } else { if (launchDisposable != null) launchDisposable.dispose(); onComplete.run(); } } /** * Application initialization tasks * NB : Heavy operations; must be performed in the background to avoid ANR at startup */ public static List<Observable<Float>> getPreLaunchTasks(@NonNull final Context context) { List<Observable<Float>> result = new ArrayList<>(); result.add(createObservableFrom(context, AppStartup::processAppUpdate)); result.add(createObservableFrom(context, AppStartup::loadSiteProperties)); result.add(createObservableFrom(context, AppStartup::initUtils)); return result; } public static List<Observable<Float>> getPostLaunchTasks(@NonNull final Context context) { List<Observable<Float>> result = new ArrayList<>(); result.add(createObservableFrom(context, AppStartup::searchForUpdates)); result.add(createObservableFrom(context, AppStartup::sendFirebaseStats)); return result; } private static Observable<Float> createObservableFrom(@NonNull final Context context, BiConsumer<Context, ObservableEmitter<Float>> function) { return Observable.create(emitter -> function.accept(context, emitter)); } private static void loadSiteProperties(@NonNull final Context context, ObservableEmitter<Float> emitter) { try (InputStream is = context.getResources().openRawResource(R.raw.sites)) { String siteSettingsStr = FileHelper.readStreamAsString(is); JsonSiteSettings siteSettings = JsonHelper.jsonToObject(siteSettingsStr, JsonSiteSettings.class); for (Map.Entry<String, JsonSiteSettings.JsonSite> entry : siteSettings.sites.entrySet()) { for (Site site : Site.values()) { if (site.name().equalsIgnoreCase(entry.getKey())) { site.updateFrom(entry.getValue()); break; } } } } catch (IOException e) { Timber.e(e); } finally { emitter.onComplete(); } } private static void initUtils(@NonNull final Context context, ObservableEmitter<Float> emitter) { try { Timber.i("Init user agents : start"); HttpHelper.initUserAgents(context); Timber.i("Init user agents : done"); Timber.i("Init notifications : start"); // Init notification channels UpdateNotificationChannel.init(context); DownloadNotificationChannel.init(context); // Clears all previous notifications NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (manager != null) manager.cancelAll(); Timber.i("Init notifications : done"); } finally { emitter.onComplete(); } } private static void processAppUpdate(@NonNull final Context context, ObservableEmitter<Float> emitter) { Timber.i("Process app update : start"); try { if (Preferences.getLastKnownAppVersionCode() < BuildConfig.VERSION_CODE) { Timber.d("Process app update : update detected from %s to %s", Preferences.getLastKnownAppVersionCode(), BuildConfig.VERSION_CODE); // Clear webview cache (needs to execute inside the activity's Looper) Timber.d("Process app update : Clearing webview cache"); Handler h = new Handler(Looper.getMainLooper()); h.post(() -> { WebView webView; try { webView = new NestedScrollWebView(context); } catch (Resources.NotFoundException e) { // Some older devices can crash when instantiating a WebView, due to a Resources$NotFoundException // Creating with the application Context fixes this, but is not generally recommended for view creation webView = new NestedScrollWebView(Helper.getFixedContext(context)); } webView.clearCache(true); }); // Clear app cache Timber.d("Process app update : Clearing app cache"); try { File dir = context.getCacheDir(); FileHelper.removeFile(dir); } catch (Exception e) { Timber.e(e, "Error when clearing app cache upon update"); } EventBus.getDefault().postSticky(new AppUpdatedEvent()); Preferences.setLastKnownAppVersionCode(BuildConfig.VERSION_CODE); } } finally { emitter.onComplete(); } Timber.i("Process app update : done"); } private static void searchForUpdates(@NonNull final Context context, ObservableEmitter<Float> emitter) { Timber.i("Run app update : start"); try { if (Preferences.isAutomaticUpdateEnabled()) { Timber.i("Run app update : auto-check is enabled"); Intent intent = UpdateCheckService.makeIntent(context, false); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(intent); } else { context.startService(intent); } } } finally { emitter.onComplete(); } Timber.i("Run app update : done"); } private static void sendFirebaseStats(@NonNull final Context context, ObservableEmitter<Float> emitter) { Timber.i("Send Firebase stats : start"); try { FirebaseAnalytics.getInstance(context).setUserProperty("color_theme", Integer.toString(Preferences.getColorTheme())); FirebaseAnalytics.getInstance(context).setUserProperty("endless", Boolean.toString(Preferences.getEndlessScroll())); FirebaseCrashlytics.getInstance().setCustomKey("Library display mode", Preferences.getEndlessScroll() ? "endless" : "paged"); } catch (IllegalStateException e) { // Happens during unit tests Log.e("fail@init Crashlytics", e); } finally { emitter.onComplete(); } Timber.i("Send Firebase stats : done"); } }
Prevent init from happening multiple times
app/src/main/java/me/devsaki/hentoid/core/AppStartup.java
Prevent init from happening multiple times
<ide><path>pp/src/main/java/me/devsaki/hentoid/core/AppStartup.java <ide> private List<Observable<Float>> launchTasks; <ide> private Disposable launchDisposable = null; <ide> <add> private static boolean isInitialized = false; <add> <ide> public void initApp( <ide> @NonNull final Context context, <ide> @NonNull Consumer<Float> onMainProgress, <ide> @NonNull Consumer<Float> onSecondaryProgress, <ide> @NonNull Runnable onComplete <ide> ) { <add> if (isInitialized) onComplete.run(); <add> <ide> // Wait until launch tasks are completed <ide> launchTasks = getPreLaunchTasks(context); <ide> launchTasks.addAll(DatabaseMaintenance.getPreLaunchCleanupTasks(context)); <ide> ); <ide> } else { <ide> if (launchDisposable != null) launchDisposable.dispose(); <add> isInitialized = true; <ide> onComplete.run(); <ide> } <ide> }
Java
apache-2.0
9d62b4e644fc9ce53a4729eb5dd784d739f1cf90
0
BrentDouglas/chainlink,BrentDouglas/chainlink
package io.machinecode.chainlink.transport.jgroups; import gnu.trove.map.TLongObjectMap; import gnu.trove.map.TMap; import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.TLongObjectHashMap; import io.machinecode.chainlink.core.registry.LocalRegistry; import io.machinecode.chainlink.core.then.WhenImpl; import io.machinecode.chainlink.spi.configuration.RegistryConfiguration; import io.machinecode.chainlink.spi.execution.Worker; import io.machinecode.chainlink.spi.registry.ChainId; import io.machinecode.chainlink.spi.registry.ExecutableAndContext; import io.machinecode.chainlink.spi.registry.ExecutableId; import io.machinecode.chainlink.spi.registry.ExecutionRepositoryId; import io.machinecode.chainlink.spi.registry.WorkerId; import io.machinecode.chainlink.spi.repository.ExecutionRepository; import io.machinecode.chainlink.spi.serialization.Serializer; import io.machinecode.chainlink.spi.then.Chain; import io.machinecode.chainlink.spi.then.When; import io.machinecode.chainlink.spi.util.Messages; import io.machinecode.chainlink.spi.util.Pair; import io.machinecode.chainlink.transport.jgroups.cmd.CleanupCommand; import io.machinecode.chainlink.transport.jgroups.cmd.Command; import io.machinecode.chainlink.transport.jgroups.cmd.FindExecutableAndContextCommand; import io.machinecode.chainlink.transport.jgroups.cmd.FindExecutionRepositoryWithIdCommand; import io.machinecode.chainlink.transport.jgroups.cmd.FindWorkerCommand; import io.machinecode.chainlink.transport.jgroups.cmd.LeastBusyWorkerCommand; import io.machinecode.then.api.OnComplete; import io.machinecode.then.api.Promise; import io.machinecode.then.core.PromiseImpl; import org.jboss.logging.Logger; import org.jgroups.Address; import org.jgroups.JChannel; import org.jgroups.MembershipListener; import org.jgroups.Message; import org.jgroups.View; import org.jgroups.blocks.MessageDispatcher; import org.jgroups.blocks.RequestHandler; import org.jgroups.blocks.RequestOptions; import javax.batch.operations.JobExecutionNotRunningException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * @author Brent Douglas <[email protected]> */ public class JGroupsRegistry extends LocalRegistry implements RequestHandler, MembershipListener { private static final Logger log = Logger.getLogger(JGroupsRegistry.class); final Serializer serializer; final When network; final When reaper; final JChannel channel; final MessageDispatcher dispatcher; final Address local; protected volatile List<Address> remotes; final TMap<WorkerId, Worker> remoteWorkers = new THashMap<WorkerId, Worker>(); final TLongObjectMap<List<Pair<ChainId,Address>>> remoteExecutions = new TLongObjectHashMap<List<Pair<ChainId,Address>>>(); public JGroupsRegistry(final RegistryConfiguration configuration, final JChannel channel, final String clusterName) throws Exception { this.serializer = configuration.getSerializerFactory().produce(configuration); this.channel = channel; this.network= configuration.getWhenFactory().produce(configuration); this.reaper = configuration.getWhenFactory().produce(configuration); try { channel.connect(clusterName); } catch (Exception e) { throw new IllegalStateException(e); } this.local = channel.getAddress(); this.dispatcher = new MessageDispatcher(channel, null, this); this.dispatcher.setRequestHandler(this); } @Override public void startup() { super.startup(); this.remotes = _remoteMembers(this.channel.getView().getMembers()); log.infof("JGroupsRegistry started on address: [%s]", this.local); //TODO Message } @Override public void shutdown() { log.infof("JGroupsRegistry is shutting down."); //TODO Message this.channel.close(); super.shutdown(); } @Override protected void onRegisterJob(final long jobExecutionId) { remoteExecutions.put(jobExecutionId, new ArrayList<Pair<ChainId, Address>>()); } @Override protected Promise<?,?> onUnregisterJob(final long jobExecutionId, final Chain<?> job) { final Promise<Object, Throwable> promise = new PromiseImpl<Object, Throwable>().onComplete(new OnComplete() { @Override public void complete() { for (final Pair<ChainId, Address> pair : remoteExecutions.remove(jobExecutionId)) { final Address address = pair.getValue(); if (!address.equals(local)) { try { _invoke(address, new CleanupCommand(jobExecutionId)); } catch (Exception e) { // TODO } } } log.debugf(Messages.get("CHAINLINK-005101.registry.removed.job"), jobExecutionId); } }); this.reaper.when((Future<Object>) job, promise); return promise; } @Override public ChainId generateChainId() { return new JGroupsUUIDId(local); } @Override public ExecutableId generateExecutableId() { return new JGroupsUUIDId(local); } @Override public WorkerId generateWorkerId(final Worker worker) { if (worker instanceof Thread) { return new JGroupsThreadId((Thread)worker, local); } else { return new JGroupsUUIDId(local); } } @Override public ExecutionRepositoryId generateExecutionRepositoryId() { return new JGroupsUUIDId(local); } private Worker _localWorker(final WorkerId workerId) { return super.getWorker(workerId); } @Override public Worker getWorker(final WorkerId workerId) { final Worker worker = _localWorker(workerId); if (worker != null) { return worker; } final Worker remoteWorker = remoteWorkers.get(workerId); if (remoteWorker != null) { return remoteWorker; } Address remote = null; if (workerId instanceof JGroupsThreadId) { remote = ((JGroupsThreadId) workerId).address; } if (remote != null) { if (remote.equals(local)) { throw new IllegalStateException(); //This should have been handled at the start } final Worker rpcWorker = new JGroupsWorker(this, local, remote, workerId); remoteWorkers.put(workerId, rpcWorker); return rpcWorker; } final List<Future<Address>> futures = new ArrayList<Future<Address>>(); final List<Address> members = this.remotes; for (final Address address : members) { try { futures.add(_invoke(address, new FindWorkerCommand(workerId))); } catch (Exception e) { log.errorf(e, ""); //TODO Message } } for (final Future<Address> future : futures) { try { //TODO Search these for completes rather that .get() them in order final Address address = future.get(); if (address == null) { continue; } final Worker rpcWorker; if (address.equals(local)) { throw new IllegalStateException(); //Also should not have been distributed } else { rpcWorker = new JGroupsWorker(this, local, address, workerId); remoteWorkers.put(workerId, rpcWorker); } return rpcWorker; } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } throw new IllegalStateException(); //TODO message } private List<Worker> _localWorkers(final int required) { return super.getWorkers(required); } @Override public List<Worker> getWorkers(final int required) { final List<Address> members = new ArrayList<Address>(this.remotes); members.add(this.local); final List<Future<JGroupsThreadId>> futures = new ArrayList<Future<JGroupsThreadId>>(required); for (final Address address : filterMembers(members, required)) { try { futures.add(_invoke(address, new LeastBusyWorkerCommand())); } catch (final Exception e) { log.errorf(e, ""); //TODO Message } } final ArrayList<Worker> workers = new ArrayList<Worker>(required); for (final Future<JGroupsThreadId> future : futures) { try { final JGroupsThreadId threadId = future.get(); if (local.equals(threadId.address)) { workers.add(getWorker(threadId)); } else { workers.add(new JGroupsWorker(this, local, threadId.address, threadId)); } } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } return workers; } @Override public Chain<?> getJob(final long jobExecutionId) throws JobExecutionNotRunningException { //Todo Remote return super.getJob(jobExecutionId); } @Override public ExecutionRepository getExecutionRepository(final ExecutionRepositoryId id) { final ExecutionRepository ours = super.getExecutionRepository(id); if (ours != null) { return ours; } final List<Address> members = this.remotes; final List<Future<Address>> futures = new ArrayList<Future<Address>>(members.size()); for (final Address address : members) { try { futures.add(_invoke(address, new FindExecutionRepositoryWithIdCommand(id))); } catch (Exception e) { log.errorf(e, ""); //TODO Message } } for (final Future<Address> future : futures) { try { final Address address = future.get(); if (address == null) { continue; } else if (local.equals(address)) { throw new IllegalStateException(); //TODO Message } return new JGroupsRemoteExecutionRepository(this, id, address); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } throw new IllegalStateException(); //TODO Message } @Override public ExecutableAndContext getExecutableAndContext(final long jobExecutionId, final ExecutableId id) { final ExecutableAndContext ours = super.getExecutableAndContext(jobExecutionId, id); if (ours != null) { return ours; } final List<Address> members = this.remotes; final List<Future<ExecutableAndContext>> futures = new ArrayList<Future<ExecutableAndContext>>(members.size()); for (final Address address : members) { try { futures.add(_invoke(address, new FindExecutableAndContextCommand(jobExecutionId, id))); } catch (Exception e) { log.errorf(e, ""); //TODO Message } } for (final Future<ExecutableAndContext> future : futures) { try { final ExecutableAndContext executable = future.get(); if (executable == null) { continue; } return executable; } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } throw new IllegalStateException(); //TODO Message } public ExecutionRepository getLocalExecutionRepository(final ExecutionRepositoryId id) { return super.getExecutionRepository(id); } //TODO protected List<Address> filterMembers(final List<Address> all, final int required) { return all.subList(0, required > all.size() ? all.size() : required); } public JGroupsThreadId leastBusyWorker() { return (JGroupsThreadId)getWorker().id(); } public Address getLocal() { return local; } public boolean hasWorker(final WorkerId workerId) { return _localWorker(workerId) != null; } @Override public Object handle(final Message msg) throws Exception { final Command<?> command = serializer.read(msg.getBuffer(), Command.class); try { return command.invoke(this, msg.src()); } catch (final Exception e) { throw e; } catch (final Throwable e) { throw new RuntimeException(e); } } public <T> void invoke(final Address address, final Command command, final Promise<T,Throwable> promise) { try { this.network.when( this.dispatcher.<T>sendMessageWithFuture( new Message(address, serializer.bytes(command)), RequestOptions.SYNC() ), promise ); } catch (Exception e) { promise.reject(e); } } public <T> void invoke(final Address address, final Command<T> command, final Promise<T,Throwable> promise, final long timeout, final TimeUnit unit) { try { this.network.when( this.dispatcher.<T>sendMessageWithFuture( new Message(address, serializer.bytes(command)), RequestOptions.SYNC().setTimeout(unit.toMillis(timeout)) ), promise ); } catch (Exception e) { promise.reject(e); } } private <T> Future<T> _invoke(final Address address, final Command<T> command) throws Exception { return this.dispatcher.sendMessageWithFuture( new Message(address, serializer.bytes(command)), RequestOptions.SYNC() ); } @Override public void viewAccepted(final View view) { final List<Address> members = this.remotes = _remoteMembers(view.getMembers()); final StringBuilder builder = new StringBuilder(); final String nl = System.lineSeparator(); builder.append("Members[").append(members.size() + 1).append("] {").append(nl); builder.append("\t").append(this.local).append(" this").append(nl); for (final Address member : members) { builder.append("\t").append(member).append(nl); } builder.append("}"); log.infof("Cluster: %s", builder); //TODO Message } private List<Address> _remoteMembers(final List<Address> all) { final List<Address> that = new ArrayList<Address>(all); that.remove(this.local); return Collections.unmodifiableList(that); } @Override public void suspect(final Address suspected) {} @Override public void block() {} @Override public void unblock() {} }
transport/jgroups/src/main/java/io/machinecode/chainlink/transport/jgroups/JGroupsRegistry.java
package io.machinecode.chainlink.transport.jgroups; import gnu.trove.map.TLongObjectMap; import gnu.trove.map.TMap; import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.TLongObjectHashMap; import io.machinecode.chainlink.core.registry.LocalRegistry; import io.machinecode.chainlink.core.then.WhenImpl; import io.machinecode.chainlink.spi.configuration.RegistryConfiguration; import io.machinecode.chainlink.spi.execution.Worker; import io.machinecode.chainlink.spi.registry.ChainId; import io.machinecode.chainlink.spi.registry.ExecutableAndContext; import io.machinecode.chainlink.spi.registry.ExecutableId; import io.machinecode.chainlink.spi.registry.ExecutionRepositoryId; import io.machinecode.chainlink.spi.registry.WorkerId; import io.machinecode.chainlink.spi.repository.ExecutionRepository; import io.machinecode.chainlink.spi.serialization.Serializer; import io.machinecode.chainlink.spi.then.Chain; import io.machinecode.chainlink.spi.then.When; import io.machinecode.chainlink.spi.util.Messages; import io.machinecode.chainlink.spi.util.Pair; import io.machinecode.chainlink.transport.jgroups.cmd.CleanupCommand; import io.machinecode.chainlink.transport.jgroups.cmd.Command; import io.machinecode.chainlink.transport.jgroups.cmd.FindExecutableAndContextCommand; import io.machinecode.chainlink.transport.jgroups.cmd.FindExecutionRepositoryWithIdCommand; import io.machinecode.chainlink.transport.jgroups.cmd.FindWorkerCommand; import io.machinecode.chainlink.transport.jgroups.cmd.LeastBusyWorkerCommand; import io.machinecode.then.api.OnComplete; import io.machinecode.then.api.Promise; import io.machinecode.then.core.PromiseImpl; import org.jboss.logging.Logger; import org.jgroups.Address; import org.jgroups.JChannel; import org.jgroups.MembershipListener; import org.jgroups.Message; import org.jgroups.View; import org.jgroups.blocks.MessageDispatcher; import org.jgroups.blocks.RequestHandler; import org.jgroups.blocks.RequestOptions; import javax.batch.operations.JobExecutionNotRunningException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * @author Brent Douglas <[email protected]> */ public class JGroupsRegistry extends LocalRegistry implements RequestHandler, MembershipListener { private static final Logger log = Logger.getLogger(JGroupsRegistry.class); final Serializer serializer; final When network; final When reaper; final JChannel channel; final MessageDispatcher dispatcher; final Address local; protected volatile List<Address> remotes; final TMap<WorkerId, Worker> remoteWorkers = new THashMap<WorkerId, Worker>(); final TLongObjectMap<List<Pair<ChainId,Address>>> remoteExecutions = new TLongObjectHashMap<List<Pair<ChainId,Address>>>(); public JGroupsRegistry(final RegistryConfiguration configuration, final JChannel channel, final String clusterName) throws Exception { this.serializer = configuration.getSerializerFactory().produce(configuration); this.channel = channel; this.network= configuration.getWhenFactory().produce(configuration); this.reaper = configuration.getWhenFactory().produce(configuration); try { channel.connect(clusterName); } catch (Exception e) { throw new IllegalStateException(e); } this.local = channel.getAddress(); this.dispatcher = new MessageDispatcher(channel, null, this); this.dispatcher.setRequestHandler(this); } @Override public void startup() { super.startup(); this.remotes = _remoteMembers(this.channel.getView().getMembers()); log.infof("JGroupsRegistry started on address: [%s]", this.local); //TODO Message } @Override public void shutdown() { log.infof("JGroupsRegistry is shutting down."); //TODO Message this.channel.close(); super.shutdown(); } @Override protected void onRegisterJob(final long jobExecutionId) { remoteExecutions.put(jobExecutionId, new ArrayList<Pair<ChainId, Address>>()); } @Override protected Promise<?,?> onUnregisterJob(final long jobExecutionId, final Chain<?> job) { final Promise<Object, Throwable> promise = new PromiseImpl<Object, Throwable>().onComplete(new OnComplete() { @Override public void complete() { for (final Pair<ChainId, Address> pair : remoteExecutions.remove(jobExecutionId)) { final Address address = pair.getValue(); if (!address.equals(local)) { try { _invoke(address, new CleanupCommand(jobExecutionId)); } catch (Exception e) { // TODO } } } log.debugf(Messages.get("CHAINLINK-005101.registry.removed.job"), jobExecutionId); } }); this.reaper.when((Future<Object>) job, promise); return promise; } @Override public ChainId generateChainId() { return new JGroupsUUIDId(local); } @Override public ExecutableId generateExecutableId() { return new JGroupsUUIDId(local); } @Override public WorkerId generateWorkerId(final Worker worker) { if (worker instanceof Thread) { return new JGroupsThreadId((Thread)worker, local); } else { return new JGroupsUUIDId(local); } } @Override public ExecutionRepositoryId generateExecutionRepositoryId() { return new JGroupsUUIDId(local); } private Worker _localWorker(final WorkerId workerId) { return super.getWorker(workerId); } @Override public Worker getWorker(final WorkerId workerId) { final Worker worker = _localWorker(workerId); if (worker != null) { return worker; } final Worker remoteWorker = remoteWorkers.get(workerId); if (remoteWorker != null) { return remoteWorker; } Address remote = null; if (workerId instanceof JGroupsThreadId) { remote = ((JGroupsThreadId) workerId).address; } if (remote != null) { if (remote.equals(local)) { throw new IllegalStateException(); //This should have been handled at the start } final Worker rpcWorker = new JGroupsWorker(this, local, remote, workerId); remoteWorkers.put(workerId, rpcWorker); return rpcWorker; } final List<Future<Address>> futures = new ArrayList<Future<Address>>(); final List<Address> members = this.remotes; for (final Address address : members) { try { futures.add(_invoke(address, new FindWorkerCommand(workerId))); } catch (Exception e) { log.errorf(e, ""); //TODO Message } } for (final Future<Address> future : futures) { try { //TODO Search these for completes rather that .get() them in order final Address address = future.get(); if (address == null) { continue; } final Worker rpcWorker; if (address.equals(local)) { throw new IllegalStateException(); //Also should not have been distributed } else { rpcWorker = new JGroupsWorker(this, local, address, workerId); remoteWorkers.put(workerId, rpcWorker); } return rpcWorker; } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } throw new IllegalStateException(); //TODO message } private List<Worker> _localWorkers(final int required) { return super.getWorkers(required); } @Override public List<Worker> getWorkers(final int required) { final List<Address> members = new ArrayList<Address>(this.remotes); members.add(this.local); final List<Future<JGroupsThreadId>> futures = new ArrayList<Future<JGroupsThreadId>>(required); for (final Address address : filterMembers(members, required)) { try { futures.add(_invoke(address, new LeastBusyWorkerCommand())); } catch (final Exception e) { log.errorf(e, ""); //TODO Message } } final ArrayList<Worker> workers = new ArrayList<Worker>(required); for (final Future<JGroupsThreadId> future : futures) { try { final JGroupsThreadId threadId = future.get(); if (local.equals(threadId.address)) { workers.add(getWorker(threadId)); } else { workers.add(new JGroupsWorker(this, local, threadId.address, threadId)); } } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } return workers; } @Override public Chain<?> getJob(final long jobExecutionId) throws JobExecutionNotRunningException { //Todo Remote return super.getJob(jobExecutionId); } @Override public ExecutionRepository getExecutionRepository(final ExecutionRepositoryId id) { final ExecutionRepository ours = super.getExecutionRepository(id); if (ours != null) { return ours; } final List<Address> members = this.remotes; final List<Future<Address>> futures = new ArrayList<Future<Address>>(members.size()); for (final Address address : members) { try { futures.add(_invoke(address, new FindExecutionRepositoryWithIdCommand(id))); } catch (Exception e) { log.errorf(e, ""); //TODO Message } } for (final Future<Address> future : futures) { try { final Address address = future.get(); if (address == null) { continue; } else if (local.equals(address)) { throw new IllegalStateException(); //TODO Message } return new JGroupsRemoteExecutionRepository(this, id, address); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } throw new IllegalStateException(); //TODO Message } @Override public ExecutableAndContext getExecutableAndContext(final long jobExecutionId, final ExecutableId id) { final ExecutableAndContext ours = super.getExecutableAndContext(jobExecutionId, id); if (ours != null) { return ours; } final List<Address> members = this.remotes; final List<Future<ExecutableAndContext>> futures = new ArrayList<Future<ExecutableAndContext>>(members.size()); for (final Address address : members) { try { futures.add(_invoke(address, new FindExecutableAndContextCommand(jobExecutionId, id))); } catch (Exception e) { log.errorf(e, ""); //TODO Message } } for (final Future<ExecutableAndContext> future : futures) { try { final ExecutableAndContext executable = future.get(); if (executable == null) { continue; } return executable; } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } throw new IllegalStateException(); //TODO Message } public ExecutionRepository getLocalExecutionRepository(final ExecutionRepositoryId id) { return super.getExecutionRepository(id); } //TODO protected List<Address> filterMembers(final List<Address> all, final int required) { return all.subList(0, required > all.size() ? all.size() : required); } public JGroupsThreadId leastBusyWorker() { return (JGroupsThreadId)getWorker().id(); } public Address getLocal() { return local; } public boolean hasWorker(final WorkerId workerId) { return _localWorker(workerId) != null; } @Override public Object handle(final Message msg) throws Exception { final Command<?> command = serializer.read(msg.getBuffer(), Command.class); try { return command.invoke(this, msg.src()); } catch (final Exception e) { throw e; } catch (final Throwable e) { throw new RuntimeException(e); } } public <T> void invoke(final Address address, final Command command, final Promise<T,Throwable> promise) { try { this.network.when( this.dispatcher.<T>sendMessageWithFuture( new Message(address, serializer.bytes(command)), RequestOptions.SYNC() ), promise ); } catch (Exception e) { promise.reject(e); } } public <T> void invoke(final Address address, final Command<T> command, final Promise<T,Throwable> promise, final long timeout, final TimeUnit unit) { try { this.network.when( this.dispatcher.<T>sendMessageWithFuture( new Message(address, serializer.bytes(command)), RequestOptions.SYNC().setTimeout(unit.toMillis(timeout)) ), promise ); } catch (Exception e) { promise.reject(e); } } private <T> Future<T> _invoke(final Address address, final Command<T> command) throws Exception { return this.dispatcher.sendMessageWithFuture( new Message(address, serializer.bytes(command)), RequestOptions.SYNC() ); } @Override public void viewAccepted(final View view) { final List<Address> members = this.remotes = _remoteMembers(view.getMembers()); final StringBuilder builder = new StringBuilder(); builder.append("[").append(this.local).append("]"); for (final Address member : members) { builder.append(" | ").append(member); } log.infof("Cluster: %s", builder); //TODO Message } private List<Address> _remoteMembers(final List<Address> all) { final List<Address> that = new ArrayList<Address>(all); that.remove(this.local); return Collections.unmodifiableList(that); } @Override public void suspect(final Address suspected) {} @Override public void block() {} @Override public void unblock() {} }
Improve JGroups membership logging.
transport/jgroups/src/main/java/io/machinecode/chainlink/transport/jgroups/JGroupsRegistry.java
Improve JGroups membership logging.
<ide><path>ransport/jgroups/src/main/java/io/machinecode/chainlink/transport/jgroups/JGroupsRegistry.java <ide> public void viewAccepted(final View view) { <ide> final List<Address> members = this.remotes = _remoteMembers(view.getMembers()); <ide> final StringBuilder builder = new StringBuilder(); <del> builder.append("[").append(this.local).append("]"); <add> final String nl = System.lineSeparator(); <add> builder.append("Members[").append(members.size() + 1).append("] {").append(nl); <add> builder.append("\t").append(this.local).append(" this").append(nl); <ide> for (final Address member : members) { <del> builder.append(" | ").append(member); <del> } <add> builder.append("\t").append(member).append(nl); <add> } <add> builder.append("}"); <ide> log.infof("Cluster: %s", builder); //TODO Message <ide> } <ide>
Java
bsd-3-clause
fe30371216c198a42bcff94ca4979e95a3250f2a
0
vincentml/basex,JensErat/basex,BaseXdb/basex,joansmith/basex,joansmith/basex,JensErat/basex,ksclarke/basex,JensErat/basex,drmacro/basex,drmacro/basex,vincentml/basex,deshmnnit04/basex,deshmnnit04/basex,JensErat/basex,drmacro/basex,deshmnnit04/basex,JensErat/basex,BaseXdb/basex,dimitarp/basex,dimitarp/basex,ksclarke/basex,ksclarke/basex,JensErat/basex,BaseXdb/basex,JensErat/basex,vincentml/basex,vincentml/basex,dimitarp/basex,BaseXdb/basex,vincentml/basex,ksclarke/basex,drmacro/basex,joansmith/basex,drmacro/basex,deshmnnit04/basex,joansmith/basex,joansmith/basex,dimitarp/basex,deshmnnit04/basex,ksclarke/basex,BaseXdb/basex,joansmith/basex,vincentml/basex,BaseXdb/basex,deshmnnit04/basex,ksclarke/basex,vincentml/basex,vincentml/basex,dimitarp/basex,drmacro/basex,BaseXdb/basex,dimitarp/basex,dimitarp/basex,JensErat/basex,drmacro/basex,dimitarp/basex,ksclarke/basex,BaseXdb/basex,deshmnnit04/basex,deshmnnit04/basex,drmacro/basex,vincentml/basex,joansmith/basex,deshmnnit04/basex,vincentml/basex,vincentml/basex,JensErat/basex,joansmith/basex,joansmith/basex,ksclarke/basex,drmacro/basex,joansmith/basex,drmacro/basex,drmacro/basex,deshmnnit04/basex,drmacro/basex,dimitarp/basex,vincentml/basex,ksclarke/basex,ksclarke/basex,deshmnnit04/basex,dimitarp/basex,BaseXdb/basex,BaseXdb/basex,joansmith/basex,joansmith/basex,dimitarp/basex,ksclarke/basex,ksclarke/basex,JensErat/basex,JensErat/basex,JensErat/basex,deshmnnit04/basex,BaseXdb/basex,BaseXdb/basex,dimitarp/basex
package org.basex.examples.server; import java.io.IOException; import java.util.Random; import org.basex.BaseXServer; import org.basex.server.ClientSession; import org.basex.util.Performance; import org.basex.util.Util; /** * This class performs a client/server stress tests with a specified * number of threads and queries. * * @author Workgroup DBIS, University of Konstanz 2005-10, ISC License * @author BaseX Team */ public final class StressTest { /** Verbose flag. */ static final boolean VERBOSE = false; /** Number of clients. */ static final int NCLIENTS = 50; /** Number of runs per client. */ static final int NQUERIES = 50; /** Input document. */ static final String INPUT = "etc/xml/factbook.xml"; /** Query to be run ("%" serves as placeholder for dynamic content). */ static final String QUERY = "doc('test')/descendant::text()[position() = %]"; /** Server reference. */ static BaseXServer server; /** Random number generator. */ static final Random RND = new Random(); /** Result counter. */ static int counter; /** * Runs the example code. * @param args (ignored) command-line arguments * @throws Exception exception */ public static void main(final String[] args) throws Exception { System.out.println("=== Server StressTest ==="); // Run server instance System.out.println("\n* Start server."); server = new BaseXServer("-z"); // Create test database System.out.println("\n* Create test database."); final ClientSession cs = newSession(); cs.execute("create db test " + INPUT); System.out.print(cs.info()); cs.close(); // Run clients System.out.println("\n* Run " + NCLIENTS + " client threads."); final Client[] cl = new Client[NCLIENTS]; for(int i = 0; i < NCLIENTS; ++i) cl[i] = new Client(); for(final Client c : cl) c.start(); for(final Client c : cl) c.join(); stopServer(); } /** * Stops the server. * @throws Exception exception */ static void stopServer() throws Exception { // Drop database and stop server System.out.println("\n* Stop server and drop test database."); final ClientSession cs = newSession(); try { cs.execute("drop db test"); } catch(Exception e) { System.out.print(cs.info() + "\n"); e.printStackTrace(); } cs.close(); server.stop(); } /** * Returns a session instance. * @return session * @throws IOException exception */ static ClientSession newSession() throws IOException { return new ClientSession("localhost", 1984, "admin", "admin"); } /** Single client. */ static class Client extends Thread { /** Client session. */ private ClientSession session; /** * Default constructor. */ public Client() { try { session = newSession(); } catch(IOException e) { e.printStackTrace(); } } @Override public void run() { try { // Perform some queries for(int i = 0; i < NQUERIES; ++i) { Performance.sleep((long) (50 * RND.nextDouble())); // Return nth text of the database final int n = (RND.nextInt() & 0xFF) + 1; final String qu = Util.info(QUERY, n); final String result = session.execute("xquery " + qu); if(VERBOSE) System.out.println("[" + counter++ + "] Thread " + getId() + ", Pos " + n + ": " + result); } session.close(); } catch(final Exception ex) { ex.printStackTrace(); } } } }
src/main/java/org/basex/examples/server/StressTest.java
package org.basex.examples.server; import java.io.IOException; import java.util.Random; import org.basex.BaseXServer; import org.basex.server.ClientSession; import org.basex.util.Performance; import org.basex.util.Util; /** * This class performs a client/server stress tests with a specified * number of threads and queries. * * @author Workgroup DBIS, University of Konstanz 2005-10, ISC License * @author BaseX Team */ public final class StressTest { /** Verbose flag. */ static final boolean VERBOSE = false; /** Number of clients. */ static final int NCLIENTS = 500; /** Number of runs per client. */ static final int NQUERIES = 50; /** Input document. */ static final String INPUT = "etc/xml/factbook.xml"; /** Query to be run ("%" serves as placeholder for dynamic content). */ static final String QUERY = "doc('test')/descendant::text()[position() = %]"; /** Server reference. */ static BaseXServer server; /** Random number generator. */ static final Random RND = new Random(); /** Result counter. */ static int counter; /** * Runs the example code. * @param args (ignored) command-line arguments * @throws Exception exception */ public static void main(final String[] args) throws Exception { System.out.println("=== Server StressTest ==="); // Run server instance System.out.println("\n* Start server."); server = new BaseXServer("-z"); // Create test database System.out.println("\n* Create test database."); final ClientSession cs = newSession(); cs.execute("create db test " + INPUT); System.out.print(cs.info()); cs.close(); // Run clients System.out.println("\n* Run " + NCLIENTS + " client threads."); final Client[] cl = new Client[NCLIENTS]; for(int i = 0; i < NCLIENTS; ++i) cl[i] = new Client(); for(final Client c : cl) c.start(); for(final Client c : cl) c.join(); stopServer(); } /** * Stops the server. * @throws Exception exception */ static void stopServer() throws Exception { // Drop database and stop server System.out.println("\n* Stop server and drop test database."); final ClientSession cs = newSession(); try { cs.execute("drop db test"); } catch(Exception e) { System.out.print(cs.info() + "\n"); e.printStackTrace(); } cs.close(); server.stop(); } /** * Returns a session instance. * @return session * @throws IOException exception */ static ClientSession newSession() throws IOException { return new ClientSession("localhost", 1984, "admin", "admin"); } /** Single client. */ static class Client extends Thread { /** Client session. */ private ClientSession session; /** * Default constructor. */ public Client() { try { session = newSession(); } catch(IOException e) { e.printStackTrace(); } } @Override public void run() { try { // Perform some queries for(int i = 0; i < NQUERIES; ++i) { Performance.sleep((long) (50 * RND.nextDouble())); // Return nth text of the database final int n = (RND.nextInt() & 0xFF) + 1; final String qu = Util.info(QUERY, n); final String result = session.execute("xquery " + qu); if(VERBOSE) System.out.println("[" + counter++ + "] Thread " + getId() + ", Pos " + n + ": " + result); } session.close(); } catch(final Exception ex) { ex.printStackTrace(); } } } }
[FIX] Storage: text decompression synchronized (fixes local StressTest)
src/main/java/org/basex/examples/server/StressTest.java
[FIX] Storage: text decompression synchronized (fixes local StressTest)
<ide><path>rc/main/java/org/basex/examples/server/StressTest.java <ide> /** Verbose flag. */ <ide> static final boolean VERBOSE = false; <ide> /** Number of clients. */ <del> static final int NCLIENTS = 500; <add> static final int NCLIENTS = 50; <ide> /** Number of runs per client. */ <ide> static final int NQUERIES = 50; <ide> /** Input document. */
JavaScript
apache-2.0
a73d2e64196d34d7ee821ee559a15a1911456245
0
jadman02/testphonegap,jadman02/testphonegap
var refreshIntervalId; var desktoparray = ['media/dateicon.png','media/duckicon.png','media/datetongue.png','media/dateorducklogo.png'] function setWant(val){ if (val == 0){ if ($( ".homedate" ).hasClass( "active" )){$( ".homedate" ).removeClass("active"); if ($( ".homeduck" ).hasClass( "active" )){homewant = 'duck';updateWant(); }else {homewant = 'offline';updateWant(); } } else{$( ".homedate" ).addClass("active"); if ($( ".homeduck" ).hasClass( "active" )){homewant = 'dateduck';updateWant(); }else {homewant = 'date';updateWant(); } } } if (val == 1){ if ($( ".homeduck" ).hasClass( "active" )){$( ".homeduck" ).removeClass("active"); if ($( ".homedate" ).hasClass( "active" )){homewant = 'date';updateWant(); }else {homewant = 'offline';updateWant(); } } else{$( ".homeduck" ).addClass("active"); if ($( ".homedate" ).hasClass( "active" )){homewant = 'dateduck';updateWant(); }else {homewant = 'duck';updateWant(); } } } } function updateWant(){ firebase.database().ref('users/' + f_uid).update({ homewant : homewant }); //Will update firebase user homewant //Check if updateuser function is in go daddy file firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/updatewant.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,want:homewant} ) .done(function( data ) { //getMatches(); }); }).catch(function(error) { // Handle error }); } function startCamera(){ navigator.camera.getPicture(conSuccess, conFail, { quality: 50, destinationType: Camera.DestinationType.FILE_URI,sourceType:Camera.PictureSourceType.PHOTOLIBRARY}); } function conSuccess(imageURI) { alert('gotimage'); //var image = document.getElementById('myImage'); //image.src = imageURI; } function conFail(message) { alert('Failed because: ' + message); } function doSomething() { var i = Math.floor(Math.random() * 4) + 0; $(".desktopimage").attr("src", desktoparray[i]); } var myFunction = function() { doSomething(); var rand = Math.round(Math.random() * (1000 - 700)) + 700; refreshIntervalId = setTimeout(myFunction, rand); } myFunction(); var mobile = 0; if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {mobile = 1;} else{ mobile = 0; $('.login-loader').hide(); $('.dateduckdesktop').append('<div style="clear:both;width:100%;text-align:center;border-top:1px solid #ccc;margin-top:10px;"><p>Meet people nearby for a date or a <strike>fu**</strike> duck.</br></br>Open on your phone.</p></div>'); } //if (mobile===1){ try { // try to use localStorage localStorage.test = 2; } catch (e) { // there was an error so... alert('You are in Privacy Mode\nPlease deactivate Privacy Mode and then reload the page.'); } // Initialize your app var myApp = new Framework7({dynamicNavbar: true,init: false}); // Export selectors engine var $$ = Dom7; var view1, view2, view3, view4; var updatecontinuously = false; var initialload = false; var allowedchange = true; var view3 = myApp.addView('#view-3'); var view4 = myApp.addView('#view-4'); var myMessages, myMessagebar, f_description,existingchatnotifications, message_history = false, message_historyon, datealertvar = false, datealert = false, latitudep, longitudep, incommondate, incommonduck,f_uid,f_name,f_first,f_gender,f_age,f_email,f_image,f_token, f_upper, f_lower, f_interested,sexuality; var f_to_date = [],f_to_duck = [],f_date_me = [],f_duck_me = [],f_date_match = [],f_duck_match = [],f_date_match_data = [],f_duck_match_data = []; var f_auth_id; var blocklist; var lastkey; var pickerDescribe,pickerDescribe2, pickerCustomToolbar; var existingmessages; var additions = 0; var myPhotoBrowser; var singlePhotoBrowser; var calendarInline; var keepopen; var userpref; var loadpref= false; var loadpref2= false; var loaded = false; var myList; var myphotosarray; var matcheslistener; var noresultstimeout; var timeoutactive = false; var radiussize,sortby,offsounds; var industry_u,status_u,politics_u,eyes_u,body_u,religion_u,zodiac_u,ethnicity_u,height_u,weight_u; var descriptionslist = []; var nameslist = []; var fdateicon = '<img src="media/dateicon.png" style="width:28px;margin-right:5px;">'; var fduckicon = '<img src="media/duckicon.png" style="width:28px;margin-right:5px;">'; var notifcount; var swiperPhotos; var swiperQuestions; var myswiperphotos; var flargedateicon = '<img src="media/dateicon.png" style="width:60px;">'; var flargeduckicon = '<img src="media/duckicon.png" style="width:60px;">'; var mySwiper; myApp.init(); var f_projectid; var canloadchat; var viewphotos = false; var viewscroll = false; var homewant; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var firebaseinit; var app = { // Application Constructor initialize: function() { this.bindEvents(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicitly call 'app.receivedEvent(...);' onDeviceReady: function() { app.receivedEvent('deviceready'); // alert(Keyboard); //soNow(); // Add views view1 = myApp.addView('#view-1'); view2 = myApp.addView('#view-2', { // Because we use fixed-through navbar we can enable dynamic navbar dynamicNavbar: true }); view3 = myApp.addView('#view-3'); view4 = myApp.addView('#view-4'); //authstatechanged user only firebase.auth().onAuthStateChanged(function(user) { if (user) { f_projectid = firebase.auth().currentUser.toJSON().authDomain.substr(0, firebase.auth().currentUser.toJSON().authDomain.indexOf('.')) f_uid = user.providerData[0].uid; f_auth_id = user.uid; f_name = user.providerData[0].displayName; f_first = f_name.substr(0,f_name.indexOf(' ')); f_email = user.providerData[0].email; f_image = user.providerData[0].photoURL; // $( ".userimagetoolbar" ).css("background-image","url(\'https://graph.facebook.com/"+f_uid+"/picture?type=normal\')"); // $( "#profilepic" ).empty(); // $( "#profilepic" ).append('<div style="float:left;height:70px;width:70px;border-radius:50%;margin:0 auto;background-size:cover;background-position:50% 50%;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?type=normal\');"></div>'); firebase.database().ref('users/' + f_uid).update({ auth_id : f_auth_id }).then(function() {getPreferences();}); } else { $( ".ploader" ).show(); $( ".loginbutton" ).show(); $( ".login-loader" ).hide(); // No user is signed in. } }); }, // Update DOM on a Received Event receivedEvent: function(id) {} }; function startApp(){ firebaseinit = localStorage.getItem('tokenStore'); if (firebaseinit){ var credential = firebase.auth.FacebookAuthProvider.credential(firebaseinit); firebase.auth().signInWithCredential(credential).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; if (error){ myApp.alert('Error', 'Error message: ' + errorMessage + '(code:' + errorCode + ')'); } }); } else { alert('no tokenStore'); } } $$('.panel-right').on('panel:opened', function () { leftPanel(); }); $$('.panel-right').on('panel:open', function () { $( ".upgradeli" ).slideDown(); }); $$('.panel-right').on('panel:closed', function () { myList.deleteAllItems(); myList.clearCache(); //firebase.database().ref('notifications/' + f_uid).off('value', notificationlist); }); function compare(a,b) { if (a.chat_expire < b.chat_expire) return -1; if (a.chat_expire > b.chat_expire) return 1; return 0; } $$('.panel-left').on('panel:closed', function () { $(".timeline").empty(); }); $$('.panel-left').on('panel:open', function () { rightPanel(); }); $$('.panel-right').on('panel:closed', function () { $( ".upgradeli" ).hide(); }); // Pull to refresh content var ptrContent = $$('.pull-to-refresh-content-1'); // Add 'refresh' listener on it ptrContent.on('ptr:refresh', function (e) { // Emulate 2s loading //loaded = false; getPreferences(); setTimeout(function () { // Random image myApp.pullToRefreshDone(); }, 1000); }); // Pull to refresh content var ptrContent = $$('.pull-to-refresh-content-2'); // Add 'refresh' listener on it ptrContent.on('ptr:refresh', function (e) { myList.deleteAllItems(); myList.clearCache(); setTimeout(function () { // Random image leftPanel(); myApp.pullToRefreshDone(); }, 1000); }); var onSuccess = function(position) { latitudep = position.coords.latitude; longitudep = position.coords.longitude; //alert(latitudep); //alert(longitudep); updateGeo(); $( ".age-header" ).remove(); $( ".swiper-container-loaded" ).remove(); }; function onError(error) { if (error.code == '1'){ jQuery.post( "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCAqd15w-_K31IUyLWNlmkHNmZU5YLSg6c", function(success) { apiGeolocationSuccess({coords: {latitude: success.location.lat, longitude: success.location.lng}}); }) .done(function() { //alert('done'); }) .fail(function(err) { myApp.alert('You must share your location on date or duck', 'Oops we cannot find you'); }); } if ((error.code == '2') || (error.code == '3')){ jQuery.post( "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCAqd15w-_K31IUyLWNlmkHNmZU5YLSg6c", function(success) { apiGeolocationSuccess({coords: {latitude: success.location.lat, longitude: success.location.lng}}); }) .done(function() { //alert('done'); }) .fail(function(err) { myApp.alert('There has been an error.', 'Oops we cannot find you'); }); } } function getWifilocation(){ navigator.geolocation.getCurrentPosition(onSuccess, onError); } var apiGeolocationSuccess = function(position) { latitudep = position.coords.latitude; longitudep = position.coords.longitude; //alert(latitudep); //alert(longitudep); updateGeo(); $( ".age-header" ).remove(); $( ".swiper-container-loaded" ).remove(); }; function mainLoaded(id){ $( ".iconpos_" + id ).show(); $( ".default_" + id ).hide(); var indivNotif = firebase.database().ref('notifications/' + f_uid + '/' + id); indivNotif.once('value', function(snapshot) { if (snapshot.val()){ var obj = snapshot.val(); if (obj.new_message_count >0 && obj.to_uid == f_uid && obj.received =='N'){$( ".arrowdivhome_" + id ).empty();$( ".arrowdivhome_" + id ).append('<span class="badge" style="background-color:rgb(255, 208, 0);color:black;margin-top:5px;margin-left:-5px;">'+obj.new_message_count+'</span>');} else{$( ".arrowdivhome_" + id ).empty();} } }); } var all_matches_photos=[]; var new_all = []; var main_all = []; function getMatches(){ new_all = []; //can put any ads here if ((initialload === false) && (availarray.length === 0)){ } if (!homewant || homewant =='offline'){ $('.content-here').empty(); $( ".results-loader" ).hide(); $('.content-here').append( '<div class="no-results-div" style="text-align:center;margin:0 auto;width:300px;position:absolute;top:44px;left:50%;margin-left:-150px;margin-top:54px;">'+ '<h3>Get Quacking!</h3>'+ '<p style="padding-top:0px;margin-top:0px;">Are you looking to date, or duck or both? Your profile is not visible until you make a selection.</p>'+ '<div class="row" style="border-top:1px solid #c4c4c4;padding-top:10px;padding-bottom:10px;">'+ '<div class="col-30" style="padding-top:5px;"><img src="media/datefaceonly.png" style="width:80px;margin:0 auto;"></div>'+ '<div class="col-70" style="padding-top:5px;">Press <span style="font-family: \'Pacifico\', cursive;font-size:17px;">date</span> if you want to meet someone to hang out with, find a relationship or make conversation.</div>'+ '</div>'+ '<div class="row" style="padding-top:10px;padding-bottom:10px;">'+ '<div class="col-30" style="padding-top:5px;"><img src="media/duckfaceonly.png" style="width:80px;margin:0 auto;"></div>'+ '<div class="col-70" style="padding-top:5px;">Press <span style="font-family: \'Pacifico\', cursive;font-size:17px;">duck</span> if you want to get down to...ahem...business (replace the D with an F). </div>'+ '</div>'+ '</div>'); $( ".ploader" ).hide(); $( ".toolbar" ).show(); $( ".loginbutton" ).show(); $( ".login-loader" ).hide(); return false; } initialload = true; if (updatecontinuously){} else {setInterval(function(){ justGeo(); }, 599000);updatecontinuously=true;} if (timeoutactive === true) {clearTimeout(noresultstimeout);} timeoutactive = true; firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/locations.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,upper:f_upper,lower:f_lower,radius:radiussize,sexuality:sexuality,sortby:sortby,latitudep:latitudep,longitudep:longitudep} ) .done(function( data ) { var result = JSON.parse(data); console.log(data); console.log(result); for (var i = f_lower; i <= f_upper; i++) {} var slidewidth = $( document ).width() / 1.7; var halfwidth = -Math.abs(slidewidth / 2.23); // var rownumber; // var calcrownumber = f_upper-f_lower; // var columnslides; // var specialstyles; // if (calcrownumber == 0){rownumber = 3;columnslides=9;} // if (calcrownumber > 0){rownumber = 1;columnslides=1;} var slide_number = 0; for (var i = f_lower; i <= f_upper; i++) { all_matches_photos[i] = []; $( ".content-here" ).append( // '<span class="badge age-header header_'+i+'" style="display:none;text-align:left;float:left;width:100%;border-radius:0px;background-color:white;color:black;">'+i+'</span>'+ ' <div class="swiper-container swiper-container-loaded swiper-'+i+'" style="display:none;height:'+slidewidth+'px;clear:both;background-color:white;">'+ '<div class="blockleft_'+i+'" style="display:none;color:white;padding:3px;height:20px;width:20px;-webkit-border-top-right-radius: 50%;-webkit-border-bottom-right-radius: 50%;background-color:#2196f3;position:absolute;left:0;top:50%;z-index:9999;margin-top:-10px;"><div style="float:left;"><i class="pe-7s-angle-left pe-lg" style="margin-left:-9px;color:white;float:left;margin-top:3px"></i><span style="float:left;font-size:12px;margin-left:-5px;margin-top:2px;">'+i+'</span></div></div>'+ '<div class="blockright_'+i+' multiple_'+i+'" style="display:none;margin-top:-10px;color:white;padding:3px;height:20px;width:20px;-webkit-border-top-left-radius: 50%;-webkit-border-bottom-left-radius: 50%;background-color:#2196f3;position:absolute;right:0px;top:50%;z-index:9999;margin-top:-7.5px;"><div style="float:right;"><i class="pe-7s-angle-right pe-lg" style="margin-right:-9px;color:white;float:right;margin-top:3px"></i><span style="float:right;font-size:12px;margin-right:-5px;margin-top:2px;">'+i+'</span></div></div>'+ '<div class="blockright_'+i+' single_'+i+'" style="margin-top:-10px;color:white;padding:3px;height:20px;width:20px;border-radius:50%;margin-right:5px;background-color:#2196f3;position:absolute;right:0px;top:50%;z-index:9999;margin-top:-7.5px;"><div style="float:right;"><span style="float:right;font-size:12px;margin-right:2px;margin-top:2px;">'+i+'</span></div></div>'+ '<div class="swiper-wrapper wrapper_'+i+'">'+ // '<div class="swiper-slide"><div style="background-color:white;height:50%;width:50%;margin-top:50%;margin-left:25%;"></div></div>'+ '</div>'+ '</div>' ); myApp.swiper('.swiper-' + i, { slidesPerView:1.7, freeMode:true, //slidesOffsetBefore:halfwidth, slidesOffsetAfter:12, preloadImages: false, // Enable lazy loading lazyLoading: true, //centeredSlides: true, watchSlidesVisibility:true, watchSlidesProgress: true, onSlideChangeEnd:function(swiper){ var firstclasslist = $(swiper.slides[0]).attr("class").split(' '); var currentswiper = firstclasslist[0].replace("age_", ""); var swiperslideslength = swiper.slides.length; if (swiper.activeIndex === 0){$('.blockright_' + currentswiper).show();$('.blockleft_' + currentswiper).hide(); } else { if (swiper.activeIndex > 0){ //if(swiper.isEnd){console.log('going to start');swiper.slideTo(0);} if (swiper.activeIndex == swiperslideslength-2 || swiper.activeIndex == swiperslideslength-1){ $('.blockright_' + currentswiper).hide();$('.blockleft_' + currentswiper).show();} else{ $('.blockright_' + currentswiper).hide();$('.blockleft_' + currentswiper).hide();} } } }, onClick:function(swiper, event) { var ageswiper = swiper.clickedSlide.classList[0].replace("age_", ""); photoBrowser(swiper.clickedIndex,ageswiper);} //pagination:'.swiper-pagination' }); slide_number++; } descriptionslist = []; nameslist = []; $( ".results-loader" ).hide(); if (result == 77 ||(result.length ===1 && result[0].uid == f_uid ) ){ $( ".results-loader" ).hide(); $('.content-here').append( '<div class="no-results-div" style="text-align:center;margin:0 auto;width:300px;position:absolute;top:50%;left:50%;margin-left:-150px;margin-top:-70px;">'+ '<img src="media/datetongue.png" style="width:80px;margin:0 auto;">'+ '<h3>No one is nearby</h3><p style="padding-top:0px;margin-top:-10px;">Try changing your search radius, </br>age range or filters.</p></br>'+ '</div>'); } else { var tonight = new Date(); tonight.setHours(22,59,59,999); var tonight_timestamp = Math.round(tonight/1000); for (i = 0; i < result.length; i++) { var photosstringarray =[]; var photocount; var photostring; var blocked = 0; var subtract = result[i].age; var laston = result[i].timestamp; var industry_d = result[i].industry; var status_d = result[i].status; var politics_d = result[i].politics; var eyes_d = result[i].eyes; var body_d = result[i].body; var religion_d = result[i].religion; var zodiac_d = result[i].zodiac; var ethnicity_d = result[i].ethnicity; var height_d = result[i].height; var weight_d = result[i].weight; var namescount = result[i].displayname.split(' ').length; var matchname; var minphotowidth = $( document ).width(); var imagestyle; imagestyle='width:100%;max-height:' + slidewidth + 'px;overflow:hidden;'; var availarraystring=''; var availnotexpired = false; if(result[i].availstring && (result[i].availstring != '[]') && (result[i].uid != f_uid)){ console.log(result[i].availstring); var availablearrayindividual = JSON.parse(result[i].availstring); console.log(availablearrayindividual); for (k = 0; k < availablearrayindividual.length; k++) { if (availablearrayindividual[k].id >= tonight_timestamp){availnotexpired = true;} } if (availnotexpired){availarraystring = result[i].availstring;} } var profilepicstring; var photoarrayuserlarge; var photoarrayusersmall; if(result[i].largeurl){ var heightarray = result[i].heightslides.split(","); var widtharray = result[i].widthslides.split(","); console.log(heightarray[0]); console.log(widtharray[0]); if (heightarray[0] > widtharray[0]) {imagestyle = 'width:100%;max-height:' + slidewidth + 'px;overflow:hidden;'} if (widtharray[0] > heightarray[0]) {imagestyle = 'height:100%;max-width:' + slidewidth + 'px;overflow:hidden;'} photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical" style="height:100%;"><img data-src="' + result[i].largeurl + '" class="swiper-lazy"></div></div>'; photocount = result[i].largeurl.split(",").length; photoarrayuserlarge = result[i].largeurl.split(","); photoarrayusersmall = result[i].smallurl.split(","); profilepicstringlarge = photoarrayuserlarge[0]; profilepicstringsmall = photoarrayusersmall[0]; photostring=photostring.replace(/,/g, '" class="swiper-lazy" style="height:100%;"></div></div><div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="') } else{ photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="https://graph.facebook.com/'+result[i].uid+'/picture?width=828" class="swiper-lazy" style="height:100%;"></div></div>'; profilepicstringlarge = 'https://graph.facebook.com/'+result[i].uid+'/picture?width=828&height=828'; profilepicstringsmall = 'https://graph.facebook.com/'+result[i].uid+'/picture?width=368&height=368'; photocount = 1; } //console.log(photostring); if(namescount === 1){matchname = result[i].displayname;} else {matchname = result[i].name.substr(0,result[i].displayname.indexOf(' '));} var matchdescription = result[i].description; var swipernumber = subtract - f_lower; var curswiper = $$('.swiper-container')[swipernumber].swiper; var graphid = result[i].uid; var distance = parseFloat(result[i].distance).toFixed(1); var distancerounded = parseFloat(result[i].distance).toFixed(0); if ((distance >= 0) && (distance <0.1)) {distancestring = 'Less than 100 m <span style="font-size:13px;">(328 ft.)</span>'} if ((distance >= 0.1) && (distance <0.2)) {distancestring = 'Less than 200 m <span style="font-size:13px;">(656 ft.)</span>'} if ((distance >= 0.2) && (distance <0.3)) {distancestring = 'Less than 300 m <span style="font-size:13px;">(984 ft.)</span>'} if ((distance >= 0.3) && (distance <0.4)) {distancestring = 'Less than 400 m <span style="font-size:13px;">(1312 ft.)</span>'} if ((distance >= 0.4) && (distance <0.5)) {distancestring = 'Less than 500 m <span style="font-size:13px;">(1640 ft.)</span>'} if ((distance >= 0.5) && (distance <0.6)) {distancestring = 'Less than 600 m <span style="font-size:13px;">(1968 ft.)</span>'} if ((distance >= 0.6) && (distance <0.7)) {distancestring = 'Less than 700 m <span style="font-size:13px;">(2296 ft.)</span>'} if ((distance >= 0.7) && (distance <0.8)) {distancestring = 'Less than 800 m <span style="font-size:13px;">(2624 ft.)</span>'} if ((distance >= 0.8) && (distance <0.9)) {distancestring = 'Less than 900 m <span style="font-size:13px;">(2953 ft.)</span>'} if ((distance >= 0.9) && (distance <1.0)) {distancestring = 'Less than 1 km <span style="font-size:13px;">(3280 ft.)</span>'} if ((distance >= 1.0) && (distance <1.609344)) {distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 3280.84) + ' ft.)</span>'} if (distance > 1.609344){distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 0.621371) + ' mi.)</span>'} var zz = new Date(); var mmn = zz.getTimezoneOffset(); console.log(result[i].timestamp); var timestampyear = result[i].timestamp.substring(0,4); var timestampmonth = result[i].timestamp.substring(5,7); var timestampday = result[i].timestamp.substring(8,10); var timestamphour = result[i].timestamp.substring(11,13); var timestampminute = result[i].timestamp.substring(14,16); var timestampsecond = result[i].timestamp.substring(17,20); var timestampunix=(new Date(timestampmonth + '/' + timestampday + '/' + timestampyear + ' ' + timestamphour + ':' + timestampminute + ':' + timestampsecond)).getTime() / 1000 + 64800; var d_unix = Math.round(+new Date()/1000); var diff = (d_unix - timestampunix)/60; var activecircle; if (diff<11){activecircle = '<span style="position:absolute;left:10px;height:10px;width:10px;border-radius:50%;bottom:10px;background-color:#4cd964"></span>';} else{activecircle = '<span style="position:absolute;left:10px;bottom:10px;height:10px;width:10px;border-radius:50%;background-color:transparent;border:1px solid #ccc;"></span>';} if ($('.slide_' + graphid).length){ var classremove = $('.slide_' + graphid).attr("class").split(' '); var agej = classremove[0].replace("age_", ""); for (var k = 0; i <= all_matches_photos[agej].length; k++) { if (all_matches_photos[agej][k].url == 'https://graph.facebook.com/'+graphid+'/picture?type=large'){all_matches_photos[agej].splice(k, 1);} } $('.slide_' + graphid).remove(); var slidesleft = $(".age_" + agej ).length; if (slidesleft === 0) { $('.swiper-' + agej).hide(); $('.header_' + agej).hide(); } } if (graphid != f_uid){ $('.swiper-' + subtract).show(); $('.header_' + subtract).show(); } var blockedid = blocklist.indexOf(graphid); //Do not show the users profile to themselves, and do not show profiles older than 1 month if ((graphid != f_uid) && (blockedid < 0) && (diff < 43800)){ var index1 = f_date_match.indexOf(graphid); var index2 = f_duck_match.indexOf(graphid); var index3 = f_duck_me.indexOf(graphid); var index4 = f_date_me.indexOf(graphid); var slidecontent; if (index1 > -1) { slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+graphid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:10px;top:0px;" class="arrowdivhome_'+graphid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#2196f3;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" class="swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" onload="$(this).fadeIn(700);mainLoaded(\''+graphid+'\');" style="display:none;'+imagestyle+'-webkit-filter:none;overflow:hidden;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/datefaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;">'+matchname+'</p></div></div>'; } else if (index2 > -1) { slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+graphid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:10px;top:0px;" class="arrowdivhome_'+graphid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#2196f3;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="$(this).fadeIn(700);mainLoaded(\''+graphid+'\');" class="swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:none;display:none;overflow:hidden;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/duckfaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;">'+matchname+'</p></div></div>'; } else if (index3 > -1) { slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+graphid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:10px;top:0px;" class="arrowdivhome_'+graphid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="$(this).fadeIn(700);mainLoaded(\''+graphid+'\');" class="swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;-webkit-filter:grayscale(1%);display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/duckfaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;">'+matchname+'</p></div></div>'; } else if (index4 > -1) { slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+graphid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="float" class="arrowdivhome_'+graphid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="$(this).fadeIn(700);mainLoaded(\''+graphid+'\');" class="swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;-webkit-filter:grayscale(1%);display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/datefaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;">'+matchname+'</p></div></div>'; } else { slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+graphid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:10px;top:0px;" class="arrowdivhome_'+graphid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="$(this).fadeIn(700);mainLoaded(\''+graphid+'\');" class="swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+graphid+'"></div>'+activecircle+'<p class="name_'+graphid+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-top:-30px;color:white;font-size:15px;text-align:left;float:left;margin-left:23px;">'+matchname+'</p></div></div>'; } if( all_matches_photos[subtract].length === 0){curswiper.appendSlide(slidecontent); all_matches_photos[subtract].push({widthslides:result[i].widthslides,heightslides:result[i].heightslides,availarraystring:availarraystring,minutes:diff,distancenumber:distance,distancestring:distancestring,photocount:photocount,photos:photostring,name:matchname,age:subtract,description:matchdescription,id:graphid,url:'https://graph.facebook.com/'+graphid+'/picture?width=828',caption:'...',industry: industry_d, status: status_d, politics:politics_d,eyes:eyes_d,body:body_d,religion:religion_d,zodiac:zodiac_d,ethnicity:ethnicity_d,height:height_d,weight:weight_d}); } else { if(sortby=='random'){ var insertindex = Math.floor(Math.random() * all_matches_photos[subtract].length) +0; insertAfterNthChild($('.wrapper_' + subtract), insertindex, slidecontent); all_matches_photos[subtract].splice(insertindex, 0, {widthslides:result[i].widthslides,heightslides:result[i].heightslides,availarraystring:availarraystring,minutes:diff,distancestring:distancestring,distancenumber:distance,photocount:photocount,photos:photostring,name:matchname,age:subtract,description:matchdescription,id:graphid,url:'https://graph.facebook.com/'+graphid+'/picture?width=828',caption:'...',industry: industry_d, status: status_d, politics:politics_d,eyes:eyes_d,body:body_d,religion:religion_d,zodiac:zodiac_d,ethnicity:ethnicity_d,height:height_d,weight:weight_d}); } if(sortby=='distance' || sortby == 'activity'){ curswiper.appendSlide(slidecontent); all_matches_photos[subtract].push({widthslides:result[i].widthslides,heightslides:result[i].heightslides,availarraystring:availarraystring,minutes:diff,distancestring:distancestring,distancenumber:distance,photocount:photocount,photos:photostring,name:matchname,age:subtract,description:matchdescription,id:graphid,url:'https://graph.facebook.com/'+graphid+'/picture?width=828',caption:'...',industry: industry_d, status: status_d, politics:politics_d,eyes:eyes_d,body:body_d,religion:religion_d,zodiac:zodiac_d,ethnicity:ethnicity_d,height:height_d,weight:weight_d}); } } //curswiper.slideNext(); //console.log('herenext'); if (all_matches_photos[subtract][0].id == graphid || all_matches_photos[subtract][1].id == graphid || all_matches_photos[subtract][2].id == graphid){ $(".photo_"+graphid).attr("src", profilepicstringsmall); } // all_matches_photos[subtract].push({url:'https://graph.facebook.com/'+graphid+'/picture?type=large',caption:'...'}); //all_matches_photos[subtract].push({url:'https://graph.facebook.com/'+graphid+'/picture?type=large',caption:'...'}); //all_matches_photos[subtract].unshift({url:'https://graph.facebook.com/'+graphid+'/picture?type=large',caption:'...'}); } } } var swiperselector=0; for (var i = f_lower; i <= f_upper; i++) { console.log(all_matches_photos[i].length); if (all_matches_photos[i].length >1){$('.single_'+i).hide();$('.multiple_'+i).show();}else{$('.single_'+i).show();$('.multiple_'+i).hide();} if (all_matches_photos[i].length ===0){$( ".swiper-"+i ).hide();} $$('.swiper-container')[swiperselector].swiper.updateContainerSize(); $$('.swiper-container')[swiperselector].swiper.updateProgress(); $$('.swiper-container')[swiperselector].swiper.updateSlidesSize(); $$('.swiper-container')[swiperselector].swiper.updateClasses(); //$$('.swiper-container')[swiperselector].swiper.slideTo(0); //$('.swiper-container')[swiperselector].swiper.appendSlide('<div style="width:'+slidewidth+'px;"><img src="media/datetongue.png" style="width:50px;left:50%;top:50%;margin-left:-25px;margin-top:-25px;"></div>') swiperselector ++; for (var j = 0; j < all_matches_photos[i].length; j++) { new_all.push(all_matches_photos[i][j]); } } if (new_all.length === 0){ $( ".results-loader" ).hide(); $('.content-here').append( '<div class="no-results-div" style="text-align:center;margin:0 auto;width:300px;position:absolute;top:50%;left:50%;margin-left:-150px;margin-top:-70px;">'+ '<img src="media/datetongue.png" style="width:80px;margin:0 auto;">'+ '<h3>No one is nearby</h3><p style="padding-top:0px;margin-top:-10px;">Try changing your search radius, </br>age range or filters.</p></br>'+ '</div>'); } }); //here is the id token call }).catch(function(error) { // Handle error }); $( ".ploader" ).hide(); $( ".toolbar" ).show(); $( ".loginbutton" ).show(); $( ".login-loader" ).hide(); $('.no-results-div').empty(); clearInterval(refreshIntervalId); deletePhotos(); } function justGeo(){ firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/updatelocation.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,latitude:latitudep,longitude:longitudep} ) .done(function( data ) { console.log('updatedtimestamp'); }); }).catch(function(error) { // Handle error }); } function updateGeo(){ firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/updatelocation.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,latitude:latitudep,longitude:longitudep} ) //$.post( "updatelocation.php", { uid:f_uid,latitude:latitudep,longitude:longitudep} ) .done(function( data ) { console.log('update lcoation'+data); getMatches(); }); }).catch(function(error) { // Handle error }); //var matchesRef = firebase.database().ref(sexuality + '/'+ f_age); //var geoFire = new GeoFire(matchesRef); //geoFire.set(f_uid + '*' + f_age + '*' + f_first, [latitudep, longitudep]).then(function() { //}, function(error) { //}); } function getPreferences(){ // Test if user exists if(userpref) {firebase.database().ref('users/' + f_uid).off('value', userpref);} userpref = firebase.database().ref('users/' + f_uid).on("value",function(snapshot) { var userexists = snapshot.child('lower').exists(); // true if (userexists) { // var matchessetting = firebase.database().ref("users/" + f_uid).on("value",function(snapshot) { // if (!snapshot.child("to_date").val()) {f_to_date = [];} // else{f_to_date = snapshot.child("to_date").val();} // if (!snapshot.child("to_duck").val()) {f_to_duck = [];} // else{f_to_duck = snapshot.child("to_duck").val();} // if (!snapshot.child("date_me").val()) {f_date_me = [];} // else{f_date_me = snapshot.child("date_me").val();} // if (!snapshot.child("duck_me").val()) {f_duck_me=[];} // else{f_duck_me = snapshot.child("duck_me").val();} // incommondate = f_to_date.filter(function(n) { // return f_date_me.indexOf(n) != -1; //}); //incommonduck = f_to_duck.filter(function(n) { // return f_duck_me.indexOf(n) != -1; //}); // }); industry_u = snapshot.child("industry").val(); status_u = snapshot.child("status").val(); politics_u = snapshot.child("politics").val(); eyes_u = snapshot.child("eyes").val(); body_u = snapshot.child("body").val(); religion_u = snapshot.child("religion").val(); zodiac_u = snapshot.child("zodiac").val(); ethnicity_u = snapshot.child("ethnicity").val(); height_u = snapshot.child("height").val(); weight_u = snapshot.child("weight").val(); homewant = snapshot.child("homewant").val(); if(homewant){ if (homewant == 'offline'){$( ".homedate" ).removeClass('active');$( ".homeduck" ).removeClass('active'); } if (homewant == 'dateduck'){$( ".homedate" ).addClass('active');$( ".homeduck" ).addClass('active'); } if (homewant == 'duck'){$( ".homedate" ).removeClass('active');$( ".homeduck" ).addClass('active'); } if (homewant == 'date'){$( ".homedate" ).addClass('active');$( ".homeduck" ).removeClass('active'); } } sortby = snapshot.child("sort").val(); if (snapshot.child("offsounds").val()){offsounds = snapshot.child("offsounds").val();} if (snapshot.child("availstring").val()){ availarray = JSON.parse(snapshot.child("availstring").val());} f_description = snapshot.child("description").val(); f_lower = snapshot.child("lower").val(); radiussize = snapshot.child("radius").val(); f_token = snapshot.child("token").val(); f_upper = snapshot.child("upper").val(); f_interested = snapshot.child("interested").val(); f_gender = snapshot.child("gender").val(); f_age = snapshot.child("age").val(); if (f_gender == 'Male' && f_interested == 'Men') {sexuality = 'gay';} if (f_gender == 'Male' && f_interested == 'Women') {sexuality = 'male';} if (f_gender == 'Female' && f_interested == 'Women') {sexuality = 'lesbian';} if (f_gender == 'Female' && f_interested == 'Men') {sexuality = 'female';} if (loadpref=== false){ loadpref = true; establishNotif(); } matchesListener(); } else if (!userexists) { addUser(); if (loadpref=== false){ firebase.database().ref('users/' + f_uid).once("value",function(snapshot) { f_token = snapshot.child("token").val(); swipePopup(2); }); //preferencesPopup(); } loadpref = true; } }); } function matchesListener(){ if (loaded === true){ firebase.database().ref("matches/" + f_uid).off('value', matcheslistener); } matcheslistener = firebase.database().ref("matches/" + f_uid).on("value",function(snapshot) { f_to_date = [],f_to_duck = [],f_date_me = [],f_duck_me = [],f_date_match = [],f_duck_match = [],f_date_match_data = [],f_duck_match_data = []; blocklist = []; if (snapshot.val()){ var objs = snapshot.val(); $.each(objs, function(i, obj) { if ((obj.first_number == f_uid) && (obj.firstnumberblock == 'Y' || obj.secondnumberblock == 'Y')) {blocklist.push(obj.second_number);} if ((obj.second_number == f_uid) && (obj.firstnumberblock == 'Y' || obj.secondnumberblock == 'Y')) {blocklist.push(obj.first_number);} if(obj.firstnumberdate){ //f_to_date if ((obj.first_number == f_uid) && (obj.firstnumberdate == 'Y')) {f_to_date.push(obj.second_number);} //f_date_me if ((obj.first_number != f_uid) && (obj.firstnumberdate == 'Y')) {f_date_me.push(obj.first_number);} } if(obj.firstnumberduck){ //f_duck_me if ((obj.first_number != f_uid) && (obj.firstnumberduck == 'Y')) {f_duck_me.push(obj.first_number);} //f_to_duck if ((obj.first_number == f_uid) && (obj.firstnumberduck == 'Y')) {f_to_duck.push(obj.second_number);} } if(obj.secondnumberdate){ //f_to_date if ((obj.second_number == f_uid) && (obj.secondnumberdate == 'Y')) {f_to_date.push(obj.first_number);} //f_date_me if ((obj.second_number != f_uid) && (obj.secondnumberdate == 'Y')) {f_date_me.push(obj.second_number);} } if(obj.secondnumberduck){ //f_to_duck if ((obj.second_number == f_uid) && (obj.secondnumberduck == 'Y')) {f_to_duck.push(obj.first_number);} //f_duck_me if ((obj.second_number != f_uid) && (obj.secondnumberduck == 'Y')) {f_duck_me.push(obj.second_number);} } if(obj.firstnumberdate && obj.secondnumberdate){ //f_date_match if(((obj.first_number != f_uid) && (obj.firstnumberdate == 'Y')) && ((obj.second_number == f_uid) && (obj.secondnumberdate == 'Y'))){f_date_match.push(obj.first_number);f_date_match_data.push({uid:obj.first_number,name:obj.first_name});} if(((obj.second_number != f_uid) && (obj.secondnumberdate == 'Y')) && ((obj.first_number == f_uid) && (obj.firstnumberdate == 'Y'))){f_date_match.push(obj.second_number);f_date_match_data.push({uid:obj.second_number,name:obj.second_name});} } if(obj.firstnumberduck && obj.secondnumberduck){ //f_duck_match if(((obj.first_number != f_uid) && (obj.firstnumberduck == 'Y')) && ((obj.second_number == f_uid) && (obj.secondnumberduck == 'Y'))){f_duck_match.push(obj.first_number);f_duck_match_data.push({uid:obj.first_number,name:obj.first_name});} if(((obj.second_number != f_uid) && (obj.secondnumberduck == 'Y')) && ((obj.first_number == f_uid) && (obj.firstnumberduck == 'Y'))){f_duck_match.push(obj.second_number);f_duck_match_data.push({uid:obj.second_number,name:obj.second_name});} } }); updatePhotos(); loaded = true; } else{ updatePhotos(); loaded = true; } }); $( ".content-here" ).empty(); $( ".results-loader" ).show(); getWifilocation(); } function addUser() { if (f_token){firebase.database().ref('users/' + f_uid).update({ name: f_name, email: f_email, image_url : f_image, uid:f_uid, token:f_token, auth_id : f_auth_id });} else{ firebase.database().ref('users/' + f_uid).update({ name: f_name, email: f_email, image_url : f_image, uid:f_uid, auth_id : f_auth_id }); } } function clickMe() { pickerDescribe.open(); } function keyUp(){ if (sexuality){processUpdate(); myApp.sizeNavbars(); } var inputlength = $( "#userdescription" ).val().length; $( "#maxdescription" ).empty(); $( "#maxdescription" ).append(inputlength + " / 100"); } function updateUser(){ if ((pickerDescribe.initialized === false && !f_age) || (pickerDescribe2.initialized === false && !f_lower)) { myApp.alert('Please complete more profile information.', 'Missing Information'); return false;} if (myswiperphotos){ myswiperphotos.destroy(); myswiperphotos = false; } var newage,newinterested,newgender; if (pickerDescribe.initialized === false) {newage = f_age;newgender = f_gender;} else {newage = pickerDescribe.value[1];newgender = pickerDescribe.value[0];} if (pickerDescribe2.initialized === false) {newinterested = f_interested;} else {newinterested = pickerDescribe2.value[0];} var userzdescription; if ($( "#userdescription" ).val()) {userzdescription = $( "#userdescription" ).val();} else {userzdescription = '';} //Need to delete old reference if (pickerDescribe.initialized === true) {f_age = pickerDescribe.value[1];f_gender = pickerDescribe.value[0];} if (pickerDescribe2.initialized === true) {f_interested = pickerDescribe2.value[0];} if (f_gender == 'Male' && f_interested == 'Men') {sexuality = 'gay';} if (f_gender == 'Male' && f_interested == 'Women') {sexuality = 'male';} if (f_gender == 'Female' && f_interested == 'Women') {sexuality = 'lesbian';} if (f_gender == 'Female' && f_interested == 'Men') {sexuality = 'female';} var lowerage,upperage; if (pickerDescribe2.initialized === true) { if (pickerDescribe2.value[1] > pickerDescribe2.value[2]) {lowerage = pickerDescribe2.value[2];upperage = pickerDescribe2.value[1];} else {lowerage = pickerDescribe2.value[1];upperage = pickerDescribe2.value[2];} } else {lowerage = f_lower;upperage = f_upper;} if ($( "#distance_10" ).hasClass( "active" )){radiussize = '10';} if ($( "#distance_25" ).hasClass( "active" )){radiussize = '25';} if ($( "#distance_50" ).hasClass( "active" )){radiussize = '50';} if ($( "#distance_100" ).hasClass( "active" )){radiussize = '100';} if ($( "#sortrandom" ).hasClass( "active" )){sortby = 'random';} if ($( "#sortdistance" ).hasClass( "active" )){sortby = 'distance';} if ($( "#sortactivity" ).hasClass( "active" )){sortby = 'activity';} availarray = []; $( ".availrec" ).each(function() { if ($( this ).hasClass( "selecrec" )){ var availinputid = $(this).attr('id').replace('aa_', ''); var valueinputted = $( "#picker"+availinputid ).val(); var supdate = $( ".suppdate_"+availinputid ).val(); if (valueinputted == 'Now'){daysaved ='Now';timesaved='';} else{ valueinputted = valueinputted.split(' '); var daysaved = valueinputted[0]; var timesaved = valueinputted[1]; } availarray.push({id:availinputid,day:daysaved,time:timesaved,fulldate:supdate}); } }); var availstring = JSON.stringify(availarray); var availstringn = availstring.toString(); if ($('#soundnotif').prop('checked')) {offsounds = 'Y'} else {offsounds = 'N'} //User Profile details var industry_u = $( "#industry-input" ).val(); var status_u = $( "#status-input" ).val(); var politics_u = $( "#politics-input" ).val(); var eyes_u = $( "#eyes-input" ).val(); var body_u = $( "#body-input" ).val(); var religion_u = $( "#religion-input" ).val(); var zodiac_u = $( "#zodiac-input" ).val(); var ethnicity_u = $( "#ethnicity-input" ).val(); var height_u = $( "#height-input" ).val().substring(0,3); var weight_pre = $( "#weight-input" ).val(); var weight_u = weight_pre.substr(0, weight_pre.indexOf(' ')); console.log(status_u); firebase.database().ref('users/' + f_uid).update({ gender: newgender, industry:industry_u, status:status_u, politics: politics_u,eyes: eyes_u,body: body_u,religion: religion_u,zodiac: zodiac_u,ethnicity: ethnicity_u, height: height_u, weight: weight_u, age: newage, interested: newinterested, lower: lowerage, upper: upperage, description:userzdescription, radius:radiussize, sort:sortby, availstring:availstring, offsounds:offsounds }); if (deletedphoto){ var newsmall = f_smallurls.toString(); var newlarge = f_largeurls.toString(); var newwidth = addedwidth.toString(); var newheight = addedheight.toString(); console.log('there was a deleted photo'); firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} ) .done(function( data ) { console.log(data); }); }).catch(function(error) { // Handle error }); } var industry_u = $( "#industry-input" ).val(); var status_u = $( "#status-input" ).val(); var politics_u = $( "#politics-input" ).val(); var eyes_u = $( "#eyes-input" ).val(); var body_u = $( "#body-input" ).val(); var religion_u = $( "#religion-input" ).val(); var zodiac_u = $( "#zodiac-input" ).val(); var ethnicity_u = $( "#ethnicity-input" ).val(); var height_u = $( "#height-input" ).val().substring(0,3); var weight_pre = $( "#weight-input" ).val(); var weight_u = weight_pre.substr(0, weight_pre.indexOf(' ')); firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "updatedetails.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,sexuality:sexuality,uid:f_uid,name:f_name,description:userzdescription,age:newage,availstring:availstringn,industry:industry_u,status:status_u,politics:politics_u,eyes:eyes_u,body:body_u,religion:religion_u,zodiac:zodiac_u,ethnicity:ethnicity_u,height:height_u,weight:weight_u} ) .done(function( data ) { console.log('didan update'); console.log(data); //if (f_gender && (f_gender != newgender)){ //deleteDatabase(); //} //if (f_interested && (f_interested != newinterested)){ //deleteDatabase(); //} }); }).catch(function(error) { // Handle error }); f_lower = lowerage; f_upper = upperage; //if (loadpref2===true){getWifilocation();} loadpref2 = true; myApp.closeModal(); $( ".popup-overlay" ).remove(); } function processUpdate(){ $( '.donechange' ).show(); $( '.doneunchange' ).hide(); } function processDupdate(){ var unixnow = Math.round(+new Date()/1000); var middaystamp = new Date(); middaystamp.setHours(12,00,00,000); var middaystamp_timestamp = Math.round(middaystamp/1000); var threestamp = new Date(); threestamp.setHours(12,00,00,000); var threestamp_timestamp = Math.round(threestamp/1000); var fivestamp = new Date(); fivestamp.setHours(17,00,00,000); var fivestamp_timestamp = Math.round(fivestamp/1000); if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Morning') && (unixnow>middaystamp_timestamp)){myApp.alert('You must choose a time in the future', pickerCustomToolbar.cols[1].displayValue +' has past!');pickerCustomToolbar.cols[1].setValue('');return false;} if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Mid-day') && (unixnow>threestamp_timestamp)){myApp.alert('You must choose a time in the future', pickerCustomToolbar.cols[1].displayValue +' has past!');pickerCustomToolbar.cols[1].setValue('');return false;} if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Afternoon') && (unixnow>fivestamp_timestamp)){myApp.alert('You must choose a time in the future', pickerCustomToolbar.cols[1].displayValue +' has past!');pickerCustomToolbar.cols[1].setValue('');return false;} if (d_chat_expire){ var datemessageq = $( '#datemessageq' ).val(); var interestnewarray = []; $( ".interestbutton" ).each(function() { if ($( this ).hasClass( "interestchosen" )) { var classList = $(this).attr("class").split(' '); var interestadd = classList[1].split('_')[0]; interestnewarray.push(interestadd); } }); var comparedinterest; var compareninterest; if (d_interest != null) { comparedinterest = d_interest.toString(); } else {comparedinterest = '';} if (typeof interestnewarray == 'undefined' && interestnewarray.length === 0){compareninterest = '';}else{compareninterest = interestnewarray.toString();} if ((d_day == pickerCustomToolbar.cols[0].displayValue) && (d_time ==pickerCustomToolbar.cols[1].displayValue) && (datemessageq == '' ) && (compareninterest == comparedinterest)) { if (d_response=='Y'){noChange();} else if (d_response=="W"){reverseRequest();dateConfirmationPage();} } else{dateRequest();} } else {dateRequest();} } var mynotifs = []; function leftPanel(){ canscrollnotif = true; mynotifs = []; notifadditions=0; if(!myList){ myList = myApp.virtualList('.virtual-notifications', { // Array with plain HTML items items: [], height:89, renderItem: function (index, item) { var backgroundnotifcolor; if(item.colordot == ''){backgroundnotifcolor = 'white';}else{backgroundnotifcolor = 'transparent';} if(item.from_uid == f_uid){ return '<li class="item-content" style="height:89px;background-color:'+backgroundnotifcolor+'">' + '<div class="item-media" onclick="singleUser('+item.targetid+',\''+item.targetname+'\',1)" style="width:50px;height:50px;border-radius:50%;background-image:url('+item.picture+');background-size:cover;background-position:50% 50%;">'+ '</div>' + '<div class="item-inner" onclick="'+item.func+'('+item.targetid+',\''+item.targetname+'\')" style="margin-left:10px;" >' + '<div class="item-title-row" >'+ '<div class="item-title" style="font-size:14px;margin-top:5px;">'+item.targetname+'</div>'+ '<div class="item-after"><img src="media/'+item.type+'faceonly.png" style="width:30px;"></div>'+ '</div>'+ '<div class="item-subtitle">'+ item.icon + item.title + ' </div>' + '<div class="item-text" style="height:20.8px">'+ item.timestamptitle + ' </div>' + '</div>' + '</li>'; } else{ //onclick="singleBrowser('+item.targetid+')" return '<li class="item-content" style="height:89px;background-color:'+backgroundnotifcolor+'">' + '<div class="item-media" onclick="singleUser('+item.targetid+',\''+item.targetname+'\',1)" style="width:50px;height:50px;border-radius:50%;background-image:url('+item.picture+');background-size:cover;background-position:50% 50%;">'+ '</div>' + '<div class="item-inner" onclick="'+item.func+'(\''+item.targetid+'\',\''+item.targetname+'\')" style="margin-left:10px;" >' + '<div class="item-title-row" >'+ '<div class="item-title" style="font-size:14px;margin-top:5px;">'+item.targetname+item.colordot+'</div>'+ '<div class="item-after"><img src="media/'+item.type+'faceonly.png" style="width:30px;"></div>'+ '</div>'+ '<div class="item-subtitle" style="color:black;">'+ item.icon + item.title + ' </div>' + '<div class="item-text" style="height:20.8px">'+ item.timestamptitle + ' </div>' + '</div>' + '</li>'; } } }); } var notificationlist = firebase.database().ref('notifications/' + f_uid).once('value', function(snapshot) { if (snapshot.val() === null){ // $('.title-notify').remove(); // $('.virtual-notifications').append('<div class="content-block-title title-notify" style="margin-top:54px;">No notifications</div>'); $('.nonefound').remove(); $('.virtual-notifications').prepend('<div class="content-block-title nonefound" style="margin: 0 auto;margin-top:10px;text-align:center;">No Matches Yet</div>'); } //If existing notifications, get number of unseen messages, delete old notifications if (snapshot.val()){ $('.nonefound').remove(); var objs = snapshot.val(); var obg = []; $.each(objs, function(i, obk) {obg.push (obk)}); console.log(obg); function compare(a,b) { if (a.timestamp > b.timestamp) return -1; if (a.timestamp < b.timestamp) return 1; return 0; } obg.sort(compare); $.each(obg, function(i, obj) { var typetype = obj.type.substring(0, 4); var correctimage; var correctname; var iconhtml; var colordot; var message_text; var func; var mediaicon; var dateseenresponse; if (typetype == 'date') {mediaicon = fdateicon;} if (typetype == 'duck') {mediaicon = fduckicon;} //need to see if a match still and then create function based on tha var timestamptitle; var unixnow = Math.round(+new Date()/1000); var tunixago = unixnow - obj.timestamp; var tunixminago = tunixago / 60; if (tunixminago < 1) {timestamptitle = '1 minute ago';} else if (tunixminago == 1) {timestamptitle = '1 minute ago';} else if (tunixminago < 2) {timestamptitle = '1 minute ago';} else if (tunixminago < 60) {timestamptitle = Math.round(tunixminago)+' minutes ago';} else if (tunixminago == 60) {timestamptitle = '1 hour ago';} else if (tunixminago < 62) {timestamptitle = '1 hour ago';} else if (tunixminago < 1440) {timestamptitle = Math.round(tunixminago / 60) +' hours ago';} else if (tunixminago == 1440) {timestamptitle = '1 day ago';} else if (tunixminago < 2880) {timestamptitle = '1 day ago';} else if (tunixminago >= 2880) {timestamptitle = Math.round(tunixminago / 1440) +' days ago';} else if (tunixminago == 10080) {timestamptitle = '1 week ago';} else if (tunixminago < 20160) {timestamptitle = '1 week ago';} else if (tunixminago >= 20160) {timestamptitle = Math.round(tunixminago / 10080) +' weeks ago';} else if (tunixminago == 525600) {timestamptitle = '1 week ago';} else if (tunixminago < (525600*2)) {timestamptitle = '1 week ago';} else if (tunixminago >= (525600*2)) {timestamptitle = Math.round(tunixminago / 525600) +' years ago';} // onclick="singleBrowser('+targetid+')" if (obj.param=='message'){message_text = obj.message; iconhtml = '<i class="pe-7s-mail pe-lg" style="margin-right:5px;z-index:9999;"></i>'} if (obj.param=='image'){ if (obj.from_uid == f_uid){message_text = obj.message + 'sent';} else {message_text = obj.message + 'received';} iconhtml = '<i class="pe-7s-camera pe-lg" style="margin-right:5px;z-index:9999;"></i>';} if (obj.param=='daterequest'){ if (obj.from_uid == f_uid){message_text = obj.message + ' sent';} else {message_text = obj.message + ' received';} iconhtml = '<i class="pe-7s-date pe-lg" style="margin-right:5px;z-index:9999;"></i>'; } if (obj.param=='datedeleted'){ if (obj.from_uid == f_uid){message_text = obj.message;} else {message_text = obj.message;} iconhtml = '<i class="pe-7s-date pe-lg" style="margin-right:5px;z-index:9999;"></i>'; } if (obj.param=='newmatch'){ if (obj.from_uid == f_uid){message_text = obj.message;} else {message_text = obj.message;} iconhtml = '<i class="pe-7s-like pe-lg" style="margin-right:5px;z-index:9999;"></i>'; } if (obj.param=='dateconfirmed'){ message_text = obj.message; iconhtml = '<i class="pe-7f-date pe-lg" style="margin-right:5px;z-index:9999;"></i>'; } // if(obj.received=='N' && (obj.param=='datedeleted' || obj.param=='newmatch')){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;">'ssage_count+'</span>';} else{colordot = '';} // if(obj.received=='N' && (obj.param!='datedeleted' && obj.param!='newmatch')){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;">'+obj.new_message_count+'</span>';} else{colordot = '';} if(obj.received=='N' && (obj.param=='message' || obj.param=='image')){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;">'+obj.new_message_count+'</span>';} else if(obj.received=='N'){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;width:12px;height:12px;"></span>';} else{colordot = '';} if (obj.from_uid == f_uid){correctimage = String(obj.to_uid);correctname = String(obj.to_name);colordot = '';} else {correctimage = String(obj.from_uid);correctname = String(obj.from_name);image_after = 'received';} datemeinarray=0; duckmeinarray=0; datetoinarray=0; ducktoinarray=0; var datesto = f_to_date.indexOf(correctimage); if (datesto > -1) { datetoinarray=1; } var datesme = f_date_me.indexOf(correctimage); if (datesme > -1) { datemeinarray=1; } var duckto = f_to_duck.indexOf(correctimage); if (duckto > -1) { ducktoinarray=1; } var duckme = f_duck_me.indexOf(correctimage); if (duckme > -1) { duckmeinarray=1; } if ((datemeinarray==1 && datetoinarray==1) || (duckmeinarray==1 && ducktoinarray==1)) { if (typetype == 'date') {func = 'createDate1';} if (typetype == 'duck') {func = 'createDuck';} } else{func = 'singleUser'} mynotifs.push({ title: message_text, targetid:correctimage, targetname:correctname, picture:'https://graph.facebook.com/'+correctimage+'/picture?type=normal', from_name: obj.from_name, to_name: obj.to_name, from_uid: obj.from_uid, to_uid: obj.to_uid, icon:iconhtml, colordot:colordot, func:func, type:typetype, timestamptitle:timestamptitle }); }); var notif2load = mynotifs.length; if (notif2load > 12) {notifletsload = 12;} else {notifletsload = notif2load;} for (i = 0; i < notifletsload; i++) { myList.appendItem({ title: mynotifs[i].title, targetid:mynotifs[i].targetid, targetname:mynotifs[i].targetname, picture:mynotifs[i].picture, from_name: mynotifs[i].from_name, to_name: mynotifs[i].to_name, from_uid:mynotifs[i].from_uid, to_uid: mynotifs[i].to_uid, icon:mynotifs[i].icon, colordot:mynotifs[i].colordot, func:mynotifs[i].func, type:mynotifs[i].type, timestamptitle:mynotifs[i].timestamptitle }); } } }); } function rightPanel(){ $('.timeline-upcoming').empty(); $('.right-title').text('Calendar'); $('.addcreatebutton').show(); $('.backcreatebutton').hide(); myApp.sizeNavbars(); var rightdates = []; var month = []; month[0] = "JAN"; month[1] = "FEB"; month[2] = "MAR"; month[3] = "APR"; month[4] = "MAY"; month[5] = "JUN"; month[6] = "JUL"; month[7] = "AUG"; month[8] = "SEP"; month[9] = "OCT"; month[10] = "NOV"; month[11] = "DEC"; var weekday = []; weekday[0] = "SUN"; weekday[1] = "MON"; weekday[2] = "TUE"; weekday[3] = "WED"; weekday[4] = "THU"; weekday[5] = "FRI"; weekday[6] = "SAT"; var timelinedates = firebase.database().ref('/dates/' + f_uid).once('value').then(function(snapshot) { var objs = snapshot.val(); $('.timeline-upcoming').empty(); if (snapshot.val() === null){ $('.timeline').append('<div class="content-block-title" style="margin: 0 auto;text-align:center;">Calendar is empty</div>'); } //If existing notifications, get number of unseen messages, delete old notifications if (snapshot.val()){ $.each(objs, function(i, obj) { rightdates.push(obj); }); rightdates.sort(compare); for (i = 0; i < rightdates.length; i++) { var correctname; var correctid; if (rightdates[i].created_uid == f_uid) {correctname = rightdates[i].received_name;correctid = rightdates[i].received_uid;} if (rightdates[i].created_uid != f_uid) {correctname = rightdates[i].created_name;correctid = rightdates[i].created_uid;} var unix = Math.round(+new Date()/1000); var c = new Date(rightdates[i].chat_expire*1000); var cday = weekday[c.getDay()]; if ((rightdates[i].created_uid == f_uid || rightdates[i].received_uid == f_uid) && (rightdates[i].chat_expire > Number(unix)) ){ var d = new Date(rightdates[i].chat_expire*1000 - 3600); var timehere; if (rightdates[i].time) {timehere = ', ' + rightdates[i].time;} else {timehere='';} var timestamptitle; var datetype = rightdates[i].type.capitalize(); var datesidetitle; var dayday = d.getDate(); var monthmonth = month[d.getMonth()]; var subtitletext,confirmtext; if (rightdates[i].response =='Y') { if (rightdates[i].type=='date' ){datesidetitle = 'Date';} if (rightdates[i].type=='duck' ){datesidetitle = 'Duck';} timestamptitle = datesidetitle + ' Confirmed'; var name_accepted; if (rightdates[i].received_uid == f_uid) {name_accepted = 'you ';} else {name_accepted = rightdates[i].received_name;} subtitletext='<div style="font-family: \'Pacifico\', cursive;font-size:17px;background-color:#4cd964;color:white;width:100%;text-align:center;padding-top:5px;padding-bottom:5px;"><i class="pe-7s-check pe-lg" style="color:white"></i></div>'; confirmtext='Date confirmed by '+name_accepted+' on '+cday; } if (rightdates[i].response =='W') { var unixnow = Math.round(+new Date()/1000); var tunixago = unixnow - rightdates[i].timestamp; var tunixminago = tunixago / 60; if (tunixminago < 1) {timestamptitle = 'Sent now';} else if (tunixminago == 1) {timestamptitle = 'Sent 1 min ago';} else if (tunixminago < 2) {timestamptitle = 'Sent 1 min ago';} else if (tunixminago < 60) {timestamptitle = 'Sent '+Math.round(tunixminago)+' mins ago';} else if (tunixminago == 60) {timestamptitle = 'Sent 1 hour ago';} else if (tunixminago < 62) {timestamptitle = 'Sent 1 hour ago';} else if (tunixminago < 1440) {timestamptitle = 'Sent '+Math.round(tunixminago / 60) +' hours ago';} else if (tunixminago == 1440) {timestamptitle = 'Sent 1 day ago';} else if (tunixminago < 2880) {timestamptitle = 'Sent 1 day ago';} else if (tunixminago >= 2880) {timestamptitle = 'Sent '+Math.round(tunixminago / 1440) +' days ago';} if (rightdates[i].created_uid == f_uid) {confirmtext = 'Waiting for '+rightdates[i].received_name+' to respond.';} if (rightdates[i].created_uid != f_uid){confirmtext = rightdates[i].created_name + ' is waiting for your response.';} if (rightdates[i].type=='date' ){datesidetitle = 'Date Request';} if (rightdates[i].type=='duck' ){datesidetitle = 'Duck Request';} subtitletext='<div style="font-family: \'Pacifico\', cursive;font-size:17px;background-color:#ff9500;color:white;width:100%;text-align:center;padding-top:5px;padding-bottom:5px;"><i class="pe-7s-help1 pe-lg" style="color:white"></i></div>';} if ($(".time_line_" + dayday)[0]){ } else { $('.timeline').append('<div class="timeline-item" style="margin-bottom">'+ '<div class="timeline-item-date" style="margin-right:10px;">'+cday+'<br/>'+dayday+' <small> '+monthmonth+' </small></div>'+ //'<div class="timeline-item-divider"></div>'+ '<div class="timeline-item-content time_line_'+dayday+'">'+ '</div>'+ '</div>'); } $('.time_line_'+dayday).append( '<a href="#" onclick="createDate(\''+correctid+'\',\''+correctname+'\')">'+ subtitletext+ // '<div class="timeline-item-time" style="padding:2px;margin-top:0px;background-color:white;border-bottom:1px solid #c4c4c4;text-align:center;padding-top:10px;"><i class="pe-7s-clock pe-lg"></i> //'+weekday[d.getDay()]+ timehere+'<div style="clear:both;" id="interestdatediv_'+correctid+'"></div></div>'+ '<div class="timeline-item-inner" style="min-width:136px;padding:7px;border-radius:0;">'+ '<div class="timeline-item-title" style="color:black;margin-top:5px;text-align:center;"><div style="width:50px;height:50px;margin:0 auto;border-radius:50%;background-size:cover;background-position:50% 50%;background-image:url(\'https://graph.facebook.com/'+correctid+'/picture?type=normal\')"></div><span style="clear:both;">'+correctname+'<span> </div>'+ // '<div style="padding:10px;font-size:13px;"><span style="color:#6d6d72;clear:both;padding-top:-5px;">'+confirmtext+'</span></div>'+ '<div style="text-align:center;clear:both;width:100%;color:#8e8e93;">'+timestamptitle+'</div>'+ '</div>'+ '</a>' ); if(rightdates[i].type=='date'){ //for (k = 0; k < rightdates[i].interest.length; k++) { // $( "#interestdatediv_" + correctid).append('<a href="#" style="margin-right:5px"><i class="twa twa-'+rightdates[i].interest[k]+'" style="margin-top:5px;margin-right:5px"></i></a>'); // } } } } } }); } function newAm(){ $( ".originalam" ).hide(); $( ".newam" ).show(); pickerDescribe.open(); } function newMe(){ $( ".originalme" ).hide(); $( ".newme" ).show(); pickerDescribe2.open(); } var deletedphoto; function getData(){ deletedphoto = false; if(!myswiperphotos){ firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/userdata.php", {projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} ) .done(function( data ) { var result = JSON.parse(data); console.log(result); if (result!='77' && result[0].largeurl){ $( ".reorderbutton" ).removeClass('disabled'); $( ".deleteallbutton" ).removeClass('disabled'); f_smallurls = result[0].smallurl.split(','); f_largeurls = result[0].largeurl.split(','); console.log(result[0].widthslides); console.log(result[0].heightslides); addedwidth = result[0].widthslides.split(','); addedheight = result[0].heightslides.split(','); $( ".photosliderinfo" ).addClass('pictures'); if (f_largeurls.length === 0){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile'); } else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile'); } console.log(f_largeurls.length); for (i = 0; i < f_largeurls.length; i++) { $( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\''+f_largeurls[i]+'\');background-size:cover;background-position:50% 50%;"><div class="button" style="border:0;border-radius:0px;background-color:#ff3b30;color:white;position:absolute;bottom:10px;right:10px;" onclick="deleteIndividual()">Delete Photo</div></div>'); } myswiperphotos = myApp.swiper('.container-photos', { pagination:'.swiper-pagination', paginationType:'progress', direction:'vertical', onInit:function(swiper){$( ".photoswiperloader" ).hide();}, onClick:function(swiper, event){ } }); } else { f_smallurls = []; f_largeurls = []; addedheight = []; addedwidth = []; $( ".wrapper-photos" ).append('<div class="swiper-slide firsthere" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>'); $( ".photosliderinfo" ).removeClass('pictures'); $( ".photosliderinfo" ).html('Add photos to your profile below'); myswiperphotos = myApp.swiper('.container-photos', { pagination:'.swiper-pagination', paginationType:'progress', onInit:function(swiper){$( ".photoswiperloader" ).hide();}, direction:'vertical' }); } }); }).catch(function(error) { // Handle error }); } } function deleteIndividual(){ if (sexuality){processUpdate(); myApp.sizeNavbars(); } if ($( ".photosliderinfo" ).hasClass('pictures')){ myApp.confirm('Are you sure?', 'Delete Photo', function () { myswiperphotos.removeSlide(myswiperphotos.clickedIndex); f_largeurls.splice(myswiperphotos.clickedIndex, 1); f_smallurls.splice(myswiperphotos.clickedIndex, 1); addedwidth.splice(myswiperphotos.clickedIndex, 1); addedheight.splice(myswiperphotos.clickedIndex, 1); console.log(addedwidth); console.log(addedheight); if (f_largeurls.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile'); } else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile'); } deletedphoto = true; myswiperphotos.update(); if (myswiperphotos.slides.length === 0){ $( ".reorderbutton" ).addClass('disabled'); $( ".deleteallbutton" ).addClass('disabled'); $( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>'); $( ".photosliderinfo" ).removeClass('pictures'); $( ".photosliderinfo" ).html('Add photos to your profile below'); myswiperphotos.updatePagination(); myswiperphotos.update(); } }); } else { photosPopup(); } } function openAvaill(availtime){ if ($( '.li_'+ availtime ).hasClass('selecrec')){$( '.li_'+ availtime ).removeClass('selecrec');$( '.li_'+ availtime ).css('selecrec','');$( '#picker'+ availtime ).val('');} else{$( '.li_'+ availtime ).addClass('selecrec');$( '#picker'+ availtime ).val('Now');} } function openAvail(availtime){ $( '.li_'+ availtime ).addClass('selecrec'); } function removeAvail(availtime,availname,availnameonly){ $( '.li_'+ availtime ).removeClass('selecrec'); $('#picker'+availtime ).remove(); $('.readd_'+availtime ).append('<input type="text" placeholder="'+availname+'" readonly id="picker'+availtime+'" style="height:44px;text-align:center;margin-top:-10px;font-size:17px;color:white;"></li>'); myApp.picker({ input: '#picker' + availtime, onOpen: function (p){if (sexuality){processUpdate(); myApp.sizeNavbars(); }}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeAvail(\''+availtime+'\',\''+availname+'\',\''+availnameonly+'\');">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { textAlign: 'left', values: (availnameonly + ',').split(',') }, { textAlign: 'left', values: ('Anytime Morning Midday Afternoon Evening').split(' ') }, ] }); } var availarray = []; function report(){ myApp.prompt('What is the problem?', 'Report '+targetname, function (value) { if (value.length ===0){myApp.alert('You must provide a reason to report ' + targetname, 'What is the problem?');return false;} targetreported = true; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var newPostKey = firebase.database().ref().push().key; var t_unix = Math.round(+new Date()/1000); var targetData = { from_uid: f_uid, from_name: f_first, to_uid:targetid, to_name:targetname, message:value, response:'N', timestamp: t_unix, }; var updates = {}; updates['reports/' + f_uid + '/' + targetid + '/' + newPostKey] = targetData; if (f_uid == first_number){ firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list firstnumberreport:newPostKey, firstnumberreporttime:t_unix }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list firstnumberreport:newPostKey, firstnumberreporttime:t_unix }); } else{ firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list secondnumberreport:newPostKey, secondnumberreporttime:t_unix }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list secondnumberreport:newPostKey, secondnumberreporttime:t_unix }); } return firebase.database().ref().update(updates).then(function() { myApp.alert('We will review your report. We encourage you to block offensive users.', 'Report sent');}); }); $(".modal-text-input").prop('maxlength','50'); } function more(){ var swiperno = 0; myApp.confirm('Are you sure?', 'Block '+targetname, function () { var blockindex = myPhotoBrowser.swiper.activeIndex; var swipertarget = $( ".agecat" ).text(); //agearray var profilesbefore = 0; for (var i = f_lower; i < swipertarget; i++) { swiperno ++; profilesbefore = profilesbefore + all_matches_photos[i].length; } var ageindex = blockindex - profilesbefore; // console.log(all_matches_photos[swipertarget]); // console.log(new_all); all_matches_photos[swipertarget] = all_matches_photos[swipertarget].slice(0,ageindex).concat(all_matches_photos[swipertarget].slice(ageindex+1)); //new all array var firstpos; var lastpos; //alert(blockindex); //alert(new_all.length); if (blockindex == (new_all.length-1)){lastpos = 'Y';} else {lastpos ='N';} if (blockindex == 0){firstpos = 'Y';} else{firstpos ='N';} //alert(firstpos + 'firstpos'); //alert(lastpos + 'lastpos'); new_all = new_all.slice(0,blockindex).concat(new_all.slice(blockindex+1)); //console.log(all_matches_photos[swipertarget]); // console.log(new_all); //remove slide from photobrowser myPhotoBrowser.swiper.removeSlide(blockindex); myPhotoBrowser.swiper.updateSlidesSize() ; //remove from curswiper var realswiperno = swiperno + 1; $$('.swiper-container')[swiperno].swiper.removeSlide(ageindex); $$('.swiper-container')[swiperno].swiper.updateSlidesSize() ; if (all_matches_photos[swipertarget].length ===1) {$( ".single_"+i ).show();$( ".multiple_"+i ).hide();} if (all_matches_photos[swipertarget].length ===0) {$( ".single_"+i ).show();$( ".swiper-"+i ).hide();} myApp.closeModal('.actions-modal'); allowedchange = false; var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var theirnotifs = firebase.database().ref('notifications/' + targetid + '/' + f_uid); theirnotifs.remove().then(function() { console.log("their notifs Remove succeeded.") }) .catch(function(error) { console.log("their notifs failed: " + error.message) }); var mynotifs = firebase.database().ref('notifications/' + f_uid + '/' + targetid); mynotifs.remove().then(function() { console.log("my notifs Remove succeeded.") }) .catch(function(error) { console.log("my notifs failed: " + error.message) }); var theirdates = firebase.database().ref('dates/' + targetid + '/' + f_uid); theirdates.remove().then(function() { console.log("their dates Remove succeeded.") }) .catch(function(error) { console.log("their dates failed: " + error.message) }); var mydates = firebase.database().ref('dates/' + f_uid + '/' + targetid); mydates.remove().then(function() { console.log("my dates Remove succeeded.") }) .catch(function(error) { console.log("my dates failed: " + error.message) }); var ourchats = firebase.database().ref('chats/' + first_number + '/' + second_number); ourchats.remove().then(function() { console.log("Chats Remove succeeded.") }) .catch(function(error) { console.log("Chats Remove failed: " + error.message) }); var ourphotochats = firebase.database().ref('photochats/' + first_number + '/' + second_number); ourphotochats.remove().then(function() { console.log("PhotoChats Remove succeeded.") }) .catch(function(error) { console.log("PhotoChats Remove failed: " + error.message) }); if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid; firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list secondnumberblock:'Y', created:f_uid, received:targetid, first_number:first_number, first_name:targetname, second_number:second_number, second_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberdate:'N', secondnumberduck:'N', firstnumberdate:'N', firstnumberduck:'N' }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list secondnumberblock:'Y', created:f_uid, received:targetid, first_number:first_number, first_name:targetname, second_number:second_number, second_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberdate:'N', secondnumberduck:'N', firstnumberdate:'N', firstnumberduck:'N' }); } else {first_number = f_uid;second_number = targetid; firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list firstnumberblock:'Y', created:f_uid, received:targetid, first_number:first_number, second_name:targetname, second_number:second_number, first_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberdate:'N', secondnumberduck:'N', firstnumberdate:'N', firstnumberduck:'N' }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list firstnumberblock:'Y', created:f_uid, received:targetid, first_number:first_number, second_name:targetname, second_number:second_number, first_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberdate:'N', secondnumberduck:'N', firstnumberdate:'N', firstnumberduck:'N' }); } if (firstpos == 'Y'){myPhotoBrowser.swiper.slideNext();allowedchange = true;myPhotoBrowser.swiper.slidePrev(); } else if (lastpos == 'Y'){myPhotoBrowser.swiper.slidePrev();allowedchange = true;myPhotoBrowser.swiper.slideNext(); } else {myPhotoBrowser.swiper.slideNext();allowedchange = true;myPhotoBrowser.swiper.slidePrev();} //myPhotoBrowser.swiper.slideTo(blockindex); // console.log(all_matches_photos[swipertarget]); // console.log(new_all); if (new_all.length === 0){myPhotoBrowser.close();myApp.closeModal(); alert('thirdpos'); $( ".results-loader" ).hide(); $('.content-here').append( '<div class="no-results-div" style="text-align:center;margin:0 auto;width:300px;position:absolute;top:50%;left:50%;margin-left:-150px;margin-top:-70px;">'+ '<img src="media/datetongue.png" style="width:80px;margin:0 auto;">'+ '<h3>No one is nearby</h3><p style="padding-top:0px;margin-top:-10px;">Try changing your search radius, </br>age range or filters.</p></br>'+ '</div>'); } // myPhotoBrowser.swiper.slideTo(blockindex); if (new_all.length===1){ if (myPhotoBrowser.swiper.isBeginning === true){$( ".prevphoto" ).addClass( "disabled" );} else{$( ".prevphoto" ).removeClass( "disabled" );} if (myPhotoBrowser.swiper.isEnd === true){$( ".nextphoto" ).addClass( "disabled" );} else{$( ".nextphoto" ).removeClass( "disabled" );} //var windowheight = $( window ).height(); //$( ".photo-browser-slide img").css( "height", "100% - 144px)" ); $( ".photo-browser-caption" ).empty(); $( ".nametag" ).empty(); $( ".datebutton" ).removeClass( "active" ); $( ".duckbutton" ).removeClass( "active" ); $( ".duckbutton" ).addClass( "disabled" ); $( ".datebutton" ).addClass( "disabled" ); $( ".loaderlink" ).show(); $( ".orlink" ).hide(); match = 0; var target = new_all[myPhotoBrowser.activeIndex].url; var pretarget = target.replace("https://graph.facebook.com/", ""); targetid = String(pretarget.replace("/picture?width=828", "")); $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" ); //$( ".photo-browser-slide.swiper-slide-active img" ).css( "height", "100% - 144px)" ); $( ".duck-template" ).hide(); $( ".date-template" ).hide(); unmatchNavbar(); $( ".toolbardecide" ).show(); $( ".datebutton" ).removeClass( "likesme" ); $( ".duckbutton" ).removeClass( "likesme" ); var targetdescription= new_all[myPhotoBrowser.activeIndex].description; targetname = new_all[myPhotoBrowser.activeIndex].name; var targetage = new_all[myPhotoBrowser.activeIndex].age; $( ".nametag" ).empty(); $( ".nametag" ).append('<span class="rr r_'+targetid+'">'+targetname+', '+targetage+'</span>'); $( ".photo-browser-caption" ).empty(); $( ".photo-browser-caption" ).append(targetdescription); myApp.sizeNavbars(); checkMatch(targetid); } }); } var canscrollnotif = true; function scrollNotifications(){ //console.log($( ".virtual-notifications" ).height() + $( ".virtual-notifications" ).offset().top); if ((($( ".virtual-notifications" ).height() + $( ".virtual-notifications" ).offset().top) - 1 < $( document ).height())&& (canscrollnotif)) { if (notifletsload < 12){$( "#notiflistdiv" ).append('<div class="loadnotifsloader" style="clear:both;width:100%;padding-top:5px;padding-bottom:5px;background-color:#efeff4;clear:both;"><div class="preloader " style="width:20px;margin:0 auto;margin-top:5px;margin-left:125px;"></div></div>');canscrollnotif = false;var objDiv = document.getElementById("notiflistdiv"); objDiv.scrollTop = objDiv.scrollHeight; setTimeout(function(){ $( ".loadnotifsloader" ).remove();objDiv.scrollTop = objDiv.scrollHeight-44;}, 2000); } else{$( "#notiflistdiv" ).append('<div style="clear:both;width:100%;padding-top:5px;padding-bottom:5px;background-color:#efeff4;clear:both;" class="loadnotifsloader"><div class="preloader" style="width:20px;margin:0 auto;margin-top:5px;margin-left:125px;"></div></div>');canscrollnotif = false;var objDiv = document.getElementById("notiflistdiv"); objDiv.scrollTop = objDiv.scrollHeight;setTimeout(function(){ getmoreNotifs();}, 2000);} } } function scrollMessages(){ if ((($( ".scrolldetect" ).offset().top) == 120) && (canloadchat)) {if (letsload < 20){$( ".scrolldetect" ).prepend('<div class="preloader loadmessagesloader" style="width:20px;margin:0 auto;margin-top:10px;"></div>');canloadchat = false;setTimeout(function(){ $( ".loadmessagesloader" ).hide(); }, 500);}else{$( ".scrolldetect" ).prepend('<div class="preloader loadmessagesloader" style="width:20px;margin:0 auto;margin-top:10px;"></div>');canloadchat = false;setTimeout(function(){ getPrevious(); }, 500);}} } function showDecide(){ $( ".duck-template" ).hide(); $( ".date-template" ).hide(); $( ".toolbardecide" ).show(); } function closeCreate(){ myApp.closeModal('.chatpop'); } function createDate(messageid,messagename){ singleUser(targetid,targetname,88); var centerdiv; if (messageid) {targetid = messageid;} if (messagename) {targetname = messagename;} existingchatnotifications = firebase.database().ref("notifications/" + f_uid).once("value", function(snapshot) { var objs = snapshot.val(); //If existing notifications, get number of unseen messages, delete old notifications if (snapshot.val()){ $.each(objs, function(i, obj) { if ((obj.to_uid == f_uid) && (obj.from_uid == targetid) && (obj.received=='N')){ firebase.database().ref('notifications/' +f_uid + '/' + targetid).update({ received:'Y', new_message_count:'0', authcheck:f_uid, uid_accepted:f_uid }); firebase.database().ref('notifications/' +targetid + '/' + f_uid).update({ received:'Y', new_message_count:'0', authcheck:f_uid, uid_accepted:f_uid }); } }); } }); if (messageid) {centerdiv = '<div class="center center-date" onclick="singleUser(\''+targetid+'\',\''+targetname+'\')" style="cursor:pointer;"><div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+targetid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>'+targetname+'</div>';} else{centerdiv = '<div class="center center-date close-popup" onclick="clearchatHistory();"><div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+targetid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>'+targetname+'</div>';} var popupHTML = '<div class="popup chatpop">'+ '<div class="navbar" style="background-color:#2196f3;">'+ ' <div class="navbar-inner">'+ ' <div class="left">'+ '<a href="#" class="link icon-only date-back" onclick="closeCreate()" style="margin-left:-10px;color:white;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+ '<a href="#" class="link icon-only date-close" onclick="reverseRequest();" style="color:white;font-weight:bold;display:none;margin-left:-10px;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+ '<a href="#" class="link icon-only date2-close" onclick="noChange();" style="color:white;display:none;font-weight:bold;margin-left:-10px;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+ '<a href="#" class="link icon-only date1-close" onclick="reverseRequest();dateConfirmationPage();" style="color:white;display:none;font-weight:bold;margin-left:-10px;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+ '</div>'+ ' <span id="centerholder" style="color:white;"></span>'+ ' <div class="right" onclick="actionSheet()" style="font-size:14px;">'+ '<a href="#" class="link">'+ ' <i class="pe-7s-more pe-lg matchcolor" style="color:white"></i>'+ ' </a></div>'+ '</div>'+ '</div>'+ '<div class="pages" style="margin-top:-44px;">'+ '<div data-page="datepopup" class="page">'+ '<div class="toolbar messagebar datetoolbar" style="display:none;background-color:transparent;">'+ ' <div class="toolbar-inner yes-inner" style="background-color:rgba(247, 247, 248,0.9);margin-top:-10px;height:54px;padding-bottom:10px;display:none;text-align:center;">'+ '<a href="#" onclick="cancelDate()" class="link" style="height:44px;color:white;background-color:#ff3b30;width: 33%;"><span style="margin: 0 auto;">Delete</span></a>'+ '<a href="#" onclick="request()" class="link" style="height:44px;color:white;background-color:#2196f3;width:33%;"><span style="margin: 0 auto;">Change</span></a>'+ '<a href="#" onclick="acceptDate()" class="link" style="height:44px;color:white;background-color:#4cd964;width:33%;"><span style="margin: 0 auto;">Confirm</span></a>'+ '</div>'+ ' <div class="toolbar-inner sender-inner" style="background-color:rgba(247, 247, 248,0.9);margin-top:-10px;height:54px;padding-bottom:10px; display:none;text-align:center;">'+ '<a href="#" onclick="cancelDate()" class="link" style="height:44px;color:white;background-color:#ff3b30;width: 50%;"><span style="margin: 0 auto;">Delete</span></a>'+ '<a href="#" onclick="request()" class="link" style="height:44px;color:white;background-color:#2196f3;width: 50%;"><span style="margin: 0 auto;">Change</span></a>'+ '</div>'+ ' <div class="toolbar-inner date-inner" style="padding-left:0px;padding-right:0px;display:none;text-align:center;background-color:#2196f3;">'+ '<div style="width: calc(100% - 70px); height:44px;background-color:#2196f3;padding-left:5px;padding-right:5px;" class="link"><textarea id="datemessageq" placeholder="Message (optional)" style="color:white;background-color:#2196f3;margin-top:5px;"></textarea></div>'+ '<a href="#" class="link" style="height:44px;color:white;background-color:#2196f3;width:70px;" onclick="processDupdate();"><span style="margin: 0 auto;padding-right:10px;">Send</span></a>'+ '</div>'+ ' <div class="toolbar-inner message-inner" style="display:none;background-color:#2196f3;padding-left:0px;padding-right:0px;">'+ '<a href="#" class="link icon-only" style="margin-left:5px;"><i class="pe-7s-camera pe-lg" style="color:white;font-size:28px;"></i><i class="twa twa-bomb" style="z-index:999;margin-left:-10px;margin-top:-15px;"></i></a> <input type="file" size="70" accept="image/*" class="dealPictureField imagenotchosen" id="takePictureField_" onchange="getPicture();" style="background-color:transparent;color:transparent;float:left;cursor: pointer;height:54px;width:50px;z-index:1;opacity:0;background-color:red;margin-top:-12px;margin-left:-50px;"><form><input id="messagearea" type="text" placeholder="Enter Message"></form><a href="#" class="link sendbutton" style="color:white;margin-right:10px;margin-left:10px;" onclick="sendMessage();">Send</a>'+ '</div>'+ '</div>'+ '<div class="datedetailsdiv date-button" onclick="noMessages();setDate();dateConfirmationPage(1);" style="display:none;position:absolute;top:44px;text-align:center;height:44px;width:100%;z-index:999999;">'+ '</div>'+ '<div class="page-content messages-content" onscroll="scrollMessages();" id="messagediv" style="background-color:#f7f7f8">'+ '<span class="preloader login-loader messages-loader" style="width:42px;height:42px;position:absolute;top:50%;margin-top:-21px;left:50%;margin-left:-21px;"></span>'+ '<div class="datearea" style="text-align:center;"></div>'+ '<div class="messages scrolldetect" style="margin-top:100px;">'+ '</div></div></div>'+ '</div></div>'; myApp.popup(popupHTML); $('#messagearea').on('keyup', function (e) { var theEvent = e || window.event, keyPressed = theEvent.keyCode || theEvent.which; if (keyPressed === 13) { sendMessage(); document.activeElement.blur(); } }); var closedvar = $$('.chatpop').on('popup:close', function () { clearchatHistory(); }); //existingDate(); //setDate(); $( "#centerholder" ).append(centerdiv); myApp.sizeNavbars(); //$( "#centerholder" ).remove(); if (datealertvar === false) { datealertvar = true; var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} datealert = firebase.database().ref("dates/" + f_uid +'/' + targetid).on('value', function(snapshot) { var dateexists = snapshot.child('chat_expire').exists(); // true if (dateexists) { var unix = Math.round(+new Date()/1000); if (Number(snapshot.child('chat_expire').val()) > Number(unix) ) { d_type = snapshot.child('type').val(); d_chat_expire = snapshot.child('chat_expire').val(); d_interest = snapshot.child('interest').val(); d_day = snapshot.child('day').val(); d_time = snapshot.child('time').val(); d_response = snapshot.child('response').val(); if (snapshot.child('time_accepted').exists()){ d_timeaccepted = snapshot.child('time_accepted').val();} d_created_uid = snapshot.child('created_uid').val(); d_timestamp = snapshot.child('timestamp').val(); d_dateseen = snapshot.child('dateseen').val(); d_dateseentime = snapshot.child('dateseentime').val(); d_message = snapshot.child('message').val(); var newtonight = new Date(); newtonight.setHours(23,59,59,999); var newtonight_timestamp = Math.round(newtonight/1000); var weekday = new Array(7); weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; var chatdaystring; var expiredateobject = new Date((d_chat_expire * 1000) - 86400); var unixleft = d_chat_expire - newtonight_timestamp; var daysleft = unixleft / 86400; console.log('daysleft' + daysleft); var weekdaynamew = weekday[expiredateobject.getDay()]; if(daysleft === 0){chatdaystring = 'Today';} else if(daysleft === 1){chatdaystring = 'Tomorrow';} else chatdaystring = weekdaynamew; console.log(unixleft); console.log(daysleft); var hoursleft = unixleft / 3600; var salut; if (daysleft ===0){ salut='tonight'; } else if (daysleft ==1) {salut = 'in ' + Math.round(daysleft)+' day';} else{salut = 'in ' + daysleft+' days';} var aftertag; $( ".datedetailsdiv" ).empty(); $( ".datedetailsdiv" ).append('<div class="list-block media-list" style="margin-top:0px;border-bottom:1px solid #c4c4c4;">'+ '<ul style="background-color:#4cd964">'+ '<li>'+ ' <div class="item-content" style="padding-left:15px;">'+ '<div class="item-media">'+ '<img src="media/'+d_type+'faceonly.png" style="height:36px;">'+ '</div>'+ '<div class="item-inner">'+ ' <div class="item-title-row">'+ ' <div class="item-title" style="font-size:15px;color:white;">See you <span class="chatdaystringdiv">'+chatdaystring+'</span><span class="chatafternavbar"></span></div>'+ ' <div class="item-after" style="margin-top:-10px;margin-right:-15px;color:white;"><i class="pe-7s-angle-right pe-3x"></i></div>'+ ' </div>'+ '<div class="item-subtitle" style="font-size:12px;text-align:left;color:white;">Chat will end '+salut+' (at midnight)</div>'+ // '<div class="item-text">Additional description text</div>'+ '</div>'+ '</div>'+ '</li>'+ '</ul>'+ '</div> ' ); if (d_time){ var lowertime = d_time.toLowerCase() if (chatdaystring == 'today'){$( ".chatdaystringdiv").empty();$( ".chatafternavbar").append('this ' + lowertime);} else { $( ".chatafternavbar").append(' ' + d_time);} } //if (d_interest && d_type =='duck'){ // if ((d_interest == 'my') && (d_created_uid == f_uid)){aftertag = 'At '+f_first+'\'s place';} // if ((d_interest == 'your') && (d_created_uid == f_uid)){aftertag = 'At '+targetname+'\'s place';} //} //if (d_interest && d_type =='date'){ //for (i = 0; i < d_interest.length; i++) { // $( ".chatafternavbar").append('<a href="#" style="margin-left:5px"><i class="twa twa-'+d_interest[i]+'" style="margin-top:5px;margin-right:5px"></i></a>'); //} //} if (d_response == 'Y') {chatShow();} else { noMessages(); setDate(); dateConfirmationPage(); } $( ".messages-loader" ).hide(); } else{ cancelDate(); // $( ".center-date" ).empty(); //$( ".center-date" ).append(targetname); myApp.sizeNavbars(); $( ".messages-loader" ).hide(); } } else{ d_interest = false; d_chat_expire = false; d_day = false; d_time = false; d_response = false; d_timeaccepted = false; d_timestamp = false; d_message = false; d_dateseen = false; d_dateseentime = false; if (keepopen === 0){myApp.closeModal('.chatpop');clearchatHistory();} noMessages(); setDate(); // $( ".center-date" ).empty(); //$( ".center-date" ).append(targetname); myApp.sizeNavbars(); $( ".messages-loader" ).hide(); //need to check if still matched } //alert('triggered'); // if (snapshot.val().response == 'W') {noMessages(); // setDate();dateConfirmationPage();} // else {chatShow();} //dateConfirmationPage(); keepopen = 0; }); } else {} } function scrollBottom(){ var objDiv = document.getElementById("messagediv"); objDiv.scrollTop = objDiv.scrollHeight; //$("").animate({ scrollTop: $('#messagediv').prop("scrollHeight")}, 300); } function noMessages(){ $( ".messages" ).hide(); $( ".datearea" ).empty(); $( ".datearea" ).append( '<div class="nomessages" style="margin:0 auto;margin-top:44px;text-align:center;background-color:white;">'+ //'<div class="profileroundpic" style="margin:0 auto;margin-top:5px;height:70px;width:70px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+targetid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+ '<div class="dateheader" style="display:none;background-color:#ccc;padding:11px;text-align:center;font-size:20px;color:white;font-family: \'Pacifico\', cursive;"></div>'+ '<div class="waitingreply"></div>'+ '<div class="requesticon" style="padding-top:20px;"></div>'+ '<a href="#" onclick="request()" class="button dr requestbutton" style="width:150px;margin: 0 auto;margin-top:10px;font-family: \'Pacifico\', cursive;font-size:20px;"></a>'+ '<div id="createdatepicker" style="clear:both;border-bottom:1px solid #c4c4c4;margin-top:10px;"></div>'+ '<div class="row date-row" style="display:none;clear:both;margin-top:5px;padding:10px;background-color:#white;">'+ ' <div class="col-16.67 coffee_i interestbutton" onclick="interests(\'coffee\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-coffee" style="margin-top:5px;"></i></div>'+ ' <div class="col-16.67 beers_i interestbutton" onclick="interests(\'beers\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-beers" style="margin-top:5px;"></i></div>'+ ' <div class="col-16.67 wine-glass_i interestbutton" onclick="interests(\'wine-glass\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-wine-glass" style="margin-top:5px;"></i></div>'+ ' <div class="col-16.67 movie-camera_i interestbutton" onclick="interests(\'movie-camera\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-movie-camera" style="margin-top:5px;"></i></div>'+ ' <div class="col-16.67 tada_i interestbutton" onclick="interests(\'tada\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-tada" style="margin-top:5px;"></i></div>'+ ' <div class="col-16.67 fork-and-knife_i interestbutton" onclick="interests(\'fork-and-knife\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-fork-and-knife" style="margin-top:5px;"></i></div>'+ '</div> '+ '<div class="row duck-row" style="display:none;clear:both;margin-top:10px;">'+ '<div class="buttons-row" style="width:100%;">'+ ' <a href="#tab1" class="button button-big button-place button-my" onclick="duckClass(1);">My Place</a>'+ '<a href="#tab2" class="button button-big button-place button-your" onclick="duckClass(2);">Your Place</a>'+ '</div>'+ '</div> '+ '<div class="dr infop" style="padding:10px;background-color:white;color:#666;"><h3 class="titleconfirm" style="margin-top:-40px;display:none;"></h3><p class="infoconfirm">Once you agree on a time to meet you can send instant chat messages to each other.</p></div>'+ '</div>'); if (d_type == 'date') {$( ".requesticon" ).empty();$( ".requesticon" ).append(flargedateicon);$( ".requestbutton" ).text('Request Date');$( ".dateheader" ).text('Let\'s Date');} if (d_type == 'duck') {$( ".requesticon" ).empty();$( ".requesticon" ).append(flargeduckicon);$( ".requestbutton" ).text('Request Duck');$( ".dateheader" ).text('Let\'s Duck');} } function setDate(){ var dateset = 'N'; var d = new Date(); var weekday = new Array(7); weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; var n = weekday[d.getDay()]; var alldays_values = []; var alldays_names = []; var tonight = new Date(); tonight.setHours(23,59,59,999); var tonight_timestamp = Math.round(tonight/1000); alldays_values.push(tonight_timestamp - 1); alldays_values.push(tonight_timestamp); alldays_names.push('Now'); alldays_names.push('Today'); var tomorrow_timestamp = tonight_timestamp + 86400; alldays_values.push(tomorrow_timestamp); alldays_names.push('Tomorrow'); for (i = 1; i < 6; i++) { var newunix = tomorrow_timestamp + (86400 * i); alldays_values.push(newunix); var dat_number = i + 1; var datz = new Date(Date.now() + dat_number * 24*60*60*1000); n = weekday[datz.getDay()]; alldays_names.push(n); } pickerCustomToolbar = myApp.picker({ container: '#createdatepicker', rotateEffect: true, inputReadOnly: true, onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");}, toolbar:false, onChange:function(p, value, displayValue){ if (p.cols[0].displayValue == 'Now' && (dateset == 'Y')){p.cols[1].setValue('');} }, cols: [ { displayValues: alldays_names, values: alldays_values, }, { textAlign: 'left', values: (' Morning Afternoon Mid-day Evening').split(' ') }, ] }); var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var ref = firebase.database().ref("dates/" + f_uid +'/' + targetid); ref.once("value") .then(function(snapshot) { var dateexists = snapshot.child('chat_expire').exists(); // true if (dateexists){ var timecol = pickerCustomToolbar.cols[1]; timecol.setValue(snapshot.child('time').val()); var daycol = pickerCustomToolbar.cols[0]; daycol.setValue(snapshot.child('chat_expire').val()); } dateset = 'Y'; if (d_interest && d_type =='date') { for (i = 0; i < d_interest.length; i++) { $( "." + d_interest[i] +"_i" ).addClass('interestchosen'); } } if (d_interest && d_type =='duck') { if (d_interest == 'my' && d_created_uid == f_uid){ $( ".button-my" ).addClass("active");} if (d_interest == 'my' && d_created_uid != f_uid){{ $( ".button-your" ).addClass("active");}} if (d_interest == 'your' && d_created_uid == f_uid){{ $( ".button-your" ).addClass("active");}} if (d_interest == 'your' && d_created_uid != f_uid){{ $( ".button-my" ).addClass("active");}} } }); $( "#createdatepicker" ).hide(); } function infoPopup(){ var popupHTML = '<div class="popup">'+ '<div class="content-block">'+ '<p>Popup created dynamically.</p>'+ '<p><a href="#" class="close-popup">Close me</a></p>'+ '</div>'+ '</div>'; myApp.popup(popupHTML); } function dateUser(){ $( ".duckbutton" ).addClass( "disabled" ); $( ".datebutton" ).addClass( "disabled" ); if ($( ".duckbutton" ).hasClass( "active" )&& $( ".duckbutton" ).hasClass( "likesme" )){unmatchNotif();} if ( $( ".datebutton" ).hasClass( "active" )){$( ".datebutton" ).removeClass( "active" ); $( ".notifback" ).show(); $( ".mainback" ).hide(); if ($( ".datebutton" ).hasClass( "likesme" )){unmatchNotif();} removetoDate(); } else{ if ($( ".datebutton" ).hasClass( "likesme" )){matchNotif();} //clicked date $( ".datebutton" ).addClass( "active" );$( ".duckbutton" ).removeClass( "active" ); addtoDate(); } } function addtoDate(){ var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid; firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list first_number:first_number, first_name:targetname, second_number:second_number, second_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberdate:'Y', secondnumberduck:'N', created:f_uid, received:targetid }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list first_number:first_number, first_name:targetname, second_number:second_number, second_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberdate:'Y', secondnumberduck:'N', created:f_uid, received:targetid }); $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); } else {first_number = f_uid;second_number = targetid; firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list first_number:first_number, first_name:f_name.substr(0,f_name.indexOf(' ')), second_number:second_number, second_name:targetname, firstnumberdate:'Y', firstnumberduck:'N', created:f_uid, received:targetid }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list first_number:first_number, first_name:f_name.substr(0,f_name.indexOf(' ')), second_number:second_number, second_name:targetname, firstnumberdate:'Y', firstnumberduck:'N', created:f_uid, received:targetid }); } $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); if ($('.photo-browser-slide').length > 1){ var potentialdate = f_date_me.indexOf(targetid); if (potentialdate == -1) { myPhotoBrowser.swiper.slideNext(true,1000); if ($('.infopopup').length > 0) { if(swiperQuestions){comingback = 0; swiperQuestions.slideNext();comingback=1;}} } } //if button has blue border change the color } function removetoDate(){ if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid; firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list first_number:first_number, first_name:targetname, second_number:second_number, second_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberdate:'N', secondnumberduck:'N', created:f_uid, received:targetid }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list first_number:first_number, first_name:targetname, second_number:second_number, second_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberdate:'N', secondnumberduck:'N', created:f_uid, received:targetid }); $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); } else {first_number = f_uid;second_number = targetid; firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list first_number:first_number, first_name:f_name.substr(0,f_name.indexOf(' ')), second_number:second_number, second_name:targetname, firstnumberdate:'N', firstnumberduck:'N', created:f_uid, received:targetid }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list first_number:first_number, first_name:f_name.substr(0,f_name.indexOf(' ')), second_number:second_number, second_name:targetname, firstnumberdate:'N', firstnumberduck:'N', created:f_uid, received:targetid }); $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); } $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" ); $( ".duck-template" ).hide(); $( ".date-template" ).hide(); unmatchNavbar(); $( ".toolbardecide" ).show(); } function duckUser(){ $( ".duckbutton" ).addClass( "disabled" ); $( ".datebutton" ).addClass( "disabled" ); if ($( ".datebutton" ).hasClass( "active" ) && $( ".datebutton" ).hasClass( "likesme" )){unmatchNotif();} if ( $( ".duckbutton" ).hasClass( "active" )){$( ".duckbutton" ).removeClass( "active" ); if ($( ".duckbutton" ).hasClass( "likesme" )){unmatchNotif();} $( ".notifback" ).show(); $( ".mainback" ).hide(); removetoDuck(); } else{ if ($( ".duckbutton" ).hasClass( "likesme" )){matchNotif();} //clicked duck $( ".duckbutton" ).addClass( "active" );$( ".datebutton" ).removeClass( "active" ); addtoDuck(); } } function removetoDuck(){ var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid; firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list first_number:first_number, first_name:targetname, second_number:second_number, second_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberdate:'N', secondnumberduck:'N', created:f_uid, received:targetid }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list first_number:first_number, first_name:targetname, second_number:second_number, second_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberdate:'N', secondnumberduck:'N', created:f_uid, received:targetid }); $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); } else {first_number = f_uid;second_number = targetid; firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list first_number:first_number, first_name:f_name.substr(0,f_name.indexOf(' ')), second_number:second_number, second_name:targetname, firstnumberdate:'N', firstnumberduck:'N', created:f_uid, received:targetid }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list first_number:first_number, first_name:f_name.substr(0,f_name.indexOf(' ')), second_number:second_number, second_name:targetname, firstnumberdate:'N', firstnumberduck:'N', created:f_uid, received:targetid }); $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); } $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" ); $( ".duck-template" ).hide(); $( ".date-template" ).hide(); unmatchNavbar(); $( ".toolbardecide" ).show(); } function markMe(){ var mearray = ["4"]; firebase.database().ref('users/' + f_uid).update({ //add this user to my list date_me:mearray }); } function addtoDuck(){ var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid; firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list first_number:first_number, first_name:targetname, second_number:second_number, second_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberduck:'Y', secondnumberdate:'N', created:f_uid, received:targetid }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list first_number:first_number, first_number:first_number, second_number:second_number, second_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberduck:'Y', secondnumberdate:'N', created:f_uid, received:targetid }); $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); } else {first_number = f_uid;second_number = targetid; firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list first_number:first_number, first_name:f_name.substr(0,f_name.indexOf(' ')), second_number:second_number, second_name:targetname, firstnumberduck:'Y', firstnumberdate:'N', created:f_uid, received:targetid }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list first_number:first_number, first_name:f_name.substr(0,f_name.indexOf(' ')), second_number:second_number, second_name:targetname, firstnumberduck:'Y', firstnumberdate:'N', created:f_uid, received:targetid }); } $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); if ($('.photo-browser-slide').length > 1){ var potentialduck = f_duck_me.indexOf(targetid); if (potentialduck == -1) { myPhotoBrowser.swiper.slideNext(true,1000); if ($('.infopopup').length > 0) { if(swiperQuestions){comingback = 0; swiperQuestions.slideNext();comingback=1;}}} } } var singleuserarray = []; function singleUser(idw,idname,origin){ if (singleuserarray[0] != null){ if (origin){photoBrowser(0,singleuserarray[0].age,1,1);} else{photoBrowser(0,singleuserarray[0].age);} } else{ targetid = String(idw); targetname = idname; firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/singleuser.php", {projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:targetid,latitudep:latitudep,longitudep:longitudep} ) .done(function( data ) { console.log(data); var result = JSON.parse(data); var availarraystring=''; var availnotexpired = false; var tonight = new Date(); tonight.setHours(22,59,59,999); var tonight_timestamp = Math.round(tonight/1000); if(result[0].availstring && (result[0].availstring != '[]') && (result[0].uid != f_uid)){ var availablearrayindividual = JSON.parse(result[0].availstring); for (k = 0; k < availablearrayindividual.length; k++) { if (availablearrayindividual[k].id >= tonight_timestamp){availnotexpired = true;} } if (availnotexpired){availarraystring = result[0].availstring;} } var timestampyear = result[0].timestamp.substring(0,4); var timestampmonth = result[0].timestamp.substring(5,7); var timestampday = result[0].timestamp.substring(8,10); var timestamphour = result[0].timestamp.substring(11,13); var timestampminute = result[0].timestamp.substring(14,16); var timestampsecond = result[0].timestamp.substring(17,20); var timestampunix=(new Date(timestampmonth + '/' + timestampday + '/' + timestampyear + ' ' + timestamphour + ':' + timestampminute + ':' + timestampsecond)).getTime() / 1000 + 64800; var d_unix = Math.round(+new Date()/1000); var diff = (d_unix - timestampunix)/60; var photosstringarray =[]; var photocount; var photostring; var profilepicstring; var photoarrayuserlarge; var photoarrayusersmall; if(result[0].largeurl){ var heightarray = result[0].heightslides.split(","); var widtharray = result[0].widthslides.split(","); photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical" style="height:100%;"><img data-src="' + result[0].largeurl + '" class="swiper-lazy"></div></div>'; photocount = result[0].largeurl.split(",").length; photoarrayuserlarge = result[0].largeurl.split(","); photoarrayusersmall = result[0].smallurl.split(","); profilepicstringlarge = photoarrayuserlarge[0]; profilepicstringsmall = photoarrayusersmall[0]; photostring=photostring.replace(/,/g, '" class="swiper-lazy" style="height:100%;"></div></div><div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="') } else{ photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="https://graph.facebook.com/'+targetid+'/picture?width=828" class="swiper-lazy" style="height:100%;"></div></div>'; profilepicstringlarge = 'https://graph.facebook.com/'+targetid+'/picture?width=828&height=828'; profilepicstringsmall = 'https://graph.facebook.com/'+targetid+'/picture?width=368&height=368'; photocount = 1; } var distance = parseFloat(result[0].distance).toFixed(1); var distancerounded = parseFloat(result[0].distance).toFixed(0); if ((distance >= 0) && (distance <0.1)) {distancestring = 'Less than 100 m <span style="font-size:13px;">(328 ft.)</span>'} if ((distance >= 0.1) && (distance <0.2)) {distancestring = 'Less than 200 m <span style="font-size:13px;">(656 ft.)</span>'} if ((distance >= 0.2) && (distance <0.3)) {distancestring = 'Less than 300 m <span style="font-size:13px;">(984 ft.)</span>'} if ((distance >= 0.3) && (distance <0.4)) {distancestring = 'Less than 400 m <span style="font-size:13px;">(1312 ft.)</span>'} if ((distance >= 0.4) && (distance <0.5)) {distancestring = 'Less than 500 m <span style="font-size:13px;">(1640 ft.)</span>'} if ((distance >= 0.5) && (distance <0.6)) {distancestring = 'Less than 600 m <span style="font-size:13px;">(1968 ft.)</span>'} if ((distance >= 0.6) && (distance <0.7)) {distancestring = 'Less than 700 m <span style="font-size:13px;">(2296 ft.)</span>'} if ((distance >= 0.7) && (distance <0.8)) {distancestring = 'Less than 800 m <span style="font-size:13px;">(2624 ft.)</span>'} if ((distance >= 0.8) && (distance <0.9)) {distancestring = 'Less than 900 m <span style="font-size:13px;">(2953 ft.)</span>'} if ((distance >= 0.9) && (distance <1.0)) {distancestring = 'Less than 1 km <span style="font-size:13px;">(3280 ft.)</span>'} if ((distance >= 1.0) && (distance <1.609344)) {distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 3280.84) + ' ft.)</span>'} if (distance > 1.609344){distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 0.621371) + ' mi.)</span>'} var namescount = result[0].displayname.split(' ').length; var matchname; if(namescount === 1){matchname = result[0].displayname;} else {matchname = result[0].name.substr(0,result[0].displayname.indexOf(' '));} singleuserarray.push({widthslides:result[0].widthslides,heightslides:result[0].heightslides,availarraystring:availarraystring,minutes:diff,distancenumber:distance,distancestring:distancestring,photocount:photocount,photos:photostring,name:matchname,age:result[0].age,description:result[0].description,id:targetid,url:'https://graph.facebook.com/'+targetid+'/picture?width=828',caption:'...',industry: result[0].industry, status: result[0].status, politics:result[0].politics,eyes:result[0].eyes,body:result[0].body,religion:result[0].religion,zodiac:result[0].zodiac,ethnicity:result[0].ethnicity,height:result[0].height,weight:result[0].weight}); // console.log(singleuserarray); main_all = new_all; new_all = singleuserarray; if (origin == 88){alert('88');} else if (origin == 1){alert('99');photoBrowser(0,singleuserarray[0].age,1,1);} else if (!origin){alert('100');photoBrowser(0,singleuserarray[0].age);} }); }); } } function request(){ canloadchat = false; $( '.picker-items-col-wrapper' ).css("width", "auto"); $( ".requesticon" ).hide(); $( ".dateheader" ).show(); $( ".sender-inner" ).hide(); $( ".yes-inner" ).hide(); conversation_started = false; if (d_response == 'Y') { $( ".date-close" ).hide(); $( ".date2-close" ).show(); $( ".date1-close" ).hide(); } if (d_response == 'W') { $( ".date-close" ).hide(); $( ".date1-close" ).show(); $( ".date2-close" ).hide(); } if(!d_response){ $( ".date-close" ).show(); $( ".date2-close" ).hide(); $( ".date1-close" ).hide(); } $( ".messages" ).hide(); $( ".date-button" ).hide(); $( "#createdatepicker" ).show(); $( ".dr" ).hide(); $( ".date-back" ).hide(); if (d_type == 'date') {$( ".date-row" ).show();$( ".duck-row" ).hide();} if (d_type == 'duck') {$( ".duck-row" ).show();$( ".date-row" ).hide();} $( ".waitingreply" ).empty(); $( ".datetoolbar" ).slideDown(); $( ".message-inner" ).hide(); $( ".date-inner" ).show(); if (d_response=='Y'){$( "#datemessageq" ).val('');} // $( ".center-date" ).empty(); // if (d_type=='date') {$( ".center-date" ).append('Date Details');} // if (d_type=='duck') {$( ".center-date" ).append('Duck Details');} myApp.sizeNavbars(); //$( "#createdatepicker" ).focus(); $( ".page-content" ).animate({ scrollTop: 0 }, "fast"); } function noChange(){ canloadchat = true; $( ".sender-inner" ).hide(); $( ".messages" ).show(); $( ".date-close" ).hide(); $( ".date2-close" ).hide(); $( ".date1-close" ).hide(); $( ".message-inner" ).show(); $( ".date-inner" ).hide(); // $( ".center-date" ).empty(); $( "#createdatepicker" ).hide(); // $( ".center-date" ).append(targetname); $( ".nomessages" ).hide(); $( ".date-back" ).show(); $( ".date-button" ).show(); scrollBottom(); myApp.sizeNavbars(); } function reverseRequest(){ $( ".dateheader" ).hide(); $( "#createdatepicker" ).hide(); $( ".dr" ).show(); $( ".date-back" ).show(); $( ".date-row" ).hide(); $( ".duck-row" ).hide(); $( ".date-close" ).hide(); $( ".requesticon" ).show(); $( ".date-inner" ).hide(); if (!d_day){ //$( ".center-date" ).empty(); // $( ".center-date" ).append(targetname); myApp.sizeNavbars(); } } var message_count = 0; var messages_loaded = false; var conversation_started = false; var prevdatetitle; function chatShow(){ prevdatetitle = false; letsload = 20; canloadchat = true; additions = 0; $( ".yes-inner" ).hide(); $( ".sender-inner" ).hide(); $( ".datedetailsdiv" ).show(); message_count = 1; image_count = 0; $( ".messages" ).show(); $( ".datearea" ).empty(); $( ".date-back" ).show(); $( ".date-button" ).show(); $( ".date-close" ).hide(); $( ".date2-close" ).hide(); $( ".datetoolbar" ).show(); $( ".message-inner" ).show(); $( ".date-inner" ).hide(); // $( ".center-date" ).empty(); // $( ".center-date" ).append(targetname); myApp.sizeNavbars(); myMessagebar = myApp.messagebar('.messagebar', { maxHeight: 200 }); myMessages = myApp.messages('.messages', { autoLayout: true, scrollMessages:true }); //if (myMessages) {myMessages.clean();} if (message_history === true){} if (message_history === false){ message_history = true; //do the .on call here to keep receiving messages here var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} firebase.database().ref("chats/" + first_number+ '/' + second_number).once('value').then(function(snapshot) { existingmessages = snapshot.numChildren(); // $( ".messages").append( '<a href="#" class="button scrollbutton" onclick="scrollBottom();" style="border:0;margin-top:10px;"><i class="pe-7s-angle-down-circle pe-2x" style="margin-right:5px;"></i> New Messages</a>'); // $( ".messages").append('<a href="#" class="button scrollbutton" onclick="scrollBottom()" style="display:none;top:103px;position:absolute;right:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-down-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">New messages</div></div></a>'); // if (snapshot.numChildren() > 10) {$( ".messages").prepend( '<a href="#" class="button previouschats" onclick="getPrevious()" style="top:103px;position:absolute;left:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-up-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">Past messages</div></div></a>');} }).then(function(result) { var weekday = []; weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; var month = []; month[0] = "Jan"; month[1] = "Feb"; month[2] = "Mar"; month[3] = "Apr"; month[4] = "May"; month[5] = "Jun"; month[6] = "Jul"; month[7] = "Aug"; month[8] = "Sep"; month[9] = "Oct"; month[10] = "Nov"; month[11] = "Dec"; var stringnow = new Date(); var stringyestday = new Date(Date.now() - 86400); var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate(); var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate(); message_historyon = firebase.database().ref("chats/" + first_number+ '/' + second_number).orderByKey().limitToLast(20).on("child_added", function(snapshot) { if (message_count ==1) {lastkey = snapshot.getKey();} message_count ++; var checkloaded; if (existingmessages > 19){checkloaded = 20;} else if (existingmessages < 20){checkloaded = existingmessages;} if (message_count == checkloaded){messages_loaded = true;} var obj = snapshot.val(); var datechatstring; var messagedate = new Date((obj.timestamp * 1000)); var minstag = ('0'+messagedate.getMinutes()).slice(-2); messagetimetitle = messagedate.getHours() + ':' + minstag; var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate(); if (!prevdatetitle){prevdatetitle = messagedaytitle;console.log('prevdatetitle does not exist'); if (messagedaytitle == todaystring){datechatstring = 'Today';} else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';} else{datechatstring = messagedaytitle;} } else { if (prevdatetitle == messagedaytitle){console.log('it is the same day');datechatstring='';} else{console.log('it is a different day');prevdatetitle = messagedaytitle; if (messagedaytitle == todaystring){datechatstring = 'Today';} else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';} else{datechatstring = messagedaytitle;} } } //my messages var unix = Math.round(+new Date()/1000); if (obj.from_uid == f_uid) { if (obj.param == 'dateset'){ $( ".messages" ).append( '<div class="list-block media-list" style="margin-top:0px;">'+ '<ul>'+ ' <li>'+ ' <div class="item-content">'+ ' <div class="item-media">'+ ' <img src="path/to/img.jpg">'+ '</div>'+ ' <div class="item-inner">'+ ' <div class="item-title-row">'+ ' <div class="item-title">Date Details</div>'+ ' <div class="item-after">Element label</div>'+ ' </div>'+ ' <div class="item-subtitle">Subtitle</div>'+ ' <div class="item-text">Additional description text</div>'+ '</div>'+ '</div>'+ '</li>'+ '</ul>'+ '</div>'); } if (obj.param == 'message'){ myMessages.addMessage({ // Message text text: obj.message, // Random message type type: 'sent', // Avatar and name: avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal', name: f_first, // Day day:datechatstring, label: 'Sent ' + messagetimetitle }); } if (obj.param == 'image'){ if (obj.photo_expiry){ if (obj.photo_expiry < Number(unix)){ firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + obj.id).remove(); firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + obj.id).remove(); } else{ myMessages.addMessage({ // Message text text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup('+image_count+');">', // Random message type type: 'sent', // Avatar and name: avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal', name: f_first, day:datechatstring, label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle // Day }); image_count ++; } } else { myMessages.addMessage({ // Message text text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup('+image_count+');">', // Random message type type: 'sent', // Avatar and name: avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal', name: f_first, day:datechatstring, label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle }); image_count ++; } } if (conversation_started === true) { $( ".message" ).last().remove(); $( ".message" ).last().addClass("message-last"); $('#buzzer')[0].play(); } } //received messages if (obj.to_uid == f_uid) { if (messages_loaded === true) { var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) { var objs = snapshot.val(); if (snapshot.val()){ if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){ firebase.database().ref('notifications/' +f_uid + '/' + targetid).update({ received:'Y', new_message_count:'0', authcheck:f_uid, uid_accepted:f_uid }); firebase.database().ref('notifications/' +targetid + '/' + f_uid).update({ received:'Y', new_message_count:'0', authcheck:f_uid, uid_accepted:f_uid }); } } }); } if (conversation_started === true) { $('#buzzer')[0].play(); } if (obj.param == 'dateset'){ $( ".messages" ).append( '<div class="list-block media-list">'+ '<ul>'+ ' <li>'+ ' <div class="item-content">'+ ' <div class="item-media">'+ ' <img src="path/to/img.jpg">'+ '</div>'+ ' <div class="item-inner">'+ ' <div class="item-title-row">'+ ' <div class="item-title">Element title</div>'+ ' <div class="item-after">Element label</div>'+ ' </div>'+ ' <div class="item-subtitle">Subtitle</div>'+ ' <div class="item-text">Additional description text</div>'+ '</div>'+ '</div>'+ '</li>'+ '</ul>'+ '</div>'); } if (obj.param == 'message'){ myMessages.addMessage({ // Message text text: obj.message, // Random message type type: 'received', // Avatar and name: avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal', name: targetname, day:datechatstring, label: 'Sent ' + messagetimetitle }); } if (obj.param == 'image'){ if (!obj.photo_expiry){ myMessages.addMessage({ // Message text text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup('+image_count+');">', // Random message type type: 'received', // Avatar and name: avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal', name: f_first, day:datechatstring, label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle }); image_count ++; var seentime = Math.round(+new Date()/1000); var expirytime = Math.round(+new Date()/1000) + 86400; firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + obj.id).update({ photo_expiry:expirytime, seen:'Y', seentime:seentime }); firebase.database().ref('photostodelete/' + obj.from_uid + '/' +obj.to_uid+ '/' +obj.id).update({ photo_expiry:expirytime, seen:'Y', seentime:seentime }); firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + obj.id).update({ photo_expiry:expirytime, seen:'Y', seentime:seentime }); } else { if (obj.photo_expiry < Number(unix)){ firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + obj.id).remove(); firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + obj.id).remove(); } else{ myMessages.addMessage({ // Message text text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup('+image_count+');">', // Random message type type: 'received', // Avatar and name: avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal', name: f_first, day:datechatstring, label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle }); image_count ++; } } } } }, function (errorObject) { }); }); } //myMessages.layout(); //myMessages = myApp.messages('.messages', { // autoLayout: true //}); //myMessages.scrollMessages(); myApp.initPullToRefresh('.pull-to-refresh-content-9'); } var notifadditions=0; var notifletsload = 12; function getmoreNotifs(){ notifadditions ++; var notifsloaded = notifadditions * 12; var notif2load = mynotifs.length - (notifadditions * 12); if (notif2load > 12) {notifletsload = 12;} else {notifletsload = notif2load;} var lasttoaddnotif = notifsloaded + notifletsload; $(".loadnotifsloader").remove(); for (i = notifsloaded; i < lasttoaddnotif; i++) { myList.appendItem({ title: mynotifs[i].title, targetid:mynotifs[i].targetid, targetname:mynotifs[i].targetname, picture:mynotifs[i].picture, from_name: mynotifs[i].from_name, to_name: mynotifs[i].to_name, from_uid:mynotifs[i].from_uid, to_uid: mynotifs[i].to_uid, icon:mynotifs[i].icon, colordot:mynotifs[i].colordot, func:mynotifs[i].func, type:mynotifs[i].type, timestamptitle:mynotifs[i].timestamptitle }); } canscrollnotif = true; } var letsload = 20; function getPrevious(){ if (existingmessages === false){ var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} firebase.database().ref("chats/" + first_number+ '/' + second_number).once('value').then(function(snapshot) { existingmessages = snapshot.numChildren(); previousFunction(); }) } else{previousFunction();} function previousFunction(){ var weekday = []; weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; var month = []; month[0] = "Jan"; month[1] = "Feb"; month[2] = "Mar"; month[3] = "Apr"; month[4] = "May"; month[5] = "Jun"; month[6] = "Jul"; month[7] = "Aug"; month[8] = "Sep"; month[9] = "Oct"; month[10] = "Nov"; month[11] = "Dec"; var stringnow = new Date(); var stringyestday = new Date(Date.now() - 86400); var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate(); var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate(); var prevarray = []; message_count = 0; additions ++; $(".previouschats").remove(); var left2load = existingmessages - (additions * 20); if (left2load > 20) {letsload = 20;} else {letsload = left2load;} console.log('existingmessages' + existingmessages); console.log('letsload' + letsload); console.log('additions' + additions); var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var newmessage_history = firebase.database().ref("chats/" + first_number+ '/' + second_number).orderByKey().limitToLast(letsload).endAt(lastkey).on("child_added", function(snapshot) { message_count ++; if (message_count ==1) {lastkey = snapshot.getKey();} var obj = snapshot.val(); var datechatstring; var messagedate = new Date((obj.timestamp * 1000)); var minstag = ('0'+messagedate.getMinutes()).slice(-2); messagetimetitle = messagedate.getHours() + ':' + minstag; var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate(); if (!prevdatetitle){prevdatetitle = messagedaytitle;console.log('prevdatetitle does not exist'); if (messagedaytitle == todaystring){datechatstring = 'Today'} else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday'} else{datechatstring = messagedaytitle;} } else { if (prevdatetitle == messagedaytitle){console.log('it is the same day'); //console.log($(".message").length); if ((letsload < 20) && (message_count == 1) ){ if (messagedaytitle == todaystring){datechatstring = 'Today'} if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday'} else{datechatstring = messagedaytitle;} } else {datechatstring='';} } else{console.log('it is a different day');prevdatetitle = messagedaytitle; if (messagedaytitle == todaystring){datechatstring = 'Today'} else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday'} else{datechatstring = messagedaytitle;} } } //my messages if (obj.from_uid == f_uid) { if (obj.param == 'message'){ prevarray.push({ // Message text text: obj.message, // Random message type type: 'sent', // Avatar and name: avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal', name: f_first, day:datechatstring, label: 'Sent ' + messagetimetitle }); } if (obj.param == 'image'){ prevarray.push({ // Message text text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup();">', // Random message type type: 'sent', // Avatar and name: avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal', name: f_first, day:datechatstring, label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle }); } } //received messages if (obj.to_uid == f_uid) { if (obj.param == 'message'){ prevarray.push({ // Message text text: obj.message, // Random message type type: 'received', // Avatar and name: avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal', name: targetname, day:datechatstring, label: 'Sent ' + messagetimetitle }); } if (obj.param == 'image'){ prevarray.push({ // Message text text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup();">', // Random message type type: 'received', // Avatar and name: avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal', name: f_first, day:datechatstring, label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle }); } } if (message_count == letsload) { $(".loadmessagesloader").remove(); canloadchat = true; myMessages.addMessages(prevarray.slice(0, -1), 'prepend'); //$(".scrollbutton").remove(); //$(".messages").prepend('<a href="#" class="button scrollbutton" onclick="scrollBottom()" style="display:none;top:103px;position:absolute;right:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-down-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">New messages</div></div></a>'); //if (message_count == 20){$( ".messages").prepend( '<a href="#" class="button previouschats" onclick="getPrevious()" style="top:103px;position:absolute;left:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-up-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">Past messages</div></div></a>' );$( ".messages" ).css("margin-top","132px");} } }, function (errorObject) { // console.log("The read failed: " + errorObject.code); }); } } var targetid; var targetname; var targetreported; var targetdatearray,targetduckarray; var targetdate,targetduck; var match; var targetdatelikes, targetducklikes; var slideheight = $( window ).height(); function getMeta(url){ $("<img/>",{ load : function(){ if (this.height > this.width){ $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height',$(document).height() + 'px'); $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','auto'); } }, src : url }); } function backtoProfile(){ myApp.closeModal('.infopopup') ; $( ".toolbarq" ).hide(); getMeta(new_all[myPhotoBrowser.activeIndex].url); //put original image here $( ".nametag" ).addClass('whitetext'); //$( ".photo-browser-slide img" ).css("height","100%"); $( ".datebutton" ).addClass('imagelibrary'); $( ".duckbutton" ).addClass('imagelibrary'); //$( ".swiper-container-vertical" ).css("height",slideheight + "px"); //$( ".swiper-container-vertical" ).css("margin-top","0px"); //$( ".swiper-slide-active" ).css("height", "600px"); $( ".toolbarq" ).css("background-color","transparent"); $( ".datefloat" ).hide(); $( ".duckfloat" ).hide(); $( ".vertical-pag" ).show(); //$( ".infopopup" ).css("z-index","-100"); $( ".onlineblock" ).hide(); //$( ".orlink" ).show(); //$( ".uplink" ).hide(); //$( ".nextlink" ).hide(); //$( ".prevlink" ).hide(); $( ".prevphoto" ).show(); $( ".nextphoto" ).show(); $( ".nexts" ).hide(); $( ".prevs" ).hide(); $( ".photo-browser-slide" ).css("opacity","1"); //$( ".datebutton" ).css("height","40px"); //$( ".duckbutton" ).css("height","40px"); //$( ".datebutton img" ).css("height","30px"); //$( ".duckbutton img" ).css("height","30px"); //$( ".datebutton img" ).css("width","auto"); //$( ".duckbutton img" ).css("width","auto"); $( ".photobrowserbar" ).css("background-color","transparent"); } var comingback; function scrollQuestions(){ //console.log($( ".wrapper-questions" ).offset().top); //console.log($( window ).height()); var offsetline = $( window ).height() - 88; var offsetdiv = $( ".wrapper-questions" ).offset().top; //if (offsetdiv > offsetline){$( ".photo-browser-slide" ).css("opacity",1);} var setopacity = (($( ".wrapper-questions" ).offset().top +88) / $( window ).height());$( ".photo-browser-slide" ).css("opacity",setopacity);$( ".adown" ).css("opacity",setopacity); //if // if (offsetdiv > offsetline) {$( ".photo-browser-slide" ).css("opacity","1");$( ".adown" ).css("opacity","1");} //var setopacity = (($( ".wrapper-questions" ).offset().top +10) / $( window ).height());$( ".photo-browser-slide" ).css("opacity",setopacity);$( ".adown" ).css("opacity",setopacity); } function delayYo(){ } function scrolltoTop(){ $( ".swiper-questions" ).animate({ scrollTop: $( window ).height() - 130 }); } function questions(origin){ $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','cover'); $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','100%'); $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','auto'); $( ".toolbarq" ).css("background-color","transparent"); $( ".photobrowserbar" ).css("background-color","#ccc"); $( ".nametag" ).removeClass('whitetext'); var targetplugin = new_all[myPhotoBrowser.activeIndex].id; //may need to readd this //checkMatch(targetplugin); comingback = 0; if (origin){comingback = 1;} if (swiperQuestions){ swiperQuestions.removeAllSlides(); swiperQuestions.destroy(); } //alert($('.photo-browser-slide img').css('height')); if ($('.infopopup').length > 0) { alert('deleting return false');myApp.closeModal('.infopopup');return false; } $( ".vertical-pag" ).hide(); $( ".datefloat" ).show(); $( ".duckfloat" ).show(); $( ".datebutton" ).removeClass('imagelibrary'); $( ".duckbutton" ).removeClass('imagelibrary'); //$( ".swiper-container-vertical.swiper-slide-active img" ).css("height","-webkit-calc(100% - 115px)"); //$( ".swiper-container-vertical" ).css("margin-top","-27px"); //$( ".swiper-slide-active" ).css("height","100%"); //$( ".photo-browser-slide img" ).css("height","calc(100% - 80px)"); //$( ".orlink" ).hide(); //$( ".uplink" ).show(); //$( ".nextlink" ).show(); //$( ".prevlink" ).show(); $( ".onlineblock" ).show(); //$( ".datebutton" ).css("height","70px"); //$( ".duckbutton" ).css("height","70px"); //$( ".datebutton img" ).css("height","60px"); //$( ".duckbutton img" ).css("height","60px"); //$( ".datebutton img" ).css("width","auto"); //$( ".duckbutton img" ).css("width","auto"); //$( ".nametag" ).removeClass('whitetext'); var photobrowserHTML = '<div class="popup infopopup" style="background-color:transparent;margin-top:44px;height:calc(100% - 127px);padding-bottom:20px;" >'+ // ' <a href="#tab1" class="prevs button disabled" style="border-radius:5px;position:absolute;left:-37px;top:50%;margin-top:-28px;height:56px;width:56px;border:0;z-index:99;color:#2196f3;background-color:rgba(247, 247, 247, 0.952941);"><i class="pe-7s-angle-left pe-4x" style="margin-left:7px;margin-top:-1px;z-index:-1"></i></a>'+ // ' <a href="#tab3" class="nexts button" style="border-radius:5px;position:absolute;right:-37px;width:56px;top:50%;margin-top:-26px;height:56px;color:#2196f3;border:0;z-index:99;background-color:rgba(247, 247, 247, 0.952941);"><i class="pe-7s-angle-right pe-4x" style="margin-left:-35px;margin-top:-1px;"></i></a>'+ '<div class="swiper-container swiper-questions" style="height:100%;overflow-y:scroll;will-change: opacity;">'+ '<div style="height:100%;width:100%;overflow-x:hidden;" onclick="backtoProfile();">'+ '</div>'+ ' <div class="swiper-wrapper wrapper-questions" style="">'+ ' </div>'+ '</div>'+ '</div>' myApp.popup(photobrowserHTML,true,false); $( ".nexts" ).show(); $( ".prevs" ).show(); $( ".prevphoto" ).hide(); $( ".nextphoto" ).hide(); console.log(new_all); for (i = 0; i < new_all.length; i++) { var boxcolor,displayavail,availabilityli,availabletext,iconavaill; if (new_all[i].availarraystring){iconavaill='s';boxcolor = 'width:60px;color:#007aff;opacity:1;background-color:transparent;color:#4cd964';displayavail='block';availabletext='<div class="availabletxt_'+new_all[i].id+'" style="display:none;float:left;margin-top:12px;padding-right:10px;">Available</div>';} else{iconavaill='f';boxcolor = 'width:60px;color:#007aff;opacity:1;background-color:transparent';displayavail='none';availabletext='';} $( ".wrapper-questions" ).append('<div class="swiper-slide slideinfo_'+new_all[i].id+'" style="height:100%;">'+ //'<h3 class="availabilitytitle_'+new_all[i].id+'" style="color:white;font-size:16px;padding:5px;float:left;"><i class="pe-7-angle-down pe-3x"></i></h3>'+ '<h3 onclick="scrolltoTop()" class="adown arrowdown_'+new_all[i].id+' availyope availyo_'+ new_all[i].id+'" style="display:none;margin-top:-60px;right:0px;'+boxcolor+';font-size:14px;padding:0px;margin-left:10px;"><i class="pe-7f-angle-down pe-3x" style="float:left;"></i>'+ '</h3>'+ '<div onclick="scrolltoTop()" style="z-index:99999999;margin-top:15px;display:none;background-color:white;border-radius:20px;border-bottom-right-radius:0px;border-bottom-left-radius:0px;margin-bottom:20px;" class="prof_'+i+' infoprofile availyo_'+ new_all[i].id+'">'+ '<div class="content-block-title" style="padding-top:0px;clear:both;margin-top:0px;">About '+new_all[i].name+'</div>'+ '<div class="list-block" style="margin-top:0px;clear:both;">'+ '<ul class="profileul_'+new_all[i].id+'" style="background-color:transparent">'+ ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Online</div>'+ ' <div class="item-input">'+ '<div class="timetag_'+ new_all[i].id+'"></div>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Distance</div>'+ ' <div class="item-input">'+ '<div class="distancetag_'+ new_all[i].id+'"></div>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Hometown</div>'+ ' <div class="item-input">'+ ' <input type="text" name="name" value="Melbourne" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' </ul></div>'+ '<div class="profileyo_'+ new_all[i].id+'"></div>'+ '</div>'+ '</div>'); //put here if (new_all[i].description){ $( ".profileul_"+new_all[i].id ).prepend( ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-input">'+ ' <textarea class="resizable" name="name" style="max-height:200px;font-size:14px;" readonly>'+new_all[i].description+'</textarea>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } if (new_all[i].industry){ $( ".profileul_"+new_all[i].id ).append( ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Industry</div>'+ ' <div class="item-input">'+ ' <input type="text" name="name" value="'+new_all[i].industry+'" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } if (new_all[i].zodiac){ $( ".profileul_"+new_all[i].id ).append( ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Zodiac</div>'+ ' <div class="item-input">'+ ' <input type="text" name="name" value="'+new_all[i].zodiac+'" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } if (new_all[i].politics){ $( ".profileul_"+new_all[i].id ).append( ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Politics</div>'+ ' <div class="item-input">'+ ' <input type="text" name="name" value="'+new_all[i].politics+'" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } if (new_all[i].religion){ $( ".profileul_"+new_all[i].id ).append( ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Religion</div>'+ ' <div class="item-input">'+ ' <input type="text" name="name" value="'+new_all[i].religion+'" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } if (new_all[i].ethnicity){ $( ".profileul_"+new_all[i].id ).append( ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Ethnicity</div>'+ ' <div class="item-input">'+ ' <input type="text" name="name" value="'+new_all[i].ethnicity+'" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } if (new_all[i].eyes){ $( ".profileul_"+new_all[i].id ).append( ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Eye Color</div>'+ ' <div class="item-input">'+ ' <input type="text" name="name" value="'+new_all[i].eyes+'" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } if (new_all[i].body){ $( ".profileul_"+new_all[i].id ).append( ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Body Type</div>'+ ' <div class="item-input">'+ ' <input type="text" name="name" value="'+new_all[i].body+'" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } if (new_all[i].height != 0){ if (new_all[i].height == 122) {var heightset = '122 cm (4\' 0\'\')';} if (new_all[i].height == 124) {var heightset = '124 cm (4\' 1\'\')';} if (new_all[i].height == 127) {var heightset = '127 cm (4\' 2\'\')';} if (new_all[i].height == 130) {var heightset = '130 cm (4\' 3\'\')';} if (new_all[i].height == 132) {var heightset = '132 cm (4\' 4\'\')';} if (new_all[i].height == 135) {var heightset = '135 cm (4\' 5\'\')';} if (new_all[i].height == 137) {var heightset = '137 cm (4\' 6\'\')';} if (new_all[i].height == 140) {var heightset = '140 cm (4\' 7\'\')';} if (new_all[i].height == 142) {var heightset = '142 cm (4\' 8\'\')';} if (new_all[i].height == 145) {var heightset = '145 cm (4\' 9\'\')';} if (new_all[i].height == 147) {var heightset = '147 cm (4\' 10\'\')';} if (new_all[i].height == 150) {var heightset = '150 cm (4\' 11\'\')';} if (new_all[i].height == 152) {var heightset = '152 cm (5\' 0\'\')';} if (new_all[i].height == 155) {var heightset = '155 cm (5\' 1\'\')';} if (new_all[i].height == 157) {var heightset = '157 cm (5\' 2\'\')';} if (new_all[i].height == 160) {var heightset = '160 cm (5\' 3\'\')';} if (new_all[i].height == 163) {var heightset = '163 cm (5\' 4\'\')';} if (new_all[i].height == 165) {var heightset = '165 cm (5\' 5\'\')';} if (new_all[i].height == 168) {var heightset = '168 cm (5\' 6\'\')';} if (new_all[i].height == 170) {var heightset = '170 cm (5\' 7\'\')';} if (new_all[i].height == 173) {var heightset = '173 cm (5\' 8\'\')';} if (new_all[i].height == 175) {var heightset = '175 cm (5\' 9\'\')';} if (new_all[i].height == 178) {var heightset = '178 cm (5\' 10\'\')';} if (new_all[i].height == 180) {var heightset = '180 cm (5\' 11\'\')';} if (new_all[i].height == 183) {var heightset = '183 cm (6\' 0\'\')';} if (new_all[i].height == 185) {var heightset = '185 cm (6\' 1\'\')';} if (new_all[i].height == 188) {var heightset = '185 cm (6\' 2\'\')';} if (new_all[i].height == 191) {var heightset = '191 cm (6\' 3\'\')';} if (new_all[i].height == 193) {var heightset = '193 cm (6\' 4\'\')';} if (new_all[i].height == 195) {var heightset = '195 cm (6\' 5\'\')';} if (new_all[i].height == 198) {var heightset = '198 cm (6\' 6\'\')';} if (new_all[i].height == 201) {var heightset = '201 cm (6\' 7\'\')';} if (new_all[i].height == 203) {var heightset = '203 cm (6\' 8\'\')';} $(".profileul_"+new_all[i].id ).append( ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Height</div>'+ ' <div class="item-input">'+ ' <input type="text" name="name" value="'+heightset+'" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } if (new_all[i].weight != 0){ $( ".profileul_"+new_all[i].id ).append( ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Weight</div>'+ ' <div class="item-input">'+ ' <input type="text" name="name" value="'+new_all[i].weight+' kg (' + Math.round(new_all[i].weight* 2.20462262) + ' lbs)" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } var timestring; var minutevalue; if (new_all[i].minutes <= 0){timestring = 'Now';} if (new_all[i].minutes == 1){timestring = '1 minute ago';} if ((new_all[i].minutes >= 0) && (new_all[i].minutes <60)){timestring = Math.round(new_all[i].minutes) + ' minutes ago';} if (new_all[i].minutes == 60){timestring = '1 hour ago';} if ((new_all[i].minutes >= 60) && (new_all[i].minutes <1440)){ minutevalue = Math.round((new_all[i].minutes / 60)); if (minutevalue == 1) {timestring = '1 hour ago';} else {timestring = minutevalue + ' hours ago';} } if ((new_all[i].minutes >= 60) && (new_all[i].minutes <1440)){timestring = Math.round((new_all[i].minutes / 60)) + ' hours ago';} if (new_all[i].minutes == 1440){timestring = '1 day ago';} if ((new_all[i].minutes >= 1440) && (new_all[i].minutes <10080)){ minutevalue = Math.round((new_all[i].minutes / 1440)); if (minutevalue == 1) {timestring = '1 day ago';} else {timestring = minutevalue + ' days ago';} } if (new_all[i].minutes >= 10080){timestring = '1 week';} if (new_all[i].minutes >= 20160){timestring = '2 weeks';} if (new_all[i].minutes >= 30240){timestring = '3 weeks';} $( ".timetag_" + new_all[i].id ).html(timestring); $( ".distancetag_" + new_all[i].id ).html(new_all[i].distancestring); if (new_all[i].availarraystring !== ''){ $( ".profileyo_" + new_all[i].id ).prepend( '<div class="content-block-title" style="padding-top:0px;clear:both;margin-top:-20px;">Availability</div>'+ '<div class="list-block media-list availabilitylistblock_'+new_all[i].id+'" style="margin-top:0px;clear:both;margin-bottom:-40px;">'+ '<ul style="background-color:transparent">'+ ' </ul></div>'); var availablearrayindividual = JSON.parse(new_all[i].availarraystring); console.log(availablearrayindividual); var tonight = new Date(); tonight.setHours(22,59,59,999); var tonight_timestamp = Math.round(tonight/1000); for (k = 0; k < availablearrayindividual.length; k++) { if (availablearrayindividual[k].id >= tonight_timestamp){ $( ".availabilitylistblock_"+new_all[i].id ).append( ' <li style="list-style-type:none;">'+ '<div class="item-content">'+ '<div class="item-media">'+ '<span class="badge" style="background-color:#4cd964;">'+availablearrayindividual[k].day.charAt(0)+'</span>'+ '</div>'+ ' <div class="item-inner">'+ ' <div class="item-input">'+ ' <input type="text" name="name" style="height:30px;font-size:15px;" value="'+availablearrayindividual[k].day+', '+availablearrayindividual[k].time+'" readonly>'+ ' <input type="text" style="float:right;color:#333;text-align:left;height:30px;font-size:15px;" name="name" value="'+availablearrayindividual[k].fulldate+'" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } } } } swiperQuestions = myApp.swiper('.swiper-questions', { nextButton:'.nexts', prevButton:'.prevs', onSetTranslate:function(swiper, translate){myPhotoBrowser.swiper.setWrapperTranslate(translate - (20 * swiper.activeIndex));}, onInit:function(swiper){ myPhotoBrowser.swiper.setWrapperTranslate(0); $( ".infoprofile").hide();$( ".adown" ).css( "opacity","1" ); var wrapperheightshould = $(".prof_" + swiper.activeIndex).height(); $( ".wrapper-questions").css("height",(wrapperheightshould - 150)+ "px"); $( ".availyope").hide(); $( ".availyo_"+ new_all[0].id ).show(); if (new_all.length === 1){swiper.lockSwipes();myPhotoBrowser.swiper.lockSwipes();} checkMatch(targetid); }, onSlideChangeStart:function(swiper){ var wrapperheightshould = $(".prof_" + swiper.activeIndex).height(); $( ".wrapper-questions").css("height",(wrapperheightshould - 150)+ "px"); if(comingback === 1){ if (swiper.activeIndex > swiper.previousIndex){myPhotoBrowser.swiper.slideNext();} if (swiper.activeIndex < swiper.previousIndex){myPhotoBrowser.swiper.slidePrev();} } // if (swiper.isBeginning === true){$( ".prevs" ).addClass( "disabled" ); //} // else{$( ".prevs" ).removeClass( "disabled" );} // if (swiper.isEnd === true){$( ".nexts" ).addClass( "disabled" );} // else{$( ".nexts" ).removeClass( "disabled" );} //if (swiper.isBeginning === true){$( ".prevs" ).addClass( "disabled" ); // $(".arrowdown_"+new_all[swiper.activeIndex + 1].id).hide(); //$(".arrowdown_"+new_all[swiper.activeIndex].id).show(); // } //else if (swiper.isEnd === true){$(".arrowdown_"+new_all[swiper.activeIndex -1].id).hide(); //$(".arrowdown_"+new_all[swiper.activeIndex].id).show(); } //else{$(".arrowdown_"+new_all[swiper.activeIndex + 1].id).hide(); //$(".arrowdown_"+new_all[swiper.activeIndex -1].id).hide(); //$(".arrowdown_"+new_all[swiper.activeIndex].id).show(); } //$( ".adown" ).css( "opacity","1" ); $( ".camerabadge" ).text(new_all[swiper.activeIndex].photocount); $( ".infoprofile").hide(); $( ".availyope").hide(); $( ".availyo_"+ new_all[swiper.activeIndex].id ).show(); //$(".swiper-questions").css("background-image", "url("+new_all[swiper.activeIndex].url+")"); //$(".slideinfo_"+new_all[swiper.activeIndex + 1].id).css("background-size", "cover"); //$(".slideinfo_"+new_all[swiper.activeIndex + 1].id).css("background-position", "50% 50%"); //$(".swiper-questions".css("background", "transparent"); $( ".swiper-questions" ).scrollTop( 0 ); if ($('.toolbarq').css('display') == 'block') { if (((swiper.activeIndex - swiper.previousIndex) > 1) ||((swiper.activeIndex - swiper.previousIndex) < -1) ){ //alert(swiper.activeIndex - swiper.previousIndex); //myPhotoBrowser.swiper.slideTo(0); myPhotoBrowser.swiper.slideTo(swiper.activeIndex); //swiper.slideTo(myPhotoBrowser.swiper.activeIndex); } } checkMatch(targetid); } }); //console.log(myPhotoBrowser.swiper.activeIndex); swiperQuestions.slideTo(myPhotoBrowser.swiper.activeIndex,0); $( ".toolbarq" ).show(); comingback = 1; $( ".camerabadge" ).text(new_all[myPhotoBrowser.swiper.activeIndex].photocount); $( ".distancetag" ).text(new_all[myPhotoBrowser.swiper.activeIndex].distancestring); //if (myPhotoBrowser.swiper.activeIndex === 0){ //myPhotoBrowser.swiper.slideNext(); //myPhotoBrowser.swiper.slidePrev(); //} //else { //} //swiperQuestions.slideTo(myPhotoBrowser.swiper.activeIndex); } function checkMatch(targetid){ var indivNotif = firebase.database().ref('notifications/' + f_uid + '/' + targetid); indivNotif.once('value', function(snapshot) { if (snapshot.val()){ var obj = snapshot.val(); if (obj.new_message_count >0 && obj.to_uid == f_uid && obj.received =='N'){$( ".indivnotifcount" ).remove();$( ".arrowdivbrowser" ).append('<span class="badge indivnotifcount" style="position:absolute;right:0px;background-color:rgb(255, 208, 0);color:black;">'+obj.new_message_count+'</span>');} else{$( ".indivnotifcount" ).remove();} } }); var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} return firebase.database().ref('matches/' + f_uid + '/' + targetid).once('value').then(function(snapshot) { $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); $( ".loaderlink" ).hide(); $( ".orlink" ).show(); if (snapshot.val() === null) {} else { if (first_number == f_uid){ if (snapshot.val().firstnumberreport){targetreported = true;}else {targetreported = false;} //Dates if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );} if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );} if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){ $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" ); $( ".duck-template" ).hide(); $( ".date-template" ).show(); $( ".toolbardecide" ).hide(); matchNavbar(); d_type='date'; } else {} //Duck if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );} if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );} if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberduck == 'Y'){ $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" ); $( ".duck-template" ).show(); $( ".date-template" ).hide(); $( ".toolbardecide" ).hide(); matchNavbar(); d_type='duck'; } else {} } if (first_number == targetid){ if (snapshot.val().secondnumberreport){targetreported = true;}else {targetreported = false;} //Date if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );} if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );} if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){ $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" ); $( ".duck-template" ).hide(); $( ".date-template" ).show(); $( ".toolbardecide" ).hide(); matchNavbar(); d_type='date'; } else {} //Duck if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );} if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );} if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberduck == 'Y'){ $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" ); $( ".duck-template" ).show(); $( ".date-template" ).hide(); $( ".toolbardecide" ).hide(); matchNavbar(); d_type='duck'; } else {} } } }); } function photoBrowser(openprofile,arraynumber,mainchange,chatorigin){ allowedchange = true; photoresize = false; if ($('.photo-browser').length > 0){return false;} myApp.closeModal('.picker-sub'); //firebase.database().ref("users/" + f_uid).off('value', userpref); var photobrowserclass=""; var duckfunction = "" var datefunction = "" if ($('.chatpop').length > 0) {$( ".chatpop" ).css( "z-index","10000" );photobrowserclass="photo-browser-close-link";} else{duckfunction = "createDuck()";datefunction = "createDate1()";} var to_open = 0; if ($('.chatpop').length > 0 || chatorigin) {alert('yo3');} else { var countednumbers = 0; for (var i = f_lower; i < arraynumber; i++) { countednumbers = countednumbers + all_matches_photos[i].length; } to_open = countednumbers + openprofile; alert('got here'); } var hiddendivheight = $( window ).height() - 40; myPhotoBrowser = myApp.photoBrowser({ zoom: false, expositionHideCaptions:true, lazyLoading:true, lazyLoadingInPrevNext:true, lazyPhotoTemplate: '<div class="photo-browser-slide photo-browser-slide-lazy swiper-slide">'+ '<div class="preloader {{@root.preloaderColorClass}}">{{#if @root.material}}{{@root.materialPreloaderSvg}}{{/if}}</div>'+ '<div class="swiper-container swiper-vertical" style="height:100%;min-width:'+$(document).width()+'px">'+ '<div class="swiper-wrapper vertical-wrapper-swiper">'+ '{{js "this.photos"}}'+ '</div><div class="swiper-pagination vertical-pag" style="top:0;left:0;z-index:999999;"></div></div>'+ '</div>', exposition:false, photos: new_all, captionTemplate:'<div style="width:40px;height:40px;background-color:transparent;margin-top:-80px;margin-left:50px;float:right;display:none;"></div><div class="photo-browser-caption" data-caption-index="{{@index}}">{{caption}}</div>', toolbarTemplate:'<div class="toolbar tabbar toolbarq" style="height:84px;background-color:transparent;">'+ //<img src="media/datefaceonly.png" style="width:100px;"> //<img src="media/duckfaceonly.png" style="width:100px;"> ' <div class="toolbar-inner date-template" style="display:none;padding:0;background-color:#2196f3;height:74px;border-bottom-right:20px;border-bottom-left:20px;">'+ '<a href="#" onclick="dateUser();" class="button link" style="color:#ccc;font-size:15px;max-width:80px;border:0;">'+ ' Unmatch'+ '</a>'+ '<p style="font-family: \'Pacifico\', cursive;font-size:20px;visibility:hidden;">or</p>'+ '<a href="#" onclick="'+datefunction+'" class="button link active lets '+photobrowserclass+'" style="border:1px solid white;margin-right:15px;margin-left:-15px;font-family: \'Pacifico\', cursive;font-size:26px;height:40px;">Let\'s Date <div style="font-family: -apple-system, SF UI Text, Helvetica Neue, Helvetica, Arial, sans-serif;position:absolute;right:0px;top:-8px;" class="arrowdivbrowser"><i class="pe-7s-angle-right pe-2x"></i></div></a></div>'+ // '<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:26px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+ ' <div class="toolbar-inner duck-template" style="display:none;padding:0;background-color:#2196f3;height:74px;border-bottom-right:20px;border-bottom-left:20px;">'+ '<a href="#" onclick="duckUser();" class="button link" style="color:#ccc;font-size:15px;max-width:80px;border:0;">'+ ' Unmatch'+ '</a>'+ // '<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:26px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+ '<a href="#" onclick="'+duckfunction+'" class="button link active lets '+photobrowserclass+'" style="border:1px solid white;margin-right:15px;margin-left:-15px;font-family: \'Pacifico\', cursive;font-size:26px;height:40px;">Let\'s Duck</a></div>'+ ' <div class="toolbar-inner toolbardecide" style="padding-bottom:10px;padding-left:0px;padding-right:0px;">'+ // ' <a href="#" class="link prevphoto" style="color:black">'+ // '<i class="pe-7s-angle-left pe-3x" ></i>'+ // ' </a>'+ //' <a href="#" class="link prevs" style="display:none;color:black;">'+ // '<i class="pe-7s-angle-left pe-3x"></i>'+ // ' </a>'+ '<a href="#tab3" onclick="dateUser();" class="datebutton disabled button link" style="border:1px solid white;border-right:0;border-radius:20px;border-top-right-radius:0px;border-top-left-radius:0px;border-bottom-right-radius:0px;font-family: \'Pacifico\', cursive;font-size:24px;">'+ '<span class="datefloat" style="padding:10px;border-radius:5px;margin-right:20px;">Date</span>'+ ' <div style="width:50px;overflow-x:hidden;position:absolute;right:-1px;bottom:-8px;"><img src="media/datefaceonly.png" style="width:100px;">'+ '</div>'+ ' </a>'+ ' <a href="#tab3" onclick="duckUser();" class="duckbutton disabled button link" style="border:1px solid white;border-left:0;border-radius:20px;border-top-left-radius:0px;border-top-right-radius:0px;border-bottom-left-radius:0px;font-family: \'Pacifico\', cursive;font-size:24px;">'+ '<span class="duckfloat" style="padding:10px;border-radius:5px;margin-left:20px;">Duck</span>'+ ' <div style="width:54px;overflow-x:hidden;position:absolute;left:-1px;bottom:-8px;"> <img src="media/duckfaceonly.png" style="width:100px;margin-left:-50px;"></div>'+ '</a>'+ //'<a href="#" onclick="dateUser();" class="datebutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:70px;width:72px;overflow:hidden;"><img //src="media/dateicon.png" style="width:70px;margin-left:40px;"></a>'+ // ' <a href="#" class="link orlink">'+ // '<p class="dateducktitle" style="font-family: \'Pacifico\', cursive;font-size:20px;text-align:center;">or</p>'+ // ' </a>'+ '<a href="#" class="link loaderlink"><span class="preloader preloader-white login-loader"></span></a>'+ //'<a href="#" onclick="duckUser();" class="duckbutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:70px;width:72px;overflow:hidden;"><img //src="media/duckicon.png" style="width:70px;margin-right:40px;"></a>'+ //' <a href="#" class="link nextphoto" style="color:black">'+ // '<i class="pe-7s-angle-right pe-3x"></i>'+ // ' </a>'+ // ' <a href="#" class="link nexts" style="display:none;color:black;">'+ // '<i class="pe-7s-angle-right pe-3x"></i>'+ // ' </a>'+ ' </div>'+ '</div>', onClose:function(photobrowser){hideProfile(); viewphotos = false; viewscroll = false; if ($('.chatpop').length > 0) {$( ".chatpop" ).css( "z-index","20000" );if ($('.chatpop').length > 0){myApp.closeModal('.infopopup');} if (swiperQuestions){ swiperQuestions.removeAllSlides(); swiperQuestions.destroy();swiperQuestions = false;} } else{myApp.closeModal(); } if (mainchange){new_all = main_all;singleuserarray = [];} //getPreferences(); }, swipeToClose:false, // onClick:function(swiper, event){showProfile();}, nextButton:'.nextphoto', prevButton:'.prevphoto', onSlideChangeStart:function(swiper){ if (allowedchange){ if (photoresize){ if ($('.infopopup').length > 0){} else{getMeta(new_all[swiper.activeIndex].url); } } if (swiper.activeIndex != openprofile){ photoresize = true;} if (swiper.isBeginning === true){$( ".prevphoto" ).addClass( "disabled" );} else{$( ".prevphoto" ).removeClass( "disabled" );} if (swiper.isEnd === true){$( ".nextphoto" ).addClass( "disabled" );} else{$( ".nextphoto" ).removeClass( "disabled" );} //var windowheight = $( window ).height(); //$( ".photo-browser-slide img").css( "height", "100% - 144px)" ); $( ".photo-browser-caption" ).empty(); $( ".nametag" ).empty(); $( ".datebutton" ).removeClass( "active" ); $( ".duckbutton" ).removeClass( "active" ); $( ".duckbutton" ).addClass( "disabled" ); $( ".datebutton" ).addClass( "disabled" ); $( ".loaderlink" ).show(); $( ".orlink" ).hide(); match = 0; targetid = new_all[myPhotoBrowser.activeIndex].id; $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" ); //$( ".photo-browser-slide.swiper-slide-active img" ).css( "height", "100% - 144px)" ); $( ".duck-template" ).hide(); $( ".date-template" ).hide(); unmatchNavbar(); $( ".toolbardecide" ).show(); $( ".datebutton" ).removeClass( "likesme" ); $( ".duckbutton" ).removeClass( "likesme" ); var activecircle; var targetdescription= new_all[myPhotoBrowser.activeIndex].description; targetname = new_all[myPhotoBrowser.activeIndex].name; var targetage = new_all[myPhotoBrowser.activeIndex].age; $( ".agecat" ).text(targetage); $( ".nametag" ).empty(); $( ".nametag" ).append('<div class="rr r_'+targetid+'">'+targetname+', '+targetage+'</div>'); $( ".photo-browser-caption" ).empty(); $( ".photo-browser-caption" ).append(targetdescription); myApp.sizeNavbars(); } }, backLinkText: '', //expositionHideCaptions:true, navbarTemplate: // ' <a href="#tab1" class="prevphoto button disabled" style="border-radius:5px;position:absolute;left:-31px;top:50%;margin-top:-28px;height:56px;width:56px;border:0;z-index:99999;color:#2196f3;background-color:transparent;"><i class="pe-7s-angle-left pe-4x" style="margin-left:5px;margin-top:-1px;"></i></a>'+ // ' <a href="#tab3" class="nextphoto button" style="border-radius:5px;position:absolute;right:-33px;width:56px;top:50%;margin-top:-26px;height:56px;color:#2186f3;border:0;z-index:99999;background-color:transparent"><i class="pe-7s-angle-right pe-4x" style="margin-left:-35px;margin-top:-1px;"></i></a>'+ // '<div style="position:absolute;bottom:80px;right:0px;margin-left:-26px;z-index:9999;color:white;"><i class="pe-7s-info pe-4x" style="margin-top:-10px;"></i></div>'+ '<div class="navbar photobrowserbar" style="background-color:#ccc">'+ ' <div class="navbar-inner">'+ ' <div class="left sliding">'+ ' <a href="#" style="margin-left:-10px;"class="link photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'+ '<i class="pe-7s-angle-left pe-3x matchcolor"></i>'+ '<span class="badge agecat" style="margin-left:-10px;display:none;">'+arraynumber+'</span>'+ ' </a>'+ ' </div>'+ ' <div class="center sliding nametag matchcolor">'+ // ' <span class="photo-browser-current"></span> '+ // ' <span class="photo-browser-of">{{ofText}}</span> '+ // ' <span class="photo-browser-total"></span>'+ ' </div>'+ ' <div class="right" onclick="actionSheet()">' + //'<a href="#" class="link"><div class="cameradivnum" style="background-color:transparent;border-radius:50%;opacity:0.9;float:left;z-index:999;"><i class="pe-7s-camera pe-lg matchcolor" style="margin-top:3px;margin-left:-5px;"></i><div class="camerabadge badge" style="position:absolute;right:0px;margin-right:-10px;top:5px;z-index:999;"></div></div></a>'+ '<a href="#" class="link">'+ ' <i class="pe-7s-more pe-lg matchcolor"></i>'+ ' </a>'+ '</div>'+ '</div>'+ '</div> ' }); myPhotoBrowser.open(); targetid = new_all[myPhotoBrowser.activeIndex].id; var mySwiperVertical = myApp.swiper('.swiper-vertical', { direction: 'vertical', zoom:'true', pagination:'.swiper-pagination', paginationType:'progress', onSlideChangeStart:function(swiper){ var verticalheightarray = new_all[myPhotoBrowser.activeIndex].heightslides.split(","); var verticalwidtharray = new_all[myPhotoBrowser.activeIndex].widthslides.split(","); var trueh = verticalheightarray[swiper.activeIndex]; var truew = verticalwidtharray[swiper.activeIndex];; if (trueh > truew){ $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','auto'); $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','100%'); $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','cover'); } else if (trueh == trueh){ $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','100%'); $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','auto'); $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','cover'); } else{ $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','100%'); $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','auto'); $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','none'); } console.log(new_all[myPhotoBrowser.activeIndex]);}, onImagesReady:function(swiper){ console.log(swiper);}, onInit:function(swiper){ //console.log(new_all[myPhotoBrowser.activeIndex]); // if (viewphotos){ setTimeout(function(){ backtoProfile();viewphotos = false; }, 100); } if (viewscroll){ setTimeout(function(){ scrolltoTop();viewscroll = false; }, 100); } }, onClick:function(swiper, event){ questions(); //if(myPhotoBrowser.exposed === true) {$( ".swiper-container-vertical img " ).css("margin-top","0px");} //else {$( ".photo-browser-slide img " ).css("height","calc(100% - 120px)");$( ".photo-browser-slide img " ).css("margin-top","-35px");} } }); //var windowwidth = $( ".photo-browser-swiper-container" ).width(); $( ".photo-browser-slide img" ).css( "-webkit-filter","grayscale(80%)" ); $( ".photo-browser-caption" ).css( "margin-top", "-10px" ); $( ".photo-browser-caption" ).empty(); $( ".nametag" ).empty(); myPhotoBrowser.swiper.slideTo(to_open,100); questions(); if (openprofile ===0){ if (myPhotoBrowser.swiper.isBeginning === true){$( ".prevphoto" ).addClass( "disabled" );} else{$( ".prevphoto" ).removeClass( "disabled" );} if (myPhotoBrowser.swiper.isEnd === true){$( ".nextphoto" ).addClass( "disabled" );} else{$( ".nextphoto" ).removeClass( "disabled" );} //var windowheight = $( window ).height(); //$( ".photo-browser-slide img").css( "height", "100% - 144px)" ); $( ".photo-browser-caption" ).empty(); $( ".nametag" ).empty(); $( ".datebutton" ).removeClass( "active" ); $( ".duckbutton" ).removeClass( "active" ); $( ".duckbutton" ).addClass( "disabled" ); $( ".datebutton" ).addClass( "disabled" ); $( ".loaderlink" ).show(); $( ".orlink" ).hide(); match = 0; var target = new_all[myPhotoBrowser.activeIndex].url; var pretarget = target.replace("https://graph.facebook.com/", ""); targetid = String(pretarget.replace("/picture?width=828", "")); $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" ); //$( ".photo-browser-slide.swiper-slide-active img" ).css( "height", "100% - 144px)" ); $( ".duck-template" ).hide(); $( ".date-template" ).hide(); unmatchNavbar(); $( ".toolbardecide" ).show(); $( ".datebutton" ).removeClass( "likesme" ); $( ".duckbutton" ).removeClass( "likesme" ); var activecircle; var targetdescription= new_all[myPhotoBrowser.activeIndex].description; targetname = new_all[myPhotoBrowser.activeIndex].name; var targetage = new_all[myPhotoBrowser.activeIndex].age; $( ".agecat" ).text(targetage); $( ".nametag" ).empty(); $( ".nametag" ).append('<span class="rr r_'+targetid+'">'+targetname+', '+targetage+'</span>'); $( ".photo-browser-caption" ).empty(); $( ".photo-browser-caption" ).append(targetdescription); myApp.sizeNavbars(); //may need to readd } } function showProfile(){ $( ".profile-info" ).show(); } function hideProfile(){ $( ".profile-info" ).hide(); } function dateRequest(){ $( ".dateheader" ).hide(); $( ".date-close" ).hide(); $( ".date-button" ).hide(); var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var ref = firebase.database().ref(); var datemessageq = $( '#datemessageq' ).val(); var unix = Math.round(+new Date()/1000); var day = pickerCustomToolbar.cols[0].displayValue; var time; if (pickerCustomToolbar.cols[0].displayValue =='Now'){time='';} else if (pickerCustomToolbar.cols[0].displayValue =='Today'){ var daterequestnow = new Date; var hournow = daterequestnow.getHours(); if((pickerCustomToolbar.cols[0].displayValue =='Morning') && (hournow >= '12')){time='';} else if((pickerCustomToolbar.cols[0].displayValue =='Mid-day') && (hournow > '14')){time='';} else if((pickerCustomToolbar.cols[0].displayValue =='Afternoon') && (hournow > '17')){time='';} else{time = pickerCustomToolbar.cols[1].value;} } else{time = pickerCustomToolbar.cols[1].value;} var chat_expire = pickerCustomToolbar.cols[0].value; var interestarray = []; if (d_type == 'date'){ $( ".interestbutton" ).each(function() { if ($( this ).hasClass( "interestchosen" )) { var classList = $(this).attr("class").split(' '); var interestadd = classList[1].split('_')[0]; interestarray.push(interestadd); } }); } if (d_type == 'duck'){ if ($( '.button-my' ).hasClass( "active" )){interestarray = 'my'} if ($( '.button-your' ).hasClass( "active" )){interestarray = 'your'} } firebase.database().ref("dates/" + f_uid +'/' + targetid).set({ created_uid: f_uid, created_name: f_first, received_uid:targetid, received_name:targetname, timestamp:unix, day:day, time:time, chat_expire:chat_expire, seen:'N', interest:interestarray, response:'W', type:d_type, message:datemessageq, authcheck:f_uid }); firebase.database().ref("dates/" + targetid +'/' + f_uid).set({ created_uid: f_uid, created_name: f_first, received_uid:targetid, received_name:targetname, timestamp:unix, day:day, time:time, chat_expire:chat_expire, seen:'N', interest:interestarray, response:'W', type:d_type, message:datemessageq, authcheck:f_uid }); var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) { var objs = snapshot.val(); var messageq; //If existing notifications, get number of unseen messages, delete old notifications if (snapshot.val()){ $.each(objs, function(i, obj) { if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){ firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove(); firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove(); if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){ messageq = obj.new_message_count; messageq ++; } } }); } newNotification(); }); function newNotification(messagenum){ if (!messagenum) {messagenum = 1;} var smessage; if (d_type=='duck'){smessage = 'Duck request'} if (d_type=='date'){smessage = 'Date request'} // Get a key for a new Post. var newPostKey = firebase.database().ref().push().key; var t_unix = Math.round(+new Date()/1000); var targetData = { id:newPostKey, from_uid: f_uid, from_name: f_first, to_uid:targetid, to_name:targetname, message:smessage, timestamp: t_unix, type:d_type, param:'daterequest', new_message_count:messagenum, received:'N', expire:d_chat_expire, authcheck:f_uid }; // Write the new post's data simultaneously in the posts list and the user's post list. var updates = {}; updates['notifications/' + f_uid + '/' + targetid] = targetData; updates['notifications/' + targetid + '/' + f_uid] = targetData; return firebase.database().ref().update(updates).then(function() { if(d_response=='Y') {chatShow();} else {reverseRequest();} }); } } var d_interest,d_day,d_chat_expire,d_time,d_response,d_type,d_timestamp,d_dateseen,d_dateseentime,d_timeaccepted; function existingDate(){ $( ".datearea" ).empty(); var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} // Test if user exists var ref = firebase.database().ref("dates/" + f_uid +'/' + targetid); ref.once("value") .then(function(snapshot) { var dateexists = snapshot.child('chat_expire').exists(); // true if (dateexists) { var unix = Math.round(+new Date()/1000); if (Number(snapshot.child('chat_expire').val()) > Number(unix) ) { d_chat_expire = snapshot.child('chat_expire').val(); d_interest = snapshot.child('interest').val(); d_type = snapshot.child('type').val(); d_day = snapshot.child('day').val(); d_time = snapshot.child('time').val(); d_response = snapshot.child('response').val(); if (snapshot.child('time_accepted').exists()){ d_timeaccepted = snapshot.child('time_accepted').val();} d_created_uid = snapshot.child('created_uid').val(); d_timestamp = snapshot.child('timestamp').val(); d_dateseen = snapshot.child('dateseen').val(); d_dateseentime = snapshot.child('dateseentime').val(); d_message = snapshot.child('message').val(); if (d_response == 'Y') {chatShow();} else { noMessages(); setDate(); dateConfirmationPage(); } $( ".messages-loader" ).hide(); } else{ cancelDate(); //$( ".center-date" ).empty(); //$( ".center-date" ).append(targetname); myApp.sizeNavbars(); $( ".messages-loader" ).hide(); } } else{ d_chat_expire = false; d_interest = false; d_day = false; d_time = false; d_response = false; d_message = false; d_timeaccepted; d_dateseen = false; d_dateseentime = false; d_timestamp = false; noMessages(); setDate(); // $( ".center-date" ).empty(); //$( ".center-date" ).append(targetname); myApp.sizeNavbars(); $( ".messages-loader" ).hide(); } }); } function interests(id){ $( "." + id + "_i" ).toggleClass( "interestchosen" ); } function sendMessage(){ var weekday = []; weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; var month = []; month[0] = "Jan"; month[1] = "Feb"; month[2] = "Mar"; month[3] = "Apr"; month[4] = "May"; month[5] = "Jun"; month[6] = "Jul"; month[7] = "Aug"; month[8] = "Sep"; month[9] = "Oct"; month[10] = "Nov"; month[11] = "Dec"; var stringnow = new Date(); var stringyestday = new Date(Date.now() - 86400); var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate(); var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate(); var datechatstring; var messagedate = new Date(); var minstag = ('0'+messagedate.getMinutes()).slice(-2); messagetimetitle = messagedate.getHours() + ':' + minstag; var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate(); if (!prevdatetitle){prevdatetitle = messagedaytitle;console.log('prevdatetitle does not exist'); if (messagedaytitle == todaystring){datechatstring = 'Today';} else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';} else{datechatstring = messagedaytitle;} } else { if (prevdatetitle == messagedaytitle){console.log('it is the same day');datechatstring='';} else{console.log('it is a different day');prevdatetitle = messagedaytitle; if (messagedaytitle == todaystring){datechatstring = 'Today';} else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';} else{datechatstring = messagedaytitle;} } } var newmessage = $( "#messagearea" ).val(); if (newmessage === ''){return false;} conversation_started = true; var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var t_unix = Math.round(+new Date()/1000); firebase.database().ref("chats/" + first_number+ '/' + second_number).push({ from_uid: f_uid, from_name: f_first, to_uid:targetid, to_name:targetname, message:newmessage, seen:'N', timestamp: t_unix, type: d_type, param:'message', authcheck:f_uid }); myMessages.addMessage({ // Message text text: newmessage, // Random message type type: 'sent', // Avatar and name: avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal', name: f_first, day:datechatstring, label: 'Sent ' + messagetimetitle }); myMessagebar.clear(); var messageq; var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) { var objs = snapshot.val(); //If existing notifications, get number of unseen messages, delete old notifications if (snapshot.val()){ //alert('yo3'); $.each(objs, function(i, obj) { if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){ //alert(obj.param); // alert(obj.received); if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){ // alert('param'+obj.param); // alert('new_message_count'+obj.new_message_count); if (obj.param =='message'){ messageq = obj.new_message_count; messageq ++;} else{ messageq = 1; } } firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove(); firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove(); } }); } newNotification(messageq); }); function newNotification(messagenum){ //alert('messagenum'+messagenum); if (!messagenum) {messagenum = 1;} //alert(messagenum); // Get a key for a new Post. var newPostKey = firebase.database().ref().push().key; var targetData = { id:newPostKey, from_uid: f_uid, from_name: f_first, to_uid:targetid, to_name:targetname, message:newmessage, timestamp: t_unix, type:d_type, param:'message', new_message_count:messagenum, received:'N', expire:d_chat_expire, authcheck:f_uid }; // Write the new post's data simultaneously in the posts list and the user's post list. var updates = {}; updates['notifications/' + f_uid + '/' + targetid] = targetData; updates['notifications/' + targetid + '/' + f_uid] = targetData; return firebase.database().ref().update(updates); } $( "#messagearea" ).val(''); $( ".sendbutton" ).removeClass('disabled'); $( ".sendbutton" ).css('color','white'); } function clearchatHistory(){ messages_loaded = false; if (main_all[0] != null){ new_all = main_all; } singleuserarray = []; letsload = 20; var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} if (message_history){ //firebase.database().ref("notifications/" + f_uid).off('value', existingchatnotifications); firebase.database().ref("chats/" + first_number+ '/' + second_number).off('child_added', message_historyon); if(additions>0){ for (i = 0; i < additions.length; i++) { firebase.database().ref("chats/" + first_number+ '/' + second_number).off('child_added', newmessage_history); } } message_history = false; message_count = 0; additions = 0; existingmessages = false; conversation_started = false; myMessages.clean(); myMessages.destroy(); } if (datealertvar === true){ firebase.database().ref("dates/" + f_uid +'/' + targetid).off('value', datealert); } datealertvar = false; if ($$('body').hasClass('with-panel-left-reveal')) { $(".timeline").empty(); rightPanel(); } if ($$('body').hasClass('with-panel-right-reveal')) { myList.deleteAllItems(); myList.clearCache(); leftPanel(); } } function dateConfirmationPage(details){ canloadchat = false; var g = new Date(d_chat_expire*1000 - 3600); var weekday = []; weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; var gday = weekday[g.getDay()]; var proposeddate = g.getDate(); var month = []; month[0] = "January"; month[1] = "February"; month[2] = "March"; month[3] = "April"; month[4] = "May"; month[5] = "June"; month[6] = "July"; month[7] = "August"; month[8] = "September"; month[9] = "October"; month[10] = "November"; month[11] = "December"; var messageclass; if (d_created_uid == f_uid){messageclass="message-sent";messagestyle="";} else{messageclass = "message-received";messagestyle="margin-left:70px;";} var proposedmonth = month[g.getMonth()]; var proposedyear = g.getFullYear(); var dending; if (proposeddate == '1' || proposeddate == '21' || proposeddate == '31'){dending = 'st'} else if (proposeddate == '2' || proposeddate == '22'){dending = 'nd'} else if (proposeddate == '3' || proposeddate == '23'){dending = 'rd'} else {dending = 'th'} $( ".dateheader" ).hide(); $( ".profileroundpic" ).show(); $( ".date1-close" ).hide(); $( ".date2-close" ).hide(); $( ".message-inner" ).hide(); $( ".date-inner" ).hide(); $( ".date-back" ).show(); var timedisplay; // $( ".center-date" ).empty(); //$( ".center-date" ).append(targetname.capitalize()); var titleblock; var namefromdate; var nametodate; if (d_created_uid == f_uid){namefromdate = f_first;nametodate = targetname;} else{nametodate = f_first;namefromdate = targetname;} var whatrow; var dateseentitle; var timestamptitle; var capitalD; if (d_type =='duck'){titleblock = '<span style="font-family: \'Pacifico\', cursive;">Duck Request</span>';whatrow = 'Duck';capitalD = 'Duck';} if (d_type =='date'){titleblock = '<span style="font-family: \'Pacifico\', cursive;">Date Request</span>';whatrow = 'Date';capitalD = 'Date';} var unixnow = Math.round(+new Date()/1000); var tunixago = unixnow - d_timestamp; var tunixminago = tunixago / 60; if (tunixminago < 1) {timestamptitle = 'Sent less than 1 minute ago';} else if (tunixminago == 1) {timestamptitle = 'Sent 1 minute ago';} else if (tunixminago < 2) {timestamptitle = 'Sent 1 minute ago';} else if (tunixminago < 60) {timestamptitle = 'Sent '+Math.round(tunixminago)+' minutes ago';} else if (tunixminago == 60) {timestamptitle = 'Sent 1 hour ago';} else if (tunixminago < 62) {timestamptitle = 'Sent 1 hour ago';} else if (tunixminago < 1440) {timestamptitle = 'Sent '+Math.round(tunixminago / 60) +' hours ago';} else if (tunixminago == 1440) {timestamptitle = 'Sent 1 day ago';} else if (tunixminago < 2880) {timestamptitle = 'Sent 1 day ago';} else if (tunixminago >= 2880) {timestamptitle = 'Sent '+Math.round(tunixminago / 1440) +' days ago';} if (d_dateseen){ var unixago = unixnow - d_dateseentime; var unixminago = unixago / 60; if (unixminago < 1) {dateseentitle = 'Seen less than 1 minute ago';} else if (unixminago == 1) {dateseentitle = 'Seen 1 minute ago';} else if (unixminago < 2) {dateseentitle = 'Seen 1 minute ago';} else if (unixminago < 60) {dateseentitle = 'Seen '+Math.round(unixminago)+' minutes ago';} else if (unixminago == 60) {dateseentitle = 'Seen 1 hour ago';} else if (unixminago < 62) {dateseentitle = 'Seen 1 hour ago';} else if (unixminago < 1440) {dateseentitle = 'Seen '+Math.round(unixminago / 60) +' hours ago';} else if (unixminago == 1440) {dateseentitle = 'Seen 1 day ago';} else if (unixminago < 2880) {dateseentitle = 'Seen 1 day ago';} else if (unixminago >= 2880) {dateseentitle = 'Seen '+Math.round(unixminago / 1440) +' days ago';} } else{dateseentitle = 'Request not seen yet';} myApp.sizeNavbars(); var messagedateblock; if (d_message){ messagedateblock='<li><div class="item-content"><div class="item-inner"><div class="messages-content"><div class="messages messages-init" data-auto-layout="true" style="width:100%;clear:both;"> <div class="item-title label" style="width:80px;float:left;margin-top:10px;text-align:left;">Message</div><div class="message '+messageclass+' message-with-avatar message-appear-from-top message-last message-with-tail" style="'+messagestyle+'clear:both;text-align:left;"><div class="message-text">'+d_message+'</div><div class="message-avatar" style="background-image:url(https://graph.facebook.com/'+d_created_uid+'/picture?type=normal)"></div></div></div></div></div></div></li><li style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'; } else {messagedateblock='';} if (d_time) {timedisplay = ', ' + d_time} else {timedisplay='';} if (details){ var junixago = unixnow - d_timeaccepted; var junixminago = junixago / 60; var acceptedtitle; if (junixminago < 1) {acceptedtitle = 'Confirmed less than 1 minute ago';} else if (junixminago == 1) {acceptedtitle = 'Confirmed 1 minute ago';} else if (junixminago < 2) {acceptedtitle = 'Confirmed 1 minute ago';} else if (junixminago < 60) {acceptedtitle = 'Confirmed '+Math.round(junixminago)+' minutes ago';} else if (junixminago == 60) {acceptedtitle = 'Confirmed 1 hour ago';} else if (junixminago < 62) {acceptedtitle = 'Confirmed 1 hour ago';} else if (junixminago < 1440) {acceptedtitle = 'Confirmed '+Math.round(junixminago / 60) +' hours ago';} else if (junixminago == 1440) {acceptedtitle = 'Confirmed 1 day ago';} else if (junixminago < 2880) {acceptedtitle = 'Confirmed 1 day ago';} else if (junixminago >= 2880) {acceptedtitle = 'Confirmed '+Math.round(junixminago / 1440) +' days ago';} $( ".date1-close" ).hide(); $( ".date2-close" ).show(); $( ".date-close" ).hide(); $( ".date-back" ).hide(); $( ".datetoolbar" ).show(); $( ".sender-inner" ).show(); $( ".yes-inner" ).hide(); //$( ".datetoolbar" ).css("background-color","#ccc"); $( ".waitingreply" ).empty(); $( ".datedetailsdiv" ).hide(); $( ".requestbutton" ).remove(); $( ".requesticon" ).remove(); $( ".waitingreply" ).append( '<div style="background-color:#4cd964;padding:10px;text-align:center;font-size:20px;color:white;"><span style="font-family: \'Pacifico\', cursive;">'+capitalD+' Details</span></div>'+ '<div class="list-block media-list" onclick="request();" style="margin-top:0px;"><ul style="background-color:white;padding-bottom:10px;">'+ '<img src="media/'+d_type+'faceonly.png" style="height:60px;margin-top:15px;">'+ '<li>'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label" style="width:70px;float:left;text-align:left;">When?</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<input type="text" name="name" value="'+gday+timedisplay+'" readonly>'+ '<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+proposeddate + dending + ' '+ proposedmonth + ' ' + proposedyear +'" readonly>'+ '</div>'+ ' </div></div>'+ ' </li>'+ '<li class="interestli" style="display:none;">'+ '<div class="item-content">'+ ' <div class="item-inner" style="padding-top:15px;padding-bottom:15px;">'+ ' <div class="item-title label" style="float:left;width:70px;text-align:left;">Where?</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<span class="interestdiv" style="float:left;text-align:center;"></span>'+ '</div>'+ '</div>'+ '</div>'+ ' </li>'+ '<li class="interestli" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+ '<li>'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label" style="width:70px;float:left;text-align:left;">From</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<input type="text" name="name" value="'+namefromdate+'" readonly>'+ '<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+timestamptitle+'" readonly>'+ '</div>'+ ' </div></div>'+ ' </li>'+ messagedateblock + '<li>'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label" style="width:70px;float:left;text-align:left;">To</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<input type="text" name="name" value="'+nametodate+'" readonly>'+ '<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+acceptedtitle+'" readonly>'+ '</div>'+ ' </div></div>'+ ' </li>'+ '<li class="" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+ '</ul>'+ '</div>' ); $( ".titleconfirm" ).show(); $( ".titleconfirm" ).html(capitalD + ' confirmed'); $( ".infoconfirm" ).html('You can continue chatting until midnight of your scheduled '+d_type); } else if (d_created_uid == f_uid) { $( ".datetoolbar" ).show(); $( ".sender-inner" ).show(); $( ".yes-inner" ).hide(); //$( ".datetoolbar" ).css("background-color","#ccc"); $( ".waitingreply" ).empty(); $( ".datedetailsdiv" ).hide(); $( ".requestbutton" ).remove(); $( ".requesticon" ).remove(); $( ".titleconfirm" ).show(); $( ".titleconfirm" ).html('Waiting for '+targetname+' to respond'); $( ".waitingreply" ).append( '<div style="background-color:#ff9500;padding:10px;text-align:center;font-size:20px;color:white;">'+titleblock+'</div>'+ '<div class="list-block media-list" onclick="request();" style="margin-top:0px;"><ul style="background-color:white;padding-bottom:10px;">'+ '<img src="media/'+d_type+'faceonly.png" style="height:60px;margin-top:15px;">'+ '<li>'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label" style="width:70px;float:left;text-align:left;">When?</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<input type="text" name="name" value="'+gday+timedisplay+'" readonly>'+ '<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+proposeddate + dending + ' '+ proposedmonth + ' ' + proposedyear +'" readonly>'+ '</div>'+ ' </div></div>'+ ' </li>'+ '<li class="interestli" style="display:none;">'+ '<div class="item-content">'+ ' <div class="item-inner" style="padding-top:15px;padding-bottom:15px;">'+ ' <div class="item-title label" style="float:left;width:70px;text-align:left;">Where?</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<span class="interestdiv" style="float:left;text-align:center;"></span>'+ '</div>'+ '</div>'+ '</div>'+ ' </li>'+ '<li class="interestli" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+ '<li>'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label" style="width:70px;float:left;text-align:left;">From</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<input type="text" name="name" value="'+namefromdate+'" readonly>'+ '<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+timestamptitle+'" readonly>'+ '</div>'+ ' </div></div>'+ ' </li>'+ messagedateblock + '<li>'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label" style="width:70px;float:left;text-align:left;">To</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<input type="text" name="name" value="'+nametodate+'" readonly>'+ '<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+dateseentitle+'" readonly>'+ '</div>'+ ' </div></div>'+ ' </li>'+ '<li class="" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+ '</ul>'+ '</div>' ); } else{ if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var unix = Math.round(+new Date()/1000); firebase.database().ref("dates/" + f_uid +'/' + targetid).update({ dateseen:'Y', dateseentime:unix }); firebase.database().ref("dates/" + targetid +'/' + f_uid).update({ dateseen:'Y', dateseentime:unix }); firebase.database().ref("notifications/" + f_uid +'/' + targetid).update({ dateseen:'Y', dateseentime:unix }); firebase.database().ref("notifications/" + targetid +'/' + f_uid).update({ dateseen:'Y', dateseentime:unix }); $( ".datetoolbar" ).show(); $( ".sender-inner" ).hide(); $( ".yes-inner" ).show(); $( ".waitingreply" ).empty(); $( ".datedetailsdiv" ).hide(); $( ".requestbutton" ).remove(); $( ".requesticon" ).remove(); $( ".titleconfirm" ).show(); $( ".titleconfirm" ).html(targetname+' is waiting for your response'); $( ".waitingreply" ).append( '<div style="background-color:#ff9500;padding:10px;text-align:center;font-size:20px;color:white;">'+titleblock+'</div>'+ '<div class="list-block media-list" onclick="request();" style="margin-top:0px;"><ul style="background-color:white;padding-bottom:10px;">'+ '<img src="media/'+d_type+'faceonly.png" style="height:60px;margin-top:15px;">'+ '<li>'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label" style="width:70px;float:left;text-align:left;">When?</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<input type="text" name="name" value="'+gday+timedisplay+'" readonly>'+ '<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+proposeddate + dending + ' '+ proposedmonth + ' ' + proposedyear +'" readonly>'+ '</div>'+ ' </div></div>'+ ' </li>'+ '<li class="interestli" style="display:none;">'+ '<div class="item-content">'+ ' <div class="item-inner" style="padding-top:15px;padding-bottom:15px;">'+ ' <div class="item-title label" style="float:left;width:70px;text-align:left;">Where?</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<span class="interestdiv" style="float:left;text-align:center;"></span>'+ '</div>'+ '</div>'+ '</div>'+ ' </li>'+ '<li class="interestli" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+ '<li>'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label" style="width:70px;float:left;text-align:left;">From</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<input type="text" name="name" value="'+namefromdate+'" readonly>'+ '<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+timestamptitle+'" readonly>'+ '</div>'+ ' </div></div>'+ ' </li>'+ messagedateblock + '<li>'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label" style="width:70px;float:left;text-align:left;">To</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<input type="text" name="name" value="'+nametodate+'" readonly>'+ '<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+dateseentitle+'" readonly>'+ '</div>'+ ' </div></div>'+ ' </li>'+ '<li class="" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+ '</ul>'+ '</div>' ); } if (d_interest && d_type =='duck'){ $( ".interestli").show(); if ((d_interest == 'my') && (d_created_uid == f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+f_first+'\'s place </div>');} if ((d_interest == 'my') && (d_created_uid != f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+targetname+'\'s place </div>');} if ((d_interest == 'your') && (d_created_uid == f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+targetname+'\'s place </div>');} if ((d_interest == 'your') && (d_created_uid != f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+f_first+'\'s place </div>');} } if (d_interest && d_type =='date'){ for (i = 0; i < d_interest.length; i++) { $( ".interestli").show(); $( ".interestdiv").append('<a href="#" style="margin-right:5px"><i class="twa twa-2x twa-'+d_interest[i]+'" style="margin-top:5px;margin-right:5px"></i></a>'); } } } function acceptDate(){ var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var unix = Math.round(+new Date()/1000); $( ".sender-inner" ).hide(); $( ".yes-inner" ).hide(); var datemessageq = $( '#datemessageq' ).val(); var unix = Math.round(+new Date()/1000); var day = pickerCustomToolbar.cols[0].displayValue; var time; if (pickerCustomToolbar.cols[0].displayValue =='Now'){time='';} else if (pickerCustomToolbar.cols[0].displayValue =='Today'){ var daterequestnow = new Date; var hournow = daterequestnow.getHours(); if((pickerCustomToolbar.cols[0].displayValue =='Morning') && (hournow >= '12')){time='';} else if((pickerCustomToolbar.cols[0].displayValue =='Mid-day') && (hournow > '14')){time='';} else if((pickerCustomToolbar.cols[0].displayValue =='Afternoon') && (hournow > '17')){time='';} else{time = pickerCustomToolbar.cols[1].value;} } else{time = pickerCustomToolbar.cols[1].value;} var chat_expire = pickerCustomToolbar.cols[0].value; var interestarray = []; if (d_type == 'date'){ $( ".interestbutton" ).each(function() { if ($( this ).hasClass( "interestchosen" )) { var classList = $(this).attr("class").split(' '); var interestadd = classList[1].split('_')[0]; interestarray.push(interestadd); } }); } if (d_type == 'duck'){ if ($( '.button-my' ).hasClass( "active" )){interestarray = 'my'} if ($( '.button-your' ).hasClass( "active" )){interestarray = 'your'} } firebase.database().ref("dates/" + f_uid +'/' + targetid).update({ response: 'Y', time_accepted: unix, uid_accepted: f_uid, authcheck:f_uid }); firebase.database().ref("dates/" + targetid +'/' + f_uid).update({ response: 'Y', time_accepted: unix, uid_accepted: f_uid, authcheck:f_uid }); var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) { var objs = snapshot.val(); var messageq; //If existing notifications, get number of unseen messages, delete old notifications console.log(snapshot.val()); if (snapshot.val()){ $.each(objs, function(i, obj) { if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){ messageq = obj.new_message_count; console.log(messageq); messageq ++; } }); } newNotification(); }); function newNotification(messagenum){ if (!messagenum) {messagenum = 1;} // Get a key for a new Post. var newPostKey = firebase.database().ref().push().key; var t_unix = Math.round(+new Date()/1000); var targetData = { id:newPostKey, from_uid: f_uid, from_name: f_first, to_uid:targetid, to_name:targetname, message:'Date scheduled', timestamp: t_unix, type:d_type, param:'dateconfirmed', new_message_count:messagenum, received:'N', expire:d_chat_expire, authcheck:f_uid }; // Write the new post's data simultaneously in the posts list and the user's post list. var updates = {}; updates['notifications/' + f_uid + '/' + targetid] = targetData; updates['notifications/' + targetid + '/' + f_uid] = targetData; return firebase.database().ref().update(updates).then(function() {chatShow();}); } } function cancelDate(){ // Create a reference to the file to delete $( ".dateheader" ).hide(); $( ".sender-inner" ).hide(); var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} // Delete the file firebase.database().ref("dates/" + f_uid +'/' + targetid).remove().then(function() { // File deleted successfully $( ".datearea" ).empty(); d_chat_expire = false; d_interest = false; d_day = false; d_time = false; d_response = false; d_timeaccepted = false; d_created_uid = false; d_timestamp = false; d_dateseen = false; d_dateseentime = false; d_message = false; noMessages(); setDate(); console.log('deleted'); }).catch(function(error) { // Uh-oh, an error occurred! }); // Delete the file firebase.database().ref("dates/" + targetid +'/' + f_uid).remove().then(function() { // File deleted successfully console.log('deleted'); }).catch(function(error) { // Uh-oh, an error occurred! }); var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) { var objs = snapshot.val(); var messageq; //If existing notifications, get number of unseen messages, delete old notifications if (snapshot.val()){ $.each(objs, function(i, obj) { if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){ messageq = obj.new_message_count; messageq ++; } }); } newNotification(); }); function newNotification(messagenum){ if (!messagenum) {messagenum = 1;} var smessage; if (d_type=='duck'){smessage = 'Duck request deleted'} if (d_type=='date'){smessage = 'Date request deleted'} // Get a key for a new Post. var newPostKey = firebase.database().ref().push().key; var t_unix = Math.round(+new Date()/1000); var targetData = { id:newPostKey, from_uid: f_uid, from_name: f_first, to_uid:targetid, to_name:targetname, message:smessage, timestamp: t_unix, type:d_type, param:'datedeleted', new_message_count:messagenum, received:'N', expire:d_chat_expire, authcheck:f_uid }; // Write the new post's data simultaneously in the posts list and the user's post list. var updates = {}; updates['notifications/' + f_uid + '/' + targetid] = targetData; updates['notifications/' + targetid + '/' + f_uid] = targetData; return firebase.database().ref().update(updates).then(function() { console.log('delete notification sent'); }); } } function getPicture(key){ var weekday = []; weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; var month = []; month[0] = "Jan"; month[1] = "Feb"; month[2] = "Mar"; month[3] = "Apr"; month[4] = "May"; month[5] = "Jun"; month[6] = "Jul"; month[7] = "Aug"; month[8] = "Sep"; month[9] = "Oct"; month[10] = "Nov"; month[11] = "Dec"; var stringnow = new Date(); var stringyestday = new Date(Date.now() - 86400); var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate(); var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate(); var datechatstring; var messagedate = new Date(); var minstag = ('0'+messagedate.getMinutes()).slice(-2); messagetimetitle = messagedate.getHours() + ':' + minstag; var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate(); if (!prevdatetitle){prevdatetitle = messagedaytitle;console.log('prevdatetitle does not exist'); if (messagedaytitle == todaystring){datechatstring = 'Today';} else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';} else{datechatstring = messagedaytitle;} } else { if (prevdatetitle == messagedaytitle){console.log('it is the same day');datechatstring='';} else{console.log('it is a different day');prevdatetitle = messagedaytitle; if (messagedaytitle == todaystring){datechatstring = 'Today';} else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';} else{datechatstring = messagedaytitle;} } } var t_unix = Math.round(+new Date()/1000); var returned = 0; var postkeyarray = []; var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var eventy = document.getElementById('takePictureField_').files[0]; // var number_of_pictures = $(".imageli").length + 1; if (eventy == 'undefined') {console.log('undefined');} if (eventy !== 'undefined') { for (i = 0; i < document.getElementById('takePictureField_').files.length; i++) { var photoname = t_unix + i; var newValue = firebase.database().ref().push().key; postkeyarray.push(newValue); myMessages.addMessage({ // Message text text: '<img src="'+URL.createObjectURL($('#takePictureField_').prop('files')[i])+'" onload="$(this).fadeIn(700);scrollBottom();" onclick="imagesPopup('+image_count+');" style="display:none">', // Random message type type: 'sent', // Avatar and name: avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal', name: f_first, day:datechatstring, label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle }); //$("#dealimagediv_"+imagenumber).attr("src",URL.createObjectURL(eventy)); image_count ++; //$('.image_' + t_unix).onclick = function(){ // openPhoto(url);}; //var randomstring = (Math.random() +1).toString(36).substr(2, 30); var photochatspath = 'photochats/' + first_number + '/' + second_number + '/'+ photoname; var photostorage = 'images/' + f_auth_id + '/' + photoname; var photochatsRef = storageRef.child(photostorage); photochatsRef.put($('#takePictureField_').prop('files')[i]).then(function(snapshot) { alert(snapshot.metadata.name); var photodownloadstorage = 'images/' + f_auth_id + '/' + snapshot.metadata.name; var photodownloadRef = storageRef.child(photodownloadstorage); photodownloadRef.getDownloadURL().then(function(url) { returned ++; alert(returned + ',' + postkeyarray[(returned-1)]); var newPostKey = postkeyarray[(returned-1)]; conversation_started = true; var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var chatvar = { id:newPostKey, from_uid: f_uid, from_name: f_first, to_uid:targetid, to_name:targetname, message:'<img src="'+url+'" onload="$(this).fadeIn(700);" style="display:none" >', seen:'N', timestamp: snapshot.metadata.name, type:d_type, param:'image', downloadurl:url, first_number:first_number, second_number:second_number }; var photovar1 = { id:newPostKey, uid: f_uid, user_name: f_first, photo_name:photostorage, downloadurl:url, to_uid:targetid, from_uid: f_uid, first_number:first_number, second_number:second_number, folder:f_auth_id }; var photovar2 = { id:newPostKey, uid: f_uid, user_name: f_first, downloadurl:url, to_uid:targetid, from_uid: f_uid, first_number:first_number, second_number:second_number }; firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + newPostKey).set(chatvar); firebase.database().ref("photostodelete/" + f_uid + '/' + targetid + '/' + newPostKey).set(photovar1); firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + newPostKey).set(photovar2); }); }); } var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) { var objs = snapshot.val(); var messageq; //If existing notifications, get number of unseen messages, delete old notifications if (snapshot.val()){ $.each(objs, function(i, obj) { if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){ firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove(); firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove(); console.log(obj.received); console.log(obj.from_uid); if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){ messageq = obj.new_message_count; messageq ++; } } }); } newpictureNotification(messageq); }); } function newpictureNotification(messagenum){ if (!messagenum) {messagenum = 1;} // Get a key for a new Post. var newPostKey = firebase.database().ref().push().key; var targetData = { id:newPostKey, from_uid: f_uid, from_name: f_first, to_uid:targetid, to_name:targetname, message:'Image ', timestamp: t_unix, type:d_type, param:'image', new_message_count:messagenum, received:'N', expire:d_chat_expire, authcheck:f_uid }; // Write the new post's data simultaneously in the posts list and the user's post list. var updates = {}; updates['notifications/' + f_uid + '/' + targetid] = targetData; updates['notifications/' + targetid + '/' + f_uid] = targetData; return firebase.database().ref().update(updates); } } function toTimestamp(year,month,day,hour,minute,second){ var datum = new Date(Date.UTC(year,month-1,day,hour,minute,second)); return datum.getTime()/1000; } var photoarray; function showPhotos(){ photoarray= []; myApp.pickerModal( '<div class="picker-modal photo-picker" style="height:132px;">' + '<div class="toolbar" style="background-color:#2196f3">' + '<div class="toolbar-inner">' + '<div class="left"></div>' + '<div class="right"><a href="#" class="close-picker" style="color:white;">Close</a></div>' + '</div>' + '</div>' + '<div class="picker-modal-inner" style="background-color:#2196f3">' + '<div class="content-block" style="margin:0px;padding:0px;">' + '<div class="swiper-container swiper-photos">'+ '<div class="swiper-wrapper wrapper-photos">'+ ' <div class="swiper-slide" style="text-align:center;margin:-5px;height:88px;">'+ '<i class="pe-7s-plus pe-3x" style="color:white;margin-top:10px;"></i>'+ ' <input type="file" size="70" accept="image/*" class="dealPictureField imagenotchosen" id="takePictureField_" onchange="getPicture();" style="background-color:transparent;color:transparent;float:left;cursor: pointer;height:60px;width:100%;z-index:1;opacity:0;background-color:red;height:88px;margin-top:-44px;" multiple="multiple"> '+ '</div>'+ '</div>'+ '</div>'+ '</div>' + '</div>' + '</div>' ); var photosswiper = myApp.swiper('.swiper-photos', { slidesPerView:3, freeMode:true, preloadImages: false, // Enable lazy loading lazyLoading: true, watchSlidesVisibility:true //pagination:'.swiper-pagination' }); firebase.database().ref("photos/" + f_uid).once('value').then(function(snapshot) { var childcount = 0; snapshot.forEach(function(childSnapshot) { // key will be "ada" the first time and "alan" the second time //var key = childSnapshot.key; // childData will be the actual contents of the child childcount ++; var childData = childSnapshot.val(); photoarray.push(childSnapshot.val()); $( ".wrapper-photos" ).append('<div onclick="sendphotoExisting(\''+childData.downloadurl+'\',\''+childData.filename+'\')" data-background="'+childData.downloadurl+'" style="border:1px solid black;margin:-5px;height:88px;background-size:cover;background-position:50% 50%;" class="swiper-slide swiper-lazy">'+ ' <div class="swiper-lazy-preloader"></div>'+ '</div>'); if (childcount == snapshot.numChildren()){ photosswiper.updateSlidesSize(); photosswiper.slideTo(snapshot.numChildren()); // photosswiper.slideTo(0); } }); }); } function sendphotoExisting(oldurl,filenamez){ conversation_started = true; var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var t_unix = Math.round(+new Date()/1000); myMessages.addMessage({ // Message text text: '<img src="'+oldurl+'" onload="scrollBottom();">', // Random message type type: 'sent', // Avatar and name: avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal', name: f_first // Day // day: !conversationStarted ? 'Today' : false, // time: !conversationStarted ? (new Date()).getHours() + ':' + (new Date()).getMinutes() : false }); firebase.database().ref("chats/" + first_number+ '/' + second_number).push({ from_uid: f_uid, from_name: f_first, to_uid:targetid, to_name:targetname, message:'<img src="'+oldurl+'" onload="scrollBottom();">', seen:'N', timestamp: t_unix, type:d_type, param:'image', filename:filenamez }); myApp.closeModal('.photo-picker'); } (function($){ $.fn.imgLoad = function(callback) { return this.each(function() { if (callback) { if (this.complete || /*for IE 10-*/ $(this).height() > 0) { callback.apply(this); } else { $(this).on('load', function(){ callback.apply(this); }); } } }); }; })(jQuery); var xcountdown; function imagesPopup(go){ var popupHTML = '<div class="popup gallery-popupz">'+ '<div class="navbar" style="position:absolute;top:0;background-color:#2196f3;color:white;">'+ ' <div class="navbar-inner">'+ ' <div class="left"><a href="#" onclick="closeGallery();" class="link icon-only"><i class="pe-7s-angle-left pe-3x" style="margin-left:-10px;color:white;"></i> </a></div>'+ ' <div class="center gallerytitle"></div>'+ ' <div class="right photo-count"></div>'+ '</div>'+ '</div>'+ '<div class="pages">'+ '<div data-page="gallerypopup" class="page">'+ '<div class="page-content" style="background-color:white;">'+ '<div style="position:absolute;bottom:12px;right:8px;z-index:99999;background-color:white;border-radius:5px;padding:5px;"><div id="photodeletechattime" style="color:black;float:left;"></div></div>'+ '<span style="width:42px; height:42px;position:absolute;top:50%;margin-top:-21px;left:50%;margin-left:-21px;z-index:999999;" class="imagespopuploader preloader"></span> '+ '<div class="swiper-container swiper-gallery" style="height: calc(100% - 44px);margin-top:44px;">'+ ' <div class="swiper-wrapper gallery-wrapper">'+ ' </div>'+ '</div>'+ '<div class="swiper-pagination-gallery" style="position:absolute;bottom:0;left:0;z-index:999999;width:100%;height:4px;"></div>'+ '</div></div></div>'+ '</div>'; myApp.popup(popupHTML); var first_number,second_number; var gallerycount; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var galleryimagecount = 0; var photodeletetime; var phototo; var photofrom; var photochatid; var touid; firebase.database().ref("photochats/" + first_number+ '/' + second_number).once("value") .then(function(snapshot) { gallerycount = snapshot.numChildren(); var objs = snapshot.val(); $.each(objs, function(i, obj) { var expiryval; if (obj.photo_expiry == null){expiryval = i;} else {expiryval = obj.photo_expiry;} $( ".gallery-wrapper" ).append(' <div class="swiper-slide photochat_'+obj.photo_expiry+'" style="height:100%;">'+ '<div class="swiper-zoom-container">'+ '<img data-src="'+obj.downloadurl+'" class="swiper-lazy" style="width:100%;" onload="$(this).fadeIn(700);hideImagespopuploader();">'+ ' <div class="swiper-lazy-preloader"></div></div><input type="hidden" class="photoexpiryhidden_'+galleryimagecount+'" value="'+expiryval +'"><input type="text" class="fromhidden_'+galleryimagecount+'" value="'+obj.from_uid+'"><input type="text" class="tohidden_'+galleryimagecount+'" value="'+obj.user_name+'"><input type="text" class="idhidden_'+galleryimagecount+'" value="'+i+'"><input type="text" class="toidhidden_'+galleryimagecount+'" value="'+obj.to_uid+'"></div>'); galleryimagecount ++; }); var galleryswiper = myApp.swiper('.swiper-gallery', { preloadImages: false, lazyLoadingInPrevNext:true, // Enable lazy loading lazyLoading: true, watchSlidesVisibility:true, zoom:true, onInit:function(swiper){var slidenum = swiper.activeIndex + 1; photodeletetime = $( ".photoexpiryhidden_" + swiper.activeIndex).val(); phototo = $( ".tohidden_" + swiper.activeIndex).val(); photofrom = $( ".fromhidden_" + swiper.activeIndex).val(); photochatid = $( ".idhidden_" + swiper.activeIndex).val(); touid = $( ".toidhidden_" + swiper.activeIndex).val(); if (photodeletetime == photochatid){document.getElementById("photodeletechattime").innerHTML = '<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+touid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;float:left;margin-right:5px;"></div> <span style="float:left;margin-top:5px;">Photo unseen</span>';} else{photodeletecount();} $( ".gallerytitle").html('<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+photofrom+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>' + phototo); }, onSlideChangeStart:function(swiper){clearInterval(xcountdown); var slidenum = galleryswiper.activeIndex + 1; photodeletetime = $( ".photoexpiryhidden_" + swiper.activeIndex).val();photodeletecount(); phototo = $( ".tohidden_" + swiper.activeIndex).val(); photofrom = $( ".fromhidden_" + swiper.activeIndex).val(); photochatid = $( ".idhidden_" + swiper.activeIndex).val(); touid = $( ".toidhidden_" + swiper.activeIndex).val(); if (photodeletetime == photochatid){document.getElementById("photodeletechattime").innerHTML = '<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+touid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;float:left;margin-right:5px;"></div> <span style="float:left;margin-top:5px;">Photo unseen</span>';} else{photodeletecount();deletePhotochat();} $( ".gallerytitle").html('<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+photofrom+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>' + phototo); myApp.sizeNavbars(); }, pagination:'.swiper-pagination-gallery', paginationType:'progress' }); galleryswiper.slideTo(go,0); myApp.sizeNavbars(); }); function deletePhotochat(){ if (photodeletetime < (new Date().getTime() / 1000)){ alert('deleting only photochat'); $( ".photochat_"+ photodeletetime).remove(); galleryswiper.update(); firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + photochatid).remove(); firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + photochatid).remove(); } } function photodeletecount(){ var countDownDate = new Date(photodeletetime * 1000); // Get todays date and time var now = new Date().getTime(); // Find the distance between now an the count down date var distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); document.getElementById("photodeletechattime").innerHTML = '<i class="twa twa-bomb twa-lg" style="float:left;"></i>' + hours + "h " + minutes + "m " ; // Update the count down every 1 second xcountdown = setInterval(function() { // Get todays date and time var now = new Date().getTime(); // Find the distance between now an the count down date var distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // If the count down is finished, write some text if (distance < 0) { clearInterval(xcountdown); deletePhotochat(); } else{ document.getElementById("photodeletechattime").innerHTML = '<i class="twa twa-bomb twa-lg" style="float:left;"></i>' +hours + "h " + minutes + "m " ;myApp.sizeNavbars();} }, 60000); } } function hideImagespopuploader(){ $( ".imagespopuploader" ).hide();} function closeGallery(){ myApp.closeModal('.gallery-popupz'); clearInterval(xcountdown); } function updateOnce(){ var uids = ["1381063698874268","1394352877264527","393790024114307","4"]; firebase.database().ref('users/' + f_uid).update({ date_me:uids }); } function updatePhotos(){ $( ".pp" ).each(function() { var classList = $(this).attr("class").split(' '); var idofphoto = classList[2].replace("photo_", ""); var index1 = f_date_match.indexOf(idofphoto); var index2 = f_duck_match.indexOf(idofphoto); var u_date_me = f_date_me.indexOf(idofphoto); var u_to_date = f_to_date.indexOf(idofphoto); var u_duck_me = f_duck_me.indexOf(idofphoto); var u_to_duck = f_to_duck.indexOf(idofphoto); if (index2 > -1) { if ($( '.rr').hasClass('r_' + idofphoto)) { d_type='duck'; $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" ); $( ".duck-template" ).show(); $( ".date-template" ).hide(); $( ".toolbardecide" ).hide(); matchNavbar(); } $( ".iconpos_" + idofphoto ).empty(); $( ".iconpos_" + idofphoto ).append('<img src="media/duckfaceonly.png" style="width:100px;">'); $( this ).css( "-webkit-filter","none" ); $( ".distance_" + idofphoto ).css( "background-color","#2196f3" ); } else if (index1 > -1) { if ($( '.rr').hasClass('r_' + idofphoto)) { d_type='date'; $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" ); $( ".duck-template" ).hide(); $( ".date-template" ).show(); $( ".toolbardecide" ).hide(); matchNavbar(); } $( ".iconpos_" + idofphoto ).empty(); $( ".iconpos_" + idofphoto ).append('<img src="media/datefaceonly.png" style="width:100px;">'); $( this ).css( "-webkit-filter","none" ); $( ".distance_" + idofphoto ).css( "background-color","#2196f3" ); } else{$( this ).css( "-webkit-filter","grayscale(80%)" );$( ".distance_" + idofphoto ).css( "background-color","#ccc" ); $( ".iconpos_" + idofphoto ).empty(); $( ".name_" + idofphoto ).css( "-webkit-filter","grayscale(80%)" ); if (u_date_me > -1){ $( ".iconpos_" + idofphoto ).empty(); $( ".iconpos_" + idofphoto ).append('<img src="media/datefaceonly.png" style="width:100px;">');$( ".iconpos_" + idofphoto ).css( "-webkit-filter","grayscale(1%)" ); } if (u_duck_me > -1) { $( ".iconpos_" + idofphoto ).empty(); $( ".iconpos_" + idofphoto ).append('<img src="media/duckfaceonly.png" style="width:100px;">');$( ".iconpos_" + idofphoto ).css( "-webkit-filter","grayscale(1%)" ); } if ($( '.rr').hasClass('r_' + idofphoto)) { $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" ); $( ".duck-template" ).hide(); $( ".date-template" ).hide(); unmatchNavbar(); $( ".toolbardecide" ).show(); // alert(u_date_me); // alert(u_duck_me); if (u_date_me > -1) {$( ".datebutton" ).addClass( "likesme" ); } else {$( ".datebutton" ).removeClass( "likesme" );} if (u_duck_me > -1) {$( ".duckbutton" ).addClass( "likesme" ); } else {$( ".duckbutton" ).removeClass( "likesme" );} } } }); $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); } function singleBrowser(idw,idname,origin){ //firebase.database().ref("users/" + f_uid).off('value', userpref); //targetid = idw; targetid = String(idw); targetname = idname; var dbuttons; if (origin){ dbuttons= ' <div class="toolbar-inner date-template" style="display:none;background-color:#2196f3;">'+ '<a href="#" onclick="dateUser();" class="datebutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;max-width:106.47px;">'+flargedateicon +'</a>'+ '<p style="font-family: \'Pacifico\', cursive;font-size:20px;visibility:hidden;">or</p>'+ '<a href="#" onclick="createDate1()" class="button link active" style="width: calc(100% - 70px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Date</a></div>'+ // '<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+ ' <div class="toolbar-inner duck-template" style="display:none;background-color:#2196f3;">'+ '<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+ '<a href="#" onclick="createDuck()" class="button link active" style="width: calc(100% - 65px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Duck</a></div>'; } else { dbuttons=' <div class="toolbar-inner date-template" style="display:none;background-color:#2196f3;">'+ '<a href="#" onclick="dateUser();" class="datebutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;max-width:106.47px;">'+flargedateicon +'</a>'+ '<p style="font-family: \'Pacifico\', cursive;font-size:20px;visibility:hidden;">or</p>'+ '<a href="#" class="button link active photo-browser-close-link" style="width: calc(100% - 70px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Date</a></div>'+ // '<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+ ' <div class="toolbar-inner duck-template" style="display:none;background-color:#2196f3;">'+ '<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+ '<a href="#" onclick="createDuck()" class="button link active photo-browser-close-link" style="width: calc(100% - 65px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Duck</a></div>'; } singlePhotoBrowser = myApp.photoBrowser({ zoom: 400, lazyLoading:true, lazyLoadingInPrevNext:true, //exposition:false, photos: [{ url: 'https://graph.facebook.com/'+targetid+'/picture?type=large', caption: '...' }], toolbarTemplate:'<div class="toolbar tabbar" style="height:100px;">'+ dbuttons+ ' <div class="toolbar-inner toolbardecide">'+ '<a href="#" onclick="dateUser();" class="datebutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;">'+flargedateicon +'</a>'+ ' <a href="#" class="link orlink">'+ '<p style="font-family: \'Pacifico\', cursive;font-size:20px;">or</p>'+ ' </a>'+ '<a href="#" class="link loaderlink"><span class="preloader preloader-white login-loader"></span></a>'+ '<a href="#" onclick="duckUser();" class="duckbutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;">'+flargeduckicon +'</a>'+ ' </div>'+ '</div>', onOpen:function(photobrowser){ $( ".chatpop" ).css( "z-index","10000" );}, onClose:function(photobrowser){hideProfile();$( ".chatpop" ).css( "z-index","11500" ); //getPreferences(); }, swipeToClose:false, // onClick:function(swiper, event){showProfile();}, backLinkText: '', navbarTemplate: '<div class="navbar photobrowserbar">'+ ' <div class="navbar-inner">'+ ' <div class="left sliding">'+ ' <a href="#" style="margin-left:-10px;" class="matchcolor mainback link photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'+ // ' <i class="icon icon-back {{iconsColorClass}}"></i> '+ '<i class="pe-7s-angle-left pe-3x"></i> '+ // '<span class="badge agecat">'+arraynumber+'</span>'+ ' </a>'+ ' <a href="#" onclick="myApp.closeModal();clearchatHistory();" style="display:none;margin-left:-10px;" class="matchcolor notifback link photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'+ ' <i class="pe-7s-angle-left pe-3x "></i> '+ // '<span class="badge agecat">'+arraynumber+'</span>'+ ' </a>'+ ' </div>'+ ' <div class="center sliding nametag matchcolor">'+ // ' <span class="photo-browser-current"></span> '+ // ' <span class="photo-browser-of">{{ofText}}</span> '+ // ' <span class="photo-browser-total"></span>'+ ' </div>'+ ' <div class="right" >' + '<a href="#" class="link">'+ ' <i class="pe-7s-more pe-lg matchcolor"></i>'+ ' </a>'+ '</div>'+ '</div>'+ '</div> ' }); singlePhotoBrowser.open(); $( ".nametag" ).empty(); $( ".nametag" ).append('<span class="rr r_'+targetid+'">'+targetname+'</span>'); var windowwidth = $( ".photo-browser-swiper-container" ).width(); $( ".photo-browser-slide img" ).css( "width", windowwidth + "px" ); $( ".photo-browser-slide img" ).css( "-webkit-filter","grayscale(80%)" ); $( ".photo-browser-caption" ).css( "margin-top", "-10px" ); $( ".datebutton" ).removeClass( "active" ); $( ".duckbutton" ).removeClass( "active" ); $( ".duckbutton" ).addClass( "disabled" ); $( ".datebutton" ).addClass( "disabled" ); $( ".loaderlink" ).show(); $( ".orlink" ).hide(); match = 0; $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" ); $( ".duck-template" ).hide(); $( ".date-template" ).hide(); unmatchNavbar(); $( ".toolbardecide" ).show(); $( ".datebutton" ).removeClass( "likesme" ); $( ".duckbutton" ).removeClass( "likesme" ); firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/userdata.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:targetid,sexuality:sexuality} ) .done(function( data ) { var result = JSON.parse(data); var targetdescription= result[0].description; //var targetname = result[0].name.substr(0,result[0].name.indexOf(' ')); $( ".photo-browser-caption" ).empty(); $( ".photo-browser-caption" ).append(targetdescription); myApp.sizeNavbars(); }); }).catch(function(error) { // Handle error }); var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} return firebase.database().ref('matches/' + f_uid + '/' + targetid).once('value').then(function(snapshot) { $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); $( ".loaderlink" ).hide(); $( ".orlink" ).show(); if (snapshot.val() === null) {} else { if (first_number == f_uid){ //Dates if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );} if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );} if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){ $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" ); $( ".duck-template" ).hide(); $( ".date-template" ).show(); $( ".toolbardecide" ).hide(); matchNavbar(); d_type='date'; } else {} //Duck if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );} if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );} if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberduck == 'Y'){ $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" ); $( ".duck-template" ).show(); $( ".date-template" ).hide(); $( ".toolbardecide" ).hide(); matchNavbar(); d_type='duck'; } else {} } if (first_number == targetid){ //Date if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );} if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );} if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){ $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" ); $( ".duck-template" ).hide(); $( ".date-template" ).show(); $( ".toolbardecide" ).hide(); matchNavbar(); d_type='date'; } else {} //Duck if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );} if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );} if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberdate == 'Y'){ $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" ); $( ".duck-template" ).show(); $( ".date-template" ).hide(); $( ".toolbardecide" ).hide(); matchNavbar(); d_type='duck'; } else {} } } }); } function deletePhotos(){ var unix = Math.round(+new Date()/1000); firebase.database().ref('/photostodelete/' + f_uid).once('value').then(function(snapshot) { var objs = snapshot.val(); if (snapshot.val()){ $.each(objs, function(i, obj) { $.each(obj, function(i, obk) { if(obk.photo_expiry){ if (obk.photo_expiry < Number(unix)){ //alert('a photo to delete exists'); firebase.database().ref('/photochats/' + obk.first_number + '/' + obk.second_number+'/'+ obk.id).remove(); firebase.database().ref('/chats/' + obk.first_number + '/' + obk.second_number+'/'+ obk.id).remove(); var desertRef = storageRef.child(obk.photo_name); // Delete the file desertRef.delete().then(function() { firebase.database().ref('/photostodelete/' + obk.from_uid + '/' + obk.to_uid+'/'+ obk.id).remove(); }).catch(function(error) { }); //blocking out } } }); }); } }); } function createDuck(idq,nameq){ keepopen = 1; d_type = 'duck'; if (idq) {createDate(idq,nameq)} else{createDate();} } function createDate1(idz,name){ d_type = 'date'; keepopen = 1; if (idz) {createDate(idz,name)} else{createDate();} } function duckClass(place){ if (place ==1) { if ($( ".button-my" ).hasClass( "active" )){ $('.button-my').removeClass("active");$('.button-your').removeClass("active"); } else {$('.button-my').addClass("active");$('.button-your').removeClass("active");} } if (place ==2) { if ($( ".button-your" ).hasClass( "active" )){ $('.button-your').removeClass("active");$('.button-my').removeClass("active"); } else {$('.button-your').addClass("active");$('.button-my').removeClass("active");} } } function matchNotif(){ function newNotificationm(messagenum){ if (!messagenum) {messagenum = 1;} var smessage; if (d_type=='duck'){smessage = 'New match'} if (d_type=='date'){smessage = 'New match'} // Get a key for a new Post. var newPostKey = firebase.database().ref().push().key; var t_unix = Math.round(+new Date()/1000); var targetData = { id:newPostKey, from_uid: f_uid, from_name: f_first, to_uid:targetid, to_name:targetname, message:smessage, timestamp: t_unix, type:d_type, param:'newmatch', new_message_count:0, received:'N', expire:'', authcheck:f_uid }; // Write the new post's data simultaneously in the posts list and the user's post list. var updates = {}; updates['notifications/' + f_uid + '/' + targetid] = targetData; updates['notifications/' + targetid + '/' + f_uid] = targetData; return firebase.database().ref().update(updates).then(function() { console.log('delete notification sent'); }); } var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) { var objs = snapshot.val(); var messageq = 0; //If existing notifications, get number of unseen messages, delete old notifications console.log(snapshot.val()); if (snapshot.val()){ $.each(objs, function(i, obj) { if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){ firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove(); firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove(); if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){ messageq = obj.new_message_count; messageq ++; } } }); } newNotificationm(messageq); }); } function unmatchNotif(){ var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} firebase.database().ref('dates/' + f_uid +'/' + targetid).remove(); firebase.database().ref('dates/' + targetid +'/' + f_uid).remove(); firebase.database().ref('notifications/' + f_uid +'/' + targetid).remove(); firebase.database().ref('notifications/' + targetid +'/' + f_uid).remove(); myApp.closePanel(); } String.prototype.capitalize = function() { return this.charAt(0).toUpperCase() + this.slice(1); }; function insertAfterNthChild($parent, index, content){ $(content).insertBefore($parent.children().eq(index)); } function changeRadius(number){ $('.radiusbutton').removeClass('active'); $('#distance_'+ number).addClass('active'); processUpdate(); } function sortBy(number){ var relevanticon; var relevanttext; if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (number == 1){relevanticon = '<i class="pe-7s-shuffle pe-lg"></i>';relevanttext='Sort randomly';} if (number == 2){relevanticon = '<i class="pe-7s-map-marker pe-lg"></i>';relevanttext='Sort by nearby first';} if (number == 3){relevanticon = '<i class="pe-7s-clock pe-lg"></i>';relevanttext='Sort by recently active first';} $('#filterexplain').empty(); $('#filterexplain').append( '<div class="list-block" style="margin:0;">'+ '<ul>'+ '<li>'+ '<div class="item-content" style="border-top:1px solid #c8c7cc;border-bottom:1px solid #c8c7cc;">'+ '<div class="item-media">'+ relevanticon+ '</div>'+ '<div class="item-inner">'+ ' <div class="item-title">'+ relevanttext+ '</div>'+ '</div>'+ '</div>'+ '</li>'+ '</ul>'+ '</div>' ); $('.sortbutton').removeClass('active'); $('.sortby_'+ number).addClass('active'); } function addcreateDate(){ $('.addcreatebutton').hide(); $('.backcreatebutton').show(); $('.right-title').text('Matches'); myApp.sizeNavbars(); $('.timeline-upcoming').empty(); for (i = 0; i < f_date_match_data.length; i++) { $('.timeline-upcoming').append('<div class="timeline-item" onclick="createDate1(\''+f_date_match_data[i].uid+'\',\''+f_date_match_data[i].name+'\');">'+ '<div class="timeline-item-date">'+fdateicon+'</div>'+ '<div class="timeline-item-divider"></div>'+ '<div class="timeline-item-content">'+ ' <div class="timeline-item-inner">'+ ' <div class="timeline-item-title" style="width:100px;height:100px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+f_date_match_data[i].uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+ ' <div class="timeline-item-subtitle">'+f_date_match_data[i].name+'</div>'+ '</div>'+ ' </div>'+ '</div>'); } for (i = 0; i < f_duck_match_data.length; i++) { $('.timeline-upcoming').append('<div class="timeline-item" onclick="createDuck(\''+f_duck_match_data[i].uid+'\',\''+f_duck_match_data[i].name+'\');">'+ '<div class="timeline-item-date">'+fduckicon+'</div>'+ '<div class="timeline-item-divider"></div>'+ '<div class="timeline-item-content">'+ ' <div class="timeline-item-inner">'+ ' <div class="timeline-item-title" style="width:100px;height:100px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+f_duck_match_data[i].uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+ ' <div class="timeline-item-subtitle">'+f_duck_match_data[i].name+'</div>'+ '</div>'+ ' </div>'+ '</div>'); } if (f_duck_match_data.length === 0 && f_date_match_data.length ===0){ $('.timeline-upcoming').append('<div class="content-block-title" style="margin: 0 auto;text-align:center;overflow:visible;">No matches yet. <br/><br/>Keep calm and quack on!</div>'); } } function unblock(){ myApp.confirm('This will unblock all profiles, making you visible to everyone', 'Are you sure?', function () { var iblockedfirst = []; var iblockedsecond = []; firebase.database().ref("matches/" + f_uid).once("value",function(snapshot) { if (snapshot.val() != null){ var objs = snapshot.val(); $.each(objs, function(i, obj) { if((obj.first_number == f_uid)&& (obj.firstnumberblock == 'Y')){iblockedfirst.push(obj.second_number)} if((obj.second_number == f_uid)&& (obj.secondnumberblock == 'Y')){iblockedsecond.push(obj.first_number)} }); } if (iblockedfirst.length){ for (i = 0; i < iblockedfirst.length; i++) { firebase.database().ref('matches/' + f_uid + '/' + iblockedfirst[i]).update({ //add this user to my list firstnumberblock:'N', firstnumberdate:'N', firstnumberduck:'N', created:f_uid, received:iblockedfirst[i] }); firebase.database().ref('matches/' + iblockedfirst[i] + '/' + f_uid).update({ //add this user to my list firstnumberblock:'N', firstnumberdate:'N', firstnumberduck:'N', created:f_uid, received:iblockedfirst[i] }); } } if (iblockedsecond.length){ for (i = 0; i < iblockedsecond.length; i++) { firebase.database().ref('matches/' + f_uid + '/' + iblockedsecond[i]).update({ //add this user to my list secondnumberblock:'N', secondnumberdate:'N', secondnumberduck:'N', created:f_uid, received:iblockedsecond[i] }); firebase.database().ref('matches/' + iblockedsecond[i] + '/' + f_uid).update({ //add this user to my list secondnumberblock:'N', secondnumberdate:'N', secondnumberduck:'N', created:f_uid, received:iblockedsecond[i] }); } } getWifilocation(); $( ".blockbutton" ).addClass('disabled'); }) }); } function deleteAccount(){ //users //photos2delete -> photos in storage //chats //matches myApp.confirm('This will permanently delete your account and remove all your information including photos, chats and profile data', 'Delete Account', function () { var matchesarray = []; var firstnumberarray = []; var secondnumberarray = []; firebase.database().ref("matches/" + f_uid).once("value",function(snapshot) { if (snapshot.val() != null){ var objs = snapshot.val(); $.each(objs, function(i, obj) {var uidadd;if(obj.first_number == f_uid){uidadd = obj.second_number;} else{uidadd = obj.first_number} matchesarray.push(uidadd); firstnumberarray.push(obj.first_number);secondnumberarray.push(obj.second_number);}); for (i = 0; i < matchesarray.length; i++) { var mymatches = firebase.database().ref('matches/' + f_uid + '/' + matchesarray[i]); mymatches.remove().then(function() { console.log("My matches Remove succeeded.") }) .catch(function(error) { console.log("My matches Remove failed: " + error.message) }); var theirmatches = firebase.database().ref('matches/' + matchesarray[i] + '/' + f_uid); theirmatches.remove().then(function() { console.log("Their matches Remove succeeded.") }) .catch(function(error) { console.log("Their matches Remove failed: " + error.message) }); var mydates = firebase.database().ref('dates/' + f_uid + '/' + matchesarray[i]); mydates.remove().then(function() { console.log("My dates Remove succeeded.") }) .catch(function(error) { console.log("My dates Remove failed: " + error.message) }); var theirdates = firebase.database().ref('dates/' + matchesarray[i] + '/' + f_uid); theirdates.remove().then(function() { console.log("Their dates Remove succeeded.") }) .catch(function(error) { console.log("Their dates Remove failed: " + error.message) }); var theirnotifs = firebase.database().ref('notifications/' + matchesarray[i] + '/' + f_uid); theirnotifs.remove().then(function() { console.log("their notifs Remove succeeded.") }) .catch(function(error) { console.log("their notifs failed: " + error.message) }); var ourchats = firebase.database().ref('chats/' + firstnumberarray[i] + '/' + secondnumberarray[i]); ourchats.remove().then(function() { console.log("Chats Remove succeeded.") }) .catch(function(error) { console.log("Chats Remove failed: " + error.message) }); var ourphotochats = firebase.database().ref('photochats/' + firstnumberarray[i] + '/' + secondnumberarray[i]); ourphotochats.remove().then(function() { console.log("PhotoChats Remove succeeded.") }) .catch(function(error) { console.log("PhotoChats Remove failed: " + error.message) }); } } firebase.database().ref("notifications/" + f_uid).once("value", function(snapshot) { var objs = snapshot.val(); console.log(objs); if (snapshot.val()){ $.each(objs, function(i, obj) { var targetdeleteid; if (obj.from_uid == f_uid){targetdeleteid = obj.to_uid} else{targetdeleteid = obj.from_uid;} var mynotifs = firebase.database().ref('notifications/' + f_uid + '/' + targetdeleteid); mynotifs.remove().then(function() { console.log("my notifs Remove succeeded.") }) .catch(function(error) { console.log("my notifs failed: " + error.message) }); }); } firebase.database().ref('users/' + f_uid).set({ auth_id : f_auth_id, deleted:'Y' }); firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/deleteuser.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} ) .done(function( data ) { console.log(data); firebase.database().ref('/photostodelete/' + f_uid).once('value').then(function(snapshot) { var objr = snapshot.val(); if (snapshot.val()){ $.each(objr, function(i, obj) { $.each(obj, function(i, obk) { firebase.database().ref('/photostodelete/' + obk.from_uid + '/' + obk.to_uid+'/'+ obk.id).remove(); var desertRef = storageRef.child(obk.photo_name); // Delete the file desertRef.delete().then(function() { }).catch(function(error) { console.log(error); }); }); }); } logout(); }); }); }).catch(function(error) { // Handle error }); }); }); }); } function matchNavbar(){ if ($('.infopopup').length > 0) { $( ".toolbarq" ).show(); $( ".photobrowserbar" ).css("background-color","#2196f3"); $( ".matchcolor" ).addClass('whitetext'); } else {$( ".toolbarq" ).hide();} } function unmatchNavbar(){ if ($('.infopopup').length > 0) { $( ".toolbarq" ).show(); $( ".photobrowserbar" ).css("background-color","#ccc"); $( ".matchcolor" ).removeClass('whitetext'); $( ".toolbarq" ).css("background-color","transparent"); } else {$( ".toolbarq" ).hide();} } var notifloaded = false; function establishNotif(){ notifcount = firebase.database().ref('notifications/' +f_uid).on('value', function(snapshot) { var notificationscount = 0; var objs = snapshot.val(); //If existing notifications, get number of unseen messages, delete old notifications if (snapshot.val()){ $.each(objs, function(i, obj) { if (obj.to_uid == f_uid) { if (obj.received =='Y') { if (notifloaded){ $( ".arrowdivhome_" + obj.from_uid ).empty();$( ".indivnotifcount" ).remove();} } if (obj.received =='N') { var addnumber; if(obj.param == 'datedeleted' || obj.param =='newmatch'){addnumber = 1;} else {addnumber = obj.new_message_count} notificationscount = notificationscount + addnumber; if (notifloaded){ if (obj.new_message_count > 0){ //alert('Not received, greater than 0 = ' +obj.new_message_count); $( ".arrowdivhome_" + obj.from_uid ).empty();$( ".arrowdivhome_" + obj.from_uid ).append('<span class="badge" style="background-color:rgb(255, 208, 0);color:black;margin-top:5px;margin-left:-5px;">'+obj.new_message_count+'</span>'); $( ".indivnotifcount" ).remove();$( ".arrowdivbrowser" ).append('<span class="badge indivnotifcount" style="position:absolute;right:0px;background-color:rgb(255, 208, 0);color:black;">'+obj.new_message_count+'</span>'); } } } } }); notifloaded = true; if (notificationscount !=0){$( ".notifspan" ).show(); $( ".notifspan" ).addClass('notifbounce'); setTimeout(function(){ $( ".notifspan" ).removeClass('notifbounce'); }, 5000); if (offsounds == 'Y'){}else{ if ($('.chatpop').length > 0) {} else {$('#buzzer')[0].play();} } return false; } else{$( ".notifspan" ).hide();} //$( ".notifspan" ).empty(); //$( ".notifspan" ).append(notificationscount); } }); } function showPloader(){ $( ".ploader" ).css("z-index","9999999");myApp.closeModal(); } function hidePloader(tabb){ var popupHTML = '<div class="popup prefpop">'+ '<div class="views tabs toolbar-fixed">'+ '<div id="tab1" class="view tab active">'+ '<div class="navbar" style="background-color:#2196f3;">'+ ' <div class="navbar-inner">'+ ' <div class="left">Terms and Conditions of Use</div>'+ ' <div class="right"><a href="#" onclick="showPloader();" style="color:white;">Done</a></div>'+ '</div>'+ '</div>'+ '<div class="pages navbar-fixed">'+ ' <div data-page="home-1" class="page">'+ ' <div class="page-content">'+ '<div class="content-block" style="margin-top:0px;">'+ ' <div class="content-block-inner terms-inner" >'+ ' </div>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'+ '<div id="tab2" class="view tab">'+ '<div class="navbar" style="background-color:#2196f3;">'+ ' <div class="navbar-inner">'+ ' <div class="left">Privacy Policy</div>'+ ' <div class="right close-popup"><a href="#" onclick="showPloader();" class="close-popup" style="color:white;">Done</a></div>'+ '</div>'+ '</div>'+ '<div class="pages navbar-fixed">'+ ' <div data-page="home-2" class="page">'+ ' <div class="page-content">'+ '<div class="content-block" style="margin-top:0px;">'+ ' <div class="content-block-inner privacy-inner">'+ ' </div>'+ '</div>'+ '</div>'+ ' </div>'+ '</div>'+ '</div>'+ '<div class="toolbar tabbar" style="background-color:#2196f3;">'+ ' <div class="toolbar-inner">'+ ' <a href="#tab1" onclick="tabOne();" class="tab1 tab-link active"><i class="pe-7s-note2 pe-lg"></i></a>'+ ' <a href="#tab2" onclick="tabTwo();" class="tab2 tab-link"><i class="pe-7s-unlock pe-lg"></i></a>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'; myApp.popup(popupHTML); $( ".ploader" ).css("z-index","10000"); if (tabb) { tabTwo(); } else {tabOne();} } function tabOne(){ $( "#tab1" ).addClass('active'); $( "#tab2" ).removeClass('active'); myApp.sizeNavbars(); $( ".tab1" ).addClass('active'); $( ".tab2" ).removeClass('active'); $.get( "terms.html", function( data ) { $( ".terms-inner" ).html(data); console.log(data); }); } function tabTwo(){ $( "#tab1" ).removeClass('active'); $( "#tab2" ).addClass('active'); myApp.sizeNavbars(); $( ".tab1" ).removeClass('active'); $( ".tab2" ).addClass('active'); $.get( "privacy.html", function( data ) { $( ".privacy-inner" ).html(data); }); } //check if on mobile //} var pagingalbumurl; var pagingurl; var photonumber; var albumend; var addedsmallarray; var addedlargearray; var addedheight = []; var addedwidth = []; function getPhotos(albumid){ $( ".photoloader").show(); $( ".loadmorebuttonphotos").hide(); var retrieveurl; if (!pagingurl) {photonumber = 0;retrieveurl = 'https://graph.facebook.com/'+albumid+'/photos?limit=8&access_token=' + f_token} else {retrieveurl = pagingurl} $.getJSON(retrieveurl, function(response) { $( ".noparray").hide(); $( ".yesparray").show(); $( ".photoloader").hide(); if (response.data.length === 0){$( ".loadmorebuttonphotos").hide();$( "#nophotosfound").show();return false;} console.log(response); pagingurl = response.paging.next; for (i = 0; i < response.data.length; i++) { var alreadyselected = addedsmallarray.indexOf(response.data[i].source); console.log(response.data[i]); if (alreadyselected == -1) { swiperPhotos.appendSlide('<div class="swiper-slide slidee slidee_'+photonumber+' largeurl_'+response.data[i].source+' smallurl_'+response.data[i].source+' id_'+response.data[i].id+'" style="background-image:url(\''+response.data[i].source+'\');height:180px;width:180px;background-size:cover;background-position:50% 50%;"><div style="width:40px;height:40px;border-radius:50%;position:absolute;top:50%;left:50%;margin-left:-28px;margin-top:-28px;"><i class="pe-7s-check check_'+photonumber+' pe-4x" style="display:none;color:#4cd964;"></i></div><input type="hidden" class="width_'+response.data[i].id+'" value="'+response.data[i].width+'"><input type="hidden" class="height_'+response.data[i].id+'" value="'+response.data[i].height+'"><br></div>'); } else { swiperPhotos.appendSlide('<div class="swiper-slide slidee slidee_'+photonumber+' largeurl_'+response.data[i].source+' smallurl_'+response.data[i].source+' id_'+response.data[i].id+' slidee-selected" style="background-image:url(\''+response.data[i].source+'\');height:180px;width:180px;background-size:cover;background-position:50% 50%;"><div style="width:40px;height:40px;border-radius:50%;position:absolute;top:50%;left:50%;margin-left:-28px;margin-top:-28px;"><i class="pe-7s-check check_'+photonumber+' pe-4x" style="display:block;color:#4cd964;"></i></div><input type="hidden" class="width_'+response.data[i].id+'" value="'+response.data[i].width+'"><input type="hidden" class="height_'+response.data[i].id+'" value="'+response.data[i].height+'"></div>'); } photonumber ++; } if (response.data.length > 0 && response.data.length < 8) { $( ".loadmorebuttonphotos").hide();$( "#nomorephotos").show();} else{$( ".loadmorebuttonphotos").show();} }); } function closePhotos(){ $( ".albumblock").show(); $( ".leftalbum").show(); $( ".leftphoto").hide(); $( "#nomorephotos").hide(); $( "#nophotosfound").hide(); $( ".loadmorebuttonphotos").hide(); if (albumend === true){$( ".loadmorebuttonalbums").hide();$( "#nomorealbums").show();} else {$( ".loadmorebuttonalbums").show();$( "#nomorealbums").hide();} swiperPhotos.removeAllSlides(); swiperPhotos.destroy(); photonumber = 0; pagingurl = false; } function closeAlbums(){ myApp.closeModal('.photopopup'); addedsmallarray = []; addedlargearray = []; pagingalbumurl = false; albumend = false; } function photosPopup(){ addedsmallarray = f_smallurls; addedlargearray = f_largeurls; var popupHTML = '<div class="popup photopopup">'+ '<div class="views tabs toolbar-fixed">'+ '<div class="view tab active">'+ '<div class="navbar" style="background-color:#2196f3;color:white;">'+ ' <div class="navbar-inner">'+ ' <div class="left">'+ '<i class="pe-7s-angle-left pe-2x leftalbum" onclick="closeAlbums()"></i>'+ '<i class="pe-7s-angle-left pe-2x leftphoto" onclick="closePhotos()" style="display:none;"></i>'+ ' </div>'+ ' <div class="center photocount">'+ '0 photos selected'+ '</div>'+ ' <div class="right"><a href="#" onclick="closeAlbums()" class="noparray" style="color:white;">Done</a><a href="#" class="yesparray" onclick="getPhotoURL()" style="display:none;color:white;">Done</a></div>'+ '</div>'+ '</div>'+ '<div class="pages navbar-fixed">'+ ' <div data-page="photospage" class="page">'+ ' <div class="page-content" style="padding-bottom:0px;background-color:white;">'+ '<div class="col-25 photoloader" style="position:absolute;top:50%;left:50%;margin-left:-13.5px;margin-top:-13.5px;">'+ ' <span class="preloader"></span>'+ ' </div>'+ '<div class="list-block media-list albumblock" style="margin:0px;"><ul class="albumul"></ul></div>'+ '<div class="swiper-container swiper-photos">'+ ' <div class="swiper-wrapper" >'+ '</div>'+ '</div>'+ '<a href="#" class="button loadmorebuttonalbums" onclick="loadAlbums()" style="background-color:#2196f3;color:white;display:none;margin:10px;"><i class="pe-7s-albums pe-lg"></i> Load more albums</a>'+ '<a href="#" class="button loadmorebuttonphotos" onclick="getPhotos()" style="background-color:#2196f3;color:white;display:none;margin:10px;"><i class="pe-7s-photo pe-lg"></i> Load more photos</a>'+ '<div id="nomorephotos" style="display:none;width:100%;text-align:center;"><p>No more photos available in this album.</p></div>'+ '<div id="nophotosfound" style="display:none;width:100%;text-align:center;"><p>No photos found in this album.</p></div>'+ '<div id="nomorealbums" style="display:none;width:100%;text-align:center;"><p>No more albums to load.</p></div>'+ '<div><div><div>'+ '<div>'+ '<div>'+ '</div>' myApp.popup(popupHTML); if (addedlargearray.length === 1){$( ".photocount").text(addedlargearray.length + ' photo selected');} else {$( ".photocount").text(addedlargearray.length + ' photos selected');} loadAlbums(); } function loadAlbums(){ $( ".photoloader").show(); $( ".loadmorebuttonalbums").hide(); var retrievealbumurl; if (!pagingalbumurl) {retrievealbumurl = 'https://graph.facebook.com/'+f_uid+'/albums?limit=20&access_token=' + f_token} else {retrievealbumurl = pagingalbumurl} $.getJSON(retrievealbumurl, function(response) { console.log(response); pagingalbumurl = response.paging.next; for (i = 0; i < response.data.length; i++) { if (response.data[i].count > 0){ $( ".albumul" ).append( ' <li onclick="getAlbum('+response.data[i].id+')">'+ ' <div class="item-content">'+ ' <div class="item-media">'+ ' <i class="pe-7s-photo-gallery pe-lg"></i>'+ '</div>'+ '<div class="item-inner">'+ ' <div class="item-title-row">'+ ' <div class="item-title">'+response.data[i].name+'</div>'+ ' <div class="item-after">'+response.data[i].count+'</div>'+ '</div>'+ '</div>'+ ' </div>'+ ' </li>' ); } } if (response.data.length < 20) {$( ".loadmorebuttonalbums").hide();$( "#nomorealbums").show();albumend = true;} else{$( ".loadmorebuttonalbums").show();} }); } function getAlbum(albumid){ $( ".albumblock").hide(); $( ".loadmorebuttonalbums").hide(); $( "#nomorealbums").hide(); $( ".leftalbum").hide(); $( ".leftphoto").show(); swiperPhotos = myApp.swiper('.swiper-photos', { slidesPerView:2, slidesPerColumn:1000, virtualTranslate:true, slidesPerColumnFill:'row', spaceBetween: 3, onClick:function(swiper, event){if (sexuality){processUpdate(); myApp.sizeNavbars(); } console.log(swiper); if ($( ".slidee_" + swiper.clickedIndex).hasClass('slidee-selected')){$( ".slidee_" + swiper.clickedIndex).removeClass('slidee-selected');$( ".close_" + swiper.clickedIndex).show();$( ".check_" + swiper.clickedIndex).hide(); var largeurl = swiper.clickedSlide.classList[3].replace("largeurl_", ""); var smallurl = swiper.clickedSlide.classList[4].replace("smallurl_", ""); var photoselectedid = swiper.clickedSlide.classList[5].replace("id_", ""); var indexdeletedsm = addedsmallarray.indexOf(smallurl); addedsmallarray.splice(indexdeletedsm, 1); var indexdeletedsl = addedlargearray.indexOf(smallurl); addedlargearray.splice(indexdeletedsl, 1); addedheight.splice(indexdeletedsl, 1); addedwidth.splice(indexdeletedsl, 1); console.log(addedheight); } else{$( ".slidee_" + swiper.clickedIndex).addClass('slidee-selected');$( ".close_" + swiper.clickedIndex).hide();$( ".check_" + swiper.clickedIndex).show(); var largeurl = swiper.clickedSlide.classList[3].replace("largeurl_", ""); var smallurl = swiper.clickedSlide.classList[4].replace("smallurl_", ""); var photoselectedid = swiper.clickedSlide.classList[5].replace("id_", ""); addedsmallarray.push(smallurl); addedlargearray.push(largeurl); var widthselected = $( ".width_"+photoselectedid).val(); var heightselected = $( ".height_"+photoselectedid).val(); addedheight.push(heightselected); addedwidth.push(widthselected); } if (addedlargearray.length === 1){$( ".photocount").text(addedlargearray.length + ' photo selected');} else {$( ".photocount").text(addedlargearray.length + ' photos selected');} } }); getPhotos(albumid); swiperPhotos.updateContainerSize(); swiperPhotos.updateSlidesSize(); } function getPhotoURL(){ photonumber = 0; pagingurl = false; pagingalbumurl = false; albumend = false; var newsmall = addedsmallarray.toString(); var newlarge = addedlargearray.toString(); var newwidth = addedwidth.toString(); var newheight = addedheight.toString(); firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} ) .done(function( data ) { if (addedlargearray.length ===0){if ($( ".reorderbutton" ).hasClass( "disabled" )){}else {$( ".reorderbutton" ).addClass('disabled');} if ($( ".deleteallbutton" ).hasClass( "disabled" )){}else {$( ".deleteallbutton" ).addClass('disabled');} } if (addedlargearray.length > 0){if ($( ".reorderbutton" ).hasClass( "disabled" )){$( ".reorderbutton" ).removeClass('disabled');} if ($( ".deleteallbutton" ).hasClass( "disabled" )){$( ".deleteallbutton" ).removeClass('disabled');} } //swiperPhotos.removeAllSlides(); //swiperPhotos.destroy(); myApp.closeModal('.photopopup'); updatephotoslider(); }); }).catch(function(error) { // Handle error }); } function updatephotoslider(){ myswiperphotos.removeAllSlides(); console.log(addedlargearray); if (addedlargearray.length > 0){ myswiperphotos.removeAllSlides(); for (i = 0; i < addedlargearray.length; i++) { $( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\''+addedlargearray[i]+'\');background-size:cover;background-position:50% 50%;"><div class="button" style="color:#ff3b30;color:white;position:absolute;bottom:10px;right:10px;" onclick="deleteIndividual()">Delete Photo</div></div>'); } myswiperphotos.update(); $( ".photosliderinfo" ).addClass('pictures'); if (f_largeurls.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile'); } else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile'); } addedsmallarray = []; addedlargearray = []; } else { myswiperphotos.removeAllSlides(); f_smallurls = []; f_largeurls = []; addedheight = []; addedwidth = []; $( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>'); $( ".photosliderinfo" ).removeClass('pictures'); $( ".photosliderinfo" ).html('Add photos to your profile below'); } } function reorderPhotos(){ if (sexuality){processUpdate(); myApp.sizeNavbars(); } var popupHTML = '<div class="popup redorderpopup">'+ '<div class="views tabs toolbar-fixed">'+ '<div class="view tab active">'+ '<div class="navbar" style="background-color:#2196f3;color:white;">'+ ' <div class="navbar-inner">'+ ' <div class="left">'+ '<i class="pe-7s-angle-left pe-2x leftalbum" onclick="closeReorder()"></i>'+ ' </div>'+ ' <div class="center">'+ 'Order Photos'+ '</div>'+ ' <div class="right"><a href="#" onclick="changeOrder()" style="color:white;">Done</a></div>'+ '</div>'+ '</div>'+ '<div class="pages navbar-fixed">'+ ' <div data-page="redorderpage" class="page">'+ ' <div class="page-content" style="background-color:white;padding-bottom:0px;">'+ '<p style="width:100%;text-align:center;background-color:#ccc;color:white;padding-top:10px;padding-bottom:10px;">Drag photos to re-order</p>'+ ' <div class="list-block media-list" style="width:25%;float:left;margin-top:0px;">'+ ' <ul class="numbersul" style="background-color:transparent;">'+ ' </ul>'+ '</div>'+ ' <div class="list-block sortable" style="width:75%;float:left;margin-top:0px;">'+ ' <ul class="sortableul">'+ ' </ul>'+ '</div>'+ '<div><div><div>'+ '<div>'+ '<div>'+ '</div>' myApp.popup(popupHTML); for (i = 0; i < f_largeurls.length; i++) { $( ".numbersul" ).append( '<li style="margin-top:10px;">'+ ' <div class="item-content" style="height:80px;">'+ '<div class="item-inner reorderinner">'+ ' <div class="item-title badge" style="position:absolute;top:50%;left:50%;margin-top:-10px;margin-left:-20px;">'+i+'</div>'+ '</div>'+ ' </div>'+ '</li>' ); $( ".sortableul" ).append( ' <li style="margin-top:10px;">'+ ' <div class="item-content sortdivb" style="background-image:url(\''+f_largeurls[i]+'\');background-size:cover;background-position:50% 50%;height:80px;">'+ ' </div>'+ ' <div class="sortable-handler" style="width:100%;height:80px;"></div>'+ ' </li>' ); } myApp.sortableOpen(); } function closeReorder(){ myApp.closeModal('.redorderpopup'); } function changeOrder(){ var newurl = []; $( ".sortdivb" ).each(function() { var bg = $(this).css("background-image"); bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, ''); newurl.push(bg); }); myswiperphotos.removeAllSlides(); for (i = 0; i < newurl.length; i++) { $( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\''+newurl[i]+'\');background-size:cover;background-position:50% 50%;"><div class="button" style="background-color:#2196f3;color:white;position:absolute;bottom:10px;right:10px;" onclick="deleteIndividual()"><i class="pe-7s-trash pe-lg"></i> Delete</div></div>'); } myApp.closeModal('.redorderpopup'); myswiperphotos.update(); $( ".photosliderinfo" ).addClass('pictures'); if (f_largeurls.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile'); } else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile'); } var newsmall = newurl.toString(); var newlarge = newurl.toString(); firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall} ) .done(function( data ) { }); }).catch(function(error) { // Handle error }); f_largeurls = newurl; } function deleteAllPhotos(){ myApp.confirm('Are you sure?', 'Remove all photos', function () { if (sexuality){processUpdate(); myApp.sizeNavbars(); } deletedphoto = false; myswiperphotos.removeAllSlides(); $( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>'); $( ".photosliderinfo" ).removeClass('pictures'); $( ".photosliderinfo" ).html('Add'); $( ".photosliderinfo" ).html('Add photos to your profile below'); myswiperphotos.update(); $( ".reorderbutton" ).addClass('disabled'); $( ".deleteallbutton" ).addClass('disabled'); f_largeurls = []; f_smallurls = []; var newsmall = ""; var newlarge = ""; var newwidth = ""; var newheight = ""; firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} ) .done(function( data ) { console.log('deleted all'); }); }).catch(function(error) { // Handle error }); }); } function swipePopup(chosen){ $( '.picker-sub' ).hide(); myApp.closeModal('.picker-sub'); var sliderwidth = $( document ).width(); var sliderheight = $( document ).height(); var popupHTML = '<div class="popup prefpop">'+ '<div class="views tabs toolbar-fixed">'+ '<div id="tab99" class="view-99 view tab active">'+ '<div class="navbar" style="background-color:#2196f3;">'+ ' <div class="navbar-inner">'+ ' <div class="left" style="color:white;"></div>'+ ' <div class="center swipetext" style="color:white;">Filters'+ //'<div style="width:70px;height:70px;border-radius:50%;background-image:url(\''+f_image+'\');background-size:cover;background-position:50% 50%;margin-top:30px;z-index:100;border:5px solid #2196f3"></div>'+ '</div>'+ ' <div class="right"><a href="#" onclick="updateUser();" style="color:white;display:none" class="donechange">Done</a><a href="#" style="color:white;display:none;" class="close-popup doneunchange">Done</a></div>'+ '</div>'+ '</div>'+ ' <div class="pages">'+ ' <div data-page="home-3" class="page">'+ ' <div class="page-content" style="padding-top:44px;background-color:white;">'+ '<div class="swiper-container swiper-prefer" style="min-height:100%;">'+ '<div class="swiper-wrapper">'+ '<div class="swiper-slide" >'+ '<div class="slide-pref pref-0">'+ '<div class="content-block-title">Search radius</div>'+ '<p class="buttons-row" style="padding-left:10px;padding-right:10px;">'+ '<a href="#" id="distance_10" onclick="changeRadius(10)" class="button button-round radiusbutton" style="border:0;border-radius:0px;">10 km</a>'+ '<a href="#" id="distance_25" onclick="changeRadius(25)" class="button button-round radiusbutton" style="border:0;border-radius:0px;">25 km</a>'+ '<a href="#" id="distance_50" onclick="changeRadius(50)" class="button button-round radiusbutton active" style="border:0;border-radius:0px;">50 km</a>'+ '<a href="#" id="distance_100" onclick="changeRadius(100)" class="button button-round radiusbutton" style="border:0;border-radius:0px;">100 km</a>'+ '</p>'+ '<div class="content-block-title">Sort People By</div>'+ //'<div id="filterexplain"></div>'+ '<a href="#" id="sortrandom" class="button button-big sortbutton sortby_1 active" onclick="sortBy(1)" style="border:0;border-radius:0px;">Random </a>'+ '<a href="#" id="sortdistance" class="button button-big sortbutton sortby_2" onclick="sortBy(2)" style="border:0;border-radius:0px;">Nearby</a>'+ '<a href="#" id="sortactivity" class="button button-big sortbutton sortby_3" onclick="sortBy(3)" style="border:0;border-radius:0px;">Recent</a>'+ //'<p class="buttons-row" style="padding-left:10px;padding-right:10px;">'+ // '<a href="#" id="sortrandom" class="button button-round sortbutton sortby_1 active" onclick="sortBy(1)">Random</a>'+ //'<a href="#" id="sortdistance" class="button button-round sortbutton sortby_2" onclick="sortBy(2)">Distance</a>'+ // '<a href="#" id="sortactivity" class="button button-round sortbutton sortby_3" onclick="sortBy(3)">Recent</a>'+ //'</p>'+ '</div>'+ '</div>'+ '<div class="swiper-slide">'+ '<div class="slide-pref pref-1">'+ '<div class="content-block-title" style="margin-top:20px;">When are you available to meet?</div>'+ '<div class="list-block media-list availblock" style="margin-bottom:0px;">'+ ' <ul class="availul" style="padding-left:10px;padding-right:10px;padding-bottom:20px;">'+ ' </ul>'+ '<div class="list-block-label hiderowpref">Your matches will be notified when your availability changes.</div>'+ '</div> '+ '</div>'+ '</div>'+ '<div class="swiper-slide" >'+ '<div class="slide-pref pref-2">'+ '<div style="background-color:#2196f3;width:100%;padding-bottom:10px;" class="registerdiv">'+ '<div style="border-radius:50%;width:70px;height:70px;margin:0 auto;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+ '</div>'+ '<div class="list-block" style="margin-top:0px;">'+ ' <ul class="aboutul">'+ '<div class="content-block-title hiderowpref" style="margin-top:20px;">Profile Information</div>'+ '<div class="list-block-label registerdiv" style="margin-top:10px;margin-bottom:10px;">To get started, tell us about you and who you are looking to meet. </div>'+ '<li class="align-top hiderowpref">'+ ' <div class="item-content">'+ '<div class="item-media" style="border-radius:50%;width:70px;height:70px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+ ' <div class="item-inner">'+ ' <div class="item-input">'+ ' <textarea class="resizable" onkeyup="keyUp()" maxlength="100" id="userdescription" style="min-height:70px;" placeholder="Describe yourself and what you are looking for..."></textarea>'+ '</div>'+ ' </div>'+ ' </div>'+ '</li>'+ '<p id="maxdescription" class="hiderowpref" style="float:right;color:#ccc;font-size:14px;margin-top:5px;margin-right:5px;margin-bottom:-5px;">0 / 100</p>'+ '<li class="newam" style="clear:both;">'+ ' <div class="item-content">'+ '<div class="item-title label">I am</div>'+ ' <div class="item-inner">'+ ' <div class="item-input">'+ ' <input type="text" placeholder="..." readonly id="picker-describe">'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ '<li class="newme">'+ ' <div class="item-content">'+ '<div class="item-title label">Preference</div>'+ ' <div class="item-inner">'+ ' <div class="item-input">'+ ' <input type="text" placeholder="..." readonly id="picker-describe2">'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li class="hiderowpref" style="clear:both;margin-top:0px;">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Hometown</div>'+ ' <div class="item-input">'+ ' <input type="text" placeholder="Hide" name="name" placeholder="Hide" readonly >'+ ' </div>'+ ' </div>'+ '</div>'+ ''+ '</li>'+ ' <li class="hiderowpref">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Status</div>'+ ' <div class="item-input status-div">'+ ' <input type="text" placeholder="Hide" id="status-input" name="name" readonly >'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li class="hiderowpref">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Industry</div>'+ ' <div class="item-input industry-div">'+ ' <input type="text" id="industry-input" name="name" placeholder="Hide" readonly >'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li class="hiderowpref">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Zodiac</div>'+ ' <div class="item-input zodiac-div">'+ ' <input type="text" id="zodiac-input" name="name" placeholder="Hide" readonly >'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li class="hiderowpref">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Politics</div>'+ ' <div class="item-input politics-div">'+ ' <input type="text" id="politics-input" name="name" placeholder="Hide" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li class="hiderowpref">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Religion</div>'+ ' <div class="item-input religion-div">'+ ' <input type="text" id="religion-input" name="name" placeholder="Hide" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li class="hiderowpref">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Ethnicity</div>'+ ' <div class="item-input ethnicity-div">'+ ' <input type="text" id="ethnicity-input" name="name" placeholder="Hide" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li class="hiderowpref">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Eye color</div>'+ ' <div class="item-input eyes-div">'+ ' <input type="text" id="eyes-input" name="name" placeholder="Hide" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li class="hiderowpref">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Body Type</div>'+ ' <div class="item-input body-div">'+ ' <input type="text" id="body-input" name="name" placeholder="Hide" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li class="hiderowpref">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Height</div>'+ ' <div class="item-input height-div">'+ ' <input type="text" id="height-input" name="name" placeholder="Hide" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li class="hiderowpref">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Weight</div>'+ ' <div class="item-input weight-div">'+ ' <input type="text" id="weight-input" name="name" placeholder="Hide" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ '</ul>'+ '<div class="list-block-label hiderowpref">All fields are optional and will be hidden on your profile unless completed.</div>'+ '</div>'+ '</div>'+ '</div>'+ '<div class="swiper-slide">'+ '<div class="slide-pref pref-3">'+ '<div class="content-block-title photos-title" style="margin-top:20px;">Profile Photos</div>'+ '<div class="col-25 photoswiperloader" style="width:57.37px;top:50%;margin-top: -28.7px;position: absolute;left: 50%;margin-left: -28.7px;">'+ ' <span class="preloader"></span>'+ ' </div>'+ '<div class="swiper-container container-photos" style="width:'+sliderwidth+'px;height:250px;">'+ '<div class="swiper-wrapper wrapper-photos">'+ '</div>'+ '<div class="swiper-pagination"></div>'+ '</div>'+ '<p style="width:100%;text-align:center;background-color:#ccc;color:#6d6d72;padding-top:10px;padding-bottom:10px;" class="photosliderinfo"></p>'+ '<div class="content-block-title" style="margin-top:20px;">Manage Photos</div>'+ ' <div class="buttons-row">'+ '<a href="#" class="button active" onclick="photosPopup();" style="border:0;border-radius:0px;background-color:#4cd964;">Add</a>'+ '<a href="#" class="button reorderbutton active disabled" onclick="reorderPhotos();" style="border:0;border-radius:0px;">Re-order</a>'+ '<a href="#" class="button deleteallbutton active disabled" onclick="deleteAllPhotos();" style="border:0;border-radius:0px;background-color:#ff3b30;color:white">Delete All</a>'+ '</div>'+ '</div>'+ '</div>'+ '<div class="swiper-slide">'+ '<div class="slide-pref pref-4">'+ '<div class="content-block-title" style="margin-top:20px;">Notifications</div>'+ ' <div class="list-block media-list">'+ '<ul>'+ ' <li>'+ ' <div class="item-content">'+ ' <div class="item-inner" style="float:left;">'+ '<div class="item-title label" style="width:calc(100% - 62px);float:left;font-size:14px;">Turn off sounds</div>'+ ' <div class="item-input" style="width:52px;float:left;">'+ '<label class="label-switch">'+ ' <input type="checkbox" id="soundnotif" onchange="processUpdate(); myApp.sizeNavbars();">'+ '<div class="checkbox" ></div>'+ ' </label>'+ ' </div>'+ ' </div>'+ ' </div>'+ '</li>'+ '<div class="content-block-title" style="margin-top:20px;">Blocked profiles</div>'+ ' <li>'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title-row">'+ ' <div class="item-title button blockbutton active disabled" onclick="unblock()" style="border:0;border-radius:0px;">Unblock all </div>'+ '</div>'+ ' </div>'+ ' </div>'+ '</li>'+ '<div class="content-block-title" style="margin-top:20px;">My Account</div>'+ ' <li onclick="logout()">'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title-row">'+ ' <div class="item-title active button" style="border:0;border-radius:0px;">Logout</div>'+ '</div>'+ ' </div>'+ ' </div>'+ '</li>'+ ' <li onclick="deleteAccount()">'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title-row">'+ ' <div class="item-title button" style="border-color:#ff3b30;background-color:#ff3b30;color:white;border:0;border-radius:0px;">Delete Account</div>'+ '</div>'+ ' </div>'+ ' </div>'+ '</li>'+ '</ul>'+ '</div> '+ '</div>'+ '</div>'+ '</div>'+ '</div>'+ ' </div>'+ '</div>'+ '</div>'+ //tabs '</div>'+ '<div class="toolbar tabbar swipetoolbar" style="background-color:#ccc;">'+ ' <div class="toolbar-inner" style="padding:0;">'+ ' <a href="#" class="button tab-link tab-swipe pan0 active" onclick="swipePref(0)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-filter pe-lg" style="width:22px;margin:0 auto;"></i></a>'+ ' <a href="#" class="button tab-link tab-swipe pan1 " onclick="swipePref(1)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-clock pe-lg" style="width:22px;margin:0 auto;"></i></a>'+ ' <a href="#" class="button tab-link tab-swipe pan2" onclick="swipePref(2)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-info pe-lg" style="width:22px;margin:0 auto;"></i></a>'+ ' <a href="#" class="button tab-link tab-swipe pan3" onclick="swipePref(3);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-camera pe-lg" style="width:22px;margin:0 auto;"></i></a>'+ ' <a href="#" class="button tab-link tab-swipe pan4" onclick="swipePref(4)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-config pe-lg" style="width:22px;margin:0 auto;"></i></a>'+ '</div>'+ '</div>'+ '</div>'+ //tabs '</div>'; myApp.popup(popupHTML); if (blocklist){ if (blocklist.length){$( ".blockbutton" ).removeClass('disabled');} } if(sexuality){$( ".doneunchange" ).show();$( ".registerdiv" ).hide();$('.hiderowpref').removeClass('hiderowpref');} if(!sexuality){sortBy(1);$( ".swipetoolbar" ).hide();} var industrypicker = myApp.picker({ input: '#industry-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (industry_u) {industrypicker.cols[0].setValue(industry_u);} if (sexuality){processUpdate(); myApp.sizeNavbars(); } }, onChange:function (p, values, displayValues){$( '#industry-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'industry\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Accounting', 'Administration','Advertising','Agriculture','Banking and finance', 'Business', 'Charity', 'Creative arts','Construction','Consulting', 'Design', 'Education','Energy','Events', 'Engineering','Environment','Healthcare','Hospitality','HR and Recruitment', 'IT','Law','Law Enforcement','Leisure','Management','Manufacturing', 'Marketing','Media','Other','Pharmaceuticals','PR','Property','Public Services','Retail','Sales','Science','Security','Social Care','Small business','Sport','Tourism','Transport','Utilities','Voluntary work'] } ] }); var statuspicker = myApp.picker({ input: '#status-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (status_u) {statuspicker.cols[0].setValue(status_u);} if (sexuality){processUpdate(); myApp.sizeNavbars(); }}, onChange:function (p, values, displayValues){$( '#status-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'status\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Single', 'Married', 'Engaged','Open relationship', 'Committed relationship','It\'s Complicated'] } ] }); var heightpicker = myApp.picker({ input: '#height-input', onChange:function (p, values, displayValues){$( '#height-input' ).addClass("profilevaluechosen");}, onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (height_u) { if (height_u == 122) {var heightset = '122 cm (4\' 0\'\')';} if (height_u == 124) {var heightset = '124 cm (4\' 1\'\')';} if (height_u == 127) {var heightset = '127 cm (4\' 2\'\')';} if (height_u == 130) {var heightset = '130 cm (4\' 3\'\')';} if (height_u == 132) {var heightset = '132 cm (4\' 4\'\')';} if (height_u == 135) {var heightset = '135 cm (4\' 5\'\')';} if (height_u == 137) {var heightset = '137 cm (4\' 6\'\')';} if (height_u == 140) {var heightset = '140 cm (4\' 7\'\')';} if (height_u == 142) {var heightset = '142 cm (4\' 8\'\')';} if (height_u == 145) {var heightset = '145 cm (4\' 9\'\')';} if (height_u == 147) {var heightset = '147 cm (4\' 10\'\')';} if (height_u == 150) {var heightset = '150 cm (4\' 11\'\')';} if (height_u == 152) {var heightset = '152 cm (5\' 0\'\')';} if (height_u == 155) {var heightset = '155 cm (5\' 1\'\')';} if (height_u == 157) {var heightset = '157 cm (5\' 2\'\')';} if (height_u == 160) {var heightset = '160 cm (5\' 3\'\')';} if (height_u == 163) {var heightset = '163 cm (5\' 4\'\')';} if (height_u == 165) {var heightset = '165 cm (5\' 5\'\')';} if (height_u == 168) {var heightset = '168 cm (5\' 6\'\')';} if (height_u == 170) {var heightset = '170 cm (5\' 7\'\')';} if (height_u == 173) {var heightset = '173 cm (5\' 8\'\')';} if (height_u == 175) {var heightset = '175 cm (5\' 9\'\')';} if (height_u == 178) {var heightset = '178 cm (5\' 10\'\')';} if (height_u == 180) {var heightset = '180 cm (5\' 11\'\')';} if (height_u == 183) {var heightset = '183 cm (6\' 0\'\')';} if (height_u == 185) {var heightset = '185 cm (6\' 1\'\')';} if (height_u == 188) {var heightset = '185 cm (6\' 2\'\')';} if (height_u == 191) {var heightset = '191 cm (6\' 3\'\')';} if (height_u == 193) {var heightset = '193 cm (6\' 4\'\')';} if (height_u == 195) {var heightset = '195 cm (6\' 5\'\')';} if (height_u == 198) {var heightset = '198 cm (6\' 6\'\')';} if (height_u == 201) {var heightset = '201 cm (6\' 7\'\')';} if (height_u == 203) {var heightset = '203 cm (6\' 8\'\')';} heightpicker.cols[0].setValue(heightset);}}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'height\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['122 cm (4\' 0\'\')','124 cm (4\' 1\'\')','127 cm (4\' 2\'\')','130 cm (4\' 3\'\')','132 cm (4\' 4\'\')','135 cm (4\' 5\'\')','137 cm (4\' 6\'\')','140 cm (4\' 7\'\')','142 cm (4\' 8\'\')','145 cm (4\' 9\'\')','147 cm (4\' 10\'\')','150 cm (4\' 11\'\')','152 cm (5\' 0\'\')','155 cm (5\' 1\'\')','157 cm (5\' 2\'\')','160 cm (5\' 3\'\')','163 cm (5\' 4\'\')','165 cm (5\' 5\'\')','168 cm (5\' 6\'\')','170 cm (5\' 7\'\')','173 cm (5\' 8\'\')','175 cm (5\' 9\'\')','178 cm (5\' 10\'\')','180 cm (5\' 11\'\')','183 cm (6\' 0\'\')','185 cm (6\' 1\'\')','188 cm (6\' 2\'\')','191 cm (6\' 3\'\')','193 cm (6\' 3\'\')','195 cm (6\' 4\'\')','198 cm (6\' 5\'\')','201 cm (6\' 6\'\')','203 cm (6\' 8\'\')'] }, ] }); var weightpicker = myApp.picker({ input: '#weight-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (weight_u) { weightpicker.cols[0].setValue(weight_u + ' kg (' + Math.round(weight_u* 2.20462262) + ' lbs)');}}, onChange:function (p, values, displayValues){$( '#weight-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'weight\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="center">' + 'Weight'+ '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: (function () { var arr = []; for (var i = 45; i <= 150; i++) { arr.push(i + ' kg (' + Math.round(i* 2.20462262) + ' lbs)'); } return arr; })(), }, ] }); var bodypicker = myApp.picker({ input: '#body-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (body_u) {bodypicker.cols[0].setValue(body_u);}}, onChange:function (p, values, displayValues){$( '#body-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'body\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Athletic','Average', 'Slim', 'Large', 'Muscular','Unimportant'] } ] }); var eyespicker = myApp.picker({ input: '#eyes-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (eyes_u) {eyespicker.cols[0].setValue(eyes_u);}}, onChange:function (p, values, displayValues){$( '#eyes-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'eyes\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Amber', 'Blue', 'Brown','Grey','Green','Hazel','Other'] } ] }); var ethnicitypicker = myApp.picker({ input: '#ethnicity-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (ethnicity_u) {ethnicitypicker.cols[0].setValue(ethnicity_u);}}, onChange:function (p, values, displayValues){$( '#ethnicity-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'ethnicity\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Asian', 'Black', 'Latin / Hispanic','Mixed','Middle Eastern','Native American','Other','Pacific Islander','White'] } ] }); var politicspicker = myApp.picker({ input: '#politics-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (politics_u) {politicspicker.cols[0].setValue(politics_u);}}, onChange:function (p, values, displayValues){$( '#politics-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'politics\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Left / Liberal', 'Centre','Right / Conservative','Not interested'] } ] }); var zodiacpicker = myApp.picker({ input: '#zodiac-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (zodiac_u) {zodiacpicker.cols[0].setValue(zodiac_u);}}, onChange:function (p, values, displayValues){$( '#zodiac-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'zodiac\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn','Aquarius','Pisces'] } ] }); var religionpicker = myApp.picker({ input: '#religion-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (religion_u) {religionpicker.cols[0].setValue(religion_u);}}, onChange:function (p, values, displayValues){$( '#religion-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'religion\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Atheist','Agnostic','Christianity','Islam','Buddhism','Hindusim','Sikhism','Judaism','Other'] } ] }); mySwiper = myApp.swiper('.swiper-prefer', { onSlideChangeEnd:function(swiper){$( ".page-content" ).scrollTop( 0 );}, onSlideChangeStart:function(swiper){ $( ".page-content" ).scrollTop( 0 ); $( ".tab-swipe").removeClass('active'); $( ".pan" + swiper.activeIndex ).addClass('active'); if (swiper.activeIndex == 0){$( ".swipetext" ).text('Filters'); $( ".slide-pref" ).hide();$( ".pref-0").show(); } if (swiper.activeIndex == 1){$( ".swipetext" ).text('Availability'); $( ".slide-pref" ).hide();$( ".pref-1").show(); } if (swiper.activeIndex == 2){$( ".swipetext" ).text('Profile'); $( ".slide-pref" ).hide();$( ".pref-2").show(); } if (swiper.activeIndex == 3){$( ".swipetext" ).text('Photos');getData(); $( ".slide-pref" ).hide();$( ".pref-3").show(); } if (swiper.activeIndex == 4){$( ".swipetext" ).text('Settings'); $( ".slide-pref" ).hide();$( ".pref-4").show(); } if (!sexuality){$( '.swipetext' ).text("Welcome, " + f_first);mySwiper.lockSwipes();} } }); swipePref(chosen); myApp.sizeNavbars(); var dateinfo = []; var f_smallurls; var f_largeurls; var s_namesonly = []; var d = new Date(); var weekday = new Array(7); weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var daynumber; var todayday = weekday[d.getDay()]; console.log(todayday); s_namesonly.push(todayday); var f_available_array; var s_alldays_values = []; var s_alldays_names = []; var tonight = new Date(); tonight.setHours(23,59,59,999); var tonight_timestamp = Math.round(tonight/1000); daynumber; daynumber = d.getDate(); if (daynumber == '1' || daynumber == '21' || daynumber == '31'){dending = 'st'} else if (daynumber == '2' || daynumber == '22'){dending = 'nd'} else if (daynumber == '3' || daynumber == '23'){dending = 'rd'} else {dending = 'th'} dateinfo.push(daynumber + dending + ' ' + monthNames[d.getMonth()] + ', ' + d.getFullYear()); s_alldays_values.push(tonight_timestamp); s_alldays_names.push('Today'); var tomorrow_timestamp = tonight_timestamp + 86400; var tomorrowdate = new Date(Date.now() + 86400); var tomorroww = new Date(d.getTime() + 24 * 60 * 60 * 1000); var tomorrowday = weekday[tomorroww.getDay()]; daynumber = tomorroww.getDate(); if (daynumber == '1' || daynumber == '21' || daynumber == '31'){dending = 'st'} else if (daynumber == '2' || daynumber == '22'){dending = 'nd'} else if (daynumber == '3' || daynumber == '23'){dending = 'rd'} else {dending = 'th'} dateinfo.push(daynumber + dending + ' ' + monthNames[tomorrowdate.getMonth()] + ', ' + tomorrowdate.getFullYear()); console.log('tomorrow is' + tomorrowday); s_namesonly.push(tomorrowday); s_alldays_values.push(tomorrow_timestamp); s_alldays_names.push('Tomorrow'); for (i = 1; i < 7; i++) { var newunix = tomorrow_timestamp + (86400 * i); s_alldays_values.push(newunix); var dat_number = i + 1; var datz = new Date(Date.now() + dat_number * 24*60*60*1000); daynumber = datz.getDate(); var dending; if (daynumber == '1' || daynumber == '21' || daynumber == '31'){dending = 'st'} else if (daynumber == '2' || daynumber == '22'){dending = 'nd'} else if (daynumber == '3' || daynumber == '23'){dending = 'rd'} else {dending = 'th'} n = weekday[datz.getDay()]; qqq = weekday[datz.getDay() - 1]; console.log(n); s_alldays_names.push(n + ' ' + daynumber + dending); dateinfo.push(daynumber + dending + ' ' + monthNames[datz.getMonth()] + ', ' + datz.getFullYear()); s_namesonly.push(n); } s_namesonly.push(n); console.log(s_namesonly); console.log(s_alldays_values); for (i = 0; i < s_alldays_names.length; i++) { if (i==0 | i==2 || i==4 || i==6){ $( ".availul" ).append( '<li class="li_'+s_alldays_values[i]+' availrec" id="aa_'+s_alldays_values[i]+'" style="height:44px;float:left;width:100%;text-align:center;margin-bottom:10px;padding-top:10px;color:white;" onclick="openAvail('+s_alldays_values[i]+')">'+ '<div class="readd_'+s_alldays_values[i]+'"></div>'+ ' <input type="text" placeholder="'+s_alldays_names[i]+'" readonly id="picker'+s_alldays_values[i]+'" style="height:44px;text-align:center;margin-top:-10px;font-size:17px;color:white;"></li><input type="hidden" class="suppdate_'+s_alldays_values[i]+'" value="'+dateinfo[i]+'">' ); setPicker(); } else if (i==1 || i==3 || i==5 || i==7) { $( ".availul" ).append( '<li class="li_'+s_alldays_values[i]+' availrec" id="aa_'+s_alldays_values[i]+'" style="height:44px;float:left;width:100%;text-align:center;margin-bottom:10px;padding-top:10px;color:white;" onclick="openAvail('+s_alldays_values[i]+')">'+ '<div class="readd_'+s_alldays_values[i]+'"></div>'+ '<input type="text" placeholder="'+s_alldays_names[i]+'" readonly id="picker'+s_alldays_values[i]+'" style="height:44px;text-align:center;margin-top:-10px;font-size:17px;color:white;"></li><input type="hidden" class="suppdate_'+s_alldays_values[i]+'" value="'+dateinfo[i]+'">' ); setPicker(); } var alreadyavailchosen = 0; var columnone; var columntwo; var idtochange; for(var k = 0; k < availarray.length; k++) { if (availarray[k].id == s_alldays_values[i]){ alreadyavailchosen = 1;columntwo = availarray[k].time;columnone = availarray[k].day; idtochange = s_alldays_values[i];$( '.li_'+ idtochange ).addClass('selecrec');$( "#picker"+ idtochange ).val( columnone + " " + columntwo ); } else{ alreadyavailchosen = 0; } } function setPicker(){ var myavailpicker = myApp.picker({ input: '#picker' + s_alldays_values[i], onOpen: function (p){if (sexuality){processUpdate(); myApp.sizeNavbars(); }}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeAvail(\''+s_alldays_values[i]+'\',\''+s_alldays_names[i]+'\',\''+s_namesonly[i]+'\');">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { textAlign: 'left', values: (s_namesonly[i] + ',').split(',') }, { textAlign: 'left', values: ('Anytime Morning Midday Afternoon Evening').split(' ') }, ] }); } } if (myphotosarray){ } else { } if (f_description){ $( "#userdescription" ).val(f_description); var inputlengthd = $( "#userdescription" ).val().length; $( "#maxdescription" ).text(inputlengthd + ' / 100 '); } if (radiussize){ $( ".radiusbutton" ).removeClass( "active" ); $( "#distance_" + radiussize ).addClass( "active" ); } if (offsounds == 'Y'){$('#soundnotif').prop('checked', true);} else{$('#soundnotif').prop('checked', false);} if (sortby){ if (sortby == 'random'){sortBy(1);} if (sortby == 'distance'){sortBy(2);} if (sortby == 'activity'){sortBy(3);} $( ".sortbutton" ).removeClass( "active" ); $( "#sort" + sortby ).addClass( "active" ); } if (f_age) {$( ".savebutton" ).removeClass('disabled');} if(industry_u){$( "#industry-input" ).val( industry_u );} if(status_u){$( "#status-input" ).val( status_u );} if(politics_u){$( "#politics-input" ).val( politics_u );} if(eyes_u){$( "#eyes-input" ).val( eyes_u );} if(body_u){$( "#body-input" ).val( body_u );} if(religion_u){$( "#religion-input" ).val( religion_u );} if(zodiac_u){$( "#zodiac-input" ).val( zodiac_u );} if(ethnicity_u){$( "#ethnicity-input" ).val( ethnicity_u );} if(weight_u){$( "#weight-input" ).val( weight_u + ' kg (' + Math.round(weight_u* 2.20462262) + ' lbs)' );} if (height_u) { if (height_u == 122) {var heightset = '122 cm (4\' 0\'\')';} if (height_u == 124) {var heightset = '124 cm (4\' 1\'\')';} if (height_u == 127) {var heightset = '127 cm (4\' 2\'\')';} if (height_u == 130) {var heightset = '130 cm (4\' 3\'\')';} if (height_u == 132) {var heightset = '132 cm (4\' 4\'\')';} if (height_u == 135) {var heightset = '135 cm (4\' 5\'\')';} if (height_u == 137) {var heightset = '137 cm (4\' 6\'\')';} if (height_u == 140) {var heightset = '140 cm (4\' 7\'\')';} if (height_u == 142) {var heightset = '142 cm (4\' 8\'\')';} if (height_u == 145) {var heightset = '145 cm (4\' 9\'\')';} if (height_u == 147) {var heightset = '147 cm (4\' 10\'\')';} if (height_u == 150) {var heightset = '150 cm (4\' 11\'\')';} if (height_u == 152) {var heightset = '152 cm (5\' 0\'\')';} if (height_u == 155) {var heightset = '155 cm (5\' 1\'\')';} if (height_u == 157) {var heightset = '157 cm (5\' 2\'\')';} if (height_u == 160) {var heightset = '160 cm (5\' 3\'\')';} if (height_u == 163) {var heightset = '163 cm (5\' 4\'\')';} if (height_u == 165) {var heightset = '165 cm (5\' 5\'\')';} if (height_u == 168) {var heightset = '168 cm (5\' 6\'\')';} if (height_u == 170) {var heightset = '170 cm (5\' 7\'\')';} if (height_u == 173) {var heightset = '173 cm (5\' 8\'\')';} if (height_u == 175) {var heightset = '175 cm (5\' 9\'\')';} if (height_u == 178) {var heightset = '178 cm (5\' 10\'\')';} if (height_u == 180) {var heightset = '180 cm (5\' 11\'\')';} if (height_u == 183) {var heightset = '183 cm (6\' 0\'\')';} if (height_u == 185) {var heightset = '185 cm (6\' 1\'\')';} if (height_u == 188) {var heightset = '185 cm (6\' 2\'\')';} if (height_u == 191) {var heightset = '191 cm (6\' 3\'\')';} if (height_u == 193) {var heightset = '193 cm (6\' 4\'\')';} if (height_u == 195) {var heightset = '195 cm (6\' 5\'\')';} if (height_u == 198) {var heightset = '198 cm (6\' 6\'\')';} if (height_u == 201) {var heightset = '201 cm (6\' 7\'\')';} if (height_u == 203) {var heightset = '203 cm (6\' 8\'\')';} $( "#height-input" ).val( heightset ); } if (f_age && f_gender) {$( "#picker-describe" ).val( f_gender + ", " + f_age );} if (f_interested) {$( "#picker-describe2" ).val( f_interested + ", between " + f_lower + ' - ' + f_upper );} pickerDescribe = myApp.picker({ input: '#picker-describe', rotateEffect: true, onClose:function (p){ $( ".popup-overlay" ).css("z-index","10500"); }, onOpen: function (p){ if (sexuality){processUpdate(); myApp.sizeNavbars(); } $('.picker-items-col').eq(0).css('width','50%'); $('.picker-items-col').eq(1).css('width','50%'); // $( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px"); var gendercol = pickerDescribe.cols[0]; var agecol = pickerDescribe.cols[1]; if (f_age) {agecol.setValue(f_age);} if (f_gender) {gendercol.setValue(f_gender);} }, onChange: function (p, value, displayValue){ if (!f_age){ var fpick = pickerDescribe.value; var spick = pickerDescribe2.value; if (fpick && spick) { if(!sexuality){sexuality=true;$( ".registerdiv" ).slideUp();$('.hiderowpref').removeClass('hiderowpref');$( ".swipetoolbar" ).show();$( '.swipetext' ).text("Profile");mySwiper.unlockSwipes();$( ".donechange" ).show();$( ".doneunchange" ).hide();myApp.sizeNavbars(); } $( ".savebutton" ).removeClass( "disabled" );} else {$( ".savebutton" ).addClass( "disabled" );} } }, formatValue: function (p, values, displayValues) { return displayValues[0] + ', ' + values[1]; }, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left">' + 'I Am'+ '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { textAlign: 'left', values: ('Male Female').split(' ') }, { values: ('18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99').split(' ') }, ] }); pickerDescribe2 = myApp.picker({ input: '#picker-describe2', rotateEffect: true, onClose:function (p){ $( ".popup-overlay" ).css("z-index","10500"); }, onChange: function (p, value, displayValue){ if (!f_age){ var fpick = pickerDescribe.value; var spick = pickerDescribe2.value; if (fpick && spick) { if(!sexuality){sexuality=true;$( ".registerdiv" ).slideUp();$('.hiderowpref').removeClass('hiderowpref');$( ".swipetoolbar" ).show();$( '.swipetext' ).text("Profile");mySwiper.unlockSwipes();$( ".donechange" ).show();$( ".doneunchange" ).hide();myApp.sizeNavbars(); } $( ".savebutton" ).removeClass( "disabled" );} else {$( ".savebutton" ).addClass( "disabled" );} } }, onOpen: function (p){if (sexuality){processUpdate(); myApp.sizeNavbars(); } // $( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px"); $('.picker-items-col').eq(0).css('width','50%'); $('.picker-items-col').eq(1).css('width','50%'); var interestedcol = pickerDescribe2.cols[0]; var lowercol = pickerDescribe2.cols[1]; var uppercol = pickerDescribe2.cols[2]; if (f_interested) {interestedcol.setValue(f_interested);} if (f_lower) {lowercol.setValue(f_lower);} if (f_upper) {uppercol.setValue(f_upper);} }, formatValue: function (p, values, displayValues) { if (values[1] > values[2]) { return displayValues[0] + ', between ' + values[2] + ' - ' + values[1];} else { return displayValues[0] + ', between ' + values[1] + ' - ' + values[2]; } }, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left">' + 'Preference'+ '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { textAlign: 'left', values: ('Men Women').split(' ') }, { values: ('18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99').split(' ') }, { values: ('18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99').split(' ') }, ] }); } function swipePref(index){mySwiper.slideTo(index);} function navPicker(){ myApp.pickerModal( '<div class="picker-modal picker-sub" style="height:88px;">' + '<div class="toolbar tabbar" style="z-index:9999;background-color:#ccc;">' + '<div class="toolbar-inner" style="padding:0;">' + ' <a href="#" class="button tab-link tab-swipe home0" onclick="swipePopup(0);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-filter pe-lg" style="width:22px;margin:0 auto;"></i></a>'+ ' <a href="#" class="button tab-link tab-swipe home1 " onclick="swipePopup(1);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-clock pe-lg" style="width:22px;margin:0 auto;"></i></a>'+ ' <a href="#" class="button tab-link tab-swipe home2" onclick="swipePopup(2);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-info pe-lg" style="width:22px;margin:0 auto;"></i></a>'+ ' <a href="#" class="button tab-link tab-swipe home3" onclick="swipePopup(3);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-camera pe-lg" style="width:22px;margin:0 auto;"></i></a>'+ ' <a href="#" class="button tab-link tab-swipe home4" onclick="swipePopup(4);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-config pe-lg" style="width:22px;margin:0 auto;"></i></a>'+ '</div>' + '</div>' + '<div class="picker-modal-inner close-picker" style="height:44px;background-color:#2196f3;text-align:center;">' + '<i class="pe-7s-angle-down pe-2x " style="font-size:34px;margin-top:5px;color:white;"></i>'+ '</div>' + '</div>' ); } function removeProfileSet(pickertype){ $( "#" + pickertype + "-input").remove(); $( "." + pickertype + "-div").append( '<input type="text" id="'+pickertype+'-input" name="name" placeholder="Hide" readonly >' ); if (pickertype=='industry'){ var industrypicker = myApp.picker({ input: '#industry-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (industry_u) {industrypicker.cols[0].setValue(industry_u);} }, onChange:function (p, values, displayValues){$( '#industry-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'industry\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Accounting', 'Administration','Advertising','Agriculture','Banking and finance', 'Business', 'Charity', 'Creative arts','Construction','Consulting', 'Design', 'Education','Energy','Events', 'Engineering','Environment','Healthcare','Hospitality','HR and Recruitment', 'IT','Law','Law Enforcement','Leisure','Management','Manufacturing', 'Marketing','Media','Other','Pharmaceuticals','PR','Property','Public Services','Retail','Sales','Science','Security','Social Care','Small business','Sport','Tourism','Transport','Utilities','Voluntary work'] } ] }); } if (pickertype=='status'){ var statuspicker = myApp.picker({ input: '#status-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (status_u) {statuspicker.cols[0].setValue(status_u);}}, onChange:function (p, values, displayValues){$( '#status-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'status\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Single', 'Married', 'Engaged','Open relationship', 'Committed relationship','It\'s Complicated'] } ] }); } if (pickertype=='politics'){ var politicspicker = myApp.picker({ input: '#politics-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (politics_u) {politicspicker.cols[0].setValue(politics_u);}}, onChange:function (p, values, displayValues){$( '#politics-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'politics\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Left / Liberal', 'Centre','Right / Conservative','Not interested'] } ] }); } if (pickertype=='zodiac'){ var zodiacpicker = myApp.picker({ input: '#zodiac-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (zodiac_u) {zodiacpicker.cols[0].setValue(zodiac_u);}}, onChange:function (p, values, displayValues){$( '#zodiac-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'zodiac\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn','Aquarius','Pisces'] } ] }); } if (pickertype=='religion'){ var religionpicker = myApp.picker({ input: '#religion-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (religion_u) {religionpicker.cols[0].setValue(religion_u);}}, onChange:function (p, values, displayValues){$( '#religion-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'religion\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Atheist','Agnostic','Christianity','Islam','Buddhism','Hindusim','Sikhism','Judaism','Other'] } ] }); } if (pickertype=='ethnicity'){ var ethnicitypicker = myApp.picker({ input: '#ethnicity-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (ethnicity_u) {ethnicitypicker.cols[0].setValue(ethnicity_u);}}, onChange:function (p, values, displayValues){$( '#ethnicity-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'ethnicity\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Asian', 'Black', 'Latin / Hispanic','Mixed','Middle Eastern','Native American','Other','Pacific Islander','White'] } ] }); } if (pickertype=='height'){ var heightpicker = myApp.picker({ input: '#height-input', onChange:function (p, values, displayValues){$( '#height-input' ).addClass("profilevaluechosen");}, onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (height_u) { if (height_u == 122) {var heightset = '122 cm (4\' 0\'\')';} if (height_u == 124) {var heightset = '124 cm (4\' 1\'\')';} if (height_u == 127) {var heightset = '127 cm (4\' 2\'\')';} if (height_u == 130) {var heightset = '130 cm (4\' 3\'\')';} if (height_u == 132) {var heightset = '132 cm (4\' 4\'\')';} if (height_u == 135) {var heightset = '135 cm (4\' 5\'\')';} if (height_u == 137) {var heightset = '137 cm (4\' 6\'\')';} if (height_u == 140) {var heightset = '140 cm (4\' 7\'\')';} if (height_u == 142) {var heightset = '142 cm (4\' 8\'\')';} if (height_u == 145) {var heightset = '145 cm (4\' 9\'\')';} if (height_u == 147) {var heightset = '147 cm (4\' 10\'\')';} if (height_u == 150) {var heightset = '150 cm (4\' 11\'\')';} if (height_u == 152) {var heightset = '152 cm (5\' 0\'\')';} if (height_u == 155) {var heightset = '155 cm (5\' 1\'\')';} if (height_u == 157) {var heightset = '157 cm (5\' 2\'\')';} if (height_u == 160) {var heightset = '160 cm (5\' 3\'\')';} if (height_u == 163) {var heightset = '163 cm (5\' 4\'\')';} if (height_u == 165) {var heightset = '165 cm (5\' 5\'\')';} if (height_u == 168) {var heightset = '168 cm (5\' 6\'\')';} if (height_u == 170) {var heightset = '170 cm (5\' 7\'\')';} if (height_u == 173) {var heightset = '173 cm (5\' 8\'\')';} if (height_u == 175) {var heightset = '175 cm (5\' 9\'\')';} if (height_u == 178) {var heightset = '178 cm (5\' 10\'\')';} if (height_u == 180) {var heightset = '180 cm (5\' 11\'\')';} if (height_u == 183) {var heightset = '183 cm (6\' 0\'\')';} if (height_u == 185) {var heightset = '185 cm (6\' 1\'\')';} if (height_u == 188) {var heightset = '185 cm (6\' 2\'\')';} if (height_u == 191) {var heightset = '191 cm (6\' 3\'\')';} if (height_u == 193) {var heightset = '193 cm (6\' 4\'\')';} if (height_u == 195) {var heightset = '195 cm (6\' 5\'\')';} if (height_u == 198) {var heightset = '198 cm (6\' 6\'\')';} if (height_u == 201) {var heightset = '201 cm (6\' 7\'\')';} if (height_u == 203) {var heightset = '203 cm (6\' 8\'\')';} heightpicker.cols[0].setValue(heightset);}}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'height\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['122 cm (4\' 0\'\')','124 cm (4\' 1\'\')','127 cm (4\' 2\'\')','130 cm (4\' 3\'\')','132 cm (4\' 4\'\')','135 cm (4\' 5\'\')','137 cm (4\' 6\'\')','140 cm (4\' 7\'\')','142 cm (4\' 8\'\')','145 cm (4\' 9\'\')','147 cm (4\' 10\'\')','150 cm (4\' 11\'\')','152 cm (5\' 0\'\')','155 cm (5\' 1\'\')','157 cm (5\' 2\'\')','160 cm (5\' 3\'\')','163 cm (5\' 4\'\')','165 cm (5\' 5\'\')','168 cm (5\' 6\'\')','170 cm (5\' 7\'\')','173 cm (5\' 8\'\')','175 cm (5\' 9\'\')','178 cm (5\' 10\'\')','180 cm (5\' 11\'\')','183 cm (6\' 0\'\')','185 cm (6\' 1\'\')','188 cm (6\' 2\'\')','191 cm (6\' 3\'\')','193 cm (6\' 3\'\')','195 cm (6\' 4\'\')','198 cm (6\' 5\'\')','201 cm (6\' 6\'\')','203 cm (6\' 8\'\')'] }, ] }); } if (pickertype=='weight'){ var weightpicker = myApp.picker({ input: '#weight-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (weight_u) { weightpicker.cols[0].setValue(weight_u + ' kg (' + Math.round(weight_u* 2.20462262) + ' lbs)');}}, onChange:function (p, values, displayValues){$( '#weight-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'weight\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="center">' + 'Weight'+ '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: (function () { var arr = []; for (var i = 45; i <= 150; i++) { arr.push(i + ' kg (' + Math.round(i* 2.20462262) + ' lbs)'); } return arr; })(), }, ] }); } if (pickertype=='eyes'){var eyespicker = myApp.picker({ input: '#eyes-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (eyes_u) {eyespicker.cols[0].setValue(eyes_u);}}, onChange:function (p, values, displayValues){$( '#eyes-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'eyes\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Amber', 'Blue', 'Brown','Grey','Green','Hazel','Other'] } ] }); } if (pickertype=='body'){ var bodypicker = myApp.picker({ input: '#body-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (body_u) {bodypicker.cols[0].setValue(body_u);}}, onChange:function (p, values, displayValues){$( '#body-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'body\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Athletic','Average', 'Slim', 'Large', 'Muscular','Unimportant'] } ] }); } } function actionSheet(){ var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} if ($('.chatpop').length === 0 || ($('.chatpop').length === 1 && $('.chatpop').css('z-index') === '10000')){ var disabledattribute; if (targetreported){disabledattribute=true;}else{disabledattribute=false;} var buttons = [ { text: 'View Profile', bold: true, onClick: function () { if ($('.infopopup').length > 0) { scrolltoTop(); } else{questions();scrolltoTop();} } }, { text: 'View Profile Photos ('+new_all[myPhotoBrowser.swiper.activeIndex].photocount+')', bold: true, onClick: function () { if ($('.infopopup').length > 0) { myApp.closeModal() ;backtoProfile(); } else{} } }, { text: 'View Photo Bombs (0)', disabled:true, color: 'green', onClick: function () { imagesPopup(); } }, { text: 'Block', onClick: function () { more(); } },{ text: 'Report', disabled:disabledattribute, onClick: function () { report(); } }, { text: 'Cancel', color: 'red' }, ]; } else { var elementPos = new_all.map(function(x) {return x.id; }).indexOf(targetid); //var elementPos = new_all.findIndex(x => x.id==targetid); var disabledattribute; if (targetreported){disabledattribute=true;}else{disabledattribute=false;} var buttons = [ { text: 'View Profile', bold: true, onClick: function () { if($( ".center" ).hasClass( "close-popup" )){ myApp.closeModal('.chatpop'); if ($('.infopopup').length > 0) { scrolltoTop(); } else{questions();scrolltoTop();} }else{viewscroll = true;singleUser(targetid,targetname);} } }, { text: 'View Profile Photos ('+new_all[elementPos].photocount+')', bold: true, onClick: function () { if($( ".center" ).hasClass( "close-popup" )){ myApp.closeModal('.chatpop'); backtoProfile(); }else{viewphotos = true;singleUser(targetid,targetname);} } }, { text: 'View Photo Bombs (0)', disabled:true, color: 'green', onClick: function () { imagesPopup(); } }, { text: 'Block', onClick: function () { more(); } },{ text: 'Report', disabled:disabledattribute, onClick: function () { report(); } }, { text: 'Cancel', color: 'red' }, ]; } myApp.actions(buttons); var photobombsheet = firebase.database().ref('photochats/' + first_number + '/'+ second_number); photobombsheet.once('value', function(snapshot) { if(snapshot.val()){$(".color-green").removeClass('disabled'); $(".color-green").html('View Photo Bombs ('+snapshot.numChildren()+')'); } }); }
www/js/app.js
var refreshIntervalId; var desktoparray = ['media/dateicon.png','media/duckicon.png','media/datetongue.png','media/dateorducklogo.png'] function setWant(val){ if (val == 0){ if ($( ".homedate" ).hasClass( "active" )){$( ".homedate" ).removeClass("active"); if ($( ".homeduck" ).hasClass( "active" )){homewant = 'duck';updateWant(); }else {homewant = 'offline';updateWant(); } } else{$( ".homedate" ).addClass("active"); if ($( ".homeduck" ).hasClass( "active" )){homewant = 'dateduck';updateWant(); }else {homewant = 'date';updateWant(); } } } if (val == 1){ if ($( ".homeduck" ).hasClass( "active" )){$( ".homeduck" ).removeClass("active"); if ($( ".homedate" ).hasClass( "active" )){homewant = 'date';updateWant(); }else {homewant = 'offline';updateWant(); } } else{$( ".homeduck" ).addClass("active"); if ($( ".homedate" ).hasClass( "active" )){homewant = 'dateduck';updateWant(); }else {homewant = 'duck';updateWant(); } } } } function updateWant(){ firebase.database().ref('users/' + f_uid).update({ homewant : homewant }); //Will update firebase user homewant //Check if updateuser function is in go daddy file firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/updatewant.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,want:homewant} ) .done(function( data ) { //getMatches(); }); }).catch(function(error) { // Handle error }); } function startCamera(){ navigator.camera.getPicture(conSuccess, conFail, { quality: 50, destinationType: Camera.DestinationType.FILE_URI,sourceType:Camera.PictureSourceType.PHOTOLIBRARY}); } function conSuccess(imageURI) { alert('gotimage'); //var image = document.getElementById('myImage'); //image.src = imageURI; } function conFail(message) { alert('Failed because: ' + message); } function doSomething() { var i = Math.floor(Math.random() * 4) + 0; $(".desktopimage").attr("src", desktoparray[i]); } var myFunction = function() { doSomething(); var rand = Math.round(Math.random() * (1000 - 700)) + 700; refreshIntervalId = setTimeout(myFunction, rand); } myFunction(); var mobile = 0; if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {mobile = 1;} else{ mobile = 0; $('.login-loader').hide(); $('.dateduckdesktop').append('<div style="clear:both;width:100%;text-align:center;border-top:1px solid #ccc;margin-top:10px;"><p>Meet people nearby for a date or a <strike>fu**</strike> duck.</br></br>Open on your phone.</p></div>'); } //if (mobile===1){ try { // try to use localStorage localStorage.test = 2; } catch (e) { // there was an error so... alert('You are in Privacy Mode\nPlease deactivate Privacy Mode and then reload the page.'); } // Initialize your app var myApp = new Framework7({dynamicNavbar: true,init: false}); // Export selectors engine var $$ = Dom7; var view1, view2, view3, view4; var updatecontinuously = false; var initialload = false; var allowedchange = true; var view3 = myApp.addView('#view-3'); var view4 = myApp.addView('#view-4'); var myMessages, myMessagebar, f_description,existingchatnotifications, message_history = false, message_historyon, datealertvar = false, datealert = false, latitudep, longitudep, incommondate, incommonduck,f_uid,f_name,f_first,f_gender,f_age,f_email,f_image,f_token, f_upper, f_lower, f_interested,sexuality; var f_to_date = [],f_to_duck = [],f_date_me = [],f_duck_me = [],f_date_match = [],f_duck_match = [],f_date_match_data = [],f_duck_match_data = []; var f_auth_id; var blocklist; var lastkey; var pickerDescribe,pickerDescribe2, pickerCustomToolbar; var existingmessages; var additions = 0; var myPhotoBrowser; var singlePhotoBrowser; var calendarInline; var keepopen; var userpref; var loadpref= false; var loadpref2= false; var loaded = false; var myList; var myphotosarray; var matcheslistener; var noresultstimeout; var timeoutactive = false; var radiussize,sortby,offsounds; var industry_u,status_u,politics_u,eyes_u,body_u,religion_u,zodiac_u,ethnicity_u,height_u,weight_u; var descriptionslist = []; var nameslist = []; var fdateicon = '<img src="media/dateicon.png" style="width:28px;margin-right:5px;">'; var fduckicon = '<img src="media/duckicon.png" style="width:28px;margin-right:5px;">'; var notifcount; var swiperPhotos; var swiperQuestions; var myswiperphotos; var flargedateicon = '<img src="media/dateicon.png" style="width:60px;">'; var flargeduckicon = '<img src="media/duckicon.png" style="width:60px;">'; var mySwiper; myApp.init(); var f_projectid; var canloadchat; var viewphotos = false; var viewscroll = false; var homewant; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var firebaseinit; var app = { // Application Constructor initialize: function() { this.bindEvents(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicitly call 'app.receivedEvent(...);' onDeviceReady: function() { app.receivedEvent('deviceready'); // alert(Keyboard); //soNow(); // Add views view1 = myApp.addView('#view-1'); view2 = myApp.addView('#view-2', { // Because we use fixed-through navbar we can enable dynamic navbar dynamicNavbar: true }); view3 = myApp.addView('#view-3'); view4 = myApp.addView('#view-4'); //authstatechanged user only firebase.auth().onAuthStateChanged(function(user) { if (user) { f_projectid = firebase.auth().currentUser.toJSON().authDomain.substr(0, firebase.auth().currentUser.toJSON().authDomain.indexOf('.')) f_uid = user.providerData[0].uid; f_auth_id = user.uid; f_name = user.providerData[0].displayName; f_first = f_name.substr(0,f_name.indexOf(' ')); f_email = user.providerData[0].email; f_image = user.providerData[0].photoURL; // $( ".userimagetoolbar" ).css("background-image","url(\'https://graph.facebook.com/"+f_uid+"/picture?type=normal\')"); // $( "#profilepic" ).empty(); // $( "#profilepic" ).append('<div style="float:left;height:70px;width:70px;border-radius:50%;margin:0 auto;background-size:cover;background-position:50% 50%;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?type=normal\');"></div>'); firebase.database().ref('users/' + f_uid).update({ auth_id : f_auth_id }).then(function() {getPreferences();}); } else { $( ".ploader" ).show(); $( ".loginbutton" ).show(); $( ".login-loader" ).hide(); // No user is signed in. } }); }, // Update DOM on a Received Event receivedEvent: function(id) {} }; function startApp(){ firebaseinit = localStorage.getItem('tokenStore'); if (firebaseinit){ var credential = firebase.auth.FacebookAuthProvider.credential(firebaseinit); firebase.auth().signInWithCredential(credential).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; if (error){ myApp.alert('Error', 'Error message: ' + errorMessage + '(code:' + errorCode + ')'); } }); } else { alert('no tokenStore'); } } $$('.panel-right').on('panel:opened', function () { leftPanel(); }); $$('.panel-right').on('panel:open', function () { $( ".upgradeli" ).slideDown(); }); $$('.panel-right').on('panel:closed', function () { myList.deleteAllItems(); myList.clearCache(); //firebase.database().ref('notifications/' + f_uid).off('value', notificationlist); }); function compare(a,b) { if (a.chat_expire < b.chat_expire) return -1; if (a.chat_expire > b.chat_expire) return 1; return 0; } $$('.panel-left').on('panel:closed', function () { $(".timeline").empty(); }); $$('.panel-left').on('panel:open', function () { rightPanel(); }); $$('.panel-right').on('panel:closed', function () { $( ".upgradeli" ).hide(); }); // Pull to refresh content var ptrContent = $$('.pull-to-refresh-content-1'); // Add 'refresh' listener on it ptrContent.on('ptr:refresh', function (e) { // Emulate 2s loading //loaded = false; getPreferences(); setTimeout(function () { // Random image myApp.pullToRefreshDone(); }, 1000); }); // Pull to refresh content var ptrContent = $$('.pull-to-refresh-content-2'); // Add 'refresh' listener on it ptrContent.on('ptr:refresh', function (e) { myList.deleteAllItems(); myList.clearCache(); setTimeout(function () { // Random image leftPanel(); myApp.pullToRefreshDone(); }, 1000); }); var onSuccess = function(position) { latitudep = position.coords.latitude; longitudep = position.coords.longitude; //alert(latitudep); //alert(longitudep); updateGeo(); $( ".age-header" ).remove(); $( ".swiper-container-loaded" ).remove(); }; function onError(error) { if (error.code == '1'){ jQuery.post( "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCAqd15w-_K31IUyLWNlmkHNmZU5YLSg6c", function(success) { apiGeolocationSuccess({coords: {latitude: success.location.lat, longitude: success.location.lng}}); }) .done(function() { //alert('done'); }) .fail(function(err) { myApp.alert('You must share your location on date or duck', 'Oops we cannot find you'); }); } if ((error.code == '2') || (error.code == '3')){ jQuery.post( "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCAqd15w-_K31IUyLWNlmkHNmZU5YLSg6c", function(success) { apiGeolocationSuccess({coords: {latitude: success.location.lat, longitude: success.location.lng}}); }) .done(function() { //alert('done'); }) .fail(function(err) { myApp.alert('There has been an error.', 'Oops we cannot find you'); }); } } function getWifilocation(){ navigator.geolocation.getCurrentPosition(onSuccess, onError); } var apiGeolocationSuccess = function(position) { latitudep = position.coords.latitude; longitudep = position.coords.longitude; //alert(latitudep); //alert(longitudep); updateGeo(); $( ".age-header" ).remove(); $( ".swiper-container-loaded" ).remove(); }; function mainLoaded(id){ $( ".iconpos_" + id ).show(); $( ".default_" + id ).hide(); var indivNotif = firebase.database().ref('notifications/' + f_uid + '/' + id); indivNotif.once('value', function(snapshot) { if (snapshot.val()){ var obj = snapshot.val(); if (obj.new_message_count >0 && obj.to_uid == f_uid && obj.received =='N'){$( ".arrowdivhome_" + id ).empty();$( ".arrowdivhome_" + id ).append('<span class="badge" style="background-color:rgb(255, 208, 0);color:black;margin-top:5px;margin-left:-5px;">'+obj.new_message_count+'</span>');} else{$( ".arrowdivhome_" + id ).empty();} } }); } var all_matches_photos=[]; var new_all = []; var main_all = []; function getMatches(){ new_all = []; //can put any ads here if ((initialload === false) && (availarray.length === 0)){ } if (!homewant || homewant =='offline'){ $('.content-here').empty(); $( ".results-loader" ).hide(); $('.content-here').append( '<div class="no-results-div" style="text-align:center;margin:0 auto;width:300px;position:absolute;top:44px;left:50%;margin-left:-150px;margin-top:54px;">'+ '<h3>Get Quacking!</h3>'+ '<p style="padding-top:0px;margin-top:0px;">Are you looking to date, or duck or both? Your profile is not visible until you make a selection.</p>'+ '<div class="row" style="border-top:1px solid #c4c4c4;padding-top:10px;padding-bottom:10px;">'+ '<div class="col-30" style="padding-top:5px;"><img src="media/datefaceonly.png" style="width:80px;margin:0 auto;"></div>'+ '<div class="col-70" style="padding-top:5px;">Press <span style="font-family: \'Pacifico\', cursive;font-size:17px;">date</span> if you want to meet someone to hang out with, find a relationship or make conversation.</div>'+ '</div>'+ '<div class="row" style="padding-top:10px;padding-bottom:10px;">'+ '<div class="col-30" style="padding-top:5px;"><img src="media/duckfaceonly.png" style="width:80px;margin:0 auto;"></div>'+ '<div class="col-70" style="padding-top:5px;">Press <span style="font-family: \'Pacifico\', cursive;font-size:17px;">duck</span> if you want to get down to...ahem...business (replace the D with an F). </div>'+ '</div>'+ '</div>'); $( ".ploader" ).hide(); $( ".toolbar" ).show(); $( ".loginbutton" ).show(); $( ".login-loader" ).hide(); return false; } initialload = true; if (updatecontinuously){} else {setInterval(function(){ justGeo(); }, 599000);updatecontinuously=true;} if (timeoutactive === true) {clearTimeout(noresultstimeout);} timeoutactive = true; firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/locations.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,upper:f_upper,lower:f_lower,radius:radiussize,sexuality:sexuality,sortby:sortby,latitudep:latitudep,longitudep:longitudep} ) .done(function( data ) { var result = JSON.parse(data); console.log(data); console.log(result); for (var i = f_lower; i <= f_upper; i++) {} var slidewidth = $( document ).width() / 1.7; var halfwidth = -Math.abs(slidewidth / 2.23); // var rownumber; // var calcrownumber = f_upper-f_lower; // var columnslides; // var specialstyles; // if (calcrownumber == 0){rownumber = 3;columnslides=9;} // if (calcrownumber > 0){rownumber = 1;columnslides=1;} var slide_number = 0; for (var i = f_lower; i <= f_upper; i++) { all_matches_photos[i] = []; $( ".content-here" ).append( // '<span class="badge age-header header_'+i+'" style="display:none;text-align:left;float:left;width:100%;border-radius:0px;background-color:white;color:black;">'+i+'</span>'+ ' <div class="swiper-container swiper-container-loaded swiper-'+i+'" style="display:none;height:'+slidewidth+'px;clear:both;background-color:white;">'+ '<div class="blockleft_'+i+'" style="display:none;color:white;padding:3px;height:20px;width:20px;-webkit-border-top-right-radius: 50%;-webkit-border-bottom-right-radius: 50%;background-color:#2196f3;position:absolute;left:0;top:50%;z-index:9999;margin-top:-10px;"><div style="float:left;"><i class="pe-7s-angle-left pe-lg" style="margin-left:-9px;color:white;float:left;margin-top:3px"></i><span style="float:left;font-size:12px;margin-left:-5px;margin-top:2px;">'+i+'</span></div></div>'+ '<div class="blockright_'+i+' multiple_'+i+'" style="display:none;margin-top:-10px;color:white;padding:3px;height:20px;width:20px;-webkit-border-top-left-radius: 50%;-webkit-border-bottom-left-radius: 50%;background-color:#2196f3;position:absolute;right:0px;top:50%;z-index:9999;margin-top:-7.5px;"><div style="float:right;"><i class="pe-7s-angle-right pe-lg" style="margin-right:-9px;color:white;float:right;margin-top:3px"></i><span style="float:right;font-size:12px;margin-right:-5px;margin-top:2px;">'+i+'</span></div></div>'+ '<div class="blockright_'+i+' single_'+i+'" style="margin-top:-10px;color:white;padding:3px;height:20px;width:20px;border-radius:50%;margin-right:5px;background-color:#2196f3;position:absolute;right:0px;top:50%;z-index:9999;margin-top:-7.5px;"><div style="float:right;"><span style="float:right;font-size:12px;margin-right:2px;margin-top:2px;">'+i+'</span></div></div>'+ '<div class="swiper-wrapper wrapper_'+i+'">'+ // '<div class="swiper-slide"><div style="background-color:white;height:50%;width:50%;margin-top:50%;margin-left:25%;"></div></div>'+ '</div>'+ '</div>' ); myApp.swiper('.swiper-' + i, { slidesPerView:1.7, freeMode:true, //slidesOffsetBefore:halfwidth, slidesOffsetAfter:12, preloadImages: false, // Enable lazy loading lazyLoading: true, //centeredSlides: true, watchSlidesVisibility:true, watchSlidesProgress: true, onSlideChangeEnd:function(swiper){ var firstclasslist = $(swiper.slides[0]).attr("class").split(' '); var currentswiper = firstclasslist[0].replace("age_", ""); var swiperslideslength = swiper.slides.length; if (swiper.activeIndex === 0){$('.blockright_' + currentswiper).show();$('.blockleft_' + currentswiper).hide(); } else { if (swiper.activeIndex > 0){ //if(swiper.isEnd){console.log('going to start');swiper.slideTo(0);} if (swiper.activeIndex == swiperslideslength-2 || swiper.activeIndex == swiperslideslength-1){ $('.blockright_' + currentswiper).hide();$('.blockleft_' + currentswiper).show();} else{ $('.blockright_' + currentswiper).hide();$('.blockleft_' + currentswiper).hide();} } } }, onClick:function(swiper, event) { var ageswiper = swiper.clickedSlide.classList[0].replace("age_", ""); photoBrowser(swiper.clickedIndex,ageswiper);} //pagination:'.swiper-pagination' }); slide_number++; } descriptionslist = []; nameslist = []; $( ".results-loader" ).hide(); if (result == 77 ||(result.length ===1 && result[0].uid == f_uid ) ){ $( ".results-loader" ).hide(); $('.content-here').append( '<div class="no-results-div" style="text-align:center;margin:0 auto;width:300px;position:absolute;top:50%;left:50%;margin-left:-150px;margin-top:-70px;">'+ '<img src="media/datetongue.png" style="width:80px;margin:0 auto;">'+ '<h3>No one is nearby</h3><p style="padding-top:0px;margin-top:-10px;">Try changing your search radius, </br>age range or filters.</p></br>'+ '</div>'); } else { var tonight = new Date(); tonight.setHours(22,59,59,999); var tonight_timestamp = Math.round(tonight/1000); for (i = 0; i < result.length; i++) { var photosstringarray =[]; var photocount; var photostring; var blocked = 0; var subtract = result[i].age; var laston = result[i].timestamp; var industry_d = result[i].industry; var status_d = result[i].status; var politics_d = result[i].politics; var eyes_d = result[i].eyes; var body_d = result[i].body; var religion_d = result[i].religion; var zodiac_d = result[i].zodiac; var ethnicity_d = result[i].ethnicity; var height_d = result[i].height; var weight_d = result[i].weight; var namescount = result[i].displayname.split(' ').length; var matchname; var minphotowidth = $( document ).width(); var imagestyle; imagestyle='width:100%;max-height:' + slidewidth + 'px;overflow:hidden;'; var availarraystring=''; var availnotexpired = false; if(result[i].availstring && (result[i].availstring != '[]') && (result[i].uid != f_uid)){ console.log(result[i].availstring); var availablearrayindividual = JSON.parse(result[i].availstring); console.log(availablearrayindividual); for (k = 0; k < availablearrayindividual.length; k++) { if (availablearrayindividual[k].id >= tonight_timestamp){availnotexpired = true;} } if (availnotexpired){availarraystring = result[i].availstring;} } var profilepicstring; var photoarrayuserlarge; var photoarrayusersmall; if(result[i].largeurl){ var heightarray = result[i].heightslides.split(","); var widtharray = result[i].widthslides.split(","); console.log(heightarray[0]); console.log(widtharray[0]); if (heightarray[0] > widtharray[0]) {imagestyle = 'width:100%;max-height:' + slidewidth + 'px;overflow:hidden;'} if (widtharray[0] > heightarray[0]) {imagestyle = 'height:100%;max-width:' + slidewidth + 'px;overflow:hidden;'} photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical" style="height:100%;"><img data-src="' + result[i].largeurl + '" class="swiper-lazy"></div></div>'; photocount = result[i].largeurl.split(",").length; photoarrayuserlarge = result[i].largeurl.split(","); photoarrayusersmall = result[i].smallurl.split(","); profilepicstringlarge = photoarrayuserlarge[0]; profilepicstringsmall = photoarrayusersmall[0]; photostring=photostring.replace(/,/g, '" class="swiper-lazy" style="height:100%;"></div></div><div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="') } else{ photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="https://graph.facebook.com/'+result[i].uid+'/picture?width=828" class="swiper-lazy" style="height:100%;"></div></div>'; profilepicstringlarge = 'https://graph.facebook.com/'+result[i].uid+'/picture?width=828&height=828'; profilepicstringsmall = 'https://graph.facebook.com/'+result[i].uid+'/picture?width=368&height=368'; photocount = 1; } //console.log(photostring); if(namescount === 1){matchname = result[i].displayname;} else {matchname = result[i].name.substr(0,result[i].displayname.indexOf(' '));} var matchdescription = result[i].description; var swipernumber = subtract - f_lower; var curswiper = $$('.swiper-container')[swipernumber].swiper; var graphid = result[i].uid; var distance = parseFloat(result[i].distance).toFixed(1); var distancerounded = parseFloat(result[i].distance).toFixed(0); if ((distance >= 0) && (distance <0.1)) {distancestring = 'Less than 100 m <span style="font-size:13px;">(328 ft.)</span>'} if ((distance >= 0.1) && (distance <0.2)) {distancestring = 'Less than 200 m <span style="font-size:13px;">(656 ft.)</span>'} if ((distance >= 0.2) && (distance <0.3)) {distancestring = 'Less than 300 m <span style="font-size:13px;">(984 ft.)</span>'} if ((distance >= 0.3) && (distance <0.4)) {distancestring = 'Less than 400 m <span style="font-size:13px;">(1312 ft.)</span>'} if ((distance >= 0.4) && (distance <0.5)) {distancestring = 'Less than 500 m <span style="font-size:13px;">(1640 ft.)</span>'} if ((distance >= 0.5) && (distance <0.6)) {distancestring = 'Less than 600 m <span style="font-size:13px;">(1968 ft.)</span>'} if ((distance >= 0.6) && (distance <0.7)) {distancestring = 'Less than 700 m <span style="font-size:13px;">(2296 ft.)</span>'} if ((distance >= 0.7) && (distance <0.8)) {distancestring = 'Less than 800 m <span style="font-size:13px;">(2624 ft.)</span>'} if ((distance >= 0.8) && (distance <0.9)) {distancestring = 'Less than 900 m <span style="font-size:13px;">(2953 ft.)</span>'} if ((distance >= 0.9) && (distance <1.0)) {distancestring = 'Less than 1 km <span style="font-size:13px;">(3280 ft.)</span>'} if ((distance >= 1.0) && (distance <1.609344)) {distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 3280.84) + ' ft.)</span>'} if (distance > 1.609344){distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 0.621371) + ' mi.)</span>'} var zz = new Date(); var mmn = zz.getTimezoneOffset(); console.log(result[i].timestamp); var timestampyear = result[i].timestamp.substring(0,4); var timestampmonth = result[i].timestamp.substring(5,7); var timestampday = result[i].timestamp.substring(8,10); var timestamphour = result[i].timestamp.substring(11,13); var timestampminute = result[i].timestamp.substring(14,16); var timestampsecond = result[i].timestamp.substring(17,20); var timestampunix=(new Date(timestampmonth + '/' + timestampday + '/' + timestampyear + ' ' + timestamphour + ':' + timestampminute + ':' + timestampsecond)).getTime() / 1000 + 64800; var d_unix = Math.round(+new Date()/1000); var diff = (d_unix - timestampunix)/60; var activecircle; if (diff<11){activecircle = '<span style="position:absolute;left:10px;height:10px;width:10px;border-radius:50%;bottom:10px;background-color:#4cd964"></span>';} else{activecircle = '<span style="position:absolute;left:10px;bottom:10px;height:10px;width:10px;border-radius:50%;background-color:transparent;border:1px solid #ccc;"></span>';} if ($('.slide_' + graphid).length){ var classremove = $('.slide_' + graphid).attr("class").split(' '); var agej = classremove[0].replace("age_", ""); for (var k = 0; i <= all_matches_photos[agej].length; k++) { if (all_matches_photos[agej][k].url == 'https://graph.facebook.com/'+graphid+'/picture?type=large'){all_matches_photos[agej].splice(k, 1);} } $('.slide_' + graphid).remove(); var slidesleft = $(".age_" + agej ).length; if (slidesleft === 0) { $('.swiper-' + agej).hide(); $('.header_' + agej).hide(); } } if (graphid != f_uid){ $('.swiper-' + subtract).show(); $('.header_' + subtract).show(); } var blockedid = blocklist.indexOf(graphid); //Do not show the users profile to themselves, and do not show profiles older than 1 month if ((graphid != f_uid) && (blockedid < 0) && (diff < 43800)){ var index1 = f_date_match.indexOf(graphid); var index2 = f_duck_match.indexOf(graphid); var index3 = f_duck_me.indexOf(graphid); var index4 = f_date_me.indexOf(graphid); var slidecontent; if (index1 > -1) { slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+graphid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:10px;top:0px;" class="arrowdivhome_'+graphid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#2196f3;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" class="swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" onload="$(this).fadeIn(700);mainLoaded(\''+graphid+'\');" style="display:none;'+imagestyle+'-webkit-filter:none;overflow:hidden;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/datefaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;">'+matchname+'</p></div></div>'; } else if (index2 > -1) { slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+graphid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:10px;top:0px;" class="arrowdivhome_'+graphid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#2196f3;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="$(this).fadeIn(700);mainLoaded(\''+graphid+'\');" class="swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:none;display:none;overflow:hidden;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/duckfaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;">'+matchname+'</p></div></div>'; } else if (index3 > -1) { slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+graphid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:10px;top:0px;" class="arrowdivhome_'+graphid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="$(this).fadeIn(700);mainLoaded(\''+graphid+'\');" class="swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;-webkit-filter:grayscale(1%);display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/duckfaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;">'+matchname+'</p></div></div>'; } else if (index4 > -1) { slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+graphid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="float" class="arrowdivhome_'+graphid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="$(this).fadeIn(700);mainLoaded(\''+graphid+'\');" class="swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;-webkit-filter:grayscale(1%);display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/datefaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;">'+matchname+'</p></div></div>'; } else { slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+graphid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:10px;top:0px;" class="arrowdivhome_'+graphid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="$(this).fadeIn(700);mainLoaded(\''+graphid+'\');" class="swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+graphid+'"></div>'+activecircle+'<p class="name_'+graphid+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-top:-30px;color:white;font-size:15px;text-align:left;float:left;margin-left:23px;">'+matchname+'</p></div></div>'; } if( all_matches_photos[subtract].length === 0){curswiper.appendSlide(slidecontent); all_matches_photos[subtract].push({widthslides:result[i].widthslides,heightslides:result[i].heightslides,availarraystring:availarraystring,minutes:diff,distancenumber:distance,distancestring:distancestring,photocount:photocount,photos:photostring,name:matchname,age:subtract,description:matchdescription,id:graphid,url:'https://graph.facebook.com/'+graphid+'/picture?width=828',caption:'...',industry: industry_d, status: status_d, politics:politics_d,eyes:eyes_d,body:body_d,religion:religion_d,zodiac:zodiac_d,ethnicity:ethnicity_d,height:height_d,weight:weight_d}); } else { if(sortby=='random'){ var insertindex = Math.floor(Math.random() * all_matches_photos[subtract].length) +0; insertAfterNthChild($('.wrapper_' + subtract), insertindex, slidecontent); all_matches_photos[subtract].splice(insertindex, 0, {widthslides:result[i].widthslides,heightslides:result[i].heightslides,availarraystring:availarraystring,minutes:diff,distancestring:distancestring,distancenumber:distance,photocount:photocount,photos:photostring,name:matchname,age:subtract,description:matchdescription,id:graphid,url:'https://graph.facebook.com/'+graphid+'/picture?width=828',caption:'...',industry: industry_d, status: status_d, politics:politics_d,eyes:eyes_d,body:body_d,religion:religion_d,zodiac:zodiac_d,ethnicity:ethnicity_d,height:height_d,weight:weight_d}); } if(sortby=='distance' || sortby == 'activity'){ curswiper.appendSlide(slidecontent); all_matches_photos[subtract].push({widthslides:result[i].widthslides,heightslides:result[i].heightslides,availarraystring:availarraystring,minutes:diff,distancestring:distancestring,distancenumber:distance,photocount:photocount,photos:photostring,name:matchname,age:subtract,description:matchdescription,id:graphid,url:'https://graph.facebook.com/'+graphid+'/picture?width=828',caption:'...',industry: industry_d, status: status_d, politics:politics_d,eyes:eyes_d,body:body_d,religion:religion_d,zodiac:zodiac_d,ethnicity:ethnicity_d,height:height_d,weight:weight_d}); } } //curswiper.slideNext(); //console.log('herenext'); if (all_matches_photos[subtract][0].id == graphid || all_matches_photos[subtract][1].id == graphid || all_matches_photos[subtract][2].id == graphid){ $(".photo_"+graphid).attr("src", profilepicstringsmall); } // all_matches_photos[subtract].push({url:'https://graph.facebook.com/'+graphid+'/picture?type=large',caption:'...'}); //all_matches_photos[subtract].push({url:'https://graph.facebook.com/'+graphid+'/picture?type=large',caption:'...'}); //all_matches_photos[subtract].unshift({url:'https://graph.facebook.com/'+graphid+'/picture?type=large',caption:'...'}); } } } var swiperselector=0; for (var i = f_lower; i <= f_upper; i++) { console.log(all_matches_photos[i].length); if (all_matches_photos[i].length >1){$('.single_'+i).hide();$('.multiple_'+i).show();}else{$('.single_'+i).show();$('.multiple_'+i).hide();} if (all_matches_photos[i].length ===0){$( ".swiper-"+i ).hide();} $$('.swiper-container')[swiperselector].swiper.updateContainerSize(); $$('.swiper-container')[swiperselector].swiper.updateProgress(); $$('.swiper-container')[swiperselector].swiper.updateSlidesSize(); $$('.swiper-container')[swiperselector].swiper.updateClasses(); //$$('.swiper-container')[swiperselector].swiper.slideTo(0); //$('.swiper-container')[swiperselector].swiper.appendSlide('<div style="width:'+slidewidth+'px;"><img src="media/datetongue.png" style="width:50px;left:50%;top:50%;margin-left:-25px;margin-top:-25px;"></div>') swiperselector ++; for (var j = 0; j < all_matches_photos[i].length; j++) { new_all.push(all_matches_photos[i][j]); } } if (new_all.length === 0){ $( ".results-loader" ).hide(); $('.content-here').append( '<div class="no-results-div" style="text-align:center;margin:0 auto;width:300px;position:absolute;top:50%;left:50%;margin-left:-150px;margin-top:-70px;">'+ '<img src="media/datetongue.png" style="width:80px;margin:0 auto;">'+ '<h3>No one is nearby</h3><p style="padding-top:0px;margin-top:-10px;">Try changing your search radius, </br>age range or filters.</p></br>'+ '</div>'); } }); //here is the id token call }).catch(function(error) { // Handle error }); $( ".ploader" ).hide(); $( ".toolbar" ).show(); $( ".loginbutton" ).show(); $( ".login-loader" ).hide(); $('.no-results-div').empty(); clearInterval(refreshIntervalId); deletePhotos(); } function justGeo(){ firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/updatelocation.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,latitude:latitudep,longitude:longitudep} ) .done(function( data ) { console.log('updatedtimestamp'); }); }).catch(function(error) { // Handle error }); } function updateGeo(){ firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/updatelocation.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,latitude:latitudep,longitude:longitudep} ) //$.post( "updatelocation.php", { uid:f_uid,latitude:latitudep,longitude:longitudep} ) .done(function( data ) { console.log('update lcoation'+data); getMatches(); }); }).catch(function(error) { // Handle error }); //var matchesRef = firebase.database().ref(sexuality + '/'+ f_age); //var geoFire = new GeoFire(matchesRef); //geoFire.set(f_uid + '*' + f_age + '*' + f_first, [latitudep, longitudep]).then(function() { //}, function(error) { //}); } function getPreferences(){ // Test if user exists if(userpref) {firebase.database().ref('users/' + f_uid).off('value', userpref);} userpref = firebase.database().ref('users/' + f_uid).on("value",function(snapshot) { var userexists = snapshot.child('lower').exists(); // true if (userexists) { // var matchessetting = firebase.database().ref("users/" + f_uid).on("value",function(snapshot) { // if (!snapshot.child("to_date").val()) {f_to_date = [];} // else{f_to_date = snapshot.child("to_date").val();} // if (!snapshot.child("to_duck").val()) {f_to_duck = [];} // else{f_to_duck = snapshot.child("to_duck").val();} // if (!snapshot.child("date_me").val()) {f_date_me = [];} // else{f_date_me = snapshot.child("date_me").val();} // if (!snapshot.child("duck_me").val()) {f_duck_me=[];} // else{f_duck_me = snapshot.child("duck_me").val();} // incommondate = f_to_date.filter(function(n) { // return f_date_me.indexOf(n) != -1; //}); //incommonduck = f_to_duck.filter(function(n) { // return f_duck_me.indexOf(n) != -1; //}); // }); industry_u = snapshot.child("industry").val(); status_u = snapshot.child("status").val(); politics_u = snapshot.child("politics").val(); eyes_u = snapshot.child("eyes").val(); body_u = snapshot.child("body").val(); religion_u = snapshot.child("religion").val(); zodiac_u = snapshot.child("zodiac").val(); ethnicity_u = snapshot.child("ethnicity").val(); height_u = snapshot.child("height").val(); weight_u = snapshot.child("weight").val(); homewant = snapshot.child("homewant").val(); if(homewant){ if (homewant == 'offline'){$( ".homedate" ).removeClass('active');$( ".homeduck" ).removeClass('active'); } if (homewant == 'dateduck'){$( ".homedate" ).addClass('active');$( ".homeduck" ).addClass('active'); } if (homewant == 'duck'){$( ".homedate" ).removeClass('active');$( ".homeduck" ).addClass('active'); } if (homewant == 'date'){$( ".homedate" ).addClass('active');$( ".homeduck" ).removeClass('active'); } } sortby = snapshot.child("sort").val(); if (snapshot.child("offsounds").val()){offsounds = snapshot.child("offsounds").val();} if (snapshot.child("availstring").val()){ availarray = JSON.parse(snapshot.child("availstring").val());} f_description = snapshot.child("description").val(); f_lower = snapshot.child("lower").val(); radiussize = snapshot.child("radius").val(); f_token = snapshot.child("token").val(); f_upper = snapshot.child("upper").val(); f_interested = snapshot.child("interested").val(); f_gender = snapshot.child("gender").val(); f_age = snapshot.child("age").val(); if (f_gender == 'Male' && f_interested == 'Men') {sexuality = 'gay';} if (f_gender == 'Male' && f_interested == 'Women') {sexuality = 'male';} if (f_gender == 'Female' && f_interested == 'Women') {sexuality = 'lesbian';} if (f_gender == 'Female' && f_interested == 'Men') {sexuality = 'female';} if (loadpref=== false){ loadpref = true; establishNotif(); } matchesListener(); } else if (!userexists) { addUser(); if (loadpref=== false){ firebase.database().ref('users/' + f_uid).once("value",function(snapshot) { f_token = snapshot.child("token").val(); swipePopup(2); }); //preferencesPopup(); } loadpref = true; } }); } function matchesListener(){ if (loaded === true){ firebase.database().ref("matches/" + f_uid).off('value', matcheslistener); } matcheslistener = firebase.database().ref("matches/" + f_uid).on("value",function(snapshot) { f_to_date = [],f_to_duck = [],f_date_me = [],f_duck_me = [],f_date_match = [],f_duck_match = [],f_date_match_data = [],f_duck_match_data = []; blocklist = []; if (snapshot.val()){ var objs = snapshot.val(); $.each(objs, function(i, obj) { if ((obj.first_number == f_uid) && (obj.firstnumberblock == 'Y' || obj.secondnumberblock == 'Y')) {blocklist.push(obj.second_number);} if ((obj.second_number == f_uid) && (obj.firstnumberblock == 'Y' || obj.secondnumberblock == 'Y')) {blocklist.push(obj.first_number);} if(obj.firstnumberdate){ //f_to_date if ((obj.first_number == f_uid) && (obj.firstnumberdate == 'Y')) {f_to_date.push(obj.second_number);} //f_date_me if ((obj.first_number != f_uid) && (obj.firstnumberdate == 'Y')) {f_date_me.push(obj.first_number);} } if(obj.firstnumberduck){ //f_duck_me if ((obj.first_number != f_uid) && (obj.firstnumberduck == 'Y')) {f_duck_me.push(obj.first_number);} //f_to_duck if ((obj.first_number == f_uid) && (obj.firstnumberduck == 'Y')) {f_to_duck.push(obj.second_number);} } if(obj.secondnumberdate){ //f_to_date if ((obj.second_number == f_uid) && (obj.secondnumberdate == 'Y')) {f_to_date.push(obj.first_number);} //f_date_me if ((obj.second_number != f_uid) && (obj.secondnumberdate == 'Y')) {f_date_me.push(obj.second_number);} } if(obj.secondnumberduck){ //f_to_duck if ((obj.second_number == f_uid) && (obj.secondnumberduck == 'Y')) {f_to_duck.push(obj.first_number);} //f_duck_me if ((obj.second_number != f_uid) && (obj.secondnumberduck == 'Y')) {f_duck_me.push(obj.second_number);} } if(obj.firstnumberdate && obj.secondnumberdate){ //f_date_match if(((obj.first_number != f_uid) && (obj.firstnumberdate == 'Y')) && ((obj.second_number == f_uid) && (obj.secondnumberdate == 'Y'))){f_date_match.push(obj.first_number);f_date_match_data.push({uid:obj.first_number,name:obj.first_name});} if(((obj.second_number != f_uid) && (obj.secondnumberdate == 'Y')) && ((obj.first_number == f_uid) && (obj.firstnumberdate == 'Y'))){f_date_match.push(obj.second_number);f_date_match_data.push({uid:obj.second_number,name:obj.second_name});} } if(obj.firstnumberduck && obj.secondnumberduck){ //f_duck_match if(((obj.first_number != f_uid) && (obj.firstnumberduck == 'Y')) && ((obj.second_number == f_uid) && (obj.secondnumberduck == 'Y'))){f_duck_match.push(obj.first_number);f_duck_match_data.push({uid:obj.first_number,name:obj.first_name});} if(((obj.second_number != f_uid) && (obj.secondnumberduck == 'Y')) && ((obj.first_number == f_uid) && (obj.firstnumberduck == 'Y'))){f_duck_match.push(obj.second_number);f_duck_match_data.push({uid:obj.second_number,name:obj.second_name});} } }); updatePhotos(); loaded = true; } else{ updatePhotos(); loaded = true; } }); $( ".content-here" ).empty(); $( ".results-loader" ).show(); getWifilocation(); } function addUser() { if (f_token){firebase.database().ref('users/' + f_uid).update({ name: f_name, email: f_email, image_url : f_image, uid:f_uid, token:f_token, auth_id : f_auth_id });} else{ firebase.database().ref('users/' + f_uid).update({ name: f_name, email: f_email, image_url : f_image, uid:f_uid, auth_id : f_auth_id }); } } function clickMe() { pickerDescribe.open(); } function keyUp(){ if (sexuality){processUpdate(); myApp.sizeNavbars(); } var inputlength = $( "#userdescription" ).val().length; $( "#maxdescription" ).empty(); $( "#maxdescription" ).append(inputlength + " / 100"); } function updateUser(){ if ((pickerDescribe.initialized === false && !f_age) || (pickerDescribe2.initialized === false && !f_lower)) { myApp.alert('Please complete more profile information.', 'Missing Information'); return false;} if (myswiperphotos){ myswiperphotos.destroy(); myswiperphotos = false; } var newage,newinterested,newgender; if (pickerDescribe.initialized === false) {newage = f_age;newgender = f_gender;} else {newage = pickerDescribe.value[1];newgender = pickerDescribe.value[0];} if (pickerDescribe2.initialized === false) {newinterested = f_interested;} else {newinterested = pickerDescribe2.value[0];} var userzdescription; if ($( "#userdescription" ).val()) {userzdescription = $( "#userdescription" ).val();} else {userzdescription = '';} //Need to delete old reference if (pickerDescribe.initialized === true) {f_age = pickerDescribe.value[1];f_gender = pickerDescribe.value[0];} if (pickerDescribe2.initialized === true) {f_interested = pickerDescribe2.value[0];} if (f_gender == 'Male' && f_interested == 'Men') {sexuality = 'gay';} if (f_gender == 'Male' && f_interested == 'Women') {sexuality = 'male';} if (f_gender == 'Female' && f_interested == 'Women') {sexuality = 'lesbian';} if (f_gender == 'Female' && f_interested == 'Men') {sexuality = 'female';} var lowerage,upperage; if (pickerDescribe2.initialized === true) { if (pickerDescribe2.value[1] > pickerDescribe2.value[2]) {lowerage = pickerDescribe2.value[2];upperage = pickerDescribe2.value[1];} else {lowerage = pickerDescribe2.value[1];upperage = pickerDescribe2.value[2];} } else {lowerage = f_lower;upperage = f_upper;} if ($( "#distance_10" ).hasClass( "active" )){radiussize = '10';} if ($( "#distance_25" ).hasClass( "active" )){radiussize = '25';} if ($( "#distance_50" ).hasClass( "active" )){radiussize = '50';} if ($( "#distance_100" ).hasClass( "active" )){radiussize = '100';} if ($( "#sortrandom" ).hasClass( "active" )){sortby = 'random';} if ($( "#sortdistance" ).hasClass( "active" )){sortby = 'distance';} if ($( "#sortactivity" ).hasClass( "active" )){sortby = 'activity';} availarray = []; $( ".availrec" ).each(function() { if ($( this ).hasClass( "selecrec" )){ var availinputid = $(this).attr('id').replace('aa_', ''); var valueinputted = $( "#picker"+availinputid ).val(); var supdate = $( ".suppdate_"+availinputid ).val(); if (valueinputted == 'Now'){daysaved ='Now';timesaved='';} else{ valueinputted = valueinputted.split(' '); var daysaved = valueinputted[0]; var timesaved = valueinputted[1]; } availarray.push({id:availinputid,day:daysaved,time:timesaved,fulldate:supdate}); } }); var availstring = JSON.stringify(availarray); var availstringn = availstring.toString(); if ($('#soundnotif').prop('checked')) {offsounds = 'Y'} else {offsounds = 'N'} //User Profile details var industry_u = $( "#industry-input" ).val(); var status_u = $( "#status-input" ).val(); var politics_u = $( "#politics-input" ).val(); var eyes_u = $( "#eyes-input" ).val(); var body_u = $( "#body-input" ).val(); var religion_u = $( "#religion-input" ).val(); var zodiac_u = $( "#zodiac-input" ).val(); var ethnicity_u = $( "#ethnicity-input" ).val(); var height_u = $( "#height-input" ).val().substring(0,3); var weight_pre = $( "#weight-input" ).val(); var weight_u = weight_pre.substr(0, weight_pre.indexOf(' ')); console.log(status_u); firebase.database().ref('users/' + f_uid).update({ gender: newgender, industry:industry_u, status:status_u, politics: politics_u,eyes: eyes_u,body: body_u,religion: religion_u,zodiac: zodiac_u,ethnicity: ethnicity_u, height: height_u, weight: weight_u, age: newage, interested: newinterested, lower: lowerage, upper: upperage, description:userzdescription, radius:radiussize, sort:sortby, availstring:availstring, offsounds:offsounds }); if (deletedphoto){ var newsmall = f_smallurls.toString(); var newlarge = f_largeurls.toString(); var newwidth = addedwidth.toString(); var newheight = addedheight.toString(); console.log('there was a deleted photo'); firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} ) .done(function( data ) { console.log(data); }); }).catch(function(error) { // Handle error }); } var industry_u = $( "#industry-input" ).val(); var status_u = $( "#status-input" ).val(); var politics_u = $( "#politics-input" ).val(); var eyes_u = $( "#eyes-input" ).val(); var body_u = $( "#body-input" ).val(); var religion_u = $( "#religion-input" ).val(); var zodiac_u = $( "#zodiac-input" ).val(); var ethnicity_u = $( "#ethnicity-input" ).val(); var height_u = $( "#height-input" ).val().substring(0,3); var weight_pre = $( "#weight-input" ).val(); var weight_u = weight_pre.substr(0, weight_pre.indexOf(' ')); firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "updatedetails.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,sexuality:sexuality,uid:f_uid,name:f_name,description:userzdescription,age:newage,availstring:availstringn,industry:industry_u,status:status_u,politics:politics_u,eyes:eyes_u,body:body_u,religion:religion_u,zodiac:zodiac_u,ethnicity:ethnicity_u,height:height_u,weight:weight_u} ) .done(function( data ) { console.log('didan update'); console.log(data); //if (f_gender && (f_gender != newgender)){ //deleteDatabase(); //} //if (f_interested && (f_interested != newinterested)){ //deleteDatabase(); //} }); }).catch(function(error) { // Handle error }); f_lower = lowerage; f_upper = upperage; //if (loadpref2===true){getWifilocation();} loadpref2 = true; myApp.closeModal(); $( ".popup-overlay" ).remove(); } function processUpdate(){ $( '.donechange' ).show(); $( '.doneunchange' ).hide(); } function processDupdate(){ var unixnow = Math.round(+new Date()/1000); var middaystamp = new Date(); middaystamp.setHours(12,00,00,000); var middaystamp_timestamp = Math.round(middaystamp/1000); var threestamp = new Date(); threestamp.setHours(12,00,00,000); var threestamp_timestamp = Math.round(threestamp/1000); var fivestamp = new Date(); fivestamp.setHours(17,00,00,000); var fivestamp_timestamp = Math.round(fivestamp/1000); if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Morning') && (unixnow>middaystamp_timestamp)){myApp.alert('You must choose a time in the future', pickerCustomToolbar.cols[1].displayValue +' has past!');pickerCustomToolbar.cols[1].setValue('');return false;} if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Mid-day') && (unixnow>threestamp_timestamp)){myApp.alert('You must choose a time in the future', pickerCustomToolbar.cols[1].displayValue +' has past!');pickerCustomToolbar.cols[1].setValue('');return false;} if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Afternoon') && (unixnow>fivestamp_timestamp)){myApp.alert('You must choose a time in the future', pickerCustomToolbar.cols[1].displayValue +' has past!');pickerCustomToolbar.cols[1].setValue('');return false;} if (d_chat_expire){ var datemessageq = $( '#datemessageq' ).val(); var interestnewarray = []; $( ".interestbutton" ).each(function() { if ($( this ).hasClass( "interestchosen" )) { var classList = $(this).attr("class").split(' '); var interestadd = classList[1].split('_')[0]; interestnewarray.push(interestadd); } }); var comparedinterest; var compareninterest; if (d_interest != null) { comparedinterest = d_interest.toString(); } else {comparedinterest = '';} if (typeof interestnewarray == 'undefined' && interestnewarray.length === 0){compareninterest = '';}else{compareninterest = interestnewarray.toString();} if ((d_day == pickerCustomToolbar.cols[0].displayValue) && (d_time ==pickerCustomToolbar.cols[1].displayValue) && (datemessageq == '' ) && (compareninterest == comparedinterest)) { if (d_response=='Y'){noChange();} else if (d_response=="W"){reverseRequest();dateConfirmationPage();} } else{dateRequest();} } else {dateRequest();} } var mynotifs = []; function leftPanel(){ canscrollnotif = true; mynotifs = []; notifadditions=0; if(!myList){ myList = myApp.virtualList('.virtual-notifications', { // Array with plain HTML items items: [], height:89, renderItem: function (index, item) { var backgroundnotifcolor; if(item.colordot == ''){backgroundnotifcolor = 'white';}else{backgroundnotifcolor = 'transparent';} if(item.from_uid == f_uid){ return '<li class="item-content" style="height:89px;background-color:'+backgroundnotifcolor+'">' + '<div class="item-media" onclick="singleUser('+item.targetid+',\''+item.targetname+'\',1)" style="width:50px;height:50px;border-radius:50%;background-image:url('+item.picture+');background-size:cover;background-position:50% 50%;">'+ '</div>' + '<div class="item-inner" onclick="'+item.func+'('+item.targetid+',\''+item.targetname+'\')" style="margin-left:10px;" >' + '<div class="item-title-row" >'+ '<div class="item-title" style="font-size:14px;margin-top:5px;">'+item.targetname+'</div>'+ '<div class="item-after"><img src="media/'+item.type+'faceonly.png" style="width:30px;"></div>'+ '</div>'+ '<div class="item-subtitle">'+ item.icon + item.title + ' </div>' + '<div class="item-text" style="height:20.8px">'+ item.timestamptitle + ' </div>' + '</div>' + '</li>'; } else{ //onclick="singleBrowser('+item.targetid+')" return '<li class="item-content" style="height:89px;background-color:'+backgroundnotifcolor+'">' + '<div class="item-media" onclick="singleUser('+item.targetid+',\''+item.targetname+'\',1)" style="width:50px;height:50px;border-radius:50%;background-image:url('+item.picture+');background-size:cover;background-position:50% 50%;">'+ '</div>' + '<div class="item-inner" onclick="'+item.func+'(\''+item.targetid+'\',\''+item.targetname+'\')" style="margin-left:10px;" >' + '<div class="item-title-row" >'+ '<div class="item-title" style="font-size:14px;margin-top:5px;">'+item.targetname+item.colordot+'</div>'+ '<div class="item-after"><img src="media/'+item.type+'faceonly.png" style="width:30px;"></div>'+ '</div>'+ '<div class="item-subtitle" style="color:black;">'+ item.icon + item.title + ' </div>' + '<div class="item-text" style="height:20.8px">'+ item.timestamptitle + ' </div>' + '</div>' + '</li>'; } } }); } var notificationlist = firebase.database().ref('notifications/' + f_uid).once('value', function(snapshot) { if (snapshot.val() === null){ // $('.title-notify').remove(); // $('.virtual-notifications').append('<div class="content-block-title title-notify" style="margin-top:54px;">No notifications</div>'); $('.nonefound').remove(); $('.virtual-notifications').prepend('<div class="content-block-title nonefound" style="margin: 0 auto;margin-top:10px;text-align:center;">No Matches Yet</div>'); } //If existing notifications, get number of unseen messages, delete old notifications if (snapshot.val()){ $('.nonefound').remove(); var objs = snapshot.val(); var obg = []; $.each(objs, function(i, obk) {obg.push (obk)}); console.log(obg); function compare(a,b) { if (a.timestamp > b.timestamp) return -1; if (a.timestamp < b.timestamp) return 1; return 0; } obg.sort(compare); $.each(obg, function(i, obj) { var typetype = obj.type.substring(0, 4); var correctimage; var correctname; var iconhtml; var colordot; var message_text; var func; var mediaicon; var dateseenresponse; if (typetype == 'date') {mediaicon = fdateicon;} if (typetype == 'duck') {mediaicon = fduckicon;} //need to see if a match still and then create function based on tha var timestamptitle; var unixnow = Math.round(+new Date()/1000); var tunixago = unixnow - obj.timestamp; var tunixminago = tunixago / 60; if (tunixminago < 1) {timestamptitle = '1 minute ago';} else if (tunixminago == 1) {timestamptitle = '1 minute ago';} else if (tunixminago < 2) {timestamptitle = '1 minute ago';} else if (tunixminago < 60) {timestamptitle = Math.round(tunixminago)+' minutes ago';} else if (tunixminago == 60) {timestamptitle = '1 hour ago';} else if (tunixminago < 62) {timestamptitle = '1 hour ago';} else if (tunixminago < 1440) {timestamptitle = Math.round(tunixminago / 60) +' hours ago';} else if (tunixminago == 1440) {timestamptitle = '1 day ago';} else if (tunixminago < 2880) {timestamptitle = '1 day ago';} else if (tunixminago >= 2880) {timestamptitle = Math.round(tunixminago / 1440) +' days ago';} else if (tunixminago == 10080) {timestamptitle = '1 week ago';} else if (tunixminago < 20160) {timestamptitle = '1 week ago';} else if (tunixminago >= 20160) {timestamptitle = Math.round(tunixminago / 10080) +' weeks ago';} else if (tunixminago == 525600) {timestamptitle = '1 week ago';} else if (tunixminago < (525600*2)) {timestamptitle = '1 week ago';} else if (tunixminago >= (525600*2)) {timestamptitle = Math.round(tunixminago / 525600) +' years ago';} // onclick="singleBrowser('+targetid+')" if (obj.param=='message'){message_text = obj.message; iconhtml = '<i class="pe-7s-mail pe-lg" style="margin-right:5px;z-index:9999;"></i>'} if (obj.param=='image'){ if (obj.from_uid == f_uid){message_text = obj.message + 'sent';} else {message_text = obj.message + 'received';} iconhtml = '<i class="pe-7s-camera pe-lg" style="margin-right:5px;z-index:9999;"></i>';} if (obj.param=='daterequest'){ if (obj.from_uid == f_uid){message_text = obj.message + ' sent';} else {message_text = obj.message + ' received';} iconhtml = '<i class="pe-7s-date pe-lg" style="margin-right:5px;z-index:9999;"></i>'; } if (obj.param=='datedeleted'){ if (obj.from_uid == f_uid){message_text = obj.message;} else {message_text = obj.message;} iconhtml = '<i class="pe-7s-date pe-lg" style="margin-right:5px;z-index:9999;"></i>'; } if (obj.param=='newmatch'){ if (obj.from_uid == f_uid){message_text = obj.message;} else {message_text = obj.message;} iconhtml = '<i class="pe-7s-like pe-lg" style="margin-right:5px;z-index:9999;"></i>'; } if (obj.param=='dateconfirmed'){ message_text = obj.message; iconhtml = '<i class="pe-7f-date pe-lg" style="margin-right:5px;z-index:9999;"></i>'; } // if(obj.received=='N' && (obj.param=='datedeleted' || obj.param=='newmatch')){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;">'ssage_count+'</span>';} else{colordot = '';} // if(obj.received=='N' && (obj.param!='datedeleted' && obj.param!='newmatch')){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;">'+obj.new_message_count+'</span>';} else{colordot = '';} if(obj.received=='N' && (obj.param=='message' || obj.param=='image')){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;">'+obj.new_message_count+'</span>';} else if(obj.received=='N'){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;width:12px;height:12px;"></span>';} else{colordot = '';} if (obj.from_uid == f_uid){correctimage = String(obj.to_uid);correctname = String(obj.to_name);colordot = '';} else {correctimage = String(obj.from_uid);correctname = String(obj.from_name);image_after = 'received';} datemeinarray=0; duckmeinarray=0; datetoinarray=0; ducktoinarray=0; var datesto = f_to_date.indexOf(correctimage); if (datesto > -1) { datetoinarray=1; } var datesme = f_date_me.indexOf(correctimage); if (datesme > -1) { datemeinarray=1; } var duckto = f_to_duck.indexOf(correctimage); if (duckto > -1) { ducktoinarray=1; } var duckme = f_duck_me.indexOf(correctimage); if (duckme > -1) { duckmeinarray=1; } if ((datemeinarray==1 && datetoinarray==1) || (duckmeinarray==1 && ducktoinarray==1)) { if (typetype == 'date') {func = 'createDate1';} if (typetype == 'duck') {func = 'createDuck';} } else{func = 'singleUser'} mynotifs.push({ title: message_text, targetid:correctimage, targetname:correctname, picture:'https://graph.facebook.com/'+correctimage+'/picture?type=normal', from_name: obj.from_name, to_name: obj.to_name, from_uid: obj.from_uid, to_uid: obj.to_uid, icon:iconhtml, colordot:colordot, func:func, type:typetype, timestamptitle:timestamptitle }); }); var notif2load = mynotifs.length; if (notif2load > 12) {notifletsload = 12;} else {notifletsload = notif2load;} for (i = 0; i < notifletsload; i++) { myList.appendItem({ title: mynotifs[i].title, targetid:mynotifs[i].targetid, targetname:mynotifs[i].targetname, picture:mynotifs[i].picture, from_name: mynotifs[i].from_name, to_name: mynotifs[i].to_name, from_uid:mynotifs[i].from_uid, to_uid: mynotifs[i].to_uid, icon:mynotifs[i].icon, colordot:mynotifs[i].colordot, func:mynotifs[i].func, type:mynotifs[i].type, timestamptitle:mynotifs[i].timestamptitle }); } } }); } function rightPanel(){ $('.timeline-upcoming').empty(); $('.right-title').text('Calendar'); $('.addcreatebutton').show(); $('.backcreatebutton').hide(); myApp.sizeNavbars(); var rightdates = []; var month = []; month[0] = "JAN"; month[1] = "FEB"; month[2] = "MAR"; month[3] = "APR"; month[4] = "MAY"; month[5] = "JUN"; month[6] = "JUL"; month[7] = "AUG"; month[8] = "SEP"; month[9] = "OCT"; month[10] = "NOV"; month[11] = "DEC"; var weekday = []; weekday[0] = "SUN"; weekday[1] = "MON"; weekday[2] = "TUE"; weekday[3] = "WED"; weekday[4] = "THU"; weekday[5] = "FRI"; weekday[6] = "SAT"; var timelinedates = firebase.database().ref('/dates/' + f_uid).once('value').then(function(snapshot) { var objs = snapshot.val(); $('.timeline-upcoming').empty(); if (snapshot.val() === null){ $('.timeline').append('<div class="content-block-title" style="margin: 0 auto;text-align:center;">Calendar is empty</div>'); } //If existing notifications, get number of unseen messages, delete old notifications if (snapshot.val()){ $.each(objs, function(i, obj) { rightdates.push(obj); }); rightdates.sort(compare); for (i = 0; i < rightdates.length; i++) { var correctname; var correctid; if (rightdates[i].created_uid == f_uid) {correctname = rightdates[i].received_name;correctid = rightdates[i].received_uid;} if (rightdates[i].created_uid != f_uid) {correctname = rightdates[i].created_name;correctid = rightdates[i].created_uid;} var unix = Math.round(+new Date()/1000); var c = new Date(rightdates[i].chat_expire*1000); var cday = weekday[c.getDay()]; if ((rightdates[i].created_uid == f_uid || rightdates[i].received_uid == f_uid) && (rightdates[i].chat_expire > Number(unix)) ){ var d = new Date(rightdates[i].chat_expire*1000 - 3600); var timehere; if (rightdates[i].time) {timehere = ', ' + rightdates[i].time;} else {timehere='';} var timestamptitle; var datetype = rightdates[i].type.capitalize(); var datesidetitle; var dayday = d.getDate(); var monthmonth = month[d.getMonth()]; var subtitletext,confirmtext; if (rightdates[i].response =='Y') { if (rightdates[i].type=='date' ){datesidetitle = 'Date';} if (rightdates[i].type=='duck' ){datesidetitle = 'Duck';} timestamptitle = datesidetitle + ' Confirmed'; var name_accepted; if (rightdates[i].received_uid == f_uid) {name_accepted = 'you ';} else {name_accepted = rightdates[i].received_name;} subtitletext='<div style="font-family: \'Pacifico\', cursive;font-size:17px;background-color:#4cd964;color:white;width:100%;text-align:center;padding-top:5px;padding-bottom:5px;"><i class="pe-7s-check pe-lg" style="color:white"></i></div>'; confirmtext='Date confirmed by '+name_accepted+' on '+cday; } if (rightdates[i].response =='W') { var unixnow = Math.round(+new Date()/1000); var tunixago = unixnow - rightdates[i].timestamp; var tunixminago = tunixago / 60; if (tunixminago < 1) {timestamptitle = 'Sent now';} else if (tunixminago == 1) {timestamptitle = 'Sent 1 min ago';} else if (tunixminago < 2) {timestamptitle = 'Sent 1 min ago';} else if (tunixminago < 60) {timestamptitle = 'Sent '+Math.round(tunixminago)+' mins ago';} else if (tunixminago == 60) {timestamptitle = 'Sent 1 hour ago';} else if (tunixminago < 62) {timestamptitle = 'Sent 1 hour ago';} else if (tunixminago < 1440) {timestamptitle = 'Sent '+Math.round(tunixminago / 60) +' hours ago';} else if (tunixminago == 1440) {timestamptitle = 'Sent 1 day ago';} else if (tunixminago < 2880) {timestamptitle = 'Sent 1 day ago';} else if (tunixminago >= 2880) {timestamptitle = 'Sent '+Math.round(tunixminago / 1440) +' days ago';} if (rightdates[i].created_uid == f_uid) {confirmtext = 'Waiting for '+rightdates[i].received_name+' to respond.';} if (rightdates[i].created_uid != f_uid){confirmtext = rightdates[i].created_name + ' is waiting for your response.';} if (rightdates[i].type=='date' ){datesidetitle = 'Date Request';} if (rightdates[i].type=='duck' ){datesidetitle = 'Duck Request';} subtitletext='<div style="font-family: \'Pacifico\', cursive;font-size:17px;background-color:#ff9500;color:white;width:100%;text-align:center;padding-top:5px;padding-bottom:5px;"><i class="pe-7s-help1 pe-lg" style="color:white"></i></div>';} if ($(".time_line_" + dayday)[0]){ } else { $('.timeline').append('<div class="timeline-item" style="margin-bottom">'+ '<div class="timeline-item-date" style="margin-right:10px;">'+cday+'<br/>'+dayday+' <small> '+monthmonth+' </small></div>'+ //'<div class="timeline-item-divider"></div>'+ '<div class="timeline-item-content time_line_'+dayday+'">'+ '</div>'+ '</div>'); } $('.time_line_'+dayday).append( '<a href="#" onclick="createDate(\''+correctid+'\',\''+correctname+'\')">'+ subtitletext+ // '<div class="timeline-item-time" style="padding:2px;margin-top:0px;background-color:white;border-bottom:1px solid #c4c4c4;text-align:center;padding-top:10px;"><i class="pe-7s-clock pe-lg"></i> //'+weekday[d.getDay()]+ timehere+'<div style="clear:both;" id="interestdatediv_'+correctid+'"></div></div>'+ '<div class="timeline-item-inner" style="min-width:136px;padding:7px;border-radius:0;">'+ '<div class="timeline-item-title" style="color:black;margin-top:5px;text-align:center;"><div style="width:50px;height:50px;margin:0 auto;border-radius:50%;background-size:cover;background-position:50% 50%;background-image:url(\'https://graph.facebook.com/'+correctid+'/picture?type=normal\')"></div><span style="clear:both;">'+correctname+'<span> </div>'+ // '<div style="padding:10px;font-size:13px;"><span style="color:#6d6d72;clear:both;padding-top:-5px;">'+confirmtext+'</span></div>'+ '<div style="text-align:center;clear:both;width:100%;color:#8e8e93;">'+timestamptitle+'</div>'+ '</div>'+ '</a>' ); if(rightdates[i].type=='date'){ //for (k = 0; k < rightdates[i].interest.length; k++) { // $( "#interestdatediv_" + correctid).append('<a href="#" style="margin-right:5px"><i class="twa twa-'+rightdates[i].interest[k]+'" style="margin-top:5px;margin-right:5px"></i></a>'); // } } } } } }); } function newAm(){ $( ".originalam" ).hide(); $( ".newam" ).show(); pickerDescribe.open(); } function newMe(){ $( ".originalme" ).hide(); $( ".newme" ).show(); pickerDescribe2.open(); } var deletedphoto; function getData(){ deletedphoto = false; if(!myswiperphotos){ firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/userdata.php", {projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} ) .done(function( data ) { var result = JSON.parse(data); console.log(result); if (result!='77' && result[0].largeurl){ $( ".reorderbutton" ).removeClass('disabled'); $( ".deleteallbutton" ).removeClass('disabled'); f_smallurls = result[0].smallurl.split(','); f_largeurls = result[0].largeurl.split(','); console.log(result[0].widthslides); console.log(result[0].heightslides); addedwidth = result[0].widthslides.split(','); addedheight = result[0].heightslides.split(','); $( ".photosliderinfo" ).addClass('pictures'); if (f_largeurls.length === 0){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile'); } else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile'); } console.log(f_largeurls.length); for (i = 0; i < f_largeurls.length; i++) { $( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\''+f_largeurls[i]+'\');background-size:cover;background-position:50% 50%;"><div class="button" style="border:0;border-radius:0px;background-color:#ff3b30;color:white;position:absolute;bottom:10px;right:10px;" onclick="deleteIndividual()">Delete Photo</div></div>'); } myswiperphotos = myApp.swiper('.container-photos', { pagination:'.swiper-pagination', paginationType:'progress', direction:'vertical', onInit:function(swiper){$( ".photoswiperloader" ).hide();}, onClick:function(swiper, event){ } }); } else { f_smallurls = []; f_largeurls = []; addedheight = []; addedwidth = []; $( ".wrapper-photos" ).append('<div class="swiper-slide firsthere" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>'); $( ".photosliderinfo" ).removeClass('pictures'); $( ".photosliderinfo" ).html('Add photos to your profile below'); myswiperphotos = myApp.swiper('.container-photos', { pagination:'.swiper-pagination', paginationType:'progress', onInit:function(swiper){$( ".photoswiperloader" ).hide();}, direction:'vertical' }); } }); }).catch(function(error) { // Handle error }); } } function deleteIndividual(){ if (sexuality){processUpdate(); myApp.sizeNavbars(); } if ($( ".photosliderinfo" ).hasClass('pictures')){ myApp.confirm('Are you sure?', 'Delete Photo', function () { myswiperphotos.removeSlide(myswiperphotos.clickedIndex); f_largeurls.splice(myswiperphotos.clickedIndex, 1); f_smallurls.splice(myswiperphotos.clickedIndex, 1); addedwidth.splice(myswiperphotos.clickedIndex, 1); addedheight.splice(myswiperphotos.clickedIndex, 1); console.log(addedwidth); console.log(addedheight); if (f_largeurls.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile'); } else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile'); } deletedphoto = true; myswiperphotos.update(); if (myswiperphotos.slides.length === 0){ $( ".reorderbutton" ).addClass('disabled'); $( ".deleteallbutton" ).addClass('disabled'); $( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>'); $( ".photosliderinfo" ).removeClass('pictures'); $( ".photosliderinfo" ).html('Add photos to your profile below'); myswiperphotos.updatePagination(); myswiperphotos.update(); } }); } else { photosPopup(); } } function openAvaill(availtime){ if ($( '.li_'+ availtime ).hasClass('selecrec')){$( '.li_'+ availtime ).removeClass('selecrec');$( '.li_'+ availtime ).css('selecrec','');$( '#picker'+ availtime ).val('');} else{$( '.li_'+ availtime ).addClass('selecrec');$( '#picker'+ availtime ).val('Now');} } function openAvail(availtime){ $( '.li_'+ availtime ).addClass('selecrec'); } function removeAvail(availtime,availname,availnameonly){ $( '.li_'+ availtime ).removeClass('selecrec'); $('#picker'+availtime ).remove(); $('.readd_'+availtime ).append('<input type="text" placeholder="'+availname+'" readonly id="picker'+availtime+'" style="height:44px;text-align:center;margin-top:-10px;font-size:17px;color:white;"></li>'); myApp.picker({ input: '#picker' + availtime, onOpen: function (p){if (sexuality){processUpdate(); myApp.sizeNavbars(); }}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeAvail(\''+availtime+'\',\''+availname+'\',\''+availnameonly+'\');">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { textAlign: 'left', values: (availnameonly + ',').split(',') }, { textAlign: 'left', values: ('Anytime Morning Midday Afternoon Evening').split(' ') }, ] }); } var availarray = []; function report(){ myApp.prompt('What is the problem?', 'Report '+targetname, function (value) { if (value.length ===0){myApp.alert('You must provide a reason to report ' + targetname, 'What is the problem?');return false;} targetreported = true; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var newPostKey = firebase.database().ref().push().key; var t_unix = Math.round(+new Date()/1000); var targetData = { from_uid: f_uid, from_name: f_first, to_uid:targetid, to_name:targetname, message:value, response:'N', timestamp: t_unix, }; var updates = {}; updates['reports/' + f_uid + '/' + targetid + '/' + newPostKey] = targetData; if (f_uid == first_number){ firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list firstnumberreport:newPostKey, firstnumberreporttime:t_unix }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list firstnumberreport:newPostKey, firstnumberreporttime:t_unix }); } else{ firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list secondnumberreport:newPostKey, secondnumberreporttime:t_unix }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list secondnumberreport:newPostKey, secondnumberreporttime:t_unix }); } return firebase.database().ref().update(updates).then(function() { myApp.alert('We will review your report. We encourage you to block offensive users.', 'Report sent');}); }); $(".modal-text-input").prop('maxlength','50'); } function more(){ var swiperno = 0; myApp.confirm('Are you sure?', 'Block '+targetname, function () { var blockindex = myPhotoBrowser.swiper.activeIndex; var swipertarget = $( ".agecat" ).text(); //agearray var profilesbefore = 0; for (var i = f_lower; i < swipertarget; i++) { swiperno ++; profilesbefore = profilesbefore + all_matches_photos[i].length; } var ageindex = blockindex - profilesbefore; // console.log(all_matches_photos[swipertarget]); // console.log(new_all); all_matches_photos[swipertarget] = all_matches_photos[swipertarget].slice(0,ageindex).concat(all_matches_photos[swipertarget].slice(ageindex+1)); //new all array var firstpos; var lastpos; //alert(blockindex); //alert(new_all.length); if (blockindex == (new_all.length-1)){lastpos = 'Y';} else {lastpos ='N';} if (blockindex == 0){firstpos = 'Y';} else{firstpos ='N';} //alert(firstpos + 'firstpos'); //alert(lastpos + 'lastpos'); new_all = new_all.slice(0,blockindex).concat(new_all.slice(blockindex+1)); //console.log(all_matches_photos[swipertarget]); // console.log(new_all); //remove slide from photobrowser myPhotoBrowser.swiper.removeSlide(blockindex); myPhotoBrowser.swiper.updateSlidesSize() ; //remove from curswiper var realswiperno = swiperno + 1; $$('.swiper-container')[swiperno].swiper.removeSlide(ageindex); $$('.swiper-container')[swiperno].swiper.updateSlidesSize() ; if (all_matches_photos[swipertarget].length ===1) {$( ".single_"+i ).show();$( ".multiple_"+i ).hide();} if (all_matches_photos[swipertarget].length ===0) {$( ".single_"+i ).show();$( ".swiper-"+i ).hide();} myApp.closeModal('.actions-modal'); allowedchange = false; var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var theirnotifs = firebase.database().ref('notifications/' + targetid + '/' + f_uid); theirnotifs.remove().then(function() { console.log("their notifs Remove succeeded.") }) .catch(function(error) { console.log("their notifs failed: " + error.message) }); var mynotifs = firebase.database().ref('notifications/' + f_uid + '/' + targetid); mynotifs.remove().then(function() { console.log("my notifs Remove succeeded.") }) .catch(function(error) { console.log("my notifs failed: " + error.message) }); var theirdates = firebase.database().ref('dates/' + targetid + '/' + f_uid); theirdates.remove().then(function() { console.log("their dates Remove succeeded.") }) .catch(function(error) { console.log("their dates failed: " + error.message) }); var mydates = firebase.database().ref('dates/' + f_uid + '/' + targetid); mydates.remove().then(function() { console.log("my dates Remove succeeded.") }) .catch(function(error) { console.log("my dates failed: " + error.message) }); var ourchats = firebase.database().ref('chats/' + first_number + '/' + second_number); ourchats.remove().then(function() { console.log("Chats Remove succeeded.") }) .catch(function(error) { console.log("Chats Remove failed: " + error.message) }); var ourphotochats = firebase.database().ref('photochats/' + first_number + '/' + second_number); ourphotochats.remove().then(function() { console.log("PhotoChats Remove succeeded.") }) .catch(function(error) { console.log("PhotoChats Remove failed: " + error.message) }); if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid; firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list secondnumberblock:'Y', created:f_uid, received:targetid, first_number:first_number, first_name:targetname, second_number:second_number, second_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberdate:'N', secondnumberduck:'N', firstnumberdate:'N', firstnumberduck:'N' }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list secondnumberblock:'Y', created:f_uid, received:targetid, first_number:first_number, first_name:targetname, second_number:second_number, second_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberdate:'N', secondnumberduck:'N', firstnumberdate:'N', firstnumberduck:'N' }); } else {first_number = f_uid;second_number = targetid; firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list firstnumberblock:'Y', created:f_uid, received:targetid, first_number:first_number, second_name:targetname, second_number:second_number, first_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberdate:'N', secondnumberduck:'N', firstnumberdate:'N', firstnumberduck:'N' }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list firstnumberblock:'Y', created:f_uid, received:targetid, first_number:first_number, second_name:targetname, second_number:second_number, first_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberdate:'N', secondnumberduck:'N', firstnumberdate:'N', firstnumberduck:'N' }); } if (firstpos == 'Y'){myPhotoBrowser.swiper.slideNext();allowedchange = true;myPhotoBrowser.swiper.slidePrev(); } else if (lastpos == 'Y'){myPhotoBrowser.swiper.slidePrev();allowedchange = true;myPhotoBrowser.swiper.slideNext(); } else {myPhotoBrowser.swiper.slideNext();allowedchange = true;myPhotoBrowser.swiper.slidePrev();} //myPhotoBrowser.swiper.slideTo(blockindex); // console.log(all_matches_photos[swipertarget]); // console.log(new_all); if (new_all.length === 0){myPhotoBrowser.close();myApp.closeModal(); alert('thirdpos'); $( ".results-loader" ).hide(); $('.content-here').append( '<div class="no-results-div" style="text-align:center;margin:0 auto;width:300px;position:absolute;top:50%;left:50%;margin-left:-150px;margin-top:-70px;">'+ '<img src="media/datetongue.png" style="width:80px;margin:0 auto;">'+ '<h3>No one is nearby</h3><p style="padding-top:0px;margin-top:-10px;">Try changing your search radius, </br>age range or filters.</p></br>'+ '</div>'); } // myPhotoBrowser.swiper.slideTo(blockindex); if (new_all.length===1){ if (myPhotoBrowser.swiper.isBeginning === true){$( ".prevphoto" ).addClass( "disabled" );} else{$( ".prevphoto" ).removeClass( "disabled" );} if (myPhotoBrowser.swiper.isEnd === true){$( ".nextphoto" ).addClass( "disabled" );} else{$( ".nextphoto" ).removeClass( "disabled" );} //var windowheight = $( window ).height(); //$( ".photo-browser-slide img").css( "height", "100% - 144px)" ); $( ".photo-browser-caption" ).empty(); $( ".nametag" ).empty(); $( ".datebutton" ).removeClass( "active" ); $( ".duckbutton" ).removeClass( "active" ); $( ".duckbutton" ).addClass( "disabled" ); $( ".datebutton" ).addClass( "disabled" ); $( ".loaderlink" ).show(); $( ".orlink" ).hide(); match = 0; var target = new_all[myPhotoBrowser.activeIndex].url; var pretarget = target.replace("https://graph.facebook.com/", ""); targetid = String(pretarget.replace("/picture?width=828", "")); $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" ); //$( ".photo-browser-slide.swiper-slide-active img" ).css( "height", "100% - 144px)" ); $( ".duck-template" ).hide(); $( ".date-template" ).hide(); unmatchNavbar(); $( ".toolbardecide" ).show(); $( ".datebutton" ).removeClass( "likesme" ); $( ".duckbutton" ).removeClass( "likesme" ); var targetdescription= new_all[myPhotoBrowser.activeIndex].description; targetname = new_all[myPhotoBrowser.activeIndex].name; var targetage = new_all[myPhotoBrowser.activeIndex].age; $( ".nametag" ).empty(); $( ".nametag" ).append('<span class="rr r_'+targetid+'">'+targetname+', '+targetage+'</span>'); $( ".photo-browser-caption" ).empty(); $( ".photo-browser-caption" ).append(targetdescription); myApp.sizeNavbars(); checkMatch(targetid); } }); } var canscrollnotif = true; function scrollNotifications(){ //console.log($( ".virtual-notifications" ).height() + $( ".virtual-notifications" ).offset().top); if ((($( ".virtual-notifications" ).height() + $( ".virtual-notifications" ).offset().top) - 1 < $( document ).height())&& (canscrollnotif)) { if (notifletsload < 12){$( "#notiflistdiv" ).append('<div class="loadnotifsloader" style="clear:both;width:100%;padding-top:5px;padding-bottom:5px;background-color:#efeff4;clear:both;"><div class="preloader " style="width:20px;margin:0 auto;margin-top:5px;margin-left:125px;"></div></div>');canscrollnotif = false;var objDiv = document.getElementById("notiflistdiv"); objDiv.scrollTop = objDiv.scrollHeight; setTimeout(function(){ $( ".loadnotifsloader" ).remove();objDiv.scrollTop = objDiv.scrollHeight-44;}, 2000); } else{$( "#notiflistdiv" ).append('<div style="clear:both;width:100%;padding-top:5px;padding-bottom:5px;background-color:#efeff4;clear:both;" class="loadnotifsloader"><div class="preloader" style="width:20px;margin:0 auto;margin-top:5px;margin-left:125px;"></div></div>');canscrollnotif = false;var objDiv = document.getElementById("notiflistdiv"); objDiv.scrollTop = objDiv.scrollHeight;setTimeout(function(){ getmoreNotifs();}, 2000);} } } function scrollMessages(){ if ((($( ".scrolldetect" ).offset().top) == 120) && (canloadchat)) {if (letsload < 20){$( ".scrolldetect" ).prepend('<div class="preloader loadmessagesloader" style="width:20px;margin:0 auto;margin-top:10px;"></div>');canloadchat = false;setTimeout(function(){ $( ".loadmessagesloader" ).hide(); }, 500);}else{$( ".scrolldetect" ).prepend('<div class="preloader loadmessagesloader" style="width:20px;margin:0 auto;margin-top:10px;"></div>');canloadchat = false;setTimeout(function(){ getPrevious(); }, 500);}} } function showDecide(){ $( ".duck-template" ).hide(); $( ".date-template" ).hide(); $( ".toolbardecide" ).show(); } function closeCreate(){ myApp.closeModal('.chatpop'); } function createDate(messageid,messagename){ singleUser(targetid,targetname,88); var centerdiv; if (messageid) {targetid = messageid;} if (messagename) {targetname = messagename;} existingchatnotifications = firebase.database().ref("notifications/" + f_uid).once("value", function(snapshot) { var objs = snapshot.val(); //If existing notifications, get number of unseen messages, delete old notifications if (snapshot.val()){ $.each(objs, function(i, obj) { if ((obj.to_uid == f_uid) && (obj.from_uid == targetid) && (obj.received=='N')){ firebase.database().ref('notifications/' +f_uid + '/' + targetid).update({ received:'Y', new_message_count:'0', authcheck:f_uid, uid_accepted:f_uid }); firebase.database().ref('notifications/' +targetid + '/' + f_uid).update({ received:'Y', new_message_count:'0', authcheck:f_uid, uid_accepted:f_uid }); } }); } }); if (messageid) {centerdiv = '<div class="center center-date" onclick="singleUser(\''+targetid+'\',\''+targetname+'\')" style="cursor:pointer;"><div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+targetid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>'+targetname+'</div>';} else{centerdiv = '<div class="center center-date close-popup" onclick="clearchatHistory();"><div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+targetid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>'+targetname+'</div>';} var popupHTML = '<div class="popup chatpop">'+ '<div class="navbar" style="background-color:#2196f3;">'+ ' <div class="navbar-inner">'+ ' <div class="left">'+ '<a href="#" class="link icon-only date-back" onclick="closeCreate()" style="margin-left:-10px;color:white;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+ '<a href="#" class="link icon-only date-close" onclick="reverseRequest();" style="color:white;font-weight:bold;display:none;margin-left:-10px;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+ '<a href="#" class="link icon-only date2-close" onclick="noChange();" style="color:white;display:none;font-weight:bold;margin-left:-10px;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+ '<a href="#" class="link icon-only date1-close" onclick="reverseRequest();dateConfirmationPage();" style="color:white;display:none;font-weight:bold;margin-left:-10px;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+ '</div>'+ ' <span id="centerholder" style="color:white;"></span>'+ ' <div class="right" onclick="actionSheet()" style="font-size:14px;">'+ '<a href="#" class="link">'+ ' <i class="pe-7s-more pe-lg matchcolor" style="color:white"></i>'+ ' </a></div>'+ '</div>'+ '</div>'+ '<div class="pages" style="margin-top:-44px;">'+ '<div data-page="datepopup" class="page">'+ '<div class="toolbar messagebar datetoolbar" style="display:none;background-color:transparent;">'+ ' <div class="toolbar-inner yes-inner" style="background-color:rgba(247, 247, 248,0.9);margin-top:-10px;height:54px;padding-bottom:10px;display:none;text-align:center;">'+ '<a href="#" onclick="cancelDate()" class="link" style="height:44px;color:white;background-color:#ff3b30;width: 33%;"><span style="margin: 0 auto;">Delete</span></a>'+ '<a href="#" onclick="request()" class="link" style="height:44px;color:white;background-color:#2196f3;width:33%;"><span style="margin: 0 auto;">Change</span></a>'+ '<a href="#" onclick="acceptDate()" class="link" style="height:44px;color:white;background-color:#4cd964;width:33%;"><span style="margin: 0 auto;">Confirm</span></a>'+ '</div>'+ ' <div class="toolbar-inner sender-inner" style="background-color:rgba(247, 247, 248,0.9);margin-top:-10px;height:54px;padding-bottom:10px; display:none;text-align:center;">'+ '<a href="#" onclick="cancelDate()" class="link" style="height:44px;color:white;background-color:#ff3b30;width: 50%;"><span style="margin: 0 auto;">Delete</span></a>'+ '<a href="#" onclick="request()" class="link" style="height:44px;color:white;background-color:#2196f3;width: 50%;"><span style="margin: 0 auto;">Change</span></a>'+ '</div>'+ ' <div class="toolbar-inner date-inner" style="padding-left:0px;padding-right:0px;display:none;text-align:center;background-color:#2196f3;">'+ '<div style="width: calc(100% - 70px); height:44px;background-color:#2196f3;padding-left:5px;padding-right:5px;" class="link"><textarea id="datemessageq" placeholder="Message (optional)" style="color:white;background-color:#2196f3;margin-top:5px;"></textarea></div>'+ '<a href="#" class="link" style="height:44px;color:white;background-color:#2196f3;width:70px;" onclick="processDupdate();"><span style="margin: 0 auto;padding-right:10px;">Send</span></a>'+ '</div>'+ ' <div class="toolbar-inner message-inner" style="display:none;background-color:#2196f3;padding-left:0px;padding-right:0px;">'+ '<a href="#" class="link icon-only" style="margin-left:5px;"><i class="pe-7s-camera pe-lg" style="color:white;font-size:28px;"></i><i class="twa twa-bomb" style="z-index:999;margin-left:-10px;margin-top:-15px;"></i></a> <input type="file" size="70" accept="image/*" class="dealPictureField imagenotchosen" id="takePictureField_" onchange="getPicture();" style="background-color:transparent;color:transparent;float:left;cursor: pointer;height:54px;width:50px;z-index:1;opacity:0;background-color:red;margin-top:-12px;margin-left:-50px;"><form><input id="messagearea" type="text" placeholder="Enter Message"></form><a href="#" class="link sendbutton" style="color:white;margin-right:10px;margin-left:10px;" onclick="sendMessage();">Send</a>'+ '</div>'+ '</div>'+ '<div class="datedetailsdiv date-button" onclick="noMessages();setDate();dateConfirmationPage(1);" style="display:none;position:absolute;top:44px;text-align:center;height:44px;width:100%;z-index:999999;">'+ '</div>'+ '<div class="page-content messages-content" onscroll="scrollMessages();" id="messagediv" style="background-color:#f7f7f8">'+ '<span class="preloader login-loader messages-loader" style="width:42px;height:42px;position:absolute;top:50%;margin-top:-21px;left:50%;margin-left:-21px;"></span>'+ '<div class="datearea" style="text-align:center;"></div>'+ '<div class="messages scrolldetect" style="margin-top:100px;">'+ '</div></div></div>'+ '</div></div>'; myApp.popup(popupHTML); $('#messagearea').on('keyup', function (e) { var theEvent = e || window.event, keyPressed = theEvent.keyCode || theEvent.which; if (keyPressed === 13) { sendMessage(); document.activeElement.blur(); } }); var closedvar = $$('.chatpop').on('popup:close', function () { clearchatHistory(); }); //existingDate(); //setDate(); $( "#centerholder" ).append(centerdiv); myApp.sizeNavbars(); //$( "#centerholder" ).remove(); if (datealertvar === false) { datealertvar = true; var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} datealert = firebase.database().ref("dates/" + f_uid +'/' + targetid).on('value', function(snapshot) { var dateexists = snapshot.child('chat_expire').exists(); // true if (dateexists) { var unix = Math.round(+new Date()/1000); if (Number(snapshot.child('chat_expire').val()) > Number(unix) ) { d_type = snapshot.child('type').val(); d_chat_expire = snapshot.child('chat_expire').val(); d_interest = snapshot.child('interest').val(); d_day = snapshot.child('day').val(); d_time = snapshot.child('time').val(); d_response = snapshot.child('response').val(); if (snapshot.child('time_accepted').exists()){ d_timeaccepted = snapshot.child('time_accepted').val();} d_created_uid = snapshot.child('created_uid').val(); d_timestamp = snapshot.child('timestamp').val(); d_dateseen = snapshot.child('dateseen').val(); d_dateseentime = snapshot.child('dateseentime').val(); d_message = snapshot.child('message').val(); var newtonight = new Date(); newtonight.setHours(23,59,59,999); var newtonight_timestamp = Math.round(newtonight/1000); var weekday = new Array(7); weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; var chatdaystring; var expiredateobject = new Date((d_chat_expire * 1000) - 86400); var unixleft = d_chat_expire - newtonight_timestamp; var daysleft = unixleft / 86400; console.log('daysleft' + daysleft); var weekdaynamew = weekday[expiredateobject.getDay()]; if(daysleft === 0){chatdaystring = 'Today';} else if(daysleft === 1){chatdaystring = 'Tomorrow';} else chatdaystring = weekdaynamew; console.log(unixleft); console.log(daysleft); var hoursleft = unixleft / 3600; var salut; if (daysleft ===0){ salut='tonight'; } else if (daysleft ==1) {salut = 'in ' + Math.round(daysleft)+' day';} else{salut = 'in ' + daysleft+' days';} var aftertag; $( ".datedetailsdiv" ).empty(); $( ".datedetailsdiv" ).append('<div class="list-block media-list" style="margin-top:0px;border-bottom:1px solid #c4c4c4;">'+ '<ul style="background-color:#4cd964">'+ '<li>'+ ' <div class="item-content" style="padding-left:15px;">'+ '<div class="item-media">'+ '<img src="media/'+d_type+'faceonly.png" style="height:36px;">'+ '</div>'+ '<div class="item-inner">'+ ' <div class="item-title-row">'+ ' <div class="item-title" style="font-size:15px;color:white;">See you <span class="chatdaystringdiv">'+chatdaystring+'</span><span class="chatafternavbar"></span></div>'+ ' <div class="item-after" style="margin-top:-10px;margin-right:-15px;color:white;"><i class="pe-7s-angle-right pe-3x"></i></div>'+ ' </div>'+ '<div class="item-subtitle" style="font-size:12px;text-align:left;color:white;">Chat will end '+salut+' (at midnight)</div>'+ // '<div class="item-text">Additional description text</div>'+ '</div>'+ '</div>'+ '</li>'+ '</ul>'+ '</div> ' ); if (d_time){ var lowertime = d_time.toLowerCase() if (chatdaystring == 'today'){$( ".chatdaystringdiv").empty();$( ".chatafternavbar").append('this ' + lowertime);} else { $( ".chatafternavbar").append(' ' + d_time);} } //if (d_interest && d_type =='duck'){ // if ((d_interest == 'my') && (d_created_uid == f_uid)){aftertag = 'At '+f_first+'\'s place';} // if ((d_interest == 'your') && (d_created_uid == f_uid)){aftertag = 'At '+targetname+'\'s place';} //} //if (d_interest && d_type =='date'){ //for (i = 0; i < d_interest.length; i++) { // $( ".chatafternavbar").append('<a href="#" style="margin-left:5px"><i class="twa twa-'+d_interest[i]+'" style="margin-top:5px;margin-right:5px"></i></a>'); //} //} if (d_response == 'Y') {chatShow();} else { noMessages(); setDate(); dateConfirmationPage(); } $( ".messages-loader" ).hide(); } else{ cancelDate(); // $( ".center-date" ).empty(); //$( ".center-date" ).append(targetname); myApp.sizeNavbars(); $( ".messages-loader" ).hide(); } } else{ d_interest = false; d_chat_expire = false; d_day = false; d_time = false; d_response = false; d_timeaccepted = false; d_timestamp = false; d_message = false; d_dateseen = false; d_dateseentime = false; if (keepopen === 0){myApp.closeModal('.chatpop');clearchatHistory();} noMessages(); setDate(); // $( ".center-date" ).empty(); //$( ".center-date" ).append(targetname); myApp.sizeNavbars(); $( ".messages-loader" ).hide(); //need to check if still matched } //alert('triggered'); // if (snapshot.val().response == 'W') {noMessages(); // setDate();dateConfirmationPage();} // else {chatShow();} //dateConfirmationPage(); keepopen = 0; }); } else {} } function scrollBottom(){ var objDiv = document.getElementById("messagediv"); objDiv.scrollTop = objDiv.scrollHeight; //$("").animate({ scrollTop: $('#messagediv').prop("scrollHeight")}, 300); } function noMessages(){ $( ".messages" ).hide(); $( ".datearea" ).empty(); $( ".datearea" ).append( '<div class="nomessages" style="margin:0 auto;margin-top:44px;text-align:center;background-color:white;">'+ //'<div class="profileroundpic" style="margin:0 auto;margin-top:5px;height:70px;width:70px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+targetid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+ '<div class="dateheader" style="display:none;background-color:#ccc;padding:11px;text-align:center;font-size:20px;color:white;font-family: \'Pacifico\', cursive;"></div>'+ '<div class="waitingreply"></div>'+ '<div class="requesticon" style="padding-top:20px;"></div>'+ '<a href="#" onclick="request()" class="button dr requestbutton" style="width:150px;margin: 0 auto;margin-top:10px;font-family: \'Pacifico\', cursive;font-size:20px;"></a>'+ '<div id="createdatepicker" style="clear:both;border-bottom:1px solid #c4c4c4;margin-top:10px;"></div>'+ '<div class="row date-row" style="display:none;clear:both;margin-top:5px;padding:10px;background-color:#white;">'+ ' <div class="col-16.67 coffee_i interestbutton" onclick="interests(\'coffee\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-coffee" style="margin-top:5px;"></i></div>'+ ' <div class="col-16.67 beers_i interestbutton" onclick="interests(\'beers\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-beers" style="margin-top:5px;"></i></div>'+ ' <div class="col-16.67 wine-glass_i interestbutton" onclick="interests(\'wine-glass\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-wine-glass" style="margin-top:5px;"></i></div>'+ ' <div class="col-16.67 movie-camera_i interestbutton" onclick="interests(\'movie-camera\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-movie-camera" style="margin-top:5px;"></i></div>'+ ' <div class="col-16.67 tada_i interestbutton" onclick="interests(\'tada\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-tada" style="margin-top:5px;"></i></div>'+ ' <div class="col-16.67 fork-and-knife_i interestbutton" onclick="interests(\'fork-and-knife\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-fork-and-knife" style="margin-top:5px;"></i></div>'+ '</div> '+ '<div class="row duck-row" style="display:none;clear:both;margin-top:10px;">'+ '<div class="buttons-row" style="width:100%;">'+ ' <a href="#tab1" class="button button-big button-place button-my" onclick="duckClass(1);">My Place</a>'+ '<a href="#tab2" class="button button-big button-place button-your" onclick="duckClass(2);">Your Place</a>'+ '</div>'+ '</div> '+ '<div class="dr infop" style="padding:10px;background-color:white;color:#666;"><h3 class="titleconfirm" style="margin-top:-40px;display:none;"></h3><p class="infoconfirm">Once you agree on a time to meet you can send instant chat messages to each other.</p></div>'+ '</div>'); if (d_type == 'date') {$( ".requesticon" ).empty();$( ".requesticon" ).append(flargedateicon);$( ".requestbutton" ).text('Request Date');$( ".dateheader" ).text('Let\'s Date');} if (d_type == 'duck') {$( ".requesticon" ).empty();$( ".requesticon" ).append(flargeduckicon);$( ".requestbutton" ).text('Request Duck');$( ".dateheader" ).text('Let\'s Duck');} } function setDate(){ var dateset = 'N'; var d = new Date(); var weekday = new Array(7); weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; var n = weekday[d.getDay()]; var alldays_values = []; var alldays_names = []; var tonight = new Date(); tonight.setHours(23,59,59,999); var tonight_timestamp = Math.round(tonight/1000); alldays_values.push(tonight_timestamp - 1); alldays_values.push(tonight_timestamp); alldays_names.push('Now'); alldays_names.push('Today'); var tomorrow_timestamp = tonight_timestamp + 86400; alldays_values.push(tomorrow_timestamp); alldays_names.push('Tomorrow'); for (i = 1; i < 6; i++) { var newunix = tomorrow_timestamp + (86400 * i); alldays_values.push(newunix); var dat_number = i + 1; var datz = new Date(Date.now() + dat_number * 24*60*60*1000); n = weekday[datz.getDay()]; alldays_names.push(n); } pickerCustomToolbar = myApp.picker({ container: '#createdatepicker', rotateEffect: true, inputReadOnly: true, onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");}, toolbar:false, onChange:function(p, value, displayValue){ if (p.cols[0].displayValue == 'Now' && (dateset == 'Y')){p.cols[1].setValue('');} }, cols: [ { displayValues: alldays_names, values: alldays_values, }, { textAlign: 'left', values: (' Morning Afternoon Mid-day Evening').split(' ') }, ] }); var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var ref = firebase.database().ref("dates/" + f_uid +'/' + targetid); ref.once("value") .then(function(snapshot) { var dateexists = snapshot.child('chat_expire').exists(); // true if (dateexists){ var timecol = pickerCustomToolbar.cols[1]; timecol.setValue(snapshot.child('time').val()); var daycol = pickerCustomToolbar.cols[0]; daycol.setValue(snapshot.child('chat_expire').val()); } dateset = 'Y'; if (d_interest && d_type =='date') { for (i = 0; i < d_interest.length; i++) { $( "." + d_interest[i] +"_i" ).addClass('interestchosen'); } } if (d_interest && d_type =='duck') { if (d_interest == 'my' && d_created_uid == f_uid){ $( ".button-my" ).addClass("active");} if (d_interest == 'my' && d_created_uid != f_uid){{ $( ".button-your" ).addClass("active");}} if (d_interest == 'your' && d_created_uid == f_uid){{ $( ".button-your" ).addClass("active");}} if (d_interest == 'your' && d_created_uid != f_uid){{ $( ".button-my" ).addClass("active");}} } }); $( "#createdatepicker" ).hide(); } function infoPopup(){ var popupHTML = '<div class="popup">'+ '<div class="content-block">'+ '<p>Popup created dynamically.</p>'+ '<p><a href="#" class="close-popup">Close me</a></p>'+ '</div>'+ '</div>'; myApp.popup(popupHTML); } function dateUser(){ $( ".duckbutton" ).addClass( "disabled" ); $( ".datebutton" ).addClass( "disabled" ); if ($( ".duckbutton" ).hasClass( "active" )&& $( ".duckbutton" ).hasClass( "likesme" )){unmatchNotif();} if ( $( ".datebutton" ).hasClass( "active" )){$( ".datebutton" ).removeClass( "active" ); $( ".notifback" ).show(); $( ".mainback" ).hide(); if ($( ".datebutton" ).hasClass( "likesme" )){unmatchNotif();} removetoDate(); } else{ if ($( ".datebutton" ).hasClass( "likesme" )){matchNotif();} //clicked date $( ".datebutton" ).addClass( "active" );$( ".duckbutton" ).removeClass( "active" ); addtoDate(); } } function addtoDate(){ var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid; firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list first_number:first_number, first_name:targetname, second_number:second_number, second_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberdate:'Y', secondnumberduck:'N', created:f_uid, received:targetid }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list first_number:first_number, first_name:targetname, second_number:second_number, second_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberdate:'Y', secondnumberduck:'N', created:f_uid, received:targetid }); $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); } else {first_number = f_uid;second_number = targetid; firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list first_number:first_number, first_name:f_name.substr(0,f_name.indexOf(' ')), second_number:second_number, second_name:targetname, firstnumberdate:'Y', firstnumberduck:'N', created:f_uid, received:targetid }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list first_number:first_number, first_name:f_name.substr(0,f_name.indexOf(' ')), second_number:second_number, second_name:targetname, firstnumberdate:'Y', firstnumberduck:'N', created:f_uid, received:targetid }); } $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); if ($('.photo-browser-slide').length > 1){ var potentialdate = f_date_me.indexOf(targetid); if (potentialdate == -1) { myPhotoBrowser.swiper.slideNext(true,1000); if ($('.infopopup').length > 0) { if(swiperQuestions){comingback = 0; swiperQuestions.slideNext();comingback=1;}} } } //if button has blue border change the color } function removetoDate(){ if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid; firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list first_number:first_number, first_name:targetname, second_number:second_number, second_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberdate:'N', secondnumberduck:'N', created:f_uid, received:targetid }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list first_number:first_number, first_name:targetname, second_number:second_number, second_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberdate:'N', secondnumberduck:'N', created:f_uid, received:targetid }); $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); } else {first_number = f_uid;second_number = targetid; firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list first_number:first_number, first_name:f_name.substr(0,f_name.indexOf(' ')), second_number:second_number, second_name:targetname, firstnumberdate:'N', firstnumberduck:'N', created:f_uid, received:targetid }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list first_number:first_number, first_name:f_name.substr(0,f_name.indexOf(' ')), second_number:second_number, second_name:targetname, firstnumberdate:'N', firstnumberduck:'N', created:f_uid, received:targetid }); $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); } $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" ); $( ".duck-template" ).hide(); $( ".date-template" ).hide(); unmatchNavbar(); $( ".toolbardecide" ).show(); } function duckUser(){ $( ".duckbutton" ).addClass( "disabled" ); $( ".datebutton" ).addClass( "disabled" ); if ($( ".datebutton" ).hasClass( "active" ) && $( ".datebutton" ).hasClass( "likesme" )){unmatchNotif();} if ( $( ".duckbutton" ).hasClass( "active" )){$( ".duckbutton" ).removeClass( "active" ); if ($( ".duckbutton" ).hasClass( "likesme" )){unmatchNotif();} $( ".notifback" ).show(); $( ".mainback" ).hide(); removetoDuck(); } else{ if ($( ".duckbutton" ).hasClass( "likesme" )){matchNotif();} //clicked duck $( ".duckbutton" ).addClass( "active" );$( ".datebutton" ).removeClass( "active" ); addtoDuck(); } } function removetoDuck(){ var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid; firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list first_number:first_number, first_name:targetname, second_number:second_number, second_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberdate:'N', secondnumberduck:'N', created:f_uid, received:targetid }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list first_number:first_number, first_name:targetname, second_number:second_number, second_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberdate:'N', secondnumberduck:'N', created:f_uid, received:targetid }); $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); } else {first_number = f_uid;second_number = targetid; firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list first_number:first_number, first_name:f_name.substr(0,f_name.indexOf(' ')), second_number:second_number, second_name:targetname, firstnumberdate:'N', firstnumberduck:'N', created:f_uid, received:targetid }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list first_number:first_number, first_name:f_name.substr(0,f_name.indexOf(' ')), second_number:second_number, second_name:targetname, firstnumberdate:'N', firstnumberduck:'N', created:f_uid, received:targetid }); $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); } $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" ); $( ".duck-template" ).hide(); $( ".date-template" ).hide(); unmatchNavbar(); $( ".toolbardecide" ).show(); } function markMe(){ var mearray = ["4"]; firebase.database().ref('users/' + f_uid).update({ //add this user to my list date_me:mearray }); } function addtoDuck(){ var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid; firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list first_number:first_number, first_name:targetname, second_number:second_number, second_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberduck:'Y', secondnumberdate:'N', created:f_uid, received:targetid }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list first_number:first_number, first_number:first_number, second_number:second_number, second_name:f_name.substr(0,f_name.indexOf(' ')), secondnumberduck:'Y', secondnumberdate:'N', created:f_uid, received:targetid }); $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); } else {first_number = f_uid;second_number = targetid; firebase.database().ref('matches/' + f_uid + '/' + targetid).update({ //add this user to my list first_number:first_number, first_name:f_name.substr(0,f_name.indexOf(' ')), second_number:second_number, second_name:targetname, firstnumberduck:'Y', firstnumberdate:'N', created:f_uid, received:targetid }); firebase.database().ref('matches/' + targetid + '/' + f_uid).update({ //add this user to my list first_number:first_number, first_name:f_name.substr(0,f_name.indexOf(' ')), second_number:second_number, second_name:targetname, firstnumberduck:'Y', firstnumberdate:'N', created:f_uid, received:targetid }); } $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); if ($('.photo-browser-slide').length > 1){ var potentialduck = f_duck_me.indexOf(targetid); if (potentialduck == -1) { myPhotoBrowser.swiper.slideNext(true,1000); if ($('.infopopup').length > 0) { if(swiperQuestions){comingback = 0; swiperQuestions.slideNext();comingback=1;}}} } } var singleuserarray = []; function singleUser(idw,idname,origin){ if (singleuserarray[0] != null){ if (origin){photoBrowser(0,singleuserarray[0].age,1,1);} else{photoBrowser(0,singleuserarray[0].age);} } else{ targetid = String(idw); targetname = idname; firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/singleuser.php", {projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:targetid,latitudep:latitudep,longitudep:longitudep} ) .done(function( data ) { console.log(data); var result = JSON.parse(data); var availarraystring=''; var availnotexpired = false; var tonight = new Date(); tonight.setHours(22,59,59,999); var tonight_timestamp = Math.round(tonight/1000); if(result[0].availstring && (result[0].availstring != '[]') && (result[0].uid != f_uid)){ var availablearrayindividual = JSON.parse(result[0].availstring); for (k = 0; k < availablearrayindividual.length; k++) { if (availablearrayindividual[k].id >= tonight_timestamp){availnotexpired = true;} } if (availnotexpired){availarraystring = result[0].availstring;} } var timestampyear = result[0].timestamp.substring(0,4); var timestampmonth = result[0].timestamp.substring(5,7); var timestampday = result[0].timestamp.substring(8,10); var timestamphour = result[0].timestamp.substring(11,13); var timestampminute = result[0].timestamp.substring(14,16); var timestampsecond = result[0].timestamp.substring(17,20); var timestampunix=(new Date(timestampmonth + '/' + timestampday + '/' + timestampyear + ' ' + timestamphour + ':' + timestampminute + ':' + timestampsecond)).getTime() / 1000 + 64800; var d_unix = Math.round(+new Date()/1000); var diff = (d_unix - timestampunix)/60; var photosstringarray =[]; var photocount; var photostring; var profilepicstring; var photoarrayuserlarge; var photoarrayusersmall; if(result[0].largeurl){ var heightarray = result[0].heightslides.split(","); var widtharray = result[0].widthslides.split(","); photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical" style="height:100%;"><img data-src="' + result[0].largeurl + '" class="swiper-lazy"></div></div>'; photocount = result[0].largeurl.split(",").length; photoarrayuserlarge = result[0].largeurl.split(","); photoarrayusersmall = result[0].smallurl.split(","); profilepicstringlarge = photoarrayuserlarge[0]; profilepicstringsmall = photoarrayusersmall[0]; photostring=photostring.replace(/,/g, '" class="swiper-lazy" style="height:100%;"></div></div><div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="') } else{ photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="https://graph.facebook.com/'+targetid+'/picture?width=828" class="swiper-lazy" style="height:100%;"></div></div>'; profilepicstringlarge = 'https://graph.facebook.com/'+targetid+'/picture?width=828&height=828'; profilepicstringsmall = 'https://graph.facebook.com/'+targetid+'/picture?width=368&height=368'; photocount = 1; } var distance = parseFloat(result[0].distance).toFixed(1); var distancerounded = parseFloat(result[0].distance).toFixed(0); if ((distance >= 0) && (distance <0.1)) {distancestring = 'Less than 100 m <span style="font-size:13px;">(328 ft.)</span>'} if ((distance >= 0.1) && (distance <0.2)) {distancestring = 'Less than 200 m <span style="font-size:13px;">(656 ft.)</span>'} if ((distance >= 0.2) && (distance <0.3)) {distancestring = 'Less than 300 m <span style="font-size:13px;">(984 ft.)</span>'} if ((distance >= 0.3) && (distance <0.4)) {distancestring = 'Less than 400 m <span style="font-size:13px;">(1312 ft.)</span>'} if ((distance >= 0.4) && (distance <0.5)) {distancestring = 'Less than 500 m <span style="font-size:13px;">(1640 ft.)</span>'} if ((distance >= 0.5) && (distance <0.6)) {distancestring = 'Less than 600 m <span style="font-size:13px;">(1968 ft.)</span>'} if ((distance >= 0.6) && (distance <0.7)) {distancestring = 'Less than 700 m <span style="font-size:13px;">(2296 ft.)</span>'} if ((distance >= 0.7) && (distance <0.8)) {distancestring = 'Less than 800 m <span style="font-size:13px;">(2624 ft.)</span>'} if ((distance >= 0.8) && (distance <0.9)) {distancestring = 'Less than 900 m <span style="font-size:13px;">(2953 ft.)</span>'} if ((distance >= 0.9) && (distance <1.0)) {distancestring = 'Less than 1 km <span style="font-size:13px;">(3280 ft.)</span>'} if ((distance >= 1.0) && (distance <1.609344)) {distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 3280.84) + ' ft.)</span>'} if (distance > 1.609344){distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 0.621371) + ' mi.)</span>'} var namescount = result[0].displayname.split(' ').length; var matchname; if(namescount === 1){matchname = result[0].displayname;} else {matchname = result[0].name.substr(0,result[0].displayname.indexOf(' '));} singleuserarray.push({widthslides:result[0].widthslides,heightslides:result[0].heightslides,availarraystring:availarraystring,minutes:diff,distancenumber:distance,distancestring:distancestring,photocount:photocount,photos:photostring,name:matchname,age:result[0].age,description:result[0].description,id:targetid,url:'https://graph.facebook.com/'+targetid+'/picture?width=828',caption:'...',industry: result[0].industry, status: result[0].status, politics:result[0].politics,eyes:result[0].eyes,body:result[0].body,religion:result[0].religion,zodiac:result[0].zodiac,ethnicity:result[0].ethnicity,height:result[0].height,weight:result[0].weight}); // console.log(singleuserarray); main_all = new_all; new_all = singleuserarray; if (origin == 88){alert('88');} else if (origin == 1){photoBrowser(0,singleuserarray[0].age,1,1);} else if (!origin){alert('100');photoBrowser(0,singleuserarray[0].age);} }); }); } } function request(){ canloadchat = false; $( '.picker-items-col-wrapper' ).css("width", "auto"); $( ".requesticon" ).hide(); $( ".dateheader" ).show(); $( ".sender-inner" ).hide(); $( ".yes-inner" ).hide(); conversation_started = false; if (d_response == 'Y') { $( ".date-close" ).hide(); $( ".date2-close" ).show(); $( ".date1-close" ).hide(); } if (d_response == 'W') { $( ".date-close" ).hide(); $( ".date1-close" ).show(); $( ".date2-close" ).hide(); } if(!d_response){ $( ".date-close" ).show(); $( ".date2-close" ).hide(); $( ".date1-close" ).hide(); } $( ".messages" ).hide(); $( ".date-button" ).hide(); $( "#createdatepicker" ).show(); $( ".dr" ).hide(); $( ".date-back" ).hide(); if (d_type == 'date') {$( ".date-row" ).show();$( ".duck-row" ).hide();} if (d_type == 'duck') {$( ".duck-row" ).show();$( ".date-row" ).hide();} $( ".waitingreply" ).empty(); $( ".datetoolbar" ).slideDown(); $( ".message-inner" ).hide(); $( ".date-inner" ).show(); if (d_response=='Y'){$( "#datemessageq" ).val('');} // $( ".center-date" ).empty(); // if (d_type=='date') {$( ".center-date" ).append('Date Details');} // if (d_type=='duck') {$( ".center-date" ).append('Duck Details');} myApp.sizeNavbars(); //$( "#createdatepicker" ).focus(); $( ".page-content" ).animate({ scrollTop: 0 }, "fast"); } function noChange(){ canloadchat = true; $( ".sender-inner" ).hide(); $( ".messages" ).show(); $( ".date-close" ).hide(); $( ".date2-close" ).hide(); $( ".date1-close" ).hide(); $( ".message-inner" ).show(); $( ".date-inner" ).hide(); // $( ".center-date" ).empty(); $( "#createdatepicker" ).hide(); // $( ".center-date" ).append(targetname); $( ".nomessages" ).hide(); $( ".date-back" ).show(); $( ".date-button" ).show(); scrollBottom(); myApp.sizeNavbars(); } function reverseRequest(){ $( ".dateheader" ).hide(); $( "#createdatepicker" ).hide(); $( ".dr" ).show(); $( ".date-back" ).show(); $( ".date-row" ).hide(); $( ".duck-row" ).hide(); $( ".date-close" ).hide(); $( ".requesticon" ).show(); $( ".date-inner" ).hide(); if (!d_day){ //$( ".center-date" ).empty(); // $( ".center-date" ).append(targetname); myApp.sizeNavbars(); } } var message_count = 0; var messages_loaded = false; var conversation_started = false; var prevdatetitle; function chatShow(){ prevdatetitle = false; letsload = 20; canloadchat = true; additions = 0; $( ".yes-inner" ).hide(); $( ".sender-inner" ).hide(); $( ".datedetailsdiv" ).show(); message_count = 1; image_count = 0; $( ".messages" ).show(); $( ".datearea" ).empty(); $( ".date-back" ).show(); $( ".date-button" ).show(); $( ".date-close" ).hide(); $( ".date2-close" ).hide(); $( ".datetoolbar" ).show(); $( ".message-inner" ).show(); $( ".date-inner" ).hide(); // $( ".center-date" ).empty(); // $( ".center-date" ).append(targetname); myApp.sizeNavbars(); myMessagebar = myApp.messagebar('.messagebar', { maxHeight: 200 }); myMessages = myApp.messages('.messages', { autoLayout: true, scrollMessages:true }); //if (myMessages) {myMessages.clean();} if (message_history === true){} if (message_history === false){ message_history = true; //do the .on call here to keep receiving messages here var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} firebase.database().ref("chats/" + first_number+ '/' + second_number).once('value').then(function(snapshot) { existingmessages = snapshot.numChildren(); // $( ".messages").append( '<a href="#" class="button scrollbutton" onclick="scrollBottom();" style="border:0;margin-top:10px;"><i class="pe-7s-angle-down-circle pe-2x" style="margin-right:5px;"></i> New Messages</a>'); // $( ".messages").append('<a href="#" class="button scrollbutton" onclick="scrollBottom()" style="display:none;top:103px;position:absolute;right:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-down-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">New messages</div></div></a>'); // if (snapshot.numChildren() > 10) {$( ".messages").prepend( '<a href="#" class="button previouschats" onclick="getPrevious()" style="top:103px;position:absolute;left:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-up-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">Past messages</div></div></a>');} }).then(function(result) { var weekday = []; weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; var month = []; month[0] = "Jan"; month[1] = "Feb"; month[2] = "Mar"; month[3] = "Apr"; month[4] = "May"; month[5] = "Jun"; month[6] = "Jul"; month[7] = "Aug"; month[8] = "Sep"; month[9] = "Oct"; month[10] = "Nov"; month[11] = "Dec"; var stringnow = new Date(); var stringyestday = new Date(Date.now() - 86400); var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate(); var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate(); message_historyon = firebase.database().ref("chats/" + first_number+ '/' + second_number).orderByKey().limitToLast(20).on("child_added", function(snapshot) { if (message_count ==1) {lastkey = snapshot.getKey();} message_count ++; var checkloaded; if (existingmessages > 19){checkloaded = 20;} else if (existingmessages < 20){checkloaded = existingmessages;} if (message_count == checkloaded){messages_loaded = true;} var obj = snapshot.val(); var datechatstring; var messagedate = new Date((obj.timestamp * 1000)); var minstag = ('0'+messagedate.getMinutes()).slice(-2); messagetimetitle = messagedate.getHours() + ':' + minstag; var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate(); if (!prevdatetitle){prevdatetitle = messagedaytitle;console.log('prevdatetitle does not exist'); if (messagedaytitle == todaystring){datechatstring = 'Today';} else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';} else{datechatstring = messagedaytitle;} } else { if (prevdatetitle == messagedaytitle){console.log('it is the same day');datechatstring='';} else{console.log('it is a different day');prevdatetitle = messagedaytitle; if (messagedaytitle == todaystring){datechatstring = 'Today';} else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';} else{datechatstring = messagedaytitle;} } } //my messages var unix = Math.round(+new Date()/1000); if (obj.from_uid == f_uid) { if (obj.param == 'dateset'){ $( ".messages" ).append( '<div class="list-block media-list" style="margin-top:0px;">'+ '<ul>'+ ' <li>'+ ' <div class="item-content">'+ ' <div class="item-media">'+ ' <img src="path/to/img.jpg">'+ '</div>'+ ' <div class="item-inner">'+ ' <div class="item-title-row">'+ ' <div class="item-title">Date Details</div>'+ ' <div class="item-after">Element label</div>'+ ' </div>'+ ' <div class="item-subtitle">Subtitle</div>'+ ' <div class="item-text">Additional description text</div>'+ '</div>'+ '</div>'+ '</li>'+ '</ul>'+ '</div>'); } if (obj.param == 'message'){ myMessages.addMessage({ // Message text text: obj.message, // Random message type type: 'sent', // Avatar and name: avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal', name: f_first, // Day day:datechatstring, label: 'Sent ' + messagetimetitle }); } if (obj.param == 'image'){ if (obj.photo_expiry){ if (obj.photo_expiry < Number(unix)){ firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + obj.id).remove(); firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + obj.id).remove(); } else{ myMessages.addMessage({ // Message text text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup('+image_count+');">', // Random message type type: 'sent', // Avatar and name: avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal', name: f_first, day:datechatstring, label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle // Day }); image_count ++; } } else { myMessages.addMessage({ // Message text text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup('+image_count+');">', // Random message type type: 'sent', // Avatar and name: avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal', name: f_first, day:datechatstring, label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle }); image_count ++; } } if (conversation_started === true) { $( ".message" ).last().remove(); $( ".message" ).last().addClass("message-last"); $('#buzzer')[0].play(); } } //received messages if (obj.to_uid == f_uid) { if (messages_loaded === true) { var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) { var objs = snapshot.val(); if (snapshot.val()){ if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){ firebase.database().ref('notifications/' +f_uid + '/' + targetid).update({ received:'Y', new_message_count:'0', authcheck:f_uid, uid_accepted:f_uid }); firebase.database().ref('notifications/' +targetid + '/' + f_uid).update({ received:'Y', new_message_count:'0', authcheck:f_uid, uid_accepted:f_uid }); } } }); } if (conversation_started === true) { $('#buzzer')[0].play(); } if (obj.param == 'dateset'){ $( ".messages" ).append( '<div class="list-block media-list">'+ '<ul>'+ ' <li>'+ ' <div class="item-content">'+ ' <div class="item-media">'+ ' <img src="path/to/img.jpg">'+ '</div>'+ ' <div class="item-inner">'+ ' <div class="item-title-row">'+ ' <div class="item-title">Element title</div>'+ ' <div class="item-after">Element label</div>'+ ' </div>'+ ' <div class="item-subtitle">Subtitle</div>'+ ' <div class="item-text">Additional description text</div>'+ '</div>'+ '</div>'+ '</li>'+ '</ul>'+ '</div>'); } if (obj.param == 'message'){ myMessages.addMessage({ // Message text text: obj.message, // Random message type type: 'received', // Avatar and name: avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal', name: targetname, day:datechatstring, label: 'Sent ' + messagetimetitle }); } if (obj.param == 'image'){ if (!obj.photo_expiry){ myMessages.addMessage({ // Message text text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup('+image_count+');">', // Random message type type: 'received', // Avatar and name: avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal', name: f_first, day:datechatstring, label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle }); image_count ++; var seentime = Math.round(+new Date()/1000); var expirytime = Math.round(+new Date()/1000) + 86400; firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + obj.id).update({ photo_expiry:expirytime, seen:'Y', seentime:seentime }); firebase.database().ref('photostodelete/' + obj.from_uid + '/' +obj.to_uid+ '/' +obj.id).update({ photo_expiry:expirytime, seen:'Y', seentime:seentime }); firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + obj.id).update({ photo_expiry:expirytime, seen:'Y', seentime:seentime }); } else { if (obj.photo_expiry < Number(unix)){ firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + obj.id).remove(); firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + obj.id).remove(); } else{ myMessages.addMessage({ // Message text text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup('+image_count+');">', // Random message type type: 'received', // Avatar and name: avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal', name: f_first, day:datechatstring, label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle }); image_count ++; } } } } }, function (errorObject) { }); }); } //myMessages.layout(); //myMessages = myApp.messages('.messages', { // autoLayout: true //}); //myMessages.scrollMessages(); myApp.initPullToRefresh('.pull-to-refresh-content-9'); } var notifadditions=0; var notifletsload = 12; function getmoreNotifs(){ notifadditions ++; var notifsloaded = notifadditions * 12; var notif2load = mynotifs.length - (notifadditions * 12); if (notif2load > 12) {notifletsload = 12;} else {notifletsload = notif2load;} var lasttoaddnotif = notifsloaded + notifletsload; $(".loadnotifsloader").remove(); for (i = notifsloaded; i < lasttoaddnotif; i++) { myList.appendItem({ title: mynotifs[i].title, targetid:mynotifs[i].targetid, targetname:mynotifs[i].targetname, picture:mynotifs[i].picture, from_name: mynotifs[i].from_name, to_name: mynotifs[i].to_name, from_uid:mynotifs[i].from_uid, to_uid: mynotifs[i].to_uid, icon:mynotifs[i].icon, colordot:mynotifs[i].colordot, func:mynotifs[i].func, type:mynotifs[i].type, timestamptitle:mynotifs[i].timestamptitle }); } canscrollnotif = true; } var letsload = 20; function getPrevious(){ if (existingmessages === false){ var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} firebase.database().ref("chats/" + first_number+ '/' + second_number).once('value').then(function(snapshot) { existingmessages = snapshot.numChildren(); previousFunction(); }) } else{previousFunction();} function previousFunction(){ var weekday = []; weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; var month = []; month[0] = "Jan"; month[1] = "Feb"; month[2] = "Mar"; month[3] = "Apr"; month[4] = "May"; month[5] = "Jun"; month[6] = "Jul"; month[7] = "Aug"; month[8] = "Sep"; month[9] = "Oct"; month[10] = "Nov"; month[11] = "Dec"; var stringnow = new Date(); var stringyestday = new Date(Date.now() - 86400); var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate(); var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate(); var prevarray = []; message_count = 0; additions ++; $(".previouschats").remove(); var left2load = existingmessages - (additions * 20); if (left2load > 20) {letsload = 20;} else {letsload = left2load;} console.log('existingmessages' + existingmessages); console.log('letsload' + letsload); console.log('additions' + additions); var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var newmessage_history = firebase.database().ref("chats/" + first_number+ '/' + second_number).orderByKey().limitToLast(letsload).endAt(lastkey).on("child_added", function(snapshot) { message_count ++; if (message_count ==1) {lastkey = snapshot.getKey();} var obj = snapshot.val(); var datechatstring; var messagedate = new Date((obj.timestamp * 1000)); var minstag = ('0'+messagedate.getMinutes()).slice(-2); messagetimetitle = messagedate.getHours() + ':' + minstag; var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate(); if (!prevdatetitle){prevdatetitle = messagedaytitle;console.log('prevdatetitle does not exist'); if (messagedaytitle == todaystring){datechatstring = 'Today'} else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday'} else{datechatstring = messagedaytitle;} } else { if (prevdatetitle == messagedaytitle){console.log('it is the same day'); //console.log($(".message").length); if ((letsload < 20) && (message_count == 1) ){ if (messagedaytitle == todaystring){datechatstring = 'Today'} if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday'} else{datechatstring = messagedaytitle;} } else {datechatstring='';} } else{console.log('it is a different day');prevdatetitle = messagedaytitle; if (messagedaytitle == todaystring){datechatstring = 'Today'} else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday'} else{datechatstring = messagedaytitle;} } } //my messages if (obj.from_uid == f_uid) { if (obj.param == 'message'){ prevarray.push({ // Message text text: obj.message, // Random message type type: 'sent', // Avatar and name: avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal', name: f_first, day:datechatstring, label: 'Sent ' + messagetimetitle }); } if (obj.param == 'image'){ prevarray.push({ // Message text text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup();">', // Random message type type: 'sent', // Avatar and name: avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal', name: f_first, day:datechatstring, label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle }); } } //received messages if (obj.to_uid == f_uid) { if (obj.param == 'message'){ prevarray.push({ // Message text text: obj.message, // Random message type type: 'received', // Avatar and name: avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal', name: targetname, day:datechatstring, label: 'Sent ' + messagetimetitle }); } if (obj.param == 'image'){ prevarray.push({ // Message text text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup();">', // Random message type type: 'received', // Avatar and name: avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal', name: f_first, day:datechatstring, label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle }); } } if (message_count == letsload) { $(".loadmessagesloader").remove(); canloadchat = true; myMessages.addMessages(prevarray.slice(0, -1), 'prepend'); //$(".scrollbutton").remove(); //$(".messages").prepend('<a href="#" class="button scrollbutton" onclick="scrollBottom()" style="display:none;top:103px;position:absolute;right:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-down-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">New messages</div></div></a>'); //if (message_count == 20){$( ".messages").prepend( '<a href="#" class="button previouschats" onclick="getPrevious()" style="top:103px;position:absolute;left:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-up-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">Past messages</div></div></a>' );$( ".messages" ).css("margin-top","132px");} } }, function (errorObject) { // console.log("The read failed: " + errorObject.code); }); } } var targetid; var targetname; var targetreported; var targetdatearray,targetduckarray; var targetdate,targetduck; var match; var targetdatelikes, targetducklikes; var slideheight = $( window ).height(); function getMeta(url){ $("<img/>",{ load : function(){ if (this.height > this.width){ $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height',$(document).height() + 'px'); $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','auto'); } }, src : url }); } function backtoProfile(){ myApp.closeModal('.infopopup') ; $( ".toolbarq" ).hide(); getMeta(new_all[myPhotoBrowser.activeIndex].url); //put original image here $( ".nametag" ).addClass('whitetext'); //$( ".photo-browser-slide img" ).css("height","100%"); $( ".datebutton" ).addClass('imagelibrary'); $( ".duckbutton" ).addClass('imagelibrary'); //$( ".swiper-container-vertical" ).css("height",slideheight + "px"); //$( ".swiper-container-vertical" ).css("margin-top","0px"); //$( ".swiper-slide-active" ).css("height", "600px"); $( ".toolbarq" ).css("background-color","transparent"); $( ".datefloat" ).hide(); $( ".duckfloat" ).hide(); $( ".vertical-pag" ).show(); //$( ".infopopup" ).css("z-index","-100"); $( ".onlineblock" ).hide(); //$( ".orlink" ).show(); //$( ".uplink" ).hide(); //$( ".nextlink" ).hide(); //$( ".prevlink" ).hide(); $( ".prevphoto" ).show(); $( ".nextphoto" ).show(); $( ".nexts" ).hide(); $( ".prevs" ).hide(); $( ".photo-browser-slide" ).css("opacity","1"); //$( ".datebutton" ).css("height","40px"); //$( ".duckbutton" ).css("height","40px"); //$( ".datebutton img" ).css("height","30px"); //$( ".duckbutton img" ).css("height","30px"); //$( ".datebutton img" ).css("width","auto"); //$( ".duckbutton img" ).css("width","auto"); $( ".photobrowserbar" ).css("background-color","transparent"); } var comingback; function scrollQuestions(){ //console.log($( ".wrapper-questions" ).offset().top); //console.log($( window ).height()); var offsetline = $( window ).height() - 88; var offsetdiv = $( ".wrapper-questions" ).offset().top; //if (offsetdiv > offsetline){$( ".photo-browser-slide" ).css("opacity",1);} var setopacity = (($( ".wrapper-questions" ).offset().top +88) / $( window ).height());$( ".photo-browser-slide" ).css("opacity",setopacity);$( ".adown" ).css("opacity",setopacity); //if // if (offsetdiv > offsetline) {$( ".photo-browser-slide" ).css("opacity","1");$( ".adown" ).css("opacity","1");} //var setopacity = (($( ".wrapper-questions" ).offset().top +10) / $( window ).height());$( ".photo-browser-slide" ).css("opacity",setopacity);$( ".adown" ).css("opacity",setopacity); } function delayYo(){ } function scrolltoTop(){ $( ".swiper-questions" ).animate({ scrollTop: $( window ).height() - 130 }); } function questions(origin){ $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','cover'); $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','100%'); $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','auto'); $( ".toolbarq" ).css("background-color","transparent"); $( ".photobrowserbar" ).css("background-color","#ccc"); $( ".nametag" ).removeClass('whitetext'); var targetplugin = new_all[myPhotoBrowser.activeIndex].id; //may need to readd this //checkMatch(targetplugin); comingback = 0; if (origin){comingback = 1;} if (swiperQuestions){ swiperQuestions.removeAllSlides(); swiperQuestions.destroy(); } //alert($('.photo-browser-slide img').css('height')); if ($('.infopopup').length > 0) { alert('deleting return false');myApp.closeModal('.infopopup');return false; } $( ".vertical-pag" ).hide(); $( ".datefloat" ).show(); $( ".duckfloat" ).show(); $( ".datebutton" ).removeClass('imagelibrary'); $( ".duckbutton" ).removeClass('imagelibrary'); //$( ".swiper-container-vertical.swiper-slide-active img" ).css("height","-webkit-calc(100% - 115px)"); //$( ".swiper-container-vertical" ).css("margin-top","-27px"); //$( ".swiper-slide-active" ).css("height","100%"); //$( ".photo-browser-slide img" ).css("height","calc(100% - 80px)"); //$( ".orlink" ).hide(); //$( ".uplink" ).show(); //$( ".nextlink" ).show(); //$( ".prevlink" ).show(); $( ".onlineblock" ).show(); //$( ".datebutton" ).css("height","70px"); //$( ".duckbutton" ).css("height","70px"); //$( ".datebutton img" ).css("height","60px"); //$( ".duckbutton img" ).css("height","60px"); //$( ".datebutton img" ).css("width","auto"); //$( ".duckbutton img" ).css("width","auto"); //$( ".nametag" ).removeClass('whitetext'); var photobrowserHTML = '<div class="popup infopopup" style="background-color:transparent;margin-top:44px;height:calc(100% - 127px);padding-bottom:20px;" >'+ // ' <a href="#tab1" class="prevs button disabled" style="border-radius:5px;position:absolute;left:-37px;top:50%;margin-top:-28px;height:56px;width:56px;border:0;z-index:99;color:#2196f3;background-color:rgba(247, 247, 247, 0.952941);"><i class="pe-7s-angle-left pe-4x" style="margin-left:7px;margin-top:-1px;z-index:-1"></i></a>'+ // ' <a href="#tab3" class="nexts button" style="border-radius:5px;position:absolute;right:-37px;width:56px;top:50%;margin-top:-26px;height:56px;color:#2196f3;border:0;z-index:99;background-color:rgba(247, 247, 247, 0.952941);"><i class="pe-7s-angle-right pe-4x" style="margin-left:-35px;margin-top:-1px;"></i></a>'+ '<div class="swiper-container swiper-questions" style="height:100%;overflow-y:scroll;will-change: opacity;">'+ '<div style="height:100%;width:100%;overflow-x:hidden;" onclick="backtoProfile();">'+ '</div>'+ ' <div class="swiper-wrapper wrapper-questions" style="">'+ ' </div>'+ '</div>'+ '</div>' myApp.popup(photobrowserHTML,true,false); $( ".nexts" ).show(); $( ".prevs" ).show(); $( ".prevphoto" ).hide(); $( ".nextphoto" ).hide(); console.log(new_all); for (i = 0; i < new_all.length; i++) { var boxcolor,displayavail,availabilityli,availabletext,iconavaill; if (new_all[i].availarraystring){iconavaill='s';boxcolor = 'width:60px;color:#007aff;opacity:1;background-color:transparent;color:#4cd964';displayavail='block';availabletext='<div class="availabletxt_'+new_all[i].id+'" style="display:none;float:left;margin-top:12px;padding-right:10px;">Available</div>';} else{iconavaill='f';boxcolor = 'width:60px;color:#007aff;opacity:1;background-color:transparent';displayavail='none';availabletext='';} $( ".wrapper-questions" ).append('<div class="swiper-slide slideinfo_'+new_all[i].id+'" style="height:100%;">'+ //'<h3 class="availabilitytitle_'+new_all[i].id+'" style="color:white;font-size:16px;padding:5px;float:left;"><i class="pe-7-angle-down pe-3x"></i></h3>'+ '<h3 onclick="scrolltoTop()" class="adown arrowdown_'+new_all[i].id+' availyope availyo_'+ new_all[i].id+'" style="display:none;margin-top:-60px;right:0px;'+boxcolor+';font-size:14px;padding:0px;margin-left:10px;"><i class="pe-7f-angle-down pe-3x" style="float:left;"></i>'+ '</h3>'+ '<div onclick="scrolltoTop()" style="z-index:99999999;margin-top:15px;display:none;background-color:white;border-radius:20px;border-bottom-right-radius:0px;border-bottom-left-radius:0px;margin-bottom:20px;" class="prof_'+i+' infoprofile availyo_'+ new_all[i].id+'">'+ '<div class="content-block-title" style="padding-top:0px;clear:both;margin-top:0px;">About '+new_all[i].name+'</div>'+ '<div class="list-block" style="margin-top:0px;clear:both;">'+ '<ul class="profileul_'+new_all[i].id+'" style="background-color:transparent">'+ ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Online</div>'+ ' <div class="item-input">'+ '<div class="timetag_'+ new_all[i].id+'"></div>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Distance</div>'+ ' <div class="item-input">'+ '<div class="distancetag_'+ new_all[i].id+'"></div>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Hometown</div>'+ ' <div class="item-input">'+ ' <input type="text" name="name" value="Melbourne" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' </ul></div>'+ '<div class="profileyo_'+ new_all[i].id+'"></div>'+ '</div>'+ '</div>'); //put here if (new_all[i].description){ $( ".profileul_"+new_all[i].id ).prepend( ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-input">'+ ' <textarea class="resizable" name="name" style="max-height:200px;font-size:14px;" readonly>'+new_all[i].description+'</textarea>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } if (new_all[i].industry){ $( ".profileul_"+new_all[i].id ).append( ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Industry</div>'+ ' <div class="item-input">'+ ' <input type="text" name="name" value="'+new_all[i].industry+'" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } if (new_all[i].zodiac){ $( ".profileul_"+new_all[i].id ).append( ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Zodiac</div>'+ ' <div class="item-input">'+ ' <input type="text" name="name" value="'+new_all[i].zodiac+'" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } if (new_all[i].politics){ $( ".profileul_"+new_all[i].id ).append( ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Politics</div>'+ ' <div class="item-input">'+ ' <input type="text" name="name" value="'+new_all[i].politics+'" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } if (new_all[i].religion){ $( ".profileul_"+new_all[i].id ).append( ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Religion</div>'+ ' <div class="item-input">'+ ' <input type="text" name="name" value="'+new_all[i].religion+'" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } if (new_all[i].ethnicity){ $( ".profileul_"+new_all[i].id ).append( ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Ethnicity</div>'+ ' <div class="item-input">'+ ' <input type="text" name="name" value="'+new_all[i].ethnicity+'" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } if (new_all[i].eyes){ $( ".profileul_"+new_all[i].id ).append( ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Eye Color</div>'+ ' <div class="item-input">'+ ' <input type="text" name="name" value="'+new_all[i].eyes+'" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } if (new_all[i].body){ $( ".profileul_"+new_all[i].id ).append( ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Body Type</div>'+ ' <div class="item-input">'+ ' <input type="text" name="name" value="'+new_all[i].body+'" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } if (new_all[i].height != 0){ if (new_all[i].height == 122) {var heightset = '122 cm (4\' 0\'\')';} if (new_all[i].height == 124) {var heightset = '124 cm (4\' 1\'\')';} if (new_all[i].height == 127) {var heightset = '127 cm (4\' 2\'\')';} if (new_all[i].height == 130) {var heightset = '130 cm (4\' 3\'\')';} if (new_all[i].height == 132) {var heightset = '132 cm (4\' 4\'\')';} if (new_all[i].height == 135) {var heightset = '135 cm (4\' 5\'\')';} if (new_all[i].height == 137) {var heightset = '137 cm (4\' 6\'\')';} if (new_all[i].height == 140) {var heightset = '140 cm (4\' 7\'\')';} if (new_all[i].height == 142) {var heightset = '142 cm (4\' 8\'\')';} if (new_all[i].height == 145) {var heightset = '145 cm (4\' 9\'\')';} if (new_all[i].height == 147) {var heightset = '147 cm (4\' 10\'\')';} if (new_all[i].height == 150) {var heightset = '150 cm (4\' 11\'\')';} if (new_all[i].height == 152) {var heightset = '152 cm (5\' 0\'\')';} if (new_all[i].height == 155) {var heightset = '155 cm (5\' 1\'\')';} if (new_all[i].height == 157) {var heightset = '157 cm (5\' 2\'\')';} if (new_all[i].height == 160) {var heightset = '160 cm (5\' 3\'\')';} if (new_all[i].height == 163) {var heightset = '163 cm (5\' 4\'\')';} if (new_all[i].height == 165) {var heightset = '165 cm (5\' 5\'\')';} if (new_all[i].height == 168) {var heightset = '168 cm (5\' 6\'\')';} if (new_all[i].height == 170) {var heightset = '170 cm (5\' 7\'\')';} if (new_all[i].height == 173) {var heightset = '173 cm (5\' 8\'\')';} if (new_all[i].height == 175) {var heightset = '175 cm (5\' 9\'\')';} if (new_all[i].height == 178) {var heightset = '178 cm (5\' 10\'\')';} if (new_all[i].height == 180) {var heightset = '180 cm (5\' 11\'\')';} if (new_all[i].height == 183) {var heightset = '183 cm (6\' 0\'\')';} if (new_all[i].height == 185) {var heightset = '185 cm (6\' 1\'\')';} if (new_all[i].height == 188) {var heightset = '185 cm (6\' 2\'\')';} if (new_all[i].height == 191) {var heightset = '191 cm (6\' 3\'\')';} if (new_all[i].height == 193) {var heightset = '193 cm (6\' 4\'\')';} if (new_all[i].height == 195) {var heightset = '195 cm (6\' 5\'\')';} if (new_all[i].height == 198) {var heightset = '198 cm (6\' 6\'\')';} if (new_all[i].height == 201) {var heightset = '201 cm (6\' 7\'\')';} if (new_all[i].height == 203) {var heightset = '203 cm (6\' 8\'\')';} $(".profileul_"+new_all[i].id ).append( ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Height</div>'+ ' <div class="item-input">'+ ' <input type="text" name="name" value="'+heightset+'" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } if (new_all[i].weight != 0){ $( ".profileul_"+new_all[i].id ).append( ' <li>'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Weight</div>'+ ' <div class="item-input">'+ ' <input type="text" name="name" value="'+new_all[i].weight+' kg (' + Math.round(new_all[i].weight* 2.20462262) + ' lbs)" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } var timestring; var minutevalue; if (new_all[i].minutes <= 0){timestring = 'Now';} if (new_all[i].minutes == 1){timestring = '1 minute ago';} if ((new_all[i].minutes >= 0) && (new_all[i].minutes <60)){timestring = Math.round(new_all[i].minutes) + ' minutes ago';} if (new_all[i].minutes == 60){timestring = '1 hour ago';} if ((new_all[i].minutes >= 60) && (new_all[i].minutes <1440)){ minutevalue = Math.round((new_all[i].minutes / 60)); if (minutevalue == 1) {timestring = '1 hour ago';} else {timestring = minutevalue + ' hours ago';} } if ((new_all[i].minutes >= 60) && (new_all[i].minutes <1440)){timestring = Math.round((new_all[i].minutes / 60)) + ' hours ago';} if (new_all[i].minutes == 1440){timestring = '1 day ago';} if ((new_all[i].minutes >= 1440) && (new_all[i].minutes <10080)){ minutevalue = Math.round((new_all[i].minutes / 1440)); if (minutevalue == 1) {timestring = '1 day ago';} else {timestring = minutevalue + ' days ago';} } if (new_all[i].minutes >= 10080){timestring = '1 week';} if (new_all[i].minutes >= 20160){timestring = '2 weeks';} if (new_all[i].minutes >= 30240){timestring = '3 weeks';} $( ".timetag_" + new_all[i].id ).html(timestring); $( ".distancetag_" + new_all[i].id ).html(new_all[i].distancestring); if (new_all[i].availarraystring !== ''){ $( ".profileyo_" + new_all[i].id ).prepend( '<div class="content-block-title" style="padding-top:0px;clear:both;margin-top:-20px;">Availability</div>'+ '<div class="list-block media-list availabilitylistblock_'+new_all[i].id+'" style="margin-top:0px;clear:both;margin-bottom:-40px;">'+ '<ul style="background-color:transparent">'+ ' </ul></div>'); var availablearrayindividual = JSON.parse(new_all[i].availarraystring); console.log(availablearrayindividual); var tonight = new Date(); tonight.setHours(22,59,59,999); var tonight_timestamp = Math.round(tonight/1000); for (k = 0; k < availablearrayindividual.length; k++) { if (availablearrayindividual[k].id >= tonight_timestamp){ $( ".availabilitylistblock_"+new_all[i].id ).append( ' <li style="list-style-type:none;">'+ '<div class="item-content">'+ '<div class="item-media">'+ '<span class="badge" style="background-color:#4cd964;">'+availablearrayindividual[k].day.charAt(0)+'</span>'+ '</div>'+ ' <div class="item-inner">'+ ' <div class="item-input">'+ ' <input type="text" name="name" style="height:30px;font-size:15px;" value="'+availablearrayindividual[k].day+', '+availablearrayindividual[k].time+'" readonly>'+ ' <input type="text" style="float:right;color:#333;text-align:left;height:30px;font-size:15px;" name="name" value="'+availablearrayindividual[k].fulldate+'" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>' ); } } } } swiperQuestions = myApp.swiper('.swiper-questions', { nextButton:'.nexts', prevButton:'.prevs', onSetTranslate:function(swiper, translate){myPhotoBrowser.swiper.setWrapperTranslate(translate - (20 * swiper.activeIndex));}, onInit:function(swiper){ myPhotoBrowser.swiper.setWrapperTranslate(0); $( ".infoprofile").hide();$( ".adown" ).css( "opacity","1" ); var wrapperheightshould = $(".prof_" + swiper.activeIndex).height(); $( ".wrapper-questions").css("height",(wrapperheightshould - 150)+ "px"); $( ".availyope").hide(); $( ".availyo_"+ new_all[0].id ).show(); if (new_all.length === 1){swiper.lockSwipes();myPhotoBrowser.swiper.lockSwipes();} checkMatch(targetid); }, onSlideChangeStart:function(swiper){ var wrapperheightshould = $(".prof_" + swiper.activeIndex).height(); $( ".wrapper-questions").css("height",(wrapperheightshould - 150)+ "px"); if(comingback === 1){ if (swiper.activeIndex > swiper.previousIndex){myPhotoBrowser.swiper.slideNext();} if (swiper.activeIndex < swiper.previousIndex){myPhotoBrowser.swiper.slidePrev();} } // if (swiper.isBeginning === true){$( ".prevs" ).addClass( "disabled" ); //} // else{$( ".prevs" ).removeClass( "disabled" );} // if (swiper.isEnd === true){$( ".nexts" ).addClass( "disabled" );} // else{$( ".nexts" ).removeClass( "disabled" );} //if (swiper.isBeginning === true){$( ".prevs" ).addClass( "disabled" ); // $(".arrowdown_"+new_all[swiper.activeIndex + 1].id).hide(); //$(".arrowdown_"+new_all[swiper.activeIndex].id).show(); // } //else if (swiper.isEnd === true){$(".arrowdown_"+new_all[swiper.activeIndex -1].id).hide(); //$(".arrowdown_"+new_all[swiper.activeIndex].id).show(); } //else{$(".arrowdown_"+new_all[swiper.activeIndex + 1].id).hide(); //$(".arrowdown_"+new_all[swiper.activeIndex -1].id).hide(); //$(".arrowdown_"+new_all[swiper.activeIndex].id).show(); } //$( ".adown" ).css( "opacity","1" ); $( ".camerabadge" ).text(new_all[swiper.activeIndex].photocount); $( ".infoprofile").hide(); $( ".availyope").hide(); $( ".availyo_"+ new_all[swiper.activeIndex].id ).show(); //$(".swiper-questions").css("background-image", "url("+new_all[swiper.activeIndex].url+")"); //$(".slideinfo_"+new_all[swiper.activeIndex + 1].id).css("background-size", "cover"); //$(".slideinfo_"+new_all[swiper.activeIndex + 1].id).css("background-position", "50% 50%"); //$(".swiper-questions".css("background", "transparent"); $( ".swiper-questions" ).scrollTop( 0 ); if ($('.toolbarq').css('display') == 'block') { if (((swiper.activeIndex - swiper.previousIndex) > 1) ||((swiper.activeIndex - swiper.previousIndex) < -1) ){ //alert(swiper.activeIndex - swiper.previousIndex); //myPhotoBrowser.swiper.slideTo(0); myPhotoBrowser.swiper.slideTo(swiper.activeIndex); //swiper.slideTo(myPhotoBrowser.swiper.activeIndex); } } checkMatch(targetid); } }); //console.log(myPhotoBrowser.swiper.activeIndex); swiperQuestions.slideTo(myPhotoBrowser.swiper.activeIndex,0); $( ".toolbarq" ).show(); comingback = 1; $( ".camerabadge" ).text(new_all[myPhotoBrowser.swiper.activeIndex].photocount); $( ".distancetag" ).text(new_all[myPhotoBrowser.swiper.activeIndex].distancestring); //if (myPhotoBrowser.swiper.activeIndex === 0){ //myPhotoBrowser.swiper.slideNext(); //myPhotoBrowser.swiper.slidePrev(); //} //else { //} //swiperQuestions.slideTo(myPhotoBrowser.swiper.activeIndex); } function checkMatch(targetid){ var indivNotif = firebase.database().ref('notifications/' + f_uid + '/' + targetid); indivNotif.once('value', function(snapshot) { if (snapshot.val()){ var obj = snapshot.val(); if (obj.new_message_count >0 && obj.to_uid == f_uid && obj.received =='N'){$( ".indivnotifcount" ).remove();$( ".arrowdivbrowser" ).append('<span class="badge indivnotifcount" style="position:absolute;right:0px;background-color:rgb(255, 208, 0);color:black;">'+obj.new_message_count+'</span>');} else{$( ".indivnotifcount" ).remove();} } }); var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} return firebase.database().ref('matches/' + f_uid + '/' + targetid).once('value').then(function(snapshot) { $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); $( ".loaderlink" ).hide(); $( ".orlink" ).show(); if (snapshot.val() === null) {} else { if (first_number == f_uid){ if (snapshot.val().firstnumberreport){targetreported = true;}else {targetreported = false;} //Dates if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );} if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );} if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){ $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" ); $( ".duck-template" ).hide(); $( ".date-template" ).show(); $( ".toolbardecide" ).hide(); matchNavbar(); d_type='date'; } else {} //Duck if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );} if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );} if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberduck == 'Y'){ $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" ); $( ".duck-template" ).show(); $( ".date-template" ).hide(); $( ".toolbardecide" ).hide(); matchNavbar(); d_type='duck'; } else {} } if (first_number == targetid){ if (snapshot.val().secondnumberreport){targetreported = true;}else {targetreported = false;} //Date if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );} if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );} if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){ $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" ); $( ".duck-template" ).hide(); $( ".date-template" ).show(); $( ".toolbardecide" ).hide(); matchNavbar(); d_type='date'; } else {} //Duck if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );} if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );} if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberduck == 'Y'){ $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" ); $( ".duck-template" ).show(); $( ".date-template" ).hide(); $( ".toolbardecide" ).hide(); matchNavbar(); d_type='duck'; } else {} } } }); } function photoBrowser(openprofile,arraynumber,mainchange,chatorigin){ allowedchange = true; photoresize = false; if ($('.photo-browser').length > 0){alert('yo1');return false;} myApp.closeModal('.picker-sub'); alert(new_all); //firebase.database().ref("users/" + f_uid).off('value', userpref); var photobrowserclass=""; var duckfunction = "" var datefunction = "" if ($('.chatpop').length > 0) {$( ".chatpop" ).css( "z-index","10000" );photobrowserclass="photo-browser-close-link";} else{duckfunction = "createDuck()";datefunction = "createDate1()";} var to_open = 0; if ($('.chatpop').length > 0) {alert('yo3');} else { var countednumbers = 0; for (var i = f_lower; i < arraynumber; i++) { countednumbers = countednumbers + all_matches_photos[i].length; } to_open = countednumbers + openprofile; alert('got here'); } var hiddendivheight = $( window ).height() - 40; myPhotoBrowser = myApp.photoBrowser({ zoom: false, expositionHideCaptions:true, lazyLoading:true, lazyLoadingInPrevNext:true, lazyPhotoTemplate: '<div class="photo-browser-slide photo-browser-slide-lazy swiper-slide">'+ '<div class="preloader {{@root.preloaderColorClass}}">{{#if @root.material}}{{@root.materialPreloaderSvg}}{{/if}}</div>'+ '<div class="swiper-container swiper-vertical" style="height:100%;min-width:'+$(document).width()+'px">'+ '<div class="swiper-wrapper vertical-wrapper-swiper">'+ '{{js "this.photos"}}'+ '</div><div class="swiper-pagination vertical-pag" style="top:0;left:0;z-index:999999;"></div></div>'+ '</div>', exposition:false, photos: new_all, captionTemplate:'<div style="width:40px;height:40px;background-color:transparent;margin-top:-80px;margin-left:50px;float:right;display:none;"></div><div class="photo-browser-caption" data-caption-index="{{@index}}">{{caption}}</div>', toolbarTemplate:'<div class="toolbar tabbar toolbarq" style="height:84px;background-color:transparent;">'+ //<img src="media/datefaceonly.png" style="width:100px;"> //<img src="media/duckfaceonly.png" style="width:100px;"> ' <div class="toolbar-inner date-template" style="display:none;padding:0;background-color:#2196f3;height:74px;border-bottom-right:20px;border-bottom-left:20px;">'+ '<a href="#" onclick="dateUser();" class="button link" style="color:#ccc;font-size:15px;max-width:80px;border:0;">'+ ' Unmatch'+ '</a>'+ '<p style="font-family: \'Pacifico\', cursive;font-size:20px;visibility:hidden;">or</p>'+ '<a href="#" onclick="'+datefunction+'" class="button link active lets '+photobrowserclass+'" style="border:1px solid white;margin-right:15px;margin-left:-15px;font-family: \'Pacifico\', cursive;font-size:26px;height:40px;">Let\'s Date <div style="font-family: -apple-system, SF UI Text, Helvetica Neue, Helvetica, Arial, sans-serif;position:absolute;right:0px;top:-8px;" class="arrowdivbrowser"><i class="pe-7s-angle-right pe-2x"></i></div></a></div>'+ // '<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:26px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+ ' <div class="toolbar-inner duck-template" style="display:none;padding:0;background-color:#2196f3;height:74px;border-bottom-right:20px;border-bottom-left:20px;">'+ '<a href="#" onclick="duckUser();" class="button link" style="color:#ccc;font-size:15px;max-width:80px;border:0;">'+ ' Unmatch'+ '</a>'+ // '<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:26px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+ '<a href="#" onclick="'+duckfunction+'" class="button link active lets '+photobrowserclass+'" style="border:1px solid white;margin-right:15px;margin-left:-15px;font-family: \'Pacifico\', cursive;font-size:26px;height:40px;">Let\'s Duck</a></div>'+ ' <div class="toolbar-inner toolbardecide" style="padding-bottom:10px;padding-left:0px;padding-right:0px;">'+ // ' <a href="#" class="link prevphoto" style="color:black">'+ // '<i class="pe-7s-angle-left pe-3x" ></i>'+ // ' </a>'+ //' <a href="#" class="link prevs" style="display:none;color:black;">'+ // '<i class="pe-7s-angle-left pe-3x"></i>'+ // ' </a>'+ '<a href="#tab3" onclick="dateUser();" class="datebutton disabled button link" style="border:1px solid white;border-right:0;border-radius:20px;border-top-right-radius:0px;border-top-left-radius:0px;border-bottom-right-radius:0px;font-family: \'Pacifico\', cursive;font-size:24px;">'+ '<span class="datefloat" style="padding:10px;border-radius:5px;margin-right:20px;">Date</span>'+ ' <div style="width:50px;overflow-x:hidden;position:absolute;right:-1px;bottom:-8px;"><img src="media/datefaceonly.png" style="width:100px;">'+ '</div>'+ ' </a>'+ ' <a href="#tab3" onclick="duckUser();" class="duckbutton disabled button link" style="border:1px solid white;border-left:0;border-radius:20px;border-top-left-radius:0px;border-top-right-radius:0px;border-bottom-left-radius:0px;font-family: \'Pacifico\', cursive;font-size:24px;">'+ '<span class="duckfloat" style="padding:10px;border-radius:5px;margin-left:20px;">Duck</span>'+ ' <div style="width:54px;overflow-x:hidden;position:absolute;left:-1px;bottom:-8px;"> <img src="media/duckfaceonly.png" style="width:100px;margin-left:-50px;"></div>'+ '</a>'+ //'<a href="#" onclick="dateUser();" class="datebutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:70px;width:72px;overflow:hidden;"><img //src="media/dateicon.png" style="width:70px;margin-left:40px;"></a>'+ // ' <a href="#" class="link orlink">'+ // '<p class="dateducktitle" style="font-family: \'Pacifico\', cursive;font-size:20px;text-align:center;">or</p>'+ // ' </a>'+ '<a href="#" class="link loaderlink"><span class="preloader preloader-white login-loader"></span></a>'+ //'<a href="#" onclick="duckUser();" class="duckbutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:70px;width:72px;overflow:hidden;"><img //src="media/duckicon.png" style="width:70px;margin-right:40px;"></a>'+ //' <a href="#" class="link nextphoto" style="color:black">'+ // '<i class="pe-7s-angle-right pe-3x"></i>'+ // ' </a>'+ // ' <a href="#" class="link nexts" style="display:none;color:black;">'+ // '<i class="pe-7s-angle-right pe-3x"></i>'+ // ' </a>'+ ' </div>'+ '</div>', onClose:function(photobrowser){hideProfile(); viewphotos = false; viewscroll = false; if ($('.chatpop').length > 0) {$( ".chatpop" ).css( "z-index","20000" );if ($('.chatpop').length > 0){myApp.closeModal('.infopopup');} if (swiperQuestions){ swiperQuestions.removeAllSlides(); swiperQuestions.destroy();swiperQuestions = false;} } else{myApp.closeModal(); } if (mainchange){new_all = main_all;singleuserarray = [];} //getPreferences(); }, swipeToClose:false, // onClick:function(swiper, event){showProfile();}, nextButton:'.nextphoto', prevButton:'.prevphoto', onSlideChangeStart:function(swiper){ if (allowedchange){ if (photoresize){ if ($('.infopopup').length > 0){} else{getMeta(new_all[swiper.activeIndex].url); } } if (swiper.activeIndex != openprofile){ photoresize = true;} if (swiper.isBeginning === true){$( ".prevphoto" ).addClass( "disabled" );} else{$( ".prevphoto" ).removeClass( "disabled" );} if (swiper.isEnd === true){$( ".nextphoto" ).addClass( "disabled" );} else{$( ".nextphoto" ).removeClass( "disabled" );} //var windowheight = $( window ).height(); //$( ".photo-browser-slide img").css( "height", "100% - 144px)" ); $( ".photo-browser-caption" ).empty(); $( ".nametag" ).empty(); $( ".datebutton" ).removeClass( "active" ); $( ".duckbutton" ).removeClass( "active" ); $( ".duckbutton" ).addClass( "disabled" ); $( ".datebutton" ).addClass( "disabled" ); $( ".loaderlink" ).show(); $( ".orlink" ).hide(); match = 0; targetid = new_all[myPhotoBrowser.activeIndex].id; $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" ); //$( ".photo-browser-slide.swiper-slide-active img" ).css( "height", "100% - 144px)" ); $( ".duck-template" ).hide(); $( ".date-template" ).hide(); unmatchNavbar(); $( ".toolbardecide" ).show(); $( ".datebutton" ).removeClass( "likesme" ); $( ".duckbutton" ).removeClass( "likesme" ); var activecircle; var targetdescription= new_all[myPhotoBrowser.activeIndex].description; targetname = new_all[myPhotoBrowser.activeIndex].name; var targetage = new_all[myPhotoBrowser.activeIndex].age; $( ".agecat" ).text(targetage); $( ".nametag" ).empty(); $( ".nametag" ).append('<div class="rr r_'+targetid+'">'+targetname+', '+targetage+'</div>'); $( ".photo-browser-caption" ).empty(); $( ".photo-browser-caption" ).append(targetdescription); myApp.sizeNavbars(); } }, backLinkText: '', //expositionHideCaptions:true, navbarTemplate: // ' <a href="#tab1" class="prevphoto button disabled" style="border-radius:5px;position:absolute;left:-31px;top:50%;margin-top:-28px;height:56px;width:56px;border:0;z-index:99999;color:#2196f3;background-color:transparent;"><i class="pe-7s-angle-left pe-4x" style="margin-left:5px;margin-top:-1px;"></i></a>'+ // ' <a href="#tab3" class="nextphoto button" style="border-radius:5px;position:absolute;right:-33px;width:56px;top:50%;margin-top:-26px;height:56px;color:#2186f3;border:0;z-index:99999;background-color:transparent"><i class="pe-7s-angle-right pe-4x" style="margin-left:-35px;margin-top:-1px;"></i></a>'+ // '<div style="position:absolute;bottom:80px;right:0px;margin-left:-26px;z-index:9999;color:white;"><i class="pe-7s-info pe-4x" style="margin-top:-10px;"></i></div>'+ '<div class="navbar photobrowserbar" style="background-color:#ccc">'+ ' <div class="navbar-inner">'+ ' <div class="left sliding">'+ ' <a href="#" style="margin-left:-10px;"class="link photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'+ '<i class="pe-7s-angle-left pe-3x matchcolor"></i>'+ '<span class="badge agecat" style="margin-left:-10px;display:none;">'+arraynumber+'</span>'+ ' </a>'+ ' </div>'+ ' <div class="center sliding nametag matchcolor">'+ // ' <span class="photo-browser-current"></span> '+ // ' <span class="photo-browser-of">{{ofText}}</span> '+ // ' <span class="photo-browser-total"></span>'+ ' </div>'+ ' <div class="right" onclick="actionSheet()">' + //'<a href="#" class="link"><div class="cameradivnum" style="background-color:transparent;border-radius:50%;opacity:0.9;float:left;z-index:999;"><i class="pe-7s-camera pe-lg matchcolor" style="margin-top:3px;margin-left:-5px;"></i><div class="camerabadge badge" style="position:absolute;right:0px;margin-right:-10px;top:5px;z-index:999;"></div></div></a>'+ '<a href="#" class="link">'+ ' <i class="pe-7s-more pe-lg matchcolor"></i>'+ ' </a>'+ '</div>'+ '</div>'+ '</div> ' }); myPhotoBrowser.open(); targetid = new_all[myPhotoBrowser.activeIndex].id; var mySwiperVertical = myApp.swiper('.swiper-vertical', { direction: 'vertical', zoom:'true', pagination:'.swiper-pagination', paginationType:'progress', onSlideChangeStart:function(swiper){ var verticalheightarray = new_all[myPhotoBrowser.activeIndex].heightslides.split(","); var verticalwidtharray = new_all[myPhotoBrowser.activeIndex].widthslides.split(","); var trueh = verticalheightarray[swiper.activeIndex]; var truew = verticalwidtharray[swiper.activeIndex];; if (trueh > truew){ $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','auto'); $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','100%'); $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','cover'); } else if (trueh == trueh){ $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','100%'); $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','auto'); $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','cover'); } else{ $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','100%'); $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','auto'); $( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','none'); } console.log(new_all[myPhotoBrowser.activeIndex]);}, onImagesReady:function(swiper){ console.log(swiper);}, onInit:function(swiper){ //console.log(new_all[myPhotoBrowser.activeIndex]); // if (viewphotos){ setTimeout(function(){ backtoProfile();viewphotos = false; }, 100); } if (viewscroll){ setTimeout(function(){ scrolltoTop();viewscroll = false; }, 100); } }, onClick:function(swiper, event){ questions(); //if(myPhotoBrowser.exposed === true) {$( ".swiper-container-vertical img " ).css("margin-top","0px");} //else {$( ".photo-browser-slide img " ).css("height","calc(100% - 120px)");$( ".photo-browser-slide img " ).css("margin-top","-35px");} } }); //var windowwidth = $( ".photo-browser-swiper-container" ).width(); $( ".photo-browser-slide img" ).css( "-webkit-filter","grayscale(80%)" ); $( ".photo-browser-caption" ).css( "margin-top", "-10px" ); $( ".photo-browser-caption" ).empty(); $( ".nametag" ).empty(); myPhotoBrowser.swiper.slideTo(to_open,100); questions(); if (openprofile ===0){ if (myPhotoBrowser.swiper.isBeginning === true){$( ".prevphoto" ).addClass( "disabled" );} else{$( ".prevphoto" ).removeClass( "disabled" );} if (myPhotoBrowser.swiper.isEnd === true){$( ".nextphoto" ).addClass( "disabled" );} else{$( ".nextphoto" ).removeClass( "disabled" );} //var windowheight = $( window ).height(); //$( ".photo-browser-slide img").css( "height", "100% - 144px)" ); $( ".photo-browser-caption" ).empty(); $( ".nametag" ).empty(); $( ".datebutton" ).removeClass( "active" ); $( ".duckbutton" ).removeClass( "active" ); $( ".duckbutton" ).addClass( "disabled" ); $( ".datebutton" ).addClass( "disabled" ); $( ".loaderlink" ).show(); $( ".orlink" ).hide(); match = 0; var target = new_all[myPhotoBrowser.activeIndex].url; var pretarget = target.replace("https://graph.facebook.com/", ""); targetid = String(pretarget.replace("/picture?width=828", "")); $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" ); //$( ".photo-browser-slide.swiper-slide-active img" ).css( "height", "100% - 144px)" ); $( ".duck-template" ).hide(); $( ".date-template" ).hide(); unmatchNavbar(); $( ".toolbardecide" ).show(); $( ".datebutton" ).removeClass( "likesme" ); $( ".duckbutton" ).removeClass( "likesme" ); var activecircle; var targetdescription= new_all[myPhotoBrowser.activeIndex].description; targetname = new_all[myPhotoBrowser.activeIndex].name; var targetage = new_all[myPhotoBrowser.activeIndex].age; $( ".agecat" ).text(targetage); $( ".nametag" ).empty(); $( ".nametag" ).append('<span class="rr r_'+targetid+'">'+targetname+', '+targetage+'</span>'); $( ".photo-browser-caption" ).empty(); $( ".photo-browser-caption" ).append(targetdescription); myApp.sizeNavbars(); //may need to readd } } function showProfile(){ $( ".profile-info" ).show(); } function hideProfile(){ $( ".profile-info" ).hide(); } function dateRequest(){ $( ".dateheader" ).hide(); $( ".date-close" ).hide(); $( ".date-button" ).hide(); var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var ref = firebase.database().ref(); var datemessageq = $( '#datemessageq' ).val(); var unix = Math.round(+new Date()/1000); var day = pickerCustomToolbar.cols[0].displayValue; var time; if (pickerCustomToolbar.cols[0].displayValue =='Now'){time='';} else if (pickerCustomToolbar.cols[0].displayValue =='Today'){ var daterequestnow = new Date; var hournow = daterequestnow.getHours(); if((pickerCustomToolbar.cols[0].displayValue =='Morning') && (hournow >= '12')){time='';} else if((pickerCustomToolbar.cols[0].displayValue =='Mid-day') && (hournow > '14')){time='';} else if((pickerCustomToolbar.cols[0].displayValue =='Afternoon') && (hournow > '17')){time='';} else{time = pickerCustomToolbar.cols[1].value;} } else{time = pickerCustomToolbar.cols[1].value;} var chat_expire = pickerCustomToolbar.cols[0].value; var interestarray = []; if (d_type == 'date'){ $( ".interestbutton" ).each(function() { if ($( this ).hasClass( "interestchosen" )) { var classList = $(this).attr("class").split(' '); var interestadd = classList[1].split('_')[0]; interestarray.push(interestadd); } }); } if (d_type == 'duck'){ if ($( '.button-my' ).hasClass( "active" )){interestarray = 'my'} if ($( '.button-your' ).hasClass( "active" )){interestarray = 'your'} } firebase.database().ref("dates/" + f_uid +'/' + targetid).set({ created_uid: f_uid, created_name: f_first, received_uid:targetid, received_name:targetname, timestamp:unix, day:day, time:time, chat_expire:chat_expire, seen:'N', interest:interestarray, response:'W', type:d_type, message:datemessageq, authcheck:f_uid }); firebase.database().ref("dates/" + targetid +'/' + f_uid).set({ created_uid: f_uid, created_name: f_first, received_uid:targetid, received_name:targetname, timestamp:unix, day:day, time:time, chat_expire:chat_expire, seen:'N', interest:interestarray, response:'W', type:d_type, message:datemessageq, authcheck:f_uid }); var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) { var objs = snapshot.val(); var messageq; //If existing notifications, get number of unseen messages, delete old notifications if (snapshot.val()){ $.each(objs, function(i, obj) { if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){ firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove(); firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove(); if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){ messageq = obj.new_message_count; messageq ++; } } }); } newNotification(); }); function newNotification(messagenum){ if (!messagenum) {messagenum = 1;} var smessage; if (d_type=='duck'){smessage = 'Duck request'} if (d_type=='date'){smessage = 'Date request'} // Get a key for a new Post. var newPostKey = firebase.database().ref().push().key; var t_unix = Math.round(+new Date()/1000); var targetData = { id:newPostKey, from_uid: f_uid, from_name: f_first, to_uid:targetid, to_name:targetname, message:smessage, timestamp: t_unix, type:d_type, param:'daterequest', new_message_count:messagenum, received:'N', expire:d_chat_expire, authcheck:f_uid }; // Write the new post's data simultaneously in the posts list and the user's post list. var updates = {}; updates['notifications/' + f_uid + '/' + targetid] = targetData; updates['notifications/' + targetid + '/' + f_uid] = targetData; return firebase.database().ref().update(updates).then(function() { if(d_response=='Y') {chatShow();} else {reverseRequest();} }); } } var d_interest,d_day,d_chat_expire,d_time,d_response,d_type,d_timestamp,d_dateseen,d_dateseentime,d_timeaccepted; function existingDate(){ $( ".datearea" ).empty(); var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} // Test if user exists var ref = firebase.database().ref("dates/" + f_uid +'/' + targetid); ref.once("value") .then(function(snapshot) { var dateexists = snapshot.child('chat_expire').exists(); // true if (dateexists) { var unix = Math.round(+new Date()/1000); if (Number(snapshot.child('chat_expire').val()) > Number(unix) ) { d_chat_expire = snapshot.child('chat_expire').val(); d_interest = snapshot.child('interest').val(); d_type = snapshot.child('type').val(); d_day = snapshot.child('day').val(); d_time = snapshot.child('time').val(); d_response = snapshot.child('response').val(); if (snapshot.child('time_accepted').exists()){ d_timeaccepted = snapshot.child('time_accepted').val();} d_created_uid = snapshot.child('created_uid').val(); d_timestamp = snapshot.child('timestamp').val(); d_dateseen = snapshot.child('dateseen').val(); d_dateseentime = snapshot.child('dateseentime').val(); d_message = snapshot.child('message').val(); if (d_response == 'Y') {chatShow();} else { noMessages(); setDate(); dateConfirmationPage(); } $( ".messages-loader" ).hide(); } else{ cancelDate(); //$( ".center-date" ).empty(); //$( ".center-date" ).append(targetname); myApp.sizeNavbars(); $( ".messages-loader" ).hide(); } } else{ d_chat_expire = false; d_interest = false; d_day = false; d_time = false; d_response = false; d_message = false; d_timeaccepted; d_dateseen = false; d_dateseentime = false; d_timestamp = false; noMessages(); setDate(); // $( ".center-date" ).empty(); //$( ".center-date" ).append(targetname); myApp.sizeNavbars(); $( ".messages-loader" ).hide(); } }); } function interests(id){ $( "." + id + "_i" ).toggleClass( "interestchosen" ); } function sendMessage(){ var weekday = []; weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; var month = []; month[0] = "Jan"; month[1] = "Feb"; month[2] = "Mar"; month[3] = "Apr"; month[4] = "May"; month[5] = "Jun"; month[6] = "Jul"; month[7] = "Aug"; month[8] = "Sep"; month[9] = "Oct"; month[10] = "Nov"; month[11] = "Dec"; var stringnow = new Date(); var stringyestday = new Date(Date.now() - 86400); var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate(); var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate(); var datechatstring; var messagedate = new Date(); var minstag = ('0'+messagedate.getMinutes()).slice(-2); messagetimetitle = messagedate.getHours() + ':' + minstag; var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate(); if (!prevdatetitle){prevdatetitle = messagedaytitle;console.log('prevdatetitle does not exist'); if (messagedaytitle == todaystring){datechatstring = 'Today';} else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';} else{datechatstring = messagedaytitle;} } else { if (prevdatetitle == messagedaytitle){console.log('it is the same day');datechatstring='';} else{console.log('it is a different day');prevdatetitle = messagedaytitle; if (messagedaytitle == todaystring){datechatstring = 'Today';} else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';} else{datechatstring = messagedaytitle;} } } var newmessage = $( "#messagearea" ).val(); if (newmessage === ''){return false;} conversation_started = true; var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var t_unix = Math.round(+new Date()/1000); firebase.database().ref("chats/" + first_number+ '/' + second_number).push({ from_uid: f_uid, from_name: f_first, to_uid:targetid, to_name:targetname, message:newmessage, seen:'N', timestamp: t_unix, type: d_type, param:'message', authcheck:f_uid }); myMessages.addMessage({ // Message text text: newmessage, // Random message type type: 'sent', // Avatar and name: avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal', name: f_first, day:datechatstring, label: 'Sent ' + messagetimetitle }); myMessagebar.clear(); var messageq; var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) { var objs = snapshot.val(); //If existing notifications, get number of unseen messages, delete old notifications if (snapshot.val()){ //alert('yo3'); $.each(objs, function(i, obj) { if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){ //alert(obj.param); // alert(obj.received); if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){ // alert('param'+obj.param); // alert('new_message_count'+obj.new_message_count); if (obj.param =='message'){ messageq = obj.new_message_count; messageq ++;} else{ messageq = 1; } } firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove(); firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove(); } }); } newNotification(messageq); }); function newNotification(messagenum){ //alert('messagenum'+messagenum); if (!messagenum) {messagenum = 1;} //alert(messagenum); // Get a key for a new Post. var newPostKey = firebase.database().ref().push().key; var targetData = { id:newPostKey, from_uid: f_uid, from_name: f_first, to_uid:targetid, to_name:targetname, message:newmessage, timestamp: t_unix, type:d_type, param:'message', new_message_count:messagenum, received:'N', expire:d_chat_expire, authcheck:f_uid }; // Write the new post's data simultaneously in the posts list and the user's post list. var updates = {}; updates['notifications/' + f_uid + '/' + targetid] = targetData; updates['notifications/' + targetid + '/' + f_uid] = targetData; return firebase.database().ref().update(updates); } $( "#messagearea" ).val(''); $( ".sendbutton" ).removeClass('disabled'); $( ".sendbutton" ).css('color','white'); } function clearchatHistory(){ messages_loaded = false; if (main_all[0] != null){ new_all = main_all; } singleuserarray = []; letsload = 20; var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} if (message_history){ //firebase.database().ref("notifications/" + f_uid).off('value', existingchatnotifications); firebase.database().ref("chats/" + first_number+ '/' + second_number).off('child_added', message_historyon); if(additions>0){ for (i = 0; i < additions.length; i++) { firebase.database().ref("chats/" + first_number+ '/' + second_number).off('child_added', newmessage_history); } } message_history = false; message_count = 0; additions = 0; existingmessages = false; conversation_started = false; myMessages.clean(); myMessages.destroy(); } if (datealertvar === true){ firebase.database().ref("dates/" + f_uid +'/' + targetid).off('value', datealert); } datealertvar = false; if ($$('body').hasClass('with-panel-left-reveal')) { $(".timeline").empty(); rightPanel(); } if ($$('body').hasClass('with-panel-right-reveal')) { myList.deleteAllItems(); myList.clearCache(); leftPanel(); } } function dateConfirmationPage(details){ canloadchat = false; var g = new Date(d_chat_expire*1000 - 3600); var weekday = []; weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; var gday = weekday[g.getDay()]; var proposeddate = g.getDate(); var month = []; month[0] = "January"; month[1] = "February"; month[2] = "March"; month[3] = "April"; month[4] = "May"; month[5] = "June"; month[6] = "July"; month[7] = "August"; month[8] = "September"; month[9] = "October"; month[10] = "November"; month[11] = "December"; var messageclass; if (d_created_uid == f_uid){messageclass="message-sent";messagestyle="";} else{messageclass = "message-received";messagestyle="margin-left:70px;";} var proposedmonth = month[g.getMonth()]; var proposedyear = g.getFullYear(); var dending; if (proposeddate == '1' || proposeddate == '21' || proposeddate == '31'){dending = 'st'} else if (proposeddate == '2' || proposeddate == '22'){dending = 'nd'} else if (proposeddate == '3' || proposeddate == '23'){dending = 'rd'} else {dending = 'th'} $( ".dateheader" ).hide(); $( ".profileroundpic" ).show(); $( ".date1-close" ).hide(); $( ".date2-close" ).hide(); $( ".message-inner" ).hide(); $( ".date-inner" ).hide(); $( ".date-back" ).show(); var timedisplay; // $( ".center-date" ).empty(); //$( ".center-date" ).append(targetname.capitalize()); var titleblock; var namefromdate; var nametodate; if (d_created_uid == f_uid){namefromdate = f_first;nametodate = targetname;} else{nametodate = f_first;namefromdate = targetname;} var whatrow; var dateseentitle; var timestamptitle; var capitalD; if (d_type =='duck'){titleblock = '<span style="font-family: \'Pacifico\', cursive;">Duck Request</span>';whatrow = 'Duck';capitalD = 'Duck';} if (d_type =='date'){titleblock = '<span style="font-family: \'Pacifico\', cursive;">Date Request</span>';whatrow = 'Date';capitalD = 'Date';} var unixnow = Math.round(+new Date()/1000); var tunixago = unixnow - d_timestamp; var tunixminago = tunixago / 60; if (tunixminago < 1) {timestamptitle = 'Sent less than 1 minute ago';} else if (tunixminago == 1) {timestamptitle = 'Sent 1 minute ago';} else if (tunixminago < 2) {timestamptitle = 'Sent 1 minute ago';} else if (tunixminago < 60) {timestamptitle = 'Sent '+Math.round(tunixminago)+' minutes ago';} else if (tunixminago == 60) {timestamptitle = 'Sent 1 hour ago';} else if (tunixminago < 62) {timestamptitle = 'Sent 1 hour ago';} else if (tunixminago < 1440) {timestamptitle = 'Sent '+Math.round(tunixminago / 60) +' hours ago';} else if (tunixminago == 1440) {timestamptitle = 'Sent 1 day ago';} else if (tunixminago < 2880) {timestamptitle = 'Sent 1 day ago';} else if (tunixminago >= 2880) {timestamptitle = 'Sent '+Math.round(tunixminago / 1440) +' days ago';} if (d_dateseen){ var unixago = unixnow - d_dateseentime; var unixminago = unixago / 60; if (unixminago < 1) {dateseentitle = 'Seen less than 1 minute ago';} else if (unixminago == 1) {dateseentitle = 'Seen 1 minute ago';} else if (unixminago < 2) {dateseentitle = 'Seen 1 minute ago';} else if (unixminago < 60) {dateseentitle = 'Seen '+Math.round(unixminago)+' minutes ago';} else if (unixminago == 60) {dateseentitle = 'Seen 1 hour ago';} else if (unixminago < 62) {dateseentitle = 'Seen 1 hour ago';} else if (unixminago < 1440) {dateseentitle = 'Seen '+Math.round(unixminago / 60) +' hours ago';} else if (unixminago == 1440) {dateseentitle = 'Seen 1 day ago';} else if (unixminago < 2880) {dateseentitle = 'Seen 1 day ago';} else if (unixminago >= 2880) {dateseentitle = 'Seen '+Math.round(unixminago / 1440) +' days ago';} } else{dateseentitle = 'Request not seen yet';} myApp.sizeNavbars(); var messagedateblock; if (d_message){ messagedateblock='<li><div class="item-content"><div class="item-inner"><div class="messages-content"><div class="messages messages-init" data-auto-layout="true" style="width:100%;clear:both;"> <div class="item-title label" style="width:80px;float:left;margin-top:10px;text-align:left;">Message</div><div class="message '+messageclass+' message-with-avatar message-appear-from-top message-last message-with-tail" style="'+messagestyle+'clear:both;text-align:left;"><div class="message-text">'+d_message+'</div><div class="message-avatar" style="background-image:url(https://graph.facebook.com/'+d_created_uid+'/picture?type=normal)"></div></div></div></div></div></div></li><li style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'; } else {messagedateblock='';} if (d_time) {timedisplay = ', ' + d_time} else {timedisplay='';} if (details){ var junixago = unixnow - d_timeaccepted; var junixminago = junixago / 60; var acceptedtitle; if (junixminago < 1) {acceptedtitle = 'Confirmed less than 1 minute ago';} else if (junixminago == 1) {acceptedtitle = 'Confirmed 1 minute ago';} else if (junixminago < 2) {acceptedtitle = 'Confirmed 1 minute ago';} else if (junixminago < 60) {acceptedtitle = 'Confirmed '+Math.round(junixminago)+' minutes ago';} else if (junixminago == 60) {acceptedtitle = 'Confirmed 1 hour ago';} else if (junixminago < 62) {acceptedtitle = 'Confirmed 1 hour ago';} else if (junixminago < 1440) {acceptedtitle = 'Confirmed '+Math.round(junixminago / 60) +' hours ago';} else if (junixminago == 1440) {acceptedtitle = 'Confirmed 1 day ago';} else if (junixminago < 2880) {acceptedtitle = 'Confirmed 1 day ago';} else if (junixminago >= 2880) {acceptedtitle = 'Confirmed '+Math.round(junixminago / 1440) +' days ago';} $( ".date1-close" ).hide(); $( ".date2-close" ).show(); $( ".date-close" ).hide(); $( ".date-back" ).hide(); $( ".datetoolbar" ).show(); $( ".sender-inner" ).show(); $( ".yes-inner" ).hide(); //$( ".datetoolbar" ).css("background-color","#ccc"); $( ".waitingreply" ).empty(); $( ".datedetailsdiv" ).hide(); $( ".requestbutton" ).remove(); $( ".requesticon" ).remove(); $( ".waitingreply" ).append( '<div style="background-color:#4cd964;padding:10px;text-align:center;font-size:20px;color:white;"><span style="font-family: \'Pacifico\', cursive;">'+capitalD+' Details</span></div>'+ '<div class="list-block media-list" onclick="request();" style="margin-top:0px;"><ul style="background-color:white;padding-bottom:10px;">'+ '<img src="media/'+d_type+'faceonly.png" style="height:60px;margin-top:15px;">'+ '<li>'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label" style="width:70px;float:left;text-align:left;">When?</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<input type="text" name="name" value="'+gday+timedisplay+'" readonly>'+ '<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+proposeddate + dending + ' '+ proposedmonth + ' ' + proposedyear +'" readonly>'+ '</div>'+ ' </div></div>'+ ' </li>'+ '<li class="interestli" style="display:none;">'+ '<div class="item-content">'+ ' <div class="item-inner" style="padding-top:15px;padding-bottom:15px;">'+ ' <div class="item-title label" style="float:left;width:70px;text-align:left;">Where?</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<span class="interestdiv" style="float:left;text-align:center;"></span>'+ '</div>'+ '</div>'+ '</div>'+ ' </li>'+ '<li class="interestli" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+ '<li>'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label" style="width:70px;float:left;text-align:left;">From</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<input type="text" name="name" value="'+namefromdate+'" readonly>'+ '<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+timestamptitle+'" readonly>'+ '</div>'+ ' </div></div>'+ ' </li>'+ messagedateblock + '<li>'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label" style="width:70px;float:left;text-align:left;">To</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<input type="text" name="name" value="'+nametodate+'" readonly>'+ '<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+acceptedtitle+'" readonly>'+ '</div>'+ ' </div></div>'+ ' </li>'+ '<li class="" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+ '</ul>'+ '</div>' ); $( ".titleconfirm" ).show(); $( ".titleconfirm" ).html(capitalD + ' confirmed'); $( ".infoconfirm" ).html('You can continue chatting until midnight of your scheduled '+d_type); } else if (d_created_uid == f_uid) { $( ".datetoolbar" ).show(); $( ".sender-inner" ).show(); $( ".yes-inner" ).hide(); //$( ".datetoolbar" ).css("background-color","#ccc"); $( ".waitingreply" ).empty(); $( ".datedetailsdiv" ).hide(); $( ".requestbutton" ).remove(); $( ".requesticon" ).remove(); $( ".titleconfirm" ).show(); $( ".titleconfirm" ).html('Waiting for '+targetname+' to respond'); $( ".waitingreply" ).append( '<div style="background-color:#ff9500;padding:10px;text-align:center;font-size:20px;color:white;">'+titleblock+'</div>'+ '<div class="list-block media-list" onclick="request();" style="margin-top:0px;"><ul style="background-color:white;padding-bottom:10px;">'+ '<img src="media/'+d_type+'faceonly.png" style="height:60px;margin-top:15px;">'+ '<li>'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label" style="width:70px;float:left;text-align:left;">When?</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<input type="text" name="name" value="'+gday+timedisplay+'" readonly>'+ '<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+proposeddate + dending + ' '+ proposedmonth + ' ' + proposedyear +'" readonly>'+ '</div>'+ ' </div></div>'+ ' </li>'+ '<li class="interestli" style="display:none;">'+ '<div class="item-content">'+ ' <div class="item-inner" style="padding-top:15px;padding-bottom:15px;">'+ ' <div class="item-title label" style="float:left;width:70px;text-align:left;">Where?</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<span class="interestdiv" style="float:left;text-align:center;"></span>'+ '</div>'+ '</div>'+ '</div>'+ ' </li>'+ '<li class="interestli" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+ '<li>'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label" style="width:70px;float:left;text-align:left;">From</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<input type="text" name="name" value="'+namefromdate+'" readonly>'+ '<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+timestamptitle+'" readonly>'+ '</div>'+ ' </div></div>'+ ' </li>'+ messagedateblock + '<li>'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label" style="width:70px;float:left;text-align:left;">To</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<input type="text" name="name" value="'+nametodate+'" readonly>'+ '<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+dateseentitle+'" readonly>'+ '</div>'+ ' </div></div>'+ ' </li>'+ '<li class="" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+ '</ul>'+ '</div>' ); } else{ if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var unix = Math.round(+new Date()/1000); firebase.database().ref("dates/" + f_uid +'/' + targetid).update({ dateseen:'Y', dateseentime:unix }); firebase.database().ref("dates/" + targetid +'/' + f_uid).update({ dateseen:'Y', dateseentime:unix }); firebase.database().ref("notifications/" + f_uid +'/' + targetid).update({ dateseen:'Y', dateseentime:unix }); firebase.database().ref("notifications/" + targetid +'/' + f_uid).update({ dateseen:'Y', dateseentime:unix }); $( ".datetoolbar" ).show(); $( ".sender-inner" ).hide(); $( ".yes-inner" ).show(); $( ".waitingreply" ).empty(); $( ".datedetailsdiv" ).hide(); $( ".requestbutton" ).remove(); $( ".requesticon" ).remove(); $( ".titleconfirm" ).show(); $( ".titleconfirm" ).html(targetname+' is waiting for your response'); $( ".waitingreply" ).append( '<div style="background-color:#ff9500;padding:10px;text-align:center;font-size:20px;color:white;">'+titleblock+'</div>'+ '<div class="list-block media-list" onclick="request();" style="margin-top:0px;"><ul style="background-color:white;padding-bottom:10px;">'+ '<img src="media/'+d_type+'faceonly.png" style="height:60px;margin-top:15px;">'+ '<li>'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label" style="width:70px;float:left;text-align:left;">When?</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<input type="text" name="name" value="'+gday+timedisplay+'" readonly>'+ '<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+proposeddate + dending + ' '+ proposedmonth + ' ' + proposedyear +'" readonly>'+ '</div>'+ ' </div></div>'+ ' </li>'+ '<li class="interestli" style="display:none;">'+ '<div class="item-content">'+ ' <div class="item-inner" style="padding-top:15px;padding-bottom:15px;">'+ ' <div class="item-title label" style="float:left;width:70px;text-align:left;">Where?</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<span class="interestdiv" style="float:left;text-align:center;"></span>'+ '</div>'+ '</div>'+ '</div>'+ ' </li>'+ '<li class="interestli" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+ '<li>'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label" style="width:70px;float:left;text-align:left;">From</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<input type="text" name="name" value="'+namefromdate+'" readonly>'+ '<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+timestamptitle+'" readonly>'+ '</div>'+ ' </div></div>'+ ' </li>'+ messagedateblock + '<li>'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label" style="width:70px;float:left;text-align:left;">To</div>'+ '<div class="item-input" style="float:left;width:calc(100% - 80px);">'+ '<input type="text" name="name" value="'+nametodate+'" readonly>'+ '<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+dateseentitle+'" readonly>'+ '</div>'+ ' </div></div>'+ ' </li>'+ '<li class="" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+ '</ul>'+ '</div>' ); } if (d_interest && d_type =='duck'){ $( ".interestli").show(); if ((d_interest == 'my') && (d_created_uid == f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+f_first+'\'s place </div>');} if ((d_interest == 'my') && (d_created_uid != f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+targetname+'\'s place </div>');} if ((d_interest == 'your') && (d_created_uid == f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+targetname+'\'s place </div>');} if ((d_interest == 'your') && (d_created_uid != f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+f_first+'\'s place </div>');} } if (d_interest && d_type =='date'){ for (i = 0; i < d_interest.length; i++) { $( ".interestli").show(); $( ".interestdiv").append('<a href="#" style="margin-right:5px"><i class="twa twa-2x twa-'+d_interest[i]+'" style="margin-top:5px;margin-right:5px"></i></a>'); } } } function acceptDate(){ var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var unix = Math.round(+new Date()/1000); $( ".sender-inner" ).hide(); $( ".yes-inner" ).hide(); var datemessageq = $( '#datemessageq' ).val(); var unix = Math.round(+new Date()/1000); var day = pickerCustomToolbar.cols[0].displayValue; var time; if (pickerCustomToolbar.cols[0].displayValue =='Now'){time='';} else if (pickerCustomToolbar.cols[0].displayValue =='Today'){ var daterequestnow = new Date; var hournow = daterequestnow.getHours(); if((pickerCustomToolbar.cols[0].displayValue =='Morning') && (hournow >= '12')){time='';} else if((pickerCustomToolbar.cols[0].displayValue =='Mid-day') && (hournow > '14')){time='';} else if((pickerCustomToolbar.cols[0].displayValue =='Afternoon') && (hournow > '17')){time='';} else{time = pickerCustomToolbar.cols[1].value;} } else{time = pickerCustomToolbar.cols[1].value;} var chat_expire = pickerCustomToolbar.cols[0].value; var interestarray = []; if (d_type == 'date'){ $( ".interestbutton" ).each(function() { if ($( this ).hasClass( "interestchosen" )) { var classList = $(this).attr("class").split(' '); var interestadd = classList[1].split('_')[0]; interestarray.push(interestadd); } }); } if (d_type == 'duck'){ if ($( '.button-my' ).hasClass( "active" )){interestarray = 'my'} if ($( '.button-your' ).hasClass( "active" )){interestarray = 'your'} } firebase.database().ref("dates/" + f_uid +'/' + targetid).update({ response: 'Y', time_accepted: unix, uid_accepted: f_uid, authcheck:f_uid }); firebase.database().ref("dates/" + targetid +'/' + f_uid).update({ response: 'Y', time_accepted: unix, uid_accepted: f_uid, authcheck:f_uid }); var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) { var objs = snapshot.val(); var messageq; //If existing notifications, get number of unseen messages, delete old notifications console.log(snapshot.val()); if (snapshot.val()){ $.each(objs, function(i, obj) { if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){ messageq = obj.new_message_count; console.log(messageq); messageq ++; } }); } newNotification(); }); function newNotification(messagenum){ if (!messagenum) {messagenum = 1;} // Get a key for a new Post. var newPostKey = firebase.database().ref().push().key; var t_unix = Math.round(+new Date()/1000); var targetData = { id:newPostKey, from_uid: f_uid, from_name: f_first, to_uid:targetid, to_name:targetname, message:'Date scheduled', timestamp: t_unix, type:d_type, param:'dateconfirmed', new_message_count:messagenum, received:'N', expire:d_chat_expire, authcheck:f_uid }; // Write the new post's data simultaneously in the posts list and the user's post list. var updates = {}; updates['notifications/' + f_uid + '/' + targetid] = targetData; updates['notifications/' + targetid + '/' + f_uid] = targetData; return firebase.database().ref().update(updates).then(function() {chatShow();}); } } function cancelDate(){ // Create a reference to the file to delete $( ".dateheader" ).hide(); $( ".sender-inner" ).hide(); var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} // Delete the file firebase.database().ref("dates/" + f_uid +'/' + targetid).remove().then(function() { // File deleted successfully $( ".datearea" ).empty(); d_chat_expire = false; d_interest = false; d_day = false; d_time = false; d_response = false; d_timeaccepted = false; d_created_uid = false; d_timestamp = false; d_dateseen = false; d_dateseentime = false; d_message = false; noMessages(); setDate(); console.log('deleted'); }).catch(function(error) { // Uh-oh, an error occurred! }); // Delete the file firebase.database().ref("dates/" + targetid +'/' + f_uid).remove().then(function() { // File deleted successfully console.log('deleted'); }).catch(function(error) { // Uh-oh, an error occurred! }); var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) { var objs = snapshot.val(); var messageq; //If existing notifications, get number of unseen messages, delete old notifications if (snapshot.val()){ $.each(objs, function(i, obj) { if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){ messageq = obj.new_message_count; messageq ++; } }); } newNotification(); }); function newNotification(messagenum){ if (!messagenum) {messagenum = 1;} var smessage; if (d_type=='duck'){smessage = 'Duck request deleted'} if (d_type=='date'){smessage = 'Date request deleted'} // Get a key for a new Post. var newPostKey = firebase.database().ref().push().key; var t_unix = Math.round(+new Date()/1000); var targetData = { id:newPostKey, from_uid: f_uid, from_name: f_first, to_uid:targetid, to_name:targetname, message:smessage, timestamp: t_unix, type:d_type, param:'datedeleted', new_message_count:messagenum, received:'N', expire:d_chat_expire, authcheck:f_uid }; // Write the new post's data simultaneously in the posts list and the user's post list. var updates = {}; updates['notifications/' + f_uid + '/' + targetid] = targetData; updates['notifications/' + targetid + '/' + f_uid] = targetData; return firebase.database().ref().update(updates).then(function() { console.log('delete notification sent'); }); } } function getPicture(key){ var weekday = []; weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; var month = []; month[0] = "Jan"; month[1] = "Feb"; month[2] = "Mar"; month[3] = "Apr"; month[4] = "May"; month[5] = "Jun"; month[6] = "Jul"; month[7] = "Aug"; month[8] = "Sep"; month[9] = "Oct"; month[10] = "Nov"; month[11] = "Dec"; var stringnow = new Date(); var stringyestday = new Date(Date.now() - 86400); var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate(); var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate(); var datechatstring; var messagedate = new Date(); var minstag = ('0'+messagedate.getMinutes()).slice(-2); messagetimetitle = messagedate.getHours() + ':' + minstag; var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate(); if (!prevdatetitle){prevdatetitle = messagedaytitle;console.log('prevdatetitle does not exist'); if (messagedaytitle == todaystring){datechatstring = 'Today';} else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';} else{datechatstring = messagedaytitle;} } else { if (prevdatetitle == messagedaytitle){console.log('it is the same day');datechatstring='';} else{console.log('it is a different day');prevdatetitle = messagedaytitle; if (messagedaytitle == todaystring){datechatstring = 'Today';} else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';} else{datechatstring = messagedaytitle;} } } var t_unix = Math.round(+new Date()/1000); var returned = 0; var postkeyarray = []; var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var eventy = document.getElementById('takePictureField_').files[0]; // var number_of_pictures = $(".imageli").length + 1; if (eventy == 'undefined') {console.log('undefined');} if (eventy !== 'undefined') { for (i = 0; i < document.getElementById('takePictureField_').files.length; i++) { var photoname = t_unix + i; var newValue = firebase.database().ref().push().key; postkeyarray.push(newValue); myMessages.addMessage({ // Message text text: '<img src="'+URL.createObjectURL($('#takePictureField_').prop('files')[i])+'" onload="$(this).fadeIn(700);scrollBottom();" onclick="imagesPopup('+image_count+');" style="display:none">', // Random message type type: 'sent', // Avatar and name: avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal', name: f_first, day:datechatstring, label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle }); //$("#dealimagediv_"+imagenumber).attr("src",URL.createObjectURL(eventy)); image_count ++; //$('.image_' + t_unix).onclick = function(){ // openPhoto(url);}; //var randomstring = (Math.random() +1).toString(36).substr(2, 30); var photochatspath = 'photochats/' + first_number + '/' + second_number + '/'+ photoname; var photostorage = 'images/' + f_auth_id + '/' + photoname; var photochatsRef = storageRef.child(photostorage); photochatsRef.put($('#takePictureField_').prop('files')[i]).then(function(snapshot) { alert(snapshot.metadata.name); var photodownloadstorage = 'images/' + f_auth_id + '/' + snapshot.metadata.name; var photodownloadRef = storageRef.child(photodownloadstorage); photodownloadRef.getDownloadURL().then(function(url) { returned ++; alert(returned + ',' + postkeyarray[(returned-1)]); var newPostKey = postkeyarray[(returned-1)]; conversation_started = true; var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var chatvar = { id:newPostKey, from_uid: f_uid, from_name: f_first, to_uid:targetid, to_name:targetname, message:'<img src="'+url+'" onload="$(this).fadeIn(700);" style="display:none" >', seen:'N', timestamp: snapshot.metadata.name, type:d_type, param:'image', downloadurl:url, first_number:first_number, second_number:second_number }; var photovar1 = { id:newPostKey, uid: f_uid, user_name: f_first, photo_name:photostorage, downloadurl:url, to_uid:targetid, from_uid: f_uid, first_number:first_number, second_number:second_number, folder:f_auth_id }; var photovar2 = { id:newPostKey, uid: f_uid, user_name: f_first, downloadurl:url, to_uid:targetid, from_uid: f_uid, first_number:first_number, second_number:second_number }; firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + newPostKey).set(chatvar); firebase.database().ref("photostodelete/" + f_uid + '/' + targetid + '/' + newPostKey).set(photovar1); firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + newPostKey).set(photovar2); }); }); } var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) { var objs = snapshot.val(); var messageq; //If existing notifications, get number of unseen messages, delete old notifications if (snapshot.val()){ $.each(objs, function(i, obj) { if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){ firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove(); firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove(); console.log(obj.received); console.log(obj.from_uid); if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){ messageq = obj.new_message_count; messageq ++; } } }); } newpictureNotification(messageq); }); } function newpictureNotification(messagenum){ if (!messagenum) {messagenum = 1;} // Get a key for a new Post. var newPostKey = firebase.database().ref().push().key; var targetData = { id:newPostKey, from_uid: f_uid, from_name: f_first, to_uid:targetid, to_name:targetname, message:'Image ', timestamp: t_unix, type:d_type, param:'image', new_message_count:messagenum, received:'N', expire:d_chat_expire, authcheck:f_uid }; // Write the new post's data simultaneously in the posts list and the user's post list. var updates = {}; updates['notifications/' + f_uid + '/' + targetid] = targetData; updates['notifications/' + targetid + '/' + f_uid] = targetData; return firebase.database().ref().update(updates); } } function toTimestamp(year,month,day,hour,minute,second){ var datum = new Date(Date.UTC(year,month-1,day,hour,minute,second)); return datum.getTime()/1000; } var photoarray; function showPhotos(){ photoarray= []; myApp.pickerModal( '<div class="picker-modal photo-picker" style="height:132px;">' + '<div class="toolbar" style="background-color:#2196f3">' + '<div class="toolbar-inner">' + '<div class="left"></div>' + '<div class="right"><a href="#" class="close-picker" style="color:white;">Close</a></div>' + '</div>' + '</div>' + '<div class="picker-modal-inner" style="background-color:#2196f3">' + '<div class="content-block" style="margin:0px;padding:0px;">' + '<div class="swiper-container swiper-photos">'+ '<div class="swiper-wrapper wrapper-photos">'+ ' <div class="swiper-slide" style="text-align:center;margin:-5px;height:88px;">'+ '<i class="pe-7s-plus pe-3x" style="color:white;margin-top:10px;"></i>'+ ' <input type="file" size="70" accept="image/*" class="dealPictureField imagenotchosen" id="takePictureField_" onchange="getPicture();" style="background-color:transparent;color:transparent;float:left;cursor: pointer;height:60px;width:100%;z-index:1;opacity:0;background-color:red;height:88px;margin-top:-44px;" multiple="multiple"> '+ '</div>'+ '</div>'+ '</div>'+ '</div>' + '</div>' + '</div>' ); var photosswiper = myApp.swiper('.swiper-photos', { slidesPerView:3, freeMode:true, preloadImages: false, // Enable lazy loading lazyLoading: true, watchSlidesVisibility:true //pagination:'.swiper-pagination' }); firebase.database().ref("photos/" + f_uid).once('value').then(function(snapshot) { var childcount = 0; snapshot.forEach(function(childSnapshot) { // key will be "ada" the first time and "alan" the second time //var key = childSnapshot.key; // childData will be the actual contents of the child childcount ++; var childData = childSnapshot.val(); photoarray.push(childSnapshot.val()); $( ".wrapper-photos" ).append('<div onclick="sendphotoExisting(\''+childData.downloadurl+'\',\''+childData.filename+'\')" data-background="'+childData.downloadurl+'" style="border:1px solid black;margin:-5px;height:88px;background-size:cover;background-position:50% 50%;" class="swiper-slide swiper-lazy">'+ ' <div class="swiper-lazy-preloader"></div>'+ '</div>'); if (childcount == snapshot.numChildren()){ photosswiper.updateSlidesSize(); photosswiper.slideTo(snapshot.numChildren()); // photosswiper.slideTo(0); } }); }); } function sendphotoExisting(oldurl,filenamez){ conversation_started = true; var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var t_unix = Math.round(+new Date()/1000); myMessages.addMessage({ // Message text text: '<img src="'+oldurl+'" onload="scrollBottom();">', // Random message type type: 'sent', // Avatar and name: avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal', name: f_first // Day // day: !conversationStarted ? 'Today' : false, // time: !conversationStarted ? (new Date()).getHours() + ':' + (new Date()).getMinutes() : false }); firebase.database().ref("chats/" + first_number+ '/' + second_number).push({ from_uid: f_uid, from_name: f_first, to_uid:targetid, to_name:targetname, message:'<img src="'+oldurl+'" onload="scrollBottom();">', seen:'N', timestamp: t_unix, type:d_type, param:'image', filename:filenamez }); myApp.closeModal('.photo-picker'); } (function($){ $.fn.imgLoad = function(callback) { return this.each(function() { if (callback) { if (this.complete || /*for IE 10-*/ $(this).height() > 0) { callback.apply(this); } else { $(this).on('load', function(){ callback.apply(this); }); } } }); }; })(jQuery); var xcountdown; function imagesPopup(go){ var popupHTML = '<div class="popup gallery-popupz">'+ '<div class="navbar" style="position:absolute;top:0;background-color:#2196f3;color:white;">'+ ' <div class="navbar-inner">'+ ' <div class="left"><a href="#" onclick="closeGallery();" class="link icon-only"><i class="pe-7s-angle-left pe-3x" style="margin-left:-10px;color:white;"></i> </a></div>'+ ' <div class="center gallerytitle"></div>'+ ' <div class="right photo-count"></div>'+ '</div>'+ '</div>'+ '<div class="pages">'+ '<div data-page="gallerypopup" class="page">'+ '<div class="page-content" style="background-color:white;">'+ '<div style="position:absolute;bottom:12px;right:8px;z-index:99999;background-color:white;border-radius:5px;padding:5px;"><div id="photodeletechattime" style="color:black;float:left;"></div></div>'+ '<span style="width:42px; height:42px;position:absolute;top:50%;margin-top:-21px;left:50%;margin-left:-21px;z-index:999999;" class="imagespopuploader preloader"></span> '+ '<div class="swiper-container swiper-gallery" style="height: calc(100% - 44px);margin-top:44px;">'+ ' <div class="swiper-wrapper gallery-wrapper">'+ ' </div>'+ '</div>'+ '<div class="swiper-pagination-gallery" style="position:absolute;bottom:0;left:0;z-index:999999;width:100%;height:4px;"></div>'+ '</div></div></div>'+ '</div>'; myApp.popup(popupHTML); var first_number,second_number; var gallerycount; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} var galleryimagecount = 0; var photodeletetime; var phototo; var photofrom; var photochatid; var touid; firebase.database().ref("photochats/" + first_number+ '/' + second_number).once("value") .then(function(snapshot) { gallerycount = snapshot.numChildren(); var objs = snapshot.val(); $.each(objs, function(i, obj) { var expiryval; if (obj.photo_expiry == null){expiryval = i;} else {expiryval = obj.photo_expiry;} $( ".gallery-wrapper" ).append(' <div class="swiper-slide photochat_'+obj.photo_expiry+'" style="height:100%;">'+ '<div class="swiper-zoom-container">'+ '<img data-src="'+obj.downloadurl+'" class="swiper-lazy" style="width:100%;" onload="$(this).fadeIn(700);hideImagespopuploader();">'+ ' <div class="swiper-lazy-preloader"></div></div><input type="hidden" class="photoexpiryhidden_'+galleryimagecount+'" value="'+expiryval +'"><input type="text" class="fromhidden_'+galleryimagecount+'" value="'+obj.from_uid+'"><input type="text" class="tohidden_'+galleryimagecount+'" value="'+obj.user_name+'"><input type="text" class="idhidden_'+galleryimagecount+'" value="'+i+'"><input type="text" class="toidhidden_'+galleryimagecount+'" value="'+obj.to_uid+'"></div>'); galleryimagecount ++; }); var galleryswiper = myApp.swiper('.swiper-gallery', { preloadImages: false, lazyLoadingInPrevNext:true, // Enable lazy loading lazyLoading: true, watchSlidesVisibility:true, zoom:true, onInit:function(swiper){var slidenum = swiper.activeIndex + 1; photodeletetime = $( ".photoexpiryhidden_" + swiper.activeIndex).val(); phototo = $( ".tohidden_" + swiper.activeIndex).val(); photofrom = $( ".fromhidden_" + swiper.activeIndex).val(); photochatid = $( ".idhidden_" + swiper.activeIndex).val(); touid = $( ".toidhidden_" + swiper.activeIndex).val(); if (photodeletetime == photochatid){document.getElementById("photodeletechattime").innerHTML = '<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+touid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;float:left;margin-right:5px;"></div> <span style="float:left;margin-top:5px;">Photo unseen</span>';} else{photodeletecount();} $( ".gallerytitle").html('<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+photofrom+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>' + phototo); }, onSlideChangeStart:function(swiper){clearInterval(xcountdown); var slidenum = galleryswiper.activeIndex + 1; photodeletetime = $( ".photoexpiryhidden_" + swiper.activeIndex).val();photodeletecount(); phototo = $( ".tohidden_" + swiper.activeIndex).val(); photofrom = $( ".fromhidden_" + swiper.activeIndex).val(); photochatid = $( ".idhidden_" + swiper.activeIndex).val(); touid = $( ".toidhidden_" + swiper.activeIndex).val(); if (photodeletetime == photochatid){document.getElementById("photodeletechattime").innerHTML = '<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+touid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;float:left;margin-right:5px;"></div> <span style="float:left;margin-top:5px;">Photo unseen</span>';} else{photodeletecount();deletePhotochat();} $( ".gallerytitle").html('<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+photofrom+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>' + phototo); myApp.sizeNavbars(); }, pagination:'.swiper-pagination-gallery', paginationType:'progress' }); galleryswiper.slideTo(go,0); myApp.sizeNavbars(); }); function deletePhotochat(){ if (photodeletetime < (new Date().getTime() / 1000)){ alert('deleting only photochat'); $( ".photochat_"+ photodeletetime).remove(); galleryswiper.update(); firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + photochatid).remove(); firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + photochatid).remove(); } } function photodeletecount(){ var countDownDate = new Date(photodeletetime * 1000); // Get todays date and time var now = new Date().getTime(); // Find the distance between now an the count down date var distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); document.getElementById("photodeletechattime").innerHTML = '<i class="twa twa-bomb twa-lg" style="float:left;"></i>' + hours + "h " + minutes + "m " ; // Update the count down every 1 second xcountdown = setInterval(function() { // Get todays date and time var now = new Date().getTime(); // Find the distance between now an the count down date var distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // If the count down is finished, write some text if (distance < 0) { clearInterval(xcountdown); deletePhotochat(); } else{ document.getElementById("photodeletechattime").innerHTML = '<i class="twa twa-bomb twa-lg" style="float:left;"></i>' +hours + "h " + minutes + "m " ;myApp.sizeNavbars();} }, 60000); } } function hideImagespopuploader(){ $( ".imagespopuploader" ).hide();} function closeGallery(){ myApp.closeModal('.gallery-popupz'); clearInterval(xcountdown); } function updateOnce(){ var uids = ["1381063698874268","1394352877264527","393790024114307","4"]; firebase.database().ref('users/' + f_uid).update({ date_me:uids }); } function updatePhotos(){ $( ".pp" ).each(function() { var classList = $(this).attr("class").split(' '); var idofphoto = classList[2].replace("photo_", ""); var index1 = f_date_match.indexOf(idofphoto); var index2 = f_duck_match.indexOf(idofphoto); var u_date_me = f_date_me.indexOf(idofphoto); var u_to_date = f_to_date.indexOf(idofphoto); var u_duck_me = f_duck_me.indexOf(idofphoto); var u_to_duck = f_to_duck.indexOf(idofphoto); if (index2 > -1) { if ($( '.rr').hasClass('r_' + idofphoto)) { d_type='duck'; $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" ); $( ".duck-template" ).show(); $( ".date-template" ).hide(); $( ".toolbardecide" ).hide(); matchNavbar(); } $( ".iconpos_" + idofphoto ).empty(); $( ".iconpos_" + idofphoto ).append('<img src="media/duckfaceonly.png" style="width:100px;">'); $( this ).css( "-webkit-filter","none" ); $( ".distance_" + idofphoto ).css( "background-color","#2196f3" ); } else if (index1 > -1) { if ($( '.rr').hasClass('r_' + idofphoto)) { d_type='date'; $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" ); $( ".duck-template" ).hide(); $( ".date-template" ).show(); $( ".toolbardecide" ).hide(); matchNavbar(); } $( ".iconpos_" + idofphoto ).empty(); $( ".iconpos_" + idofphoto ).append('<img src="media/datefaceonly.png" style="width:100px;">'); $( this ).css( "-webkit-filter","none" ); $( ".distance_" + idofphoto ).css( "background-color","#2196f3" ); } else{$( this ).css( "-webkit-filter","grayscale(80%)" );$( ".distance_" + idofphoto ).css( "background-color","#ccc" ); $( ".iconpos_" + idofphoto ).empty(); $( ".name_" + idofphoto ).css( "-webkit-filter","grayscale(80%)" ); if (u_date_me > -1){ $( ".iconpos_" + idofphoto ).empty(); $( ".iconpos_" + idofphoto ).append('<img src="media/datefaceonly.png" style="width:100px;">');$( ".iconpos_" + idofphoto ).css( "-webkit-filter","grayscale(1%)" ); } if (u_duck_me > -1) { $( ".iconpos_" + idofphoto ).empty(); $( ".iconpos_" + idofphoto ).append('<img src="media/duckfaceonly.png" style="width:100px;">');$( ".iconpos_" + idofphoto ).css( "-webkit-filter","grayscale(1%)" ); } if ($( '.rr').hasClass('r_' + idofphoto)) { $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" ); $( ".duck-template" ).hide(); $( ".date-template" ).hide(); unmatchNavbar(); $( ".toolbardecide" ).show(); // alert(u_date_me); // alert(u_duck_me); if (u_date_me > -1) {$( ".datebutton" ).addClass( "likesme" ); } else {$( ".datebutton" ).removeClass( "likesme" );} if (u_duck_me > -1) {$( ".duckbutton" ).addClass( "likesme" ); } else {$( ".duckbutton" ).removeClass( "likesme" );} } } }); $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); } function singleBrowser(idw,idname,origin){ //firebase.database().ref("users/" + f_uid).off('value', userpref); //targetid = idw; targetid = String(idw); targetname = idname; var dbuttons; if (origin){ dbuttons= ' <div class="toolbar-inner date-template" style="display:none;background-color:#2196f3;">'+ '<a href="#" onclick="dateUser();" class="datebutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;max-width:106.47px;">'+flargedateicon +'</a>'+ '<p style="font-family: \'Pacifico\', cursive;font-size:20px;visibility:hidden;">or</p>'+ '<a href="#" onclick="createDate1()" class="button link active" style="width: calc(100% - 70px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Date</a></div>'+ // '<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+ ' <div class="toolbar-inner duck-template" style="display:none;background-color:#2196f3;">'+ '<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+ '<a href="#" onclick="createDuck()" class="button link active" style="width: calc(100% - 65px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Duck</a></div>'; } else { dbuttons=' <div class="toolbar-inner date-template" style="display:none;background-color:#2196f3;">'+ '<a href="#" onclick="dateUser();" class="datebutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;max-width:106.47px;">'+flargedateicon +'</a>'+ '<p style="font-family: \'Pacifico\', cursive;font-size:20px;visibility:hidden;">or</p>'+ '<a href="#" class="button link active photo-browser-close-link" style="width: calc(100% - 70px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Date</a></div>'+ // '<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+ ' <div class="toolbar-inner duck-template" style="display:none;background-color:#2196f3;">'+ '<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+ '<a href="#" onclick="createDuck()" class="button link active photo-browser-close-link" style="width: calc(100% - 65px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Duck</a></div>'; } singlePhotoBrowser = myApp.photoBrowser({ zoom: 400, lazyLoading:true, lazyLoadingInPrevNext:true, //exposition:false, photos: [{ url: 'https://graph.facebook.com/'+targetid+'/picture?type=large', caption: '...' }], toolbarTemplate:'<div class="toolbar tabbar" style="height:100px;">'+ dbuttons+ ' <div class="toolbar-inner toolbardecide">'+ '<a href="#" onclick="dateUser();" class="datebutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;">'+flargedateicon +'</a>'+ ' <a href="#" class="link orlink">'+ '<p style="font-family: \'Pacifico\', cursive;font-size:20px;">or</p>'+ ' </a>'+ '<a href="#" class="link loaderlink"><span class="preloader preloader-white login-loader"></span></a>'+ '<a href="#" onclick="duckUser();" class="duckbutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;">'+flargeduckicon +'</a>'+ ' </div>'+ '</div>', onOpen:function(photobrowser){ $( ".chatpop" ).css( "z-index","10000" );}, onClose:function(photobrowser){hideProfile();$( ".chatpop" ).css( "z-index","11500" ); //getPreferences(); }, swipeToClose:false, // onClick:function(swiper, event){showProfile();}, backLinkText: '', navbarTemplate: '<div class="navbar photobrowserbar">'+ ' <div class="navbar-inner">'+ ' <div class="left sliding">'+ ' <a href="#" style="margin-left:-10px;" class="matchcolor mainback link photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'+ // ' <i class="icon icon-back {{iconsColorClass}}"></i> '+ '<i class="pe-7s-angle-left pe-3x"></i> '+ // '<span class="badge agecat">'+arraynumber+'</span>'+ ' </a>'+ ' <a href="#" onclick="myApp.closeModal();clearchatHistory();" style="display:none;margin-left:-10px;" class="matchcolor notifback link photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'+ ' <i class="pe-7s-angle-left pe-3x "></i> '+ // '<span class="badge agecat">'+arraynumber+'</span>'+ ' </a>'+ ' </div>'+ ' <div class="center sliding nametag matchcolor">'+ // ' <span class="photo-browser-current"></span> '+ // ' <span class="photo-browser-of">{{ofText}}</span> '+ // ' <span class="photo-browser-total"></span>'+ ' </div>'+ ' <div class="right" >' + '<a href="#" class="link">'+ ' <i class="pe-7s-more pe-lg matchcolor"></i>'+ ' </a>'+ '</div>'+ '</div>'+ '</div> ' }); singlePhotoBrowser.open(); $( ".nametag" ).empty(); $( ".nametag" ).append('<span class="rr r_'+targetid+'">'+targetname+'</span>'); var windowwidth = $( ".photo-browser-swiper-container" ).width(); $( ".photo-browser-slide img" ).css( "width", windowwidth + "px" ); $( ".photo-browser-slide img" ).css( "-webkit-filter","grayscale(80%)" ); $( ".photo-browser-caption" ).css( "margin-top", "-10px" ); $( ".datebutton" ).removeClass( "active" ); $( ".duckbutton" ).removeClass( "active" ); $( ".duckbutton" ).addClass( "disabled" ); $( ".datebutton" ).addClass( "disabled" ); $( ".loaderlink" ).show(); $( ".orlink" ).hide(); match = 0; $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" ); $( ".duck-template" ).hide(); $( ".date-template" ).hide(); unmatchNavbar(); $( ".toolbardecide" ).show(); $( ".datebutton" ).removeClass( "likesme" ); $( ".duckbutton" ).removeClass( "likesme" ); firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/userdata.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:targetid,sexuality:sexuality} ) .done(function( data ) { var result = JSON.parse(data); var targetdescription= result[0].description; //var targetname = result[0].name.substr(0,result[0].name.indexOf(' ')); $( ".photo-browser-caption" ).empty(); $( ".photo-browser-caption" ).append(targetdescription); myApp.sizeNavbars(); }); }).catch(function(error) { // Handle error }); var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} return firebase.database().ref('matches/' + f_uid + '/' + targetid).once('value').then(function(snapshot) { $( ".duckbutton" ).removeClass( "disabled" ); $( ".datebutton" ).removeClass( "disabled" ); $( ".loaderlink" ).hide(); $( ".orlink" ).show(); if (snapshot.val() === null) {} else { if (first_number == f_uid){ //Dates if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );} if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );} if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){ $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" ); $( ".duck-template" ).hide(); $( ".date-template" ).show(); $( ".toolbardecide" ).hide(); matchNavbar(); d_type='date'; } else {} //Duck if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );} if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );} if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberduck == 'Y'){ $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" ); $( ".duck-template" ).show(); $( ".date-template" ).hide(); $( ".toolbardecide" ).hide(); matchNavbar(); d_type='duck'; } else {} } if (first_number == targetid){ //Date if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );} if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );} if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){ $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" ); $( ".duck-template" ).hide(); $( ".date-template" ).show(); $( ".toolbardecide" ).hide(); matchNavbar(); d_type='date'; } else {} //Duck if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );} if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );} if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberdate == 'Y'){ $( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" ); $( ".duck-template" ).show(); $( ".date-template" ).hide(); $( ".toolbardecide" ).hide(); matchNavbar(); d_type='duck'; } else {} } } }); } function deletePhotos(){ var unix = Math.round(+new Date()/1000); firebase.database().ref('/photostodelete/' + f_uid).once('value').then(function(snapshot) { var objs = snapshot.val(); if (snapshot.val()){ $.each(objs, function(i, obj) { $.each(obj, function(i, obk) { if(obk.photo_expiry){ if (obk.photo_expiry < Number(unix)){ //alert('a photo to delete exists'); firebase.database().ref('/photochats/' + obk.first_number + '/' + obk.second_number+'/'+ obk.id).remove(); firebase.database().ref('/chats/' + obk.first_number + '/' + obk.second_number+'/'+ obk.id).remove(); var desertRef = storageRef.child(obk.photo_name); // Delete the file desertRef.delete().then(function() { firebase.database().ref('/photostodelete/' + obk.from_uid + '/' + obk.to_uid+'/'+ obk.id).remove(); }).catch(function(error) { }); //blocking out } } }); }); } }); } function createDuck(idq,nameq){ keepopen = 1; d_type = 'duck'; if (idq) {createDate(idq,nameq)} else{createDate();} } function createDate1(idz,name){ d_type = 'date'; keepopen = 1; if (idz) {createDate(idz,name)} else{createDate();} } function duckClass(place){ if (place ==1) { if ($( ".button-my" ).hasClass( "active" )){ $('.button-my').removeClass("active");$('.button-your').removeClass("active"); } else {$('.button-my').addClass("active");$('.button-your').removeClass("active");} } if (place ==2) { if ($( ".button-your" ).hasClass( "active" )){ $('.button-your').removeClass("active");$('.button-my').removeClass("active"); } else {$('.button-your').addClass("active");$('.button-my').removeClass("active");} } } function matchNotif(){ function newNotificationm(messagenum){ if (!messagenum) {messagenum = 1;} var smessage; if (d_type=='duck'){smessage = 'New match'} if (d_type=='date'){smessage = 'New match'} // Get a key for a new Post. var newPostKey = firebase.database().ref().push().key; var t_unix = Math.round(+new Date()/1000); var targetData = { id:newPostKey, from_uid: f_uid, from_name: f_first, to_uid:targetid, to_name:targetname, message:smessage, timestamp: t_unix, type:d_type, param:'newmatch', new_message_count:0, received:'N', expire:'', authcheck:f_uid }; // Write the new post's data simultaneously in the posts list and the user's post list. var updates = {}; updates['notifications/' + f_uid + '/' + targetid] = targetData; updates['notifications/' + targetid + '/' + f_uid] = targetData; return firebase.database().ref().update(updates).then(function() { console.log('delete notification sent'); }); } var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) { var objs = snapshot.val(); var messageq = 0; //If existing notifications, get number of unseen messages, delete old notifications console.log(snapshot.val()); if (snapshot.val()){ $.each(objs, function(i, obj) { if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){ firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove(); firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove(); if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){ messageq = obj.new_message_count; messageq ++; } } }); } newNotificationm(messageq); }); } function unmatchNotif(){ var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} firebase.database().ref('dates/' + f_uid +'/' + targetid).remove(); firebase.database().ref('dates/' + targetid +'/' + f_uid).remove(); firebase.database().ref('notifications/' + f_uid +'/' + targetid).remove(); firebase.database().ref('notifications/' + targetid +'/' + f_uid).remove(); myApp.closePanel(); } String.prototype.capitalize = function() { return this.charAt(0).toUpperCase() + this.slice(1); }; function insertAfterNthChild($parent, index, content){ $(content).insertBefore($parent.children().eq(index)); } function changeRadius(number){ $('.radiusbutton').removeClass('active'); $('#distance_'+ number).addClass('active'); processUpdate(); } function sortBy(number){ var relevanticon; var relevanttext; if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (number == 1){relevanticon = '<i class="pe-7s-shuffle pe-lg"></i>';relevanttext='Sort randomly';} if (number == 2){relevanticon = '<i class="pe-7s-map-marker pe-lg"></i>';relevanttext='Sort by nearby first';} if (number == 3){relevanticon = '<i class="pe-7s-clock pe-lg"></i>';relevanttext='Sort by recently active first';} $('#filterexplain').empty(); $('#filterexplain').append( '<div class="list-block" style="margin:0;">'+ '<ul>'+ '<li>'+ '<div class="item-content" style="border-top:1px solid #c8c7cc;border-bottom:1px solid #c8c7cc;">'+ '<div class="item-media">'+ relevanticon+ '</div>'+ '<div class="item-inner">'+ ' <div class="item-title">'+ relevanttext+ '</div>'+ '</div>'+ '</div>'+ '</li>'+ '</ul>'+ '</div>' ); $('.sortbutton').removeClass('active'); $('.sortby_'+ number).addClass('active'); } function addcreateDate(){ $('.addcreatebutton').hide(); $('.backcreatebutton').show(); $('.right-title').text('Matches'); myApp.sizeNavbars(); $('.timeline-upcoming').empty(); for (i = 0; i < f_date_match_data.length; i++) { $('.timeline-upcoming').append('<div class="timeline-item" onclick="createDate1(\''+f_date_match_data[i].uid+'\',\''+f_date_match_data[i].name+'\');">'+ '<div class="timeline-item-date">'+fdateicon+'</div>'+ '<div class="timeline-item-divider"></div>'+ '<div class="timeline-item-content">'+ ' <div class="timeline-item-inner">'+ ' <div class="timeline-item-title" style="width:100px;height:100px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+f_date_match_data[i].uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+ ' <div class="timeline-item-subtitle">'+f_date_match_data[i].name+'</div>'+ '</div>'+ ' </div>'+ '</div>'); } for (i = 0; i < f_duck_match_data.length; i++) { $('.timeline-upcoming').append('<div class="timeline-item" onclick="createDuck(\''+f_duck_match_data[i].uid+'\',\''+f_duck_match_data[i].name+'\');">'+ '<div class="timeline-item-date">'+fduckicon+'</div>'+ '<div class="timeline-item-divider"></div>'+ '<div class="timeline-item-content">'+ ' <div class="timeline-item-inner">'+ ' <div class="timeline-item-title" style="width:100px;height:100px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+f_duck_match_data[i].uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+ ' <div class="timeline-item-subtitle">'+f_duck_match_data[i].name+'</div>'+ '</div>'+ ' </div>'+ '</div>'); } if (f_duck_match_data.length === 0 && f_date_match_data.length ===0){ $('.timeline-upcoming').append('<div class="content-block-title" style="margin: 0 auto;text-align:center;overflow:visible;">No matches yet. <br/><br/>Keep calm and quack on!</div>'); } } function unblock(){ myApp.confirm('This will unblock all profiles, making you visible to everyone', 'Are you sure?', function () { var iblockedfirst = []; var iblockedsecond = []; firebase.database().ref("matches/" + f_uid).once("value",function(snapshot) { if (snapshot.val() != null){ var objs = snapshot.val(); $.each(objs, function(i, obj) { if((obj.first_number == f_uid)&& (obj.firstnumberblock == 'Y')){iblockedfirst.push(obj.second_number)} if((obj.second_number == f_uid)&& (obj.secondnumberblock == 'Y')){iblockedsecond.push(obj.first_number)} }); } if (iblockedfirst.length){ for (i = 0; i < iblockedfirst.length; i++) { firebase.database().ref('matches/' + f_uid + '/' + iblockedfirst[i]).update({ //add this user to my list firstnumberblock:'N', firstnumberdate:'N', firstnumberduck:'N', created:f_uid, received:iblockedfirst[i] }); firebase.database().ref('matches/' + iblockedfirst[i] + '/' + f_uid).update({ //add this user to my list firstnumberblock:'N', firstnumberdate:'N', firstnumberduck:'N', created:f_uid, received:iblockedfirst[i] }); } } if (iblockedsecond.length){ for (i = 0; i < iblockedsecond.length; i++) { firebase.database().ref('matches/' + f_uid + '/' + iblockedsecond[i]).update({ //add this user to my list secondnumberblock:'N', secondnumberdate:'N', secondnumberduck:'N', created:f_uid, received:iblockedsecond[i] }); firebase.database().ref('matches/' + iblockedsecond[i] + '/' + f_uid).update({ //add this user to my list secondnumberblock:'N', secondnumberdate:'N', secondnumberduck:'N', created:f_uid, received:iblockedsecond[i] }); } } getWifilocation(); $( ".blockbutton" ).addClass('disabled'); }) }); } function deleteAccount(){ //users //photos2delete -> photos in storage //chats //matches myApp.confirm('This will permanently delete your account and remove all your information including photos, chats and profile data', 'Delete Account', function () { var matchesarray = []; var firstnumberarray = []; var secondnumberarray = []; firebase.database().ref("matches/" + f_uid).once("value",function(snapshot) { if (snapshot.val() != null){ var objs = snapshot.val(); $.each(objs, function(i, obj) {var uidadd;if(obj.first_number == f_uid){uidadd = obj.second_number;} else{uidadd = obj.first_number} matchesarray.push(uidadd); firstnumberarray.push(obj.first_number);secondnumberarray.push(obj.second_number);}); for (i = 0; i < matchesarray.length; i++) { var mymatches = firebase.database().ref('matches/' + f_uid + '/' + matchesarray[i]); mymatches.remove().then(function() { console.log("My matches Remove succeeded.") }) .catch(function(error) { console.log("My matches Remove failed: " + error.message) }); var theirmatches = firebase.database().ref('matches/' + matchesarray[i] + '/' + f_uid); theirmatches.remove().then(function() { console.log("Their matches Remove succeeded.") }) .catch(function(error) { console.log("Their matches Remove failed: " + error.message) }); var mydates = firebase.database().ref('dates/' + f_uid + '/' + matchesarray[i]); mydates.remove().then(function() { console.log("My dates Remove succeeded.") }) .catch(function(error) { console.log("My dates Remove failed: " + error.message) }); var theirdates = firebase.database().ref('dates/' + matchesarray[i] + '/' + f_uid); theirdates.remove().then(function() { console.log("Their dates Remove succeeded.") }) .catch(function(error) { console.log("Their dates Remove failed: " + error.message) }); var theirnotifs = firebase.database().ref('notifications/' + matchesarray[i] + '/' + f_uid); theirnotifs.remove().then(function() { console.log("their notifs Remove succeeded.") }) .catch(function(error) { console.log("their notifs failed: " + error.message) }); var ourchats = firebase.database().ref('chats/' + firstnumberarray[i] + '/' + secondnumberarray[i]); ourchats.remove().then(function() { console.log("Chats Remove succeeded.") }) .catch(function(error) { console.log("Chats Remove failed: " + error.message) }); var ourphotochats = firebase.database().ref('photochats/' + firstnumberarray[i] + '/' + secondnumberarray[i]); ourphotochats.remove().then(function() { console.log("PhotoChats Remove succeeded.") }) .catch(function(error) { console.log("PhotoChats Remove failed: " + error.message) }); } } firebase.database().ref("notifications/" + f_uid).once("value", function(snapshot) { var objs = snapshot.val(); console.log(objs); if (snapshot.val()){ $.each(objs, function(i, obj) { var targetdeleteid; if (obj.from_uid == f_uid){targetdeleteid = obj.to_uid} else{targetdeleteid = obj.from_uid;} var mynotifs = firebase.database().ref('notifications/' + f_uid + '/' + targetdeleteid); mynotifs.remove().then(function() { console.log("my notifs Remove succeeded.") }) .catch(function(error) { console.log("my notifs failed: " + error.message) }); }); } firebase.database().ref('users/' + f_uid).set({ auth_id : f_auth_id, deleted:'Y' }); firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/deleteuser.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} ) .done(function( data ) { console.log(data); firebase.database().ref('/photostodelete/' + f_uid).once('value').then(function(snapshot) { var objr = snapshot.val(); if (snapshot.val()){ $.each(objr, function(i, obj) { $.each(obj, function(i, obk) { firebase.database().ref('/photostodelete/' + obk.from_uid + '/' + obk.to_uid+'/'+ obk.id).remove(); var desertRef = storageRef.child(obk.photo_name); // Delete the file desertRef.delete().then(function() { }).catch(function(error) { console.log(error); }); }); }); } logout(); }); }); }).catch(function(error) { // Handle error }); }); }); }); } function matchNavbar(){ if ($('.infopopup').length > 0) { $( ".toolbarq" ).show(); $( ".photobrowserbar" ).css("background-color","#2196f3"); $( ".matchcolor" ).addClass('whitetext'); } else {$( ".toolbarq" ).hide();} } function unmatchNavbar(){ if ($('.infopopup').length > 0) { $( ".toolbarq" ).show(); $( ".photobrowserbar" ).css("background-color","#ccc"); $( ".matchcolor" ).removeClass('whitetext'); $( ".toolbarq" ).css("background-color","transparent"); } else {$( ".toolbarq" ).hide();} } var notifloaded = false; function establishNotif(){ notifcount = firebase.database().ref('notifications/' +f_uid).on('value', function(snapshot) { var notificationscount = 0; var objs = snapshot.val(); //If existing notifications, get number of unseen messages, delete old notifications if (snapshot.val()){ $.each(objs, function(i, obj) { if (obj.to_uid == f_uid) { if (obj.received =='Y') { if (notifloaded){ $( ".arrowdivhome_" + obj.from_uid ).empty();$( ".indivnotifcount" ).remove();} } if (obj.received =='N') { var addnumber; if(obj.param == 'datedeleted' || obj.param =='newmatch'){addnumber = 1;} else {addnumber = obj.new_message_count} notificationscount = notificationscount + addnumber; if (notifloaded){ if (obj.new_message_count > 0){ //alert('Not received, greater than 0 = ' +obj.new_message_count); $( ".arrowdivhome_" + obj.from_uid ).empty();$( ".arrowdivhome_" + obj.from_uid ).append('<span class="badge" style="background-color:rgb(255, 208, 0);color:black;margin-top:5px;margin-left:-5px;">'+obj.new_message_count+'</span>'); $( ".indivnotifcount" ).remove();$( ".arrowdivbrowser" ).append('<span class="badge indivnotifcount" style="position:absolute;right:0px;background-color:rgb(255, 208, 0);color:black;">'+obj.new_message_count+'</span>'); } } } } }); notifloaded = true; if (notificationscount !=0){$( ".notifspan" ).show(); $( ".notifspan" ).addClass('notifbounce'); setTimeout(function(){ $( ".notifspan" ).removeClass('notifbounce'); }, 5000); if (offsounds == 'Y'){}else{ if ($('.chatpop').length > 0) {} else {$('#buzzer')[0].play();} } return false; } else{$( ".notifspan" ).hide();} //$( ".notifspan" ).empty(); //$( ".notifspan" ).append(notificationscount); } }); } function showPloader(){ $( ".ploader" ).css("z-index","9999999");myApp.closeModal(); } function hidePloader(tabb){ var popupHTML = '<div class="popup prefpop">'+ '<div class="views tabs toolbar-fixed">'+ '<div id="tab1" class="view tab active">'+ '<div class="navbar" style="background-color:#2196f3;">'+ ' <div class="navbar-inner">'+ ' <div class="left">Terms and Conditions of Use</div>'+ ' <div class="right"><a href="#" onclick="showPloader();" style="color:white;">Done</a></div>'+ '</div>'+ '</div>'+ '<div class="pages navbar-fixed">'+ ' <div data-page="home-1" class="page">'+ ' <div class="page-content">'+ '<div class="content-block" style="margin-top:0px;">'+ ' <div class="content-block-inner terms-inner" >'+ ' </div>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'+ '<div id="tab2" class="view tab">'+ '<div class="navbar" style="background-color:#2196f3;">'+ ' <div class="navbar-inner">'+ ' <div class="left">Privacy Policy</div>'+ ' <div class="right close-popup"><a href="#" onclick="showPloader();" class="close-popup" style="color:white;">Done</a></div>'+ '</div>'+ '</div>'+ '<div class="pages navbar-fixed">'+ ' <div data-page="home-2" class="page">'+ ' <div class="page-content">'+ '<div class="content-block" style="margin-top:0px;">'+ ' <div class="content-block-inner privacy-inner">'+ ' </div>'+ '</div>'+ '</div>'+ ' </div>'+ '</div>'+ '</div>'+ '<div class="toolbar tabbar" style="background-color:#2196f3;">'+ ' <div class="toolbar-inner">'+ ' <a href="#tab1" onclick="tabOne();" class="tab1 tab-link active"><i class="pe-7s-note2 pe-lg"></i></a>'+ ' <a href="#tab2" onclick="tabTwo();" class="tab2 tab-link"><i class="pe-7s-unlock pe-lg"></i></a>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'; myApp.popup(popupHTML); $( ".ploader" ).css("z-index","10000"); if (tabb) { tabTwo(); } else {tabOne();} } function tabOne(){ $( "#tab1" ).addClass('active'); $( "#tab2" ).removeClass('active'); myApp.sizeNavbars(); $( ".tab1" ).addClass('active'); $( ".tab2" ).removeClass('active'); $.get( "terms.html", function( data ) { $( ".terms-inner" ).html(data); console.log(data); }); } function tabTwo(){ $( "#tab1" ).removeClass('active'); $( "#tab2" ).addClass('active'); myApp.sizeNavbars(); $( ".tab1" ).removeClass('active'); $( ".tab2" ).addClass('active'); $.get( "privacy.html", function( data ) { $( ".privacy-inner" ).html(data); }); } //check if on mobile //} var pagingalbumurl; var pagingurl; var photonumber; var albumend; var addedsmallarray; var addedlargearray; var addedheight = []; var addedwidth = []; function getPhotos(albumid){ $( ".photoloader").show(); $( ".loadmorebuttonphotos").hide(); var retrieveurl; if (!pagingurl) {photonumber = 0;retrieveurl = 'https://graph.facebook.com/'+albumid+'/photos?limit=8&access_token=' + f_token} else {retrieveurl = pagingurl} $.getJSON(retrieveurl, function(response) { $( ".noparray").hide(); $( ".yesparray").show(); $( ".photoloader").hide(); if (response.data.length === 0){$( ".loadmorebuttonphotos").hide();$( "#nophotosfound").show();return false;} console.log(response); pagingurl = response.paging.next; for (i = 0; i < response.data.length; i++) { var alreadyselected = addedsmallarray.indexOf(response.data[i].source); console.log(response.data[i]); if (alreadyselected == -1) { swiperPhotos.appendSlide('<div class="swiper-slide slidee slidee_'+photonumber+' largeurl_'+response.data[i].source+' smallurl_'+response.data[i].source+' id_'+response.data[i].id+'" style="background-image:url(\''+response.data[i].source+'\');height:180px;width:180px;background-size:cover;background-position:50% 50%;"><div style="width:40px;height:40px;border-radius:50%;position:absolute;top:50%;left:50%;margin-left:-28px;margin-top:-28px;"><i class="pe-7s-check check_'+photonumber+' pe-4x" style="display:none;color:#4cd964;"></i></div><input type="hidden" class="width_'+response.data[i].id+'" value="'+response.data[i].width+'"><input type="hidden" class="height_'+response.data[i].id+'" value="'+response.data[i].height+'"><br></div>'); } else { swiperPhotos.appendSlide('<div class="swiper-slide slidee slidee_'+photonumber+' largeurl_'+response.data[i].source+' smallurl_'+response.data[i].source+' id_'+response.data[i].id+' slidee-selected" style="background-image:url(\''+response.data[i].source+'\');height:180px;width:180px;background-size:cover;background-position:50% 50%;"><div style="width:40px;height:40px;border-radius:50%;position:absolute;top:50%;left:50%;margin-left:-28px;margin-top:-28px;"><i class="pe-7s-check check_'+photonumber+' pe-4x" style="display:block;color:#4cd964;"></i></div><input type="hidden" class="width_'+response.data[i].id+'" value="'+response.data[i].width+'"><input type="hidden" class="height_'+response.data[i].id+'" value="'+response.data[i].height+'"></div>'); } photonumber ++; } if (response.data.length > 0 && response.data.length < 8) { $( ".loadmorebuttonphotos").hide();$( "#nomorephotos").show();} else{$( ".loadmorebuttonphotos").show();} }); } function closePhotos(){ $( ".albumblock").show(); $( ".leftalbum").show(); $( ".leftphoto").hide(); $( "#nomorephotos").hide(); $( "#nophotosfound").hide(); $( ".loadmorebuttonphotos").hide(); if (albumend === true){$( ".loadmorebuttonalbums").hide();$( "#nomorealbums").show();} else {$( ".loadmorebuttonalbums").show();$( "#nomorealbums").hide();} swiperPhotos.removeAllSlides(); swiperPhotos.destroy(); photonumber = 0; pagingurl = false; } function closeAlbums(){ myApp.closeModal('.photopopup'); addedsmallarray = []; addedlargearray = []; pagingalbumurl = false; albumend = false; } function photosPopup(){ addedsmallarray = f_smallurls; addedlargearray = f_largeurls; var popupHTML = '<div class="popup photopopup">'+ '<div class="views tabs toolbar-fixed">'+ '<div class="view tab active">'+ '<div class="navbar" style="background-color:#2196f3;color:white;">'+ ' <div class="navbar-inner">'+ ' <div class="left">'+ '<i class="pe-7s-angle-left pe-2x leftalbum" onclick="closeAlbums()"></i>'+ '<i class="pe-7s-angle-left pe-2x leftphoto" onclick="closePhotos()" style="display:none;"></i>'+ ' </div>'+ ' <div class="center photocount">'+ '0 photos selected'+ '</div>'+ ' <div class="right"><a href="#" onclick="closeAlbums()" class="noparray" style="color:white;">Done</a><a href="#" class="yesparray" onclick="getPhotoURL()" style="display:none;color:white;">Done</a></div>'+ '</div>'+ '</div>'+ '<div class="pages navbar-fixed">'+ ' <div data-page="photospage" class="page">'+ ' <div class="page-content" style="padding-bottom:0px;background-color:white;">'+ '<div class="col-25 photoloader" style="position:absolute;top:50%;left:50%;margin-left:-13.5px;margin-top:-13.5px;">'+ ' <span class="preloader"></span>'+ ' </div>'+ '<div class="list-block media-list albumblock" style="margin:0px;"><ul class="albumul"></ul></div>'+ '<div class="swiper-container swiper-photos">'+ ' <div class="swiper-wrapper" >'+ '</div>'+ '</div>'+ '<a href="#" class="button loadmorebuttonalbums" onclick="loadAlbums()" style="background-color:#2196f3;color:white;display:none;margin:10px;"><i class="pe-7s-albums pe-lg"></i> Load more albums</a>'+ '<a href="#" class="button loadmorebuttonphotos" onclick="getPhotos()" style="background-color:#2196f3;color:white;display:none;margin:10px;"><i class="pe-7s-photo pe-lg"></i> Load more photos</a>'+ '<div id="nomorephotos" style="display:none;width:100%;text-align:center;"><p>No more photos available in this album.</p></div>'+ '<div id="nophotosfound" style="display:none;width:100%;text-align:center;"><p>No photos found in this album.</p></div>'+ '<div id="nomorealbums" style="display:none;width:100%;text-align:center;"><p>No more albums to load.</p></div>'+ '<div><div><div>'+ '<div>'+ '<div>'+ '</div>' myApp.popup(popupHTML); if (addedlargearray.length === 1){$( ".photocount").text(addedlargearray.length + ' photo selected');} else {$( ".photocount").text(addedlargearray.length + ' photos selected');} loadAlbums(); } function loadAlbums(){ $( ".photoloader").show(); $( ".loadmorebuttonalbums").hide(); var retrievealbumurl; if (!pagingalbumurl) {retrievealbumurl = 'https://graph.facebook.com/'+f_uid+'/albums?limit=20&access_token=' + f_token} else {retrievealbumurl = pagingalbumurl} $.getJSON(retrievealbumurl, function(response) { console.log(response); pagingalbumurl = response.paging.next; for (i = 0; i < response.data.length; i++) { if (response.data[i].count > 0){ $( ".albumul" ).append( ' <li onclick="getAlbum('+response.data[i].id+')">'+ ' <div class="item-content">'+ ' <div class="item-media">'+ ' <i class="pe-7s-photo-gallery pe-lg"></i>'+ '</div>'+ '<div class="item-inner">'+ ' <div class="item-title-row">'+ ' <div class="item-title">'+response.data[i].name+'</div>'+ ' <div class="item-after">'+response.data[i].count+'</div>'+ '</div>'+ '</div>'+ ' </div>'+ ' </li>' ); } } if (response.data.length < 20) {$( ".loadmorebuttonalbums").hide();$( "#nomorealbums").show();albumend = true;} else{$( ".loadmorebuttonalbums").show();} }); } function getAlbum(albumid){ $( ".albumblock").hide(); $( ".loadmorebuttonalbums").hide(); $( "#nomorealbums").hide(); $( ".leftalbum").hide(); $( ".leftphoto").show(); swiperPhotos = myApp.swiper('.swiper-photos', { slidesPerView:2, slidesPerColumn:1000, virtualTranslate:true, slidesPerColumnFill:'row', spaceBetween: 3, onClick:function(swiper, event){if (sexuality){processUpdate(); myApp.sizeNavbars(); } console.log(swiper); if ($( ".slidee_" + swiper.clickedIndex).hasClass('slidee-selected')){$( ".slidee_" + swiper.clickedIndex).removeClass('slidee-selected');$( ".close_" + swiper.clickedIndex).show();$( ".check_" + swiper.clickedIndex).hide(); var largeurl = swiper.clickedSlide.classList[3].replace("largeurl_", ""); var smallurl = swiper.clickedSlide.classList[4].replace("smallurl_", ""); var photoselectedid = swiper.clickedSlide.classList[5].replace("id_", ""); var indexdeletedsm = addedsmallarray.indexOf(smallurl); addedsmallarray.splice(indexdeletedsm, 1); var indexdeletedsl = addedlargearray.indexOf(smallurl); addedlargearray.splice(indexdeletedsl, 1); addedheight.splice(indexdeletedsl, 1); addedwidth.splice(indexdeletedsl, 1); console.log(addedheight); } else{$( ".slidee_" + swiper.clickedIndex).addClass('slidee-selected');$( ".close_" + swiper.clickedIndex).hide();$( ".check_" + swiper.clickedIndex).show(); var largeurl = swiper.clickedSlide.classList[3].replace("largeurl_", ""); var smallurl = swiper.clickedSlide.classList[4].replace("smallurl_", ""); var photoselectedid = swiper.clickedSlide.classList[5].replace("id_", ""); addedsmallarray.push(smallurl); addedlargearray.push(largeurl); var widthselected = $( ".width_"+photoselectedid).val(); var heightselected = $( ".height_"+photoselectedid).val(); addedheight.push(heightselected); addedwidth.push(widthselected); } if (addedlargearray.length === 1){$( ".photocount").text(addedlargearray.length + ' photo selected');} else {$( ".photocount").text(addedlargearray.length + ' photos selected');} } }); getPhotos(albumid); swiperPhotos.updateContainerSize(); swiperPhotos.updateSlidesSize(); } function getPhotoURL(){ photonumber = 0; pagingurl = false; pagingalbumurl = false; albumend = false; var newsmall = addedsmallarray.toString(); var newlarge = addedlargearray.toString(); var newwidth = addedwidth.toString(); var newheight = addedheight.toString(); firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} ) .done(function( data ) { if (addedlargearray.length ===0){if ($( ".reorderbutton" ).hasClass( "disabled" )){}else {$( ".reorderbutton" ).addClass('disabled');} if ($( ".deleteallbutton" ).hasClass( "disabled" )){}else {$( ".deleteallbutton" ).addClass('disabled');} } if (addedlargearray.length > 0){if ($( ".reorderbutton" ).hasClass( "disabled" )){$( ".reorderbutton" ).removeClass('disabled');} if ($( ".deleteallbutton" ).hasClass( "disabled" )){$( ".deleteallbutton" ).removeClass('disabled');} } //swiperPhotos.removeAllSlides(); //swiperPhotos.destroy(); myApp.closeModal('.photopopup'); updatephotoslider(); }); }).catch(function(error) { // Handle error }); } function updatephotoslider(){ myswiperphotos.removeAllSlides(); console.log(addedlargearray); if (addedlargearray.length > 0){ myswiperphotos.removeAllSlides(); for (i = 0; i < addedlargearray.length; i++) { $( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\''+addedlargearray[i]+'\');background-size:cover;background-position:50% 50%;"><div class="button" style="color:#ff3b30;color:white;position:absolute;bottom:10px;right:10px;" onclick="deleteIndividual()">Delete Photo</div></div>'); } myswiperphotos.update(); $( ".photosliderinfo" ).addClass('pictures'); if (f_largeurls.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile'); } else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile'); } addedsmallarray = []; addedlargearray = []; } else { myswiperphotos.removeAllSlides(); f_smallurls = []; f_largeurls = []; addedheight = []; addedwidth = []; $( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>'); $( ".photosliderinfo" ).removeClass('pictures'); $( ".photosliderinfo" ).html('Add photos to your profile below'); } } function reorderPhotos(){ if (sexuality){processUpdate(); myApp.sizeNavbars(); } var popupHTML = '<div class="popup redorderpopup">'+ '<div class="views tabs toolbar-fixed">'+ '<div class="view tab active">'+ '<div class="navbar" style="background-color:#2196f3;color:white;">'+ ' <div class="navbar-inner">'+ ' <div class="left">'+ '<i class="pe-7s-angle-left pe-2x leftalbum" onclick="closeReorder()"></i>'+ ' </div>'+ ' <div class="center">'+ 'Order Photos'+ '</div>'+ ' <div class="right"><a href="#" onclick="changeOrder()" style="color:white;">Done</a></div>'+ '</div>'+ '</div>'+ '<div class="pages navbar-fixed">'+ ' <div data-page="redorderpage" class="page">'+ ' <div class="page-content" style="background-color:white;padding-bottom:0px;">'+ '<p style="width:100%;text-align:center;background-color:#ccc;color:white;padding-top:10px;padding-bottom:10px;">Drag photos to re-order</p>'+ ' <div class="list-block media-list" style="width:25%;float:left;margin-top:0px;">'+ ' <ul class="numbersul" style="background-color:transparent;">'+ ' </ul>'+ '</div>'+ ' <div class="list-block sortable" style="width:75%;float:left;margin-top:0px;">'+ ' <ul class="sortableul">'+ ' </ul>'+ '</div>'+ '<div><div><div>'+ '<div>'+ '<div>'+ '</div>' myApp.popup(popupHTML); for (i = 0; i < f_largeurls.length; i++) { $( ".numbersul" ).append( '<li style="margin-top:10px;">'+ ' <div class="item-content" style="height:80px;">'+ '<div class="item-inner reorderinner">'+ ' <div class="item-title badge" style="position:absolute;top:50%;left:50%;margin-top:-10px;margin-left:-20px;">'+i+'</div>'+ '</div>'+ ' </div>'+ '</li>' ); $( ".sortableul" ).append( ' <li style="margin-top:10px;">'+ ' <div class="item-content sortdivb" style="background-image:url(\''+f_largeurls[i]+'\');background-size:cover;background-position:50% 50%;height:80px;">'+ ' </div>'+ ' <div class="sortable-handler" style="width:100%;height:80px;"></div>'+ ' </li>' ); } myApp.sortableOpen(); } function closeReorder(){ myApp.closeModal('.redorderpopup'); } function changeOrder(){ var newurl = []; $( ".sortdivb" ).each(function() { var bg = $(this).css("background-image"); bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, ''); newurl.push(bg); }); myswiperphotos.removeAllSlides(); for (i = 0; i < newurl.length; i++) { $( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\''+newurl[i]+'\');background-size:cover;background-position:50% 50%;"><div class="button" style="background-color:#2196f3;color:white;position:absolute;bottom:10px;right:10px;" onclick="deleteIndividual()"><i class="pe-7s-trash pe-lg"></i> Delete</div></div>'); } myApp.closeModal('.redorderpopup'); myswiperphotos.update(); $( ".photosliderinfo" ).addClass('pictures'); if (f_largeurls.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile'); } else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile'); } var newsmall = newurl.toString(); var newlarge = newurl.toString(); firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall} ) .done(function( data ) { }); }).catch(function(error) { // Handle error }); f_largeurls = newurl; } function deleteAllPhotos(){ myApp.confirm('Are you sure?', 'Remove all photos', function () { if (sexuality){processUpdate(); myApp.sizeNavbars(); } deletedphoto = false; myswiperphotos.removeAllSlides(); $( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>'); $( ".photosliderinfo" ).removeClass('pictures'); $( ".photosliderinfo" ).html('Add'); $( ".photosliderinfo" ).html('Add photos to your profile below'); myswiperphotos.update(); $( ".reorderbutton" ).addClass('disabled'); $( ".deleteallbutton" ).addClass('disabled'); f_largeurls = []; f_smallurls = []; var newsmall = ""; var newlarge = ""; var newwidth = ""; var newheight = ""; firebase.auth().currentUser.getToken().then(function(idToken) { $.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} ) .done(function( data ) { console.log('deleted all'); }); }).catch(function(error) { // Handle error }); }); } function swipePopup(chosen){ $( '.picker-sub' ).hide(); myApp.closeModal('.picker-sub'); var sliderwidth = $( document ).width(); var sliderheight = $( document ).height(); var popupHTML = '<div class="popup prefpop">'+ '<div class="views tabs toolbar-fixed">'+ '<div id="tab99" class="view-99 view tab active">'+ '<div class="navbar" style="background-color:#2196f3;">'+ ' <div class="navbar-inner">'+ ' <div class="left" style="color:white;"></div>'+ ' <div class="center swipetext" style="color:white;">Filters'+ //'<div style="width:70px;height:70px;border-radius:50%;background-image:url(\''+f_image+'\');background-size:cover;background-position:50% 50%;margin-top:30px;z-index:100;border:5px solid #2196f3"></div>'+ '</div>'+ ' <div class="right"><a href="#" onclick="updateUser();" style="color:white;display:none" class="donechange">Done</a><a href="#" style="color:white;display:none;" class="close-popup doneunchange">Done</a></div>'+ '</div>'+ '</div>'+ ' <div class="pages">'+ ' <div data-page="home-3" class="page">'+ ' <div class="page-content" style="padding-top:44px;background-color:white;">'+ '<div class="swiper-container swiper-prefer" style="min-height:100%;">'+ '<div class="swiper-wrapper">'+ '<div class="swiper-slide" >'+ '<div class="slide-pref pref-0">'+ '<div class="content-block-title">Search radius</div>'+ '<p class="buttons-row" style="padding-left:10px;padding-right:10px;">'+ '<a href="#" id="distance_10" onclick="changeRadius(10)" class="button button-round radiusbutton" style="border:0;border-radius:0px;">10 km</a>'+ '<a href="#" id="distance_25" onclick="changeRadius(25)" class="button button-round radiusbutton" style="border:0;border-radius:0px;">25 km</a>'+ '<a href="#" id="distance_50" onclick="changeRadius(50)" class="button button-round radiusbutton active" style="border:0;border-radius:0px;">50 km</a>'+ '<a href="#" id="distance_100" onclick="changeRadius(100)" class="button button-round radiusbutton" style="border:0;border-radius:0px;">100 km</a>'+ '</p>'+ '<div class="content-block-title">Sort People By</div>'+ //'<div id="filterexplain"></div>'+ '<a href="#" id="sortrandom" class="button button-big sortbutton sortby_1 active" onclick="sortBy(1)" style="border:0;border-radius:0px;">Random </a>'+ '<a href="#" id="sortdistance" class="button button-big sortbutton sortby_2" onclick="sortBy(2)" style="border:0;border-radius:0px;">Nearby</a>'+ '<a href="#" id="sortactivity" class="button button-big sortbutton sortby_3" onclick="sortBy(3)" style="border:0;border-radius:0px;">Recent</a>'+ //'<p class="buttons-row" style="padding-left:10px;padding-right:10px;">'+ // '<a href="#" id="sortrandom" class="button button-round sortbutton sortby_1 active" onclick="sortBy(1)">Random</a>'+ //'<a href="#" id="sortdistance" class="button button-round sortbutton sortby_2" onclick="sortBy(2)">Distance</a>'+ // '<a href="#" id="sortactivity" class="button button-round sortbutton sortby_3" onclick="sortBy(3)">Recent</a>'+ //'</p>'+ '</div>'+ '</div>'+ '<div class="swiper-slide">'+ '<div class="slide-pref pref-1">'+ '<div class="content-block-title" style="margin-top:20px;">When are you available to meet?</div>'+ '<div class="list-block media-list availblock" style="margin-bottom:0px;">'+ ' <ul class="availul" style="padding-left:10px;padding-right:10px;padding-bottom:20px;">'+ ' </ul>'+ '<div class="list-block-label hiderowpref">Your matches will be notified when your availability changes.</div>'+ '</div> '+ '</div>'+ '</div>'+ '<div class="swiper-slide" >'+ '<div class="slide-pref pref-2">'+ '<div style="background-color:#2196f3;width:100%;padding-bottom:10px;" class="registerdiv">'+ '<div style="border-radius:50%;width:70px;height:70px;margin:0 auto;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+ '</div>'+ '<div class="list-block" style="margin-top:0px;">'+ ' <ul class="aboutul">'+ '<div class="content-block-title hiderowpref" style="margin-top:20px;">Profile Information</div>'+ '<div class="list-block-label registerdiv" style="margin-top:10px;margin-bottom:10px;">To get started, tell us about you and who you are looking to meet. </div>'+ '<li class="align-top hiderowpref">'+ ' <div class="item-content">'+ '<div class="item-media" style="border-radius:50%;width:70px;height:70px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+ ' <div class="item-inner">'+ ' <div class="item-input">'+ ' <textarea class="resizable" onkeyup="keyUp()" maxlength="100" id="userdescription" style="min-height:70px;" placeholder="Describe yourself and what you are looking for..."></textarea>'+ '</div>'+ ' </div>'+ ' </div>'+ '</li>'+ '<p id="maxdescription" class="hiderowpref" style="float:right;color:#ccc;font-size:14px;margin-top:5px;margin-right:5px;margin-bottom:-5px;">0 / 100</p>'+ '<li class="newam" style="clear:both;">'+ ' <div class="item-content">'+ '<div class="item-title label">I am</div>'+ ' <div class="item-inner">'+ ' <div class="item-input">'+ ' <input type="text" placeholder="..." readonly id="picker-describe">'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ '<li class="newme">'+ ' <div class="item-content">'+ '<div class="item-title label">Preference</div>'+ ' <div class="item-inner">'+ ' <div class="item-input">'+ ' <input type="text" placeholder="..." readonly id="picker-describe2">'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li class="hiderowpref" style="clear:both;margin-top:0px;">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Hometown</div>'+ ' <div class="item-input">'+ ' <input type="text" placeholder="Hide" name="name" placeholder="Hide" readonly >'+ ' </div>'+ ' </div>'+ '</div>'+ ''+ '</li>'+ ' <li class="hiderowpref">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Status</div>'+ ' <div class="item-input status-div">'+ ' <input type="text" placeholder="Hide" id="status-input" name="name" readonly >'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li class="hiderowpref">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Industry</div>'+ ' <div class="item-input industry-div">'+ ' <input type="text" id="industry-input" name="name" placeholder="Hide" readonly >'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li class="hiderowpref">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Zodiac</div>'+ ' <div class="item-input zodiac-div">'+ ' <input type="text" id="zodiac-input" name="name" placeholder="Hide" readonly >'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li class="hiderowpref">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Politics</div>'+ ' <div class="item-input politics-div">'+ ' <input type="text" id="politics-input" name="name" placeholder="Hide" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li class="hiderowpref">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Religion</div>'+ ' <div class="item-input religion-div">'+ ' <input type="text" id="religion-input" name="name" placeholder="Hide" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li class="hiderowpref">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Ethnicity</div>'+ ' <div class="item-input ethnicity-div">'+ ' <input type="text" id="ethnicity-input" name="name" placeholder="Hide" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li class="hiderowpref">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Eye color</div>'+ ' <div class="item-input eyes-div">'+ ' <input type="text" id="eyes-input" name="name" placeholder="Hide" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li class="hiderowpref">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Body Type</div>'+ ' <div class="item-input body-div">'+ ' <input type="text" id="body-input" name="name" placeholder="Hide" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li class="hiderowpref">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Height</div>'+ ' <div class="item-input height-div">'+ ' <input type="text" id="height-input" name="name" placeholder="Hide" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ ' <li class="hiderowpref">'+ '<div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title label">Weight</div>'+ ' <div class="item-input weight-div">'+ ' <input type="text" id="weight-input" name="name" placeholder="Hide" readonly>'+ ' </div>'+ ' </div>'+ '</div>'+ '</li>'+ '</ul>'+ '<div class="list-block-label hiderowpref">All fields are optional and will be hidden on your profile unless completed.</div>'+ '</div>'+ '</div>'+ '</div>'+ '<div class="swiper-slide">'+ '<div class="slide-pref pref-3">'+ '<div class="content-block-title photos-title" style="margin-top:20px;">Profile Photos</div>'+ '<div class="col-25 photoswiperloader" style="width:57.37px;top:50%;margin-top: -28.7px;position: absolute;left: 50%;margin-left: -28.7px;">'+ ' <span class="preloader"></span>'+ ' </div>'+ '<div class="swiper-container container-photos" style="width:'+sliderwidth+'px;height:250px;">'+ '<div class="swiper-wrapper wrapper-photos">'+ '</div>'+ '<div class="swiper-pagination"></div>'+ '</div>'+ '<p style="width:100%;text-align:center;background-color:#ccc;color:#6d6d72;padding-top:10px;padding-bottom:10px;" class="photosliderinfo"></p>'+ '<div class="content-block-title" style="margin-top:20px;">Manage Photos</div>'+ ' <div class="buttons-row">'+ '<a href="#" class="button active" onclick="photosPopup();" style="border:0;border-radius:0px;background-color:#4cd964;">Add</a>'+ '<a href="#" class="button reorderbutton active disabled" onclick="reorderPhotos();" style="border:0;border-radius:0px;">Re-order</a>'+ '<a href="#" class="button deleteallbutton active disabled" onclick="deleteAllPhotos();" style="border:0;border-radius:0px;background-color:#ff3b30;color:white">Delete All</a>'+ '</div>'+ '</div>'+ '</div>'+ '<div class="swiper-slide">'+ '<div class="slide-pref pref-4">'+ '<div class="content-block-title" style="margin-top:20px;">Notifications</div>'+ ' <div class="list-block media-list">'+ '<ul>'+ ' <li>'+ ' <div class="item-content">'+ ' <div class="item-inner" style="float:left;">'+ '<div class="item-title label" style="width:calc(100% - 62px);float:left;font-size:14px;">Turn off sounds</div>'+ ' <div class="item-input" style="width:52px;float:left;">'+ '<label class="label-switch">'+ ' <input type="checkbox" id="soundnotif" onchange="processUpdate(); myApp.sizeNavbars();">'+ '<div class="checkbox" ></div>'+ ' </label>'+ ' </div>'+ ' </div>'+ ' </div>'+ '</li>'+ '<div class="content-block-title" style="margin-top:20px;">Blocked profiles</div>'+ ' <li>'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title-row">'+ ' <div class="item-title button blockbutton active disabled" onclick="unblock()" style="border:0;border-radius:0px;">Unblock all </div>'+ '</div>'+ ' </div>'+ ' </div>'+ '</li>'+ '<div class="content-block-title" style="margin-top:20px;">My Account</div>'+ ' <li onclick="logout()">'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title-row">'+ ' <div class="item-title active button" style="border:0;border-radius:0px;">Logout</div>'+ '</div>'+ ' </div>'+ ' </div>'+ '</li>'+ ' <li onclick="deleteAccount()">'+ ' <div class="item-content">'+ ' <div class="item-inner">'+ ' <div class="item-title-row">'+ ' <div class="item-title button" style="border-color:#ff3b30;background-color:#ff3b30;color:white;border:0;border-radius:0px;">Delete Account</div>'+ '</div>'+ ' </div>'+ ' </div>'+ '</li>'+ '</ul>'+ '</div> '+ '</div>'+ '</div>'+ '</div>'+ '</div>'+ ' </div>'+ '</div>'+ '</div>'+ //tabs '</div>'+ '<div class="toolbar tabbar swipetoolbar" style="background-color:#ccc;">'+ ' <div class="toolbar-inner" style="padding:0;">'+ ' <a href="#" class="button tab-link tab-swipe pan0 active" onclick="swipePref(0)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-filter pe-lg" style="width:22px;margin:0 auto;"></i></a>'+ ' <a href="#" class="button tab-link tab-swipe pan1 " onclick="swipePref(1)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-clock pe-lg" style="width:22px;margin:0 auto;"></i></a>'+ ' <a href="#" class="button tab-link tab-swipe pan2" onclick="swipePref(2)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-info pe-lg" style="width:22px;margin:0 auto;"></i></a>'+ ' <a href="#" class="button tab-link tab-swipe pan3" onclick="swipePref(3);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-camera pe-lg" style="width:22px;margin:0 auto;"></i></a>'+ ' <a href="#" class="button tab-link tab-swipe pan4" onclick="swipePref(4)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-config pe-lg" style="width:22px;margin:0 auto;"></i></a>'+ '</div>'+ '</div>'+ '</div>'+ //tabs '</div>'; myApp.popup(popupHTML); if (blocklist){ if (blocklist.length){$( ".blockbutton" ).removeClass('disabled');} } if(sexuality){$( ".doneunchange" ).show();$( ".registerdiv" ).hide();$('.hiderowpref').removeClass('hiderowpref');} if(!sexuality){sortBy(1);$( ".swipetoolbar" ).hide();} var industrypicker = myApp.picker({ input: '#industry-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (industry_u) {industrypicker.cols[0].setValue(industry_u);} if (sexuality){processUpdate(); myApp.sizeNavbars(); } }, onChange:function (p, values, displayValues){$( '#industry-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'industry\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Accounting', 'Administration','Advertising','Agriculture','Banking and finance', 'Business', 'Charity', 'Creative arts','Construction','Consulting', 'Design', 'Education','Energy','Events', 'Engineering','Environment','Healthcare','Hospitality','HR and Recruitment', 'IT','Law','Law Enforcement','Leisure','Management','Manufacturing', 'Marketing','Media','Other','Pharmaceuticals','PR','Property','Public Services','Retail','Sales','Science','Security','Social Care','Small business','Sport','Tourism','Transport','Utilities','Voluntary work'] } ] }); var statuspicker = myApp.picker({ input: '#status-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (status_u) {statuspicker.cols[0].setValue(status_u);} if (sexuality){processUpdate(); myApp.sizeNavbars(); }}, onChange:function (p, values, displayValues){$( '#status-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'status\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Single', 'Married', 'Engaged','Open relationship', 'Committed relationship','It\'s Complicated'] } ] }); var heightpicker = myApp.picker({ input: '#height-input', onChange:function (p, values, displayValues){$( '#height-input' ).addClass("profilevaluechosen");}, onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (height_u) { if (height_u == 122) {var heightset = '122 cm (4\' 0\'\')';} if (height_u == 124) {var heightset = '124 cm (4\' 1\'\')';} if (height_u == 127) {var heightset = '127 cm (4\' 2\'\')';} if (height_u == 130) {var heightset = '130 cm (4\' 3\'\')';} if (height_u == 132) {var heightset = '132 cm (4\' 4\'\')';} if (height_u == 135) {var heightset = '135 cm (4\' 5\'\')';} if (height_u == 137) {var heightset = '137 cm (4\' 6\'\')';} if (height_u == 140) {var heightset = '140 cm (4\' 7\'\')';} if (height_u == 142) {var heightset = '142 cm (4\' 8\'\')';} if (height_u == 145) {var heightset = '145 cm (4\' 9\'\')';} if (height_u == 147) {var heightset = '147 cm (4\' 10\'\')';} if (height_u == 150) {var heightset = '150 cm (4\' 11\'\')';} if (height_u == 152) {var heightset = '152 cm (5\' 0\'\')';} if (height_u == 155) {var heightset = '155 cm (5\' 1\'\')';} if (height_u == 157) {var heightset = '157 cm (5\' 2\'\')';} if (height_u == 160) {var heightset = '160 cm (5\' 3\'\')';} if (height_u == 163) {var heightset = '163 cm (5\' 4\'\')';} if (height_u == 165) {var heightset = '165 cm (5\' 5\'\')';} if (height_u == 168) {var heightset = '168 cm (5\' 6\'\')';} if (height_u == 170) {var heightset = '170 cm (5\' 7\'\')';} if (height_u == 173) {var heightset = '173 cm (5\' 8\'\')';} if (height_u == 175) {var heightset = '175 cm (5\' 9\'\')';} if (height_u == 178) {var heightset = '178 cm (5\' 10\'\')';} if (height_u == 180) {var heightset = '180 cm (5\' 11\'\')';} if (height_u == 183) {var heightset = '183 cm (6\' 0\'\')';} if (height_u == 185) {var heightset = '185 cm (6\' 1\'\')';} if (height_u == 188) {var heightset = '185 cm (6\' 2\'\')';} if (height_u == 191) {var heightset = '191 cm (6\' 3\'\')';} if (height_u == 193) {var heightset = '193 cm (6\' 4\'\')';} if (height_u == 195) {var heightset = '195 cm (6\' 5\'\')';} if (height_u == 198) {var heightset = '198 cm (6\' 6\'\')';} if (height_u == 201) {var heightset = '201 cm (6\' 7\'\')';} if (height_u == 203) {var heightset = '203 cm (6\' 8\'\')';} heightpicker.cols[0].setValue(heightset);}}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'height\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['122 cm (4\' 0\'\')','124 cm (4\' 1\'\')','127 cm (4\' 2\'\')','130 cm (4\' 3\'\')','132 cm (4\' 4\'\')','135 cm (4\' 5\'\')','137 cm (4\' 6\'\')','140 cm (4\' 7\'\')','142 cm (4\' 8\'\')','145 cm (4\' 9\'\')','147 cm (4\' 10\'\')','150 cm (4\' 11\'\')','152 cm (5\' 0\'\')','155 cm (5\' 1\'\')','157 cm (5\' 2\'\')','160 cm (5\' 3\'\')','163 cm (5\' 4\'\')','165 cm (5\' 5\'\')','168 cm (5\' 6\'\')','170 cm (5\' 7\'\')','173 cm (5\' 8\'\')','175 cm (5\' 9\'\')','178 cm (5\' 10\'\')','180 cm (5\' 11\'\')','183 cm (6\' 0\'\')','185 cm (6\' 1\'\')','188 cm (6\' 2\'\')','191 cm (6\' 3\'\')','193 cm (6\' 3\'\')','195 cm (6\' 4\'\')','198 cm (6\' 5\'\')','201 cm (6\' 6\'\')','203 cm (6\' 8\'\')'] }, ] }); var weightpicker = myApp.picker({ input: '#weight-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (weight_u) { weightpicker.cols[0].setValue(weight_u + ' kg (' + Math.round(weight_u* 2.20462262) + ' lbs)');}}, onChange:function (p, values, displayValues){$( '#weight-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'weight\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="center">' + 'Weight'+ '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: (function () { var arr = []; for (var i = 45; i <= 150; i++) { arr.push(i + ' kg (' + Math.round(i* 2.20462262) + ' lbs)'); } return arr; })(), }, ] }); var bodypicker = myApp.picker({ input: '#body-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (body_u) {bodypicker.cols[0].setValue(body_u);}}, onChange:function (p, values, displayValues){$( '#body-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'body\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Athletic','Average', 'Slim', 'Large', 'Muscular','Unimportant'] } ] }); var eyespicker = myApp.picker({ input: '#eyes-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (eyes_u) {eyespicker.cols[0].setValue(eyes_u);}}, onChange:function (p, values, displayValues){$( '#eyes-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'eyes\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Amber', 'Blue', 'Brown','Grey','Green','Hazel','Other'] } ] }); var ethnicitypicker = myApp.picker({ input: '#ethnicity-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (ethnicity_u) {ethnicitypicker.cols[0].setValue(ethnicity_u);}}, onChange:function (p, values, displayValues){$( '#ethnicity-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'ethnicity\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Asian', 'Black', 'Latin / Hispanic','Mixed','Middle Eastern','Native American','Other','Pacific Islander','White'] } ] }); var politicspicker = myApp.picker({ input: '#politics-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (politics_u) {politicspicker.cols[0].setValue(politics_u);}}, onChange:function (p, values, displayValues){$( '#politics-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'politics\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Left / Liberal', 'Centre','Right / Conservative','Not interested'] } ] }); var zodiacpicker = myApp.picker({ input: '#zodiac-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (zodiac_u) {zodiacpicker.cols[0].setValue(zodiac_u);}}, onChange:function (p, values, displayValues){$( '#zodiac-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'zodiac\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn','Aquarius','Pisces'] } ] }); var religionpicker = myApp.picker({ input: '#religion-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (religion_u) {religionpicker.cols[0].setValue(religion_u);}}, onChange:function (p, values, displayValues){$( '#religion-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'religion\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Atheist','Agnostic','Christianity','Islam','Buddhism','Hindusim','Sikhism','Judaism','Other'] } ] }); mySwiper = myApp.swiper('.swiper-prefer', { onSlideChangeEnd:function(swiper){$( ".page-content" ).scrollTop( 0 );}, onSlideChangeStart:function(swiper){ $( ".page-content" ).scrollTop( 0 ); $( ".tab-swipe").removeClass('active'); $( ".pan" + swiper.activeIndex ).addClass('active'); if (swiper.activeIndex == 0){$( ".swipetext" ).text('Filters'); $( ".slide-pref" ).hide();$( ".pref-0").show(); } if (swiper.activeIndex == 1){$( ".swipetext" ).text('Availability'); $( ".slide-pref" ).hide();$( ".pref-1").show(); } if (swiper.activeIndex == 2){$( ".swipetext" ).text('Profile'); $( ".slide-pref" ).hide();$( ".pref-2").show(); } if (swiper.activeIndex == 3){$( ".swipetext" ).text('Photos');getData(); $( ".slide-pref" ).hide();$( ".pref-3").show(); } if (swiper.activeIndex == 4){$( ".swipetext" ).text('Settings'); $( ".slide-pref" ).hide();$( ".pref-4").show(); } if (!sexuality){$( '.swipetext' ).text("Welcome, " + f_first);mySwiper.lockSwipes();} } }); swipePref(chosen); myApp.sizeNavbars(); var dateinfo = []; var f_smallurls; var f_largeurls; var s_namesonly = []; var d = new Date(); var weekday = new Array(7); weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var daynumber; var todayday = weekday[d.getDay()]; console.log(todayday); s_namesonly.push(todayday); var f_available_array; var s_alldays_values = []; var s_alldays_names = []; var tonight = new Date(); tonight.setHours(23,59,59,999); var tonight_timestamp = Math.round(tonight/1000); daynumber; daynumber = d.getDate(); if (daynumber == '1' || daynumber == '21' || daynumber == '31'){dending = 'st'} else if (daynumber == '2' || daynumber == '22'){dending = 'nd'} else if (daynumber == '3' || daynumber == '23'){dending = 'rd'} else {dending = 'th'} dateinfo.push(daynumber + dending + ' ' + monthNames[d.getMonth()] + ', ' + d.getFullYear()); s_alldays_values.push(tonight_timestamp); s_alldays_names.push('Today'); var tomorrow_timestamp = tonight_timestamp + 86400; var tomorrowdate = new Date(Date.now() + 86400); var tomorroww = new Date(d.getTime() + 24 * 60 * 60 * 1000); var tomorrowday = weekday[tomorroww.getDay()]; daynumber = tomorroww.getDate(); if (daynumber == '1' || daynumber == '21' || daynumber == '31'){dending = 'st'} else if (daynumber == '2' || daynumber == '22'){dending = 'nd'} else if (daynumber == '3' || daynumber == '23'){dending = 'rd'} else {dending = 'th'} dateinfo.push(daynumber + dending + ' ' + monthNames[tomorrowdate.getMonth()] + ', ' + tomorrowdate.getFullYear()); console.log('tomorrow is' + tomorrowday); s_namesonly.push(tomorrowday); s_alldays_values.push(tomorrow_timestamp); s_alldays_names.push('Tomorrow'); for (i = 1; i < 7; i++) { var newunix = tomorrow_timestamp + (86400 * i); s_alldays_values.push(newunix); var dat_number = i + 1; var datz = new Date(Date.now() + dat_number * 24*60*60*1000); daynumber = datz.getDate(); var dending; if (daynumber == '1' || daynumber == '21' || daynumber == '31'){dending = 'st'} else if (daynumber == '2' || daynumber == '22'){dending = 'nd'} else if (daynumber == '3' || daynumber == '23'){dending = 'rd'} else {dending = 'th'} n = weekday[datz.getDay()]; qqq = weekday[datz.getDay() - 1]; console.log(n); s_alldays_names.push(n + ' ' + daynumber + dending); dateinfo.push(daynumber + dending + ' ' + monthNames[datz.getMonth()] + ', ' + datz.getFullYear()); s_namesonly.push(n); } s_namesonly.push(n); console.log(s_namesonly); console.log(s_alldays_values); for (i = 0; i < s_alldays_names.length; i++) { if (i==0 | i==2 || i==4 || i==6){ $( ".availul" ).append( '<li class="li_'+s_alldays_values[i]+' availrec" id="aa_'+s_alldays_values[i]+'" style="height:44px;float:left;width:100%;text-align:center;margin-bottom:10px;padding-top:10px;color:white;" onclick="openAvail('+s_alldays_values[i]+')">'+ '<div class="readd_'+s_alldays_values[i]+'"></div>'+ ' <input type="text" placeholder="'+s_alldays_names[i]+'" readonly id="picker'+s_alldays_values[i]+'" style="height:44px;text-align:center;margin-top:-10px;font-size:17px;color:white;"></li><input type="hidden" class="suppdate_'+s_alldays_values[i]+'" value="'+dateinfo[i]+'">' ); setPicker(); } else if (i==1 || i==3 || i==5 || i==7) { $( ".availul" ).append( '<li class="li_'+s_alldays_values[i]+' availrec" id="aa_'+s_alldays_values[i]+'" style="height:44px;float:left;width:100%;text-align:center;margin-bottom:10px;padding-top:10px;color:white;" onclick="openAvail('+s_alldays_values[i]+')">'+ '<div class="readd_'+s_alldays_values[i]+'"></div>'+ '<input type="text" placeholder="'+s_alldays_names[i]+'" readonly id="picker'+s_alldays_values[i]+'" style="height:44px;text-align:center;margin-top:-10px;font-size:17px;color:white;"></li><input type="hidden" class="suppdate_'+s_alldays_values[i]+'" value="'+dateinfo[i]+'">' ); setPicker(); } var alreadyavailchosen = 0; var columnone; var columntwo; var idtochange; for(var k = 0; k < availarray.length; k++) { if (availarray[k].id == s_alldays_values[i]){ alreadyavailchosen = 1;columntwo = availarray[k].time;columnone = availarray[k].day; idtochange = s_alldays_values[i];$( '.li_'+ idtochange ).addClass('selecrec');$( "#picker"+ idtochange ).val( columnone + " " + columntwo ); } else{ alreadyavailchosen = 0; } } function setPicker(){ var myavailpicker = myApp.picker({ input: '#picker' + s_alldays_values[i], onOpen: function (p){if (sexuality){processUpdate(); myApp.sizeNavbars(); }}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeAvail(\''+s_alldays_values[i]+'\',\''+s_alldays_names[i]+'\',\''+s_namesonly[i]+'\');">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { textAlign: 'left', values: (s_namesonly[i] + ',').split(',') }, { textAlign: 'left', values: ('Anytime Morning Midday Afternoon Evening').split(' ') }, ] }); } } if (myphotosarray){ } else { } if (f_description){ $( "#userdescription" ).val(f_description); var inputlengthd = $( "#userdescription" ).val().length; $( "#maxdescription" ).text(inputlengthd + ' / 100 '); } if (radiussize){ $( ".radiusbutton" ).removeClass( "active" ); $( "#distance_" + radiussize ).addClass( "active" ); } if (offsounds == 'Y'){$('#soundnotif').prop('checked', true);} else{$('#soundnotif').prop('checked', false);} if (sortby){ if (sortby == 'random'){sortBy(1);} if (sortby == 'distance'){sortBy(2);} if (sortby == 'activity'){sortBy(3);} $( ".sortbutton" ).removeClass( "active" ); $( "#sort" + sortby ).addClass( "active" ); } if (f_age) {$( ".savebutton" ).removeClass('disabled');} if(industry_u){$( "#industry-input" ).val( industry_u );} if(status_u){$( "#status-input" ).val( status_u );} if(politics_u){$( "#politics-input" ).val( politics_u );} if(eyes_u){$( "#eyes-input" ).val( eyes_u );} if(body_u){$( "#body-input" ).val( body_u );} if(religion_u){$( "#religion-input" ).val( religion_u );} if(zodiac_u){$( "#zodiac-input" ).val( zodiac_u );} if(ethnicity_u){$( "#ethnicity-input" ).val( ethnicity_u );} if(weight_u){$( "#weight-input" ).val( weight_u + ' kg (' + Math.round(weight_u* 2.20462262) + ' lbs)' );} if (height_u) { if (height_u == 122) {var heightset = '122 cm (4\' 0\'\')';} if (height_u == 124) {var heightset = '124 cm (4\' 1\'\')';} if (height_u == 127) {var heightset = '127 cm (4\' 2\'\')';} if (height_u == 130) {var heightset = '130 cm (4\' 3\'\')';} if (height_u == 132) {var heightset = '132 cm (4\' 4\'\')';} if (height_u == 135) {var heightset = '135 cm (4\' 5\'\')';} if (height_u == 137) {var heightset = '137 cm (4\' 6\'\')';} if (height_u == 140) {var heightset = '140 cm (4\' 7\'\')';} if (height_u == 142) {var heightset = '142 cm (4\' 8\'\')';} if (height_u == 145) {var heightset = '145 cm (4\' 9\'\')';} if (height_u == 147) {var heightset = '147 cm (4\' 10\'\')';} if (height_u == 150) {var heightset = '150 cm (4\' 11\'\')';} if (height_u == 152) {var heightset = '152 cm (5\' 0\'\')';} if (height_u == 155) {var heightset = '155 cm (5\' 1\'\')';} if (height_u == 157) {var heightset = '157 cm (5\' 2\'\')';} if (height_u == 160) {var heightset = '160 cm (5\' 3\'\')';} if (height_u == 163) {var heightset = '163 cm (5\' 4\'\')';} if (height_u == 165) {var heightset = '165 cm (5\' 5\'\')';} if (height_u == 168) {var heightset = '168 cm (5\' 6\'\')';} if (height_u == 170) {var heightset = '170 cm (5\' 7\'\')';} if (height_u == 173) {var heightset = '173 cm (5\' 8\'\')';} if (height_u == 175) {var heightset = '175 cm (5\' 9\'\')';} if (height_u == 178) {var heightset = '178 cm (5\' 10\'\')';} if (height_u == 180) {var heightset = '180 cm (5\' 11\'\')';} if (height_u == 183) {var heightset = '183 cm (6\' 0\'\')';} if (height_u == 185) {var heightset = '185 cm (6\' 1\'\')';} if (height_u == 188) {var heightset = '185 cm (6\' 2\'\')';} if (height_u == 191) {var heightset = '191 cm (6\' 3\'\')';} if (height_u == 193) {var heightset = '193 cm (6\' 4\'\')';} if (height_u == 195) {var heightset = '195 cm (6\' 5\'\')';} if (height_u == 198) {var heightset = '198 cm (6\' 6\'\')';} if (height_u == 201) {var heightset = '201 cm (6\' 7\'\')';} if (height_u == 203) {var heightset = '203 cm (6\' 8\'\')';} $( "#height-input" ).val( heightset ); } if (f_age && f_gender) {$( "#picker-describe" ).val( f_gender + ", " + f_age );} if (f_interested) {$( "#picker-describe2" ).val( f_interested + ", between " + f_lower + ' - ' + f_upper );} pickerDescribe = myApp.picker({ input: '#picker-describe', rotateEffect: true, onClose:function (p){ $( ".popup-overlay" ).css("z-index","10500"); }, onOpen: function (p){ if (sexuality){processUpdate(); myApp.sizeNavbars(); } $('.picker-items-col').eq(0).css('width','50%'); $('.picker-items-col').eq(1).css('width','50%'); // $( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px"); var gendercol = pickerDescribe.cols[0]; var agecol = pickerDescribe.cols[1]; if (f_age) {agecol.setValue(f_age);} if (f_gender) {gendercol.setValue(f_gender);} }, onChange: function (p, value, displayValue){ if (!f_age){ var fpick = pickerDescribe.value; var spick = pickerDescribe2.value; if (fpick && spick) { if(!sexuality){sexuality=true;$( ".registerdiv" ).slideUp();$('.hiderowpref').removeClass('hiderowpref');$( ".swipetoolbar" ).show();$( '.swipetext' ).text("Profile");mySwiper.unlockSwipes();$( ".donechange" ).show();$( ".doneunchange" ).hide();myApp.sizeNavbars(); } $( ".savebutton" ).removeClass( "disabled" );} else {$( ".savebutton" ).addClass( "disabled" );} } }, formatValue: function (p, values, displayValues) { return displayValues[0] + ', ' + values[1]; }, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left">' + 'I Am'+ '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { textAlign: 'left', values: ('Male Female').split(' ') }, { values: ('18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99').split(' ') }, ] }); pickerDescribe2 = myApp.picker({ input: '#picker-describe2', rotateEffect: true, onClose:function (p){ $( ".popup-overlay" ).css("z-index","10500"); }, onChange: function (p, value, displayValue){ if (!f_age){ var fpick = pickerDescribe.value; var spick = pickerDescribe2.value; if (fpick && spick) { if(!sexuality){sexuality=true;$( ".registerdiv" ).slideUp();$('.hiderowpref').removeClass('hiderowpref');$( ".swipetoolbar" ).show();$( '.swipetext' ).text("Profile");mySwiper.unlockSwipes();$( ".donechange" ).show();$( ".doneunchange" ).hide();myApp.sizeNavbars(); } $( ".savebutton" ).removeClass( "disabled" );} else {$( ".savebutton" ).addClass( "disabled" );} } }, onOpen: function (p){if (sexuality){processUpdate(); myApp.sizeNavbars(); } // $( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px"); $('.picker-items-col').eq(0).css('width','50%'); $('.picker-items-col').eq(1).css('width','50%'); var interestedcol = pickerDescribe2.cols[0]; var lowercol = pickerDescribe2.cols[1]; var uppercol = pickerDescribe2.cols[2]; if (f_interested) {interestedcol.setValue(f_interested);} if (f_lower) {lowercol.setValue(f_lower);} if (f_upper) {uppercol.setValue(f_upper);} }, formatValue: function (p, values, displayValues) { if (values[1] > values[2]) { return displayValues[0] + ', between ' + values[2] + ' - ' + values[1];} else { return displayValues[0] + ', between ' + values[1] + ' - ' + values[2]; } }, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left">' + 'Preference'+ '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { textAlign: 'left', values: ('Men Women').split(' ') }, { values: ('18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99').split(' ') }, { values: ('18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99').split(' ') }, ] }); } function swipePref(index){mySwiper.slideTo(index);} function navPicker(){ myApp.pickerModal( '<div class="picker-modal picker-sub" style="height:88px;">' + '<div class="toolbar tabbar" style="z-index:9999;background-color:#ccc;">' + '<div class="toolbar-inner" style="padding:0;">' + ' <a href="#" class="button tab-link tab-swipe home0" onclick="swipePopup(0);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-filter pe-lg" style="width:22px;margin:0 auto;"></i></a>'+ ' <a href="#" class="button tab-link tab-swipe home1 " onclick="swipePopup(1);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-clock pe-lg" style="width:22px;margin:0 auto;"></i></a>'+ ' <a href="#" class="button tab-link tab-swipe home2" onclick="swipePopup(2);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-info pe-lg" style="width:22px;margin:0 auto;"></i></a>'+ ' <a href="#" class="button tab-link tab-swipe home3" onclick="swipePopup(3);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-camera pe-lg" style="width:22px;margin:0 auto;"></i></a>'+ ' <a href="#" class="button tab-link tab-swipe home4" onclick="swipePopup(4);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-config pe-lg" style="width:22px;margin:0 auto;"></i></a>'+ '</div>' + '</div>' + '<div class="picker-modal-inner close-picker" style="height:44px;background-color:#2196f3;text-align:center;">' + '<i class="pe-7s-angle-down pe-2x " style="font-size:34px;margin-top:5px;color:white;"></i>'+ '</div>' + '</div>' ); } function removeProfileSet(pickertype){ $( "#" + pickertype + "-input").remove(); $( "." + pickertype + "-div").append( '<input type="text" id="'+pickertype+'-input" name="name" placeholder="Hide" readonly >' ); if (pickertype=='industry'){ var industrypicker = myApp.picker({ input: '#industry-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (industry_u) {industrypicker.cols[0].setValue(industry_u);} }, onChange:function (p, values, displayValues){$( '#industry-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'industry\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Accounting', 'Administration','Advertising','Agriculture','Banking and finance', 'Business', 'Charity', 'Creative arts','Construction','Consulting', 'Design', 'Education','Energy','Events', 'Engineering','Environment','Healthcare','Hospitality','HR and Recruitment', 'IT','Law','Law Enforcement','Leisure','Management','Manufacturing', 'Marketing','Media','Other','Pharmaceuticals','PR','Property','Public Services','Retail','Sales','Science','Security','Social Care','Small business','Sport','Tourism','Transport','Utilities','Voluntary work'] } ] }); } if (pickertype=='status'){ var statuspicker = myApp.picker({ input: '#status-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (status_u) {statuspicker.cols[0].setValue(status_u);}}, onChange:function (p, values, displayValues){$( '#status-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'status\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Single', 'Married', 'Engaged','Open relationship', 'Committed relationship','It\'s Complicated'] } ] }); } if (pickertype=='politics'){ var politicspicker = myApp.picker({ input: '#politics-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (politics_u) {politicspicker.cols[0].setValue(politics_u);}}, onChange:function (p, values, displayValues){$( '#politics-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'politics\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Left / Liberal', 'Centre','Right / Conservative','Not interested'] } ] }); } if (pickertype=='zodiac'){ var zodiacpicker = myApp.picker({ input: '#zodiac-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (zodiac_u) {zodiacpicker.cols[0].setValue(zodiac_u);}}, onChange:function (p, values, displayValues){$( '#zodiac-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'zodiac\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn','Aquarius','Pisces'] } ] }); } if (pickertype=='religion'){ var religionpicker = myApp.picker({ input: '#religion-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (religion_u) {religionpicker.cols[0].setValue(religion_u);}}, onChange:function (p, values, displayValues){$( '#religion-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'religion\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Atheist','Agnostic','Christianity','Islam','Buddhism','Hindusim','Sikhism','Judaism','Other'] } ] }); } if (pickertype=='ethnicity'){ var ethnicitypicker = myApp.picker({ input: '#ethnicity-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (ethnicity_u) {ethnicitypicker.cols[0].setValue(ethnicity_u);}}, onChange:function (p, values, displayValues){$( '#ethnicity-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'ethnicity\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Asian', 'Black', 'Latin / Hispanic','Mixed','Middle Eastern','Native American','Other','Pacific Islander','White'] } ] }); } if (pickertype=='height'){ var heightpicker = myApp.picker({ input: '#height-input', onChange:function (p, values, displayValues){$( '#height-input' ).addClass("profilevaluechosen");}, onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (height_u) { if (height_u == 122) {var heightset = '122 cm (4\' 0\'\')';} if (height_u == 124) {var heightset = '124 cm (4\' 1\'\')';} if (height_u == 127) {var heightset = '127 cm (4\' 2\'\')';} if (height_u == 130) {var heightset = '130 cm (4\' 3\'\')';} if (height_u == 132) {var heightset = '132 cm (4\' 4\'\')';} if (height_u == 135) {var heightset = '135 cm (4\' 5\'\')';} if (height_u == 137) {var heightset = '137 cm (4\' 6\'\')';} if (height_u == 140) {var heightset = '140 cm (4\' 7\'\')';} if (height_u == 142) {var heightset = '142 cm (4\' 8\'\')';} if (height_u == 145) {var heightset = '145 cm (4\' 9\'\')';} if (height_u == 147) {var heightset = '147 cm (4\' 10\'\')';} if (height_u == 150) {var heightset = '150 cm (4\' 11\'\')';} if (height_u == 152) {var heightset = '152 cm (5\' 0\'\')';} if (height_u == 155) {var heightset = '155 cm (5\' 1\'\')';} if (height_u == 157) {var heightset = '157 cm (5\' 2\'\')';} if (height_u == 160) {var heightset = '160 cm (5\' 3\'\')';} if (height_u == 163) {var heightset = '163 cm (5\' 4\'\')';} if (height_u == 165) {var heightset = '165 cm (5\' 5\'\')';} if (height_u == 168) {var heightset = '168 cm (5\' 6\'\')';} if (height_u == 170) {var heightset = '170 cm (5\' 7\'\')';} if (height_u == 173) {var heightset = '173 cm (5\' 8\'\')';} if (height_u == 175) {var heightset = '175 cm (5\' 9\'\')';} if (height_u == 178) {var heightset = '178 cm (5\' 10\'\')';} if (height_u == 180) {var heightset = '180 cm (5\' 11\'\')';} if (height_u == 183) {var heightset = '183 cm (6\' 0\'\')';} if (height_u == 185) {var heightset = '185 cm (6\' 1\'\')';} if (height_u == 188) {var heightset = '185 cm (6\' 2\'\')';} if (height_u == 191) {var heightset = '191 cm (6\' 3\'\')';} if (height_u == 193) {var heightset = '193 cm (6\' 4\'\')';} if (height_u == 195) {var heightset = '195 cm (6\' 5\'\')';} if (height_u == 198) {var heightset = '198 cm (6\' 6\'\')';} if (height_u == 201) {var heightset = '201 cm (6\' 7\'\')';} if (height_u == 203) {var heightset = '203 cm (6\' 8\'\')';} heightpicker.cols[0].setValue(heightset);}}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'height\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['122 cm (4\' 0\'\')','124 cm (4\' 1\'\')','127 cm (4\' 2\'\')','130 cm (4\' 3\'\')','132 cm (4\' 4\'\')','135 cm (4\' 5\'\')','137 cm (4\' 6\'\')','140 cm (4\' 7\'\')','142 cm (4\' 8\'\')','145 cm (4\' 9\'\')','147 cm (4\' 10\'\')','150 cm (4\' 11\'\')','152 cm (5\' 0\'\')','155 cm (5\' 1\'\')','157 cm (5\' 2\'\')','160 cm (5\' 3\'\')','163 cm (5\' 4\'\')','165 cm (5\' 5\'\')','168 cm (5\' 6\'\')','170 cm (5\' 7\'\')','173 cm (5\' 8\'\')','175 cm (5\' 9\'\')','178 cm (5\' 10\'\')','180 cm (5\' 11\'\')','183 cm (6\' 0\'\')','185 cm (6\' 1\'\')','188 cm (6\' 2\'\')','191 cm (6\' 3\'\')','193 cm (6\' 3\'\')','195 cm (6\' 4\'\')','198 cm (6\' 5\'\')','201 cm (6\' 6\'\')','203 cm (6\' 8\'\')'] }, ] }); } if (pickertype=='weight'){ var weightpicker = myApp.picker({ input: '#weight-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (weight_u) { weightpicker.cols[0].setValue(weight_u + ' kg (' + Math.round(weight_u* 2.20462262) + ' lbs)');}}, onChange:function (p, values, displayValues){$( '#weight-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'weight\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="center">' + 'Weight'+ '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: (function () { var arr = []; for (var i = 45; i <= 150; i++) { arr.push(i + ' kg (' + Math.round(i* 2.20462262) + ' lbs)'); } return arr; })(), }, ] }); } if (pickertype=='eyes'){var eyespicker = myApp.picker({ input: '#eyes-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (eyes_u) {eyespicker.cols[0].setValue(eyes_u);}}, onChange:function (p, values, displayValues){$( '#eyes-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'eyes\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Amber', 'Blue', 'Brown','Grey','Green','Hazel','Other'] } ] }); } if (pickertype=='body'){ var bodypicker = myApp.picker({ input: '#body-input', onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (body_u) {bodypicker.cols[0].setValue(body_u);}}, onChange:function (p, values, displayValues){$( '#body-input' ).addClass("profilevaluechosen");}, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left" onclick="removeProfileSet(\'body\')">' + '<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">Done</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Athletic','Average', 'Slim', 'Large', 'Muscular','Unimportant'] } ] }); } } function actionSheet(){ var first_number,second_number; if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;} else {first_number = f_uid;second_number = targetid;} if ($('.chatpop').length === 0 || ($('.chatpop').length === 1 && $('.chatpop').css('z-index') === '10000')){ var disabledattribute; if (targetreported){disabledattribute=true;}else{disabledattribute=false;} var buttons = [ { text: 'View Profile', bold: true, onClick: function () { if ($('.infopopup').length > 0) { scrolltoTop(); } else{questions();scrolltoTop();} } }, { text: 'View Profile Photos ('+new_all[myPhotoBrowser.swiper.activeIndex].photocount+')', bold: true, onClick: function () { if ($('.infopopup').length > 0) { myApp.closeModal() ;backtoProfile(); } else{} } }, { text: 'View Photo Bombs (0)', disabled:true, color: 'green', onClick: function () { imagesPopup(); } }, { text: 'Block', onClick: function () { more(); } },{ text: 'Report', disabled:disabledattribute, onClick: function () { report(); } }, { text: 'Cancel', color: 'red' }, ]; } else { var elementPos = new_all.map(function(x) {return x.id; }).indexOf(targetid); //var elementPos = new_all.findIndex(x => x.id==targetid); var disabledattribute; if (targetreported){disabledattribute=true;}else{disabledattribute=false;} var buttons = [ { text: 'View Profile', bold: true, onClick: function () { if($( ".center" ).hasClass( "close-popup" )){ myApp.closeModal('.chatpop'); if ($('.infopopup').length > 0) { scrolltoTop(); } else{questions();scrolltoTop();} }else{viewscroll = true;singleUser(targetid,targetname);} } }, { text: 'View Profile Photos ('+new_all[elementPos].photocount+')', bold: true, onClick: function () { if($( ".center" ).hasClass( "close-popup" )){ myApp.closeModal('.chatpop'); backtoProfile(); }else{viewphotos = true;singleUser(targetid,targetname);} } }, { text: 'View Photo Bombs (0)', disabled:true, color: 'green', onClick: function () { imagesPopup(); } }, { text: 'Block', onClick: function () { more(); } },{ text: 'Report', disabled:disabledattribute, onClick: function () { report(); } }, { text: 'Cancel', color: 'red' }, ]; } myApp.actions(buttons); var photobombsheet = firebase.database().ref('photochats/' + first_number + '/'+ second_number); photobombsheet.once('value', function(snapshot) { if(snapshot.val()){$(".color-green").removeClass('disabled'); $(".color-green").html('View Photo Bombs ('+snapshot.numChildren()+')'); } }); }
Update app.js
www/js/app.js
Update app.js
<ide><path>ww/js/app.js <ide> <ide> <ide> if (origin == 88){alert('88');} <del>else if (origin == 1){photoBrowser(0,singleuserarray[0].age,1,1);} <add>else if (origin == 1){alert('99');photoBrowser(0,singleuserarray[0].age,1,1);} <ide> else if (!origin){alert('100');photoBrowser(0,singleuserarray[0].age);} <ide> <ide> <ide> function photoBrowser(openprofile,arraynumber,mainchange,chatorigin){ <ide> allowedchange = true; <ide> photoresize = false; <del>if ($('.photo-browser').length > 0){alert('yo1');return false;} <add>if ($('.photo-browser').length > 0){return false;} <ide> <ide> <ide> <ide> myApp.closeModal('.picker-sub'); <ide> <del>alert(new_all); <add> <ide> <ide> <ide> //firebase.database().ref("users/" + f_uid).off('value', userpref); <ide> var to_open = 0; <ide> <ide> <del> if ($('.chatpop').length > 0) {alert('yo3');} <add> if ($('.chatpop').length > 0 || chatorigin) {alert('yo3');} <ide> else { <ide> var countednumbers = 0; <ide>
Java
mit
a64a0834c64716b08b410427396841837b1125b3
0
YOTOV-LIMITED/validator,takenspc/validator,sammuelyee/validator,sammuelyee/validator,tripu/validator,takenspc/validator,sammuelyee/validator,YOTOV-LIMITED/validator,YOTOV-LIMITED/validator,tripu/validator,sammuelyee/validator,tripu/validator,YOTOV-LIMITED/validator,takenspc/validator,validator/validator,tripu/validator,takenspc/validator,validator/validator,tripu/validator,sammuelyee/validator,validator/validator,takenspc/validator,validator/validator,validator/validator,YOTOV-LIMITED/validator
/* * Copyright (c) 2005 Henri Sivonen * Copyright (c) 2013 Mozilla Foundation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package nu.validator.xml; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * @version $Id$ * @author hsivonen */ public class SystemErrErrorHandler implements ErrorHandler { private Writer out; private boolean inError = false; public SystemErrErrorHandler() { try { out = new OutputStreamWriter(System.err, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } private void emitMessage(SAXParseException e, String messageType) throws SAXException { try { String systemId = e.getSystemId(); out.write((systemId == null) ? "" : '\"' + systemId + '\"'); out.write(":"); out.write(Integer.toString(e.getLineNumber())); out.write(":"); out.write(Integer.toString(e.getColumnNumber())); out.write(": "); out.write(messageType); out.write(": "); out.write(e.getMessage()); out.write("\n"); out.flush(); } catch (IOException e1) { throw new SAXException(e1); } } /** * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException) */ public void warning(SAXParseException e) throws SAXException { emitMessage(e, "warning"); } /** * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException) */ public void error(SAXParseException e) throws SAXException { inError = true; emitMessage(e, "error"); } /** * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException) */ public void fatalError(SAXParseException e) throws SAXException { inError = true; emitMessage(e, "fatal error"); } /** * Returns the inError. * * @return the inError */ public boolean isInError() { return inError; } public void reset() { inError = false; } }
src/nu/validator/xml/SystemErrErrorHandler.java
/* * Copyright (c) 2005 Henri Sivonen * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package nu.validator.xml; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * @version $Id$ * @author hsivonen */ public class SystemErrErrorHandler implements ErrorHandler { private Writer out; private boolean inError = false; public SystemErrErrorHandler() { try { out = new OutputStreamWriter(System.err, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException) */ public void warning(SAXParseException e) throws SAXException { try { out.write("Warning:\n"); out.write(e.getMessage()); out.write("\nFile: "); String systemId = e.getSystemId(); out.write((systemId == null) ? "Unknown" : systemId); out.write("\nLine: "); out.write(Integer.toString(e.getLineNumber())); out.write(" Col: "); out.write(Integer.toString(e.getColumnNumber())); out.write("\n\n"); out.flush(); } catch (IOException e1) { throw new SAXException(e1); } } /** * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException) */ public void error(SAXParseException e) throws SAXException { inError = true; try { out.write("Error:\n"); out.write(e.getMessage()); out.write("\nFile: "); String systemId = e.getSystemId(); out.write((systemId == null) ? "Unknown" : systemId); out.write("\nLine: "); out.write(Integer.toString(e.getLineNumber())); out.write(" Col: "); out.write(Integer.toString(e.getColumnNumber())); out.write("\n\n"); out.flush(); } catch (IOException e1) { throw new SAXException(e1); } } /** * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException) */ public void fatalError(SAXParseException e) throws SAXException { inError = true; try { out.write("Fatal Error:\n"); out.write(e.getMessage()); out.write("\nFile: "); String systemId = e.getSystemId(); out.write((systemId == null) ? "Unknown" : systemId); out.write("\nLine: "); out.write(Integer.toString(e.getLineNumber())); out.write(" Col: "); out.write(Integer.toString(e.getColumnNumber())); out.write("\n\n"); out.flush(); } catch (IOException e1) { throw new SAXException(e1); } } /** * Returns the inError. * * @return the inError */ public boolean isInError() { return inError; } public void reset() { inError = false; } }
Make SystemErrErrorHandler emit GNU-format errors
src/nu/validator/xml/SystemErrErrorHandler.java
Make SystemErrErrorHandler emit GNU-format errors
<ide><path>rc/nu/validator/xml/SystemErrErrorHandler.java <ide> /* <ide> * Copyright (c) 2005 Henri Sivonen <add> * Copyright (c) 2013 Mozilla Foundation <ide> * <ide> * Permission is hereby granted, free of charge, to any person obtaining a <ide> * copy of this software and associated documentation files (the "Software"), <ide> } <ide> } <ide> <del> /** <del> * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException) <del> */ <del> public void warning(SAXParseException e) throws SAXException { <add> private void emitMessage(SAXParseException e, String messageType) <add> throws SAXException { <ide> try { <del> out.write("Warning:\n"); <add> String systemId = e.getSystemId(); <add> out.write((systemId == null) ? "" : '\"' + systemId + '\"'); <add> out.write(":"); <add> out.write(Integer.toString(e.getLineNumber())); <add> out.write(":"); <add> out.write(Integer.toString(e.getColumnNumber())); <add> out.write(": "); <add> out.write(messageType); <add> out.write(": "); <ide> out.write(e.getMessage()); <del> out.write("\nFile: "); <del> String systemId = e.getSystemId(); <del> out.write((systemId == null) ? "Unknown" : systemId); <del> out.write("\nLine: "); <del> out.write(Integer.toString(e.getLineNumber())); <del> out.write(" Col: "); <del> out.write(Integer.toString(e.getColumnNumber())); <del> out.write("\n\n"); <add> out.write("\n"); <ide> out.flush(); <ide> } catch (IOException e1) { <ide> throw new SAXException(e1); <ide> } <ide> <ide> /** <add> * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException) <add> */ <add> public void warning(SAXParseException e) throws SAXException { <add> emitMessage(e, "warning"); <add> } <add> <add> /** <ide> * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException) <ide> */ <ide> public void error(SAXParseException e) throws SAXException { <ide> inError = true; <del> try { <del> out.write("Error:\n"); <del> out.write(e.getMessage()); <del> out.write("\nFile: "); <del> String systemId = e.getSystemId(); <del> out.write((systemId == null) ? "Unknown" : systemId); <del> out.write("\nLine: "); <del> out.write(Integer.toString(e.getLineNumber())); <del> out.write(" Col: "); <del> out.write(Integer.toString(e.getColumnNumber())); <del> out.write("\n\n"); <del> out.flush(); <del> } catch (IOException e1) { <del> throw new SAXException(e1); <del> } <add> emitMessage(e, "error"); <ide> } <ide> <ide> /** <ide> */ <ide> public void fatalError(SAXParseException e) throws SAXException { <ide> inError = true; <del> try { <del> out.write("Fatal Error:\n"); <del> out.write(e.getMessage()); <del> out.write("\nFile: "); <del> String systemId = e.getSystemId(); <del> out.write((systemId == null) ? "Unknown" : systemId); <del> out.write("\nLine: "); <del> out.write(Integer.toString(e.getLineNumber())); <del> out.write(" Col: "); <del> out.write(Integer.toString(e.getColumnNumber())); <del> out.write("\n\n"); <del> out.flush(); <del> } catch (IOException e1) { <del> throw new SAXException(e1); <del> } <add> emitMessage(e, "fatal error"); <ide> } <ide> <ide> /**
Java
apache-2.0
error: pathspec 'plugins/ml/src/main/java/greycat/ml/math/timeseries/Stationary.java' did not match any file(s) known to git
cd7d85151cdf2de187eab6ed86d66660e21dc791
1
electricalwind/greycat,datathings/greycat,Neoskai/greycat,Neoskai/greycat,electricalwind/greycat,electricalwind/greycat,Neoskai/greycat,Neoskai/greycat,Neoskai/greycat,electricalwind/greycat,electricalwind/greycat,datathings/greycat,datathings/greycat,datathings/greycat,datathings/greycat,Neoskai/greycat,datathings/greycat,electricalwind/greycat
/** * Copyright 2017 The GreyCat Authors. All rights reserved. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package greycat.ml.math.timeseries; /** * Created by assaad on 20/06/2017. */ public class StationaryCalc { public static double[] diff(double[] series) { if (series.length > 1) { double[] temp = new double[series.length - 1]; for (int i = 1; i < series.length; i++) { temp[i - 1] = series[i] - series[i - 1]; } return temp; } throw new RuntimeException("Series should be at least 2 elements!"); } public static double[] diffNOrder(double[] series, int n) { if (series.length > n) { double[] temp = series; for (int i = 0; i < n; i++) { temp = diff(temp); } return temp; } throw new RuntimeException("Series should be at least N elements!"); } }
plugins/ml/src/main/java/greycat/ml/math/timeseries/Stationary.java
Stationary and finite Diff for time series in ML
plugins/ml/src/main/java/greycat/ml/math/timeseries/Stationary.java
Stationary and finite Diff for time series in ML
<ide><path>lugins/ml/src/main/java/greycat/ml/math/timeseries/Stationary.java <add>/** <add> * Copyright 2017 The GreyCat Authors. All rights reserved. <add> * <p> <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <p> <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <p> <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package greycat.ml.math.timeseries; <add> <add>/** <add> * Created by assaad on 20/06/2017. <add> */ <add>public class StationaryCalc { <add> public static double[] diff(double[] series) { <add> if (series.length > 1) { <add> double[] temp = new double[series.length - 1]; <add> <add> for (int i = 1; i < series.length; i++) { <add> temp[i - 1] = series[i] - series[i - 1]; <add> } <add> <add> return temp; <add> } <add> throw new RuntimeException("Series should be at least 2 elements!"); <add> } <add> <add> public static double[] diffNOrder(double[] series, int n) { <add> if (series.length > n) { <add> double[] temp = series; <add> for (int i = 0; i < n; i++) { <add> temp = diff(temp); <add> } <add> return temp; <add> } <add> throw new RuntimeException("Series should be at least N elements!"); <add> } <add> <add> <add> <add> <add>}
JavaScript
apache-2.0
8afc4c527144ea9d112a9fd7820a6a9bb4ff1c2c
0
tessel/rfid-pn532
// Any copyright is dedicated to the Public Domain. // http://creativecommons.org/publicdomain/zero/1.0/ /********************************************* This example authorizes a mifare classic for read/write operations. First it will read a block of data off the card, write new data over the block, and then read back the data on the card to verify that the data on the card has changed. *********************************************/ var tessel = require('tessel'); var rfidlib = require('../'); // Replace '../' with 'rfid-pn532' in your own code var rfid = rfidlib.use(tessel.port['A'], {read: false}); rfid.on('ready', function (version) { console.log('Ready to read RFID card'); rfid.on('read', function(card) { console.log('Card found!'); console.log('uid:', card.uid); console.log("Start auth #1"); var addr = 0x04; // Block address we will write to var auth_key = [0xff,0xff,0xff,0xff,0xff,0xff]; // Authentication key for data block var new_data = [0xa1,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xab,0xac,0xad,0xae,0xaf,0xff]; // New data to write to block var authType = 0; // Authorization type - 0 for A, 1 for B - A is the most common var afterAuth1 = function(err){ if (err) { console.log("Auth error", err); rfid.startListening(); } else { console.log("Read old data"); rfid.mifareClassicReadBlock(addr, afterRead1) // Read the existing data in the block } }; var afterRead1 = function(err, data){ if (err) { console.log("Read error", err); rfid.startListening(); } else { console.log("Old data", data); console.log("Start auth #2"); rfid.mifareClassicAuthenticateBlock(card.uid,addr,authType,auth_key,afterAuth2); // Just in case the previous auth has timed out } }; var afterAuth2 = function(err){ if (err) { console.log("Auth error", err); rfid.startListening(); } else { console.log('Write new data'); rfid.mifareClassicWriteBlock(addr, new_data, afterWrite); // Write the new data to the block } }; var afterWrite = function(err) { if (err){ console.log("Write error", err); rfid.startListening(); } else { console.log("Start auth #3"); rfid.mifareClassicAuthenticateBlock(card.uid,addr,authType,auth_key,afterAuth3); // Just in case the previous auth has timed out } }; var afterAuth3 = function(err){ if (err){ console.log("Auth error", err); rfid.startListening(); } else { console.log("Read new data"); rfid.mifareClassicReadBlock(addr, afterRead2); // Read back the new data we just wrote to the block } }; var afterRead2 = function(err, data){ if (err) { console.log("Read error", err); rfid.startListening(); } else { console.log("New data", data); setTimeout(function() { rfid.startListening(); }, 2500); // Wait 2.5 seconds and start listening for another card } }; rfid.mifareClassicAuthenticateBlock(card.uid,addr,authType,auth_key,afterAuth1); // Authenticate our block for read/write operations }); }); rfid.on('error', function (err) { console.log(err); });
examples/mifareClassic.js
// Any copyright is dedicated to the Public Domain. // http://creativecommons.org/publicdomain/zero/1.0/ /********************************************* This example authorizes a mifare classic for read/write operations. First it will read a block of data off the card, write new data over the block, and then read back the data on the card to verify that the data on the card has changed. *********************************************/ var tessel = require('tessel'); var rfidlib = require('../'); // Replace '../' with 'rfid-pn532' in your own code var rfid = rfidlib.use(tessel.port['A']); rfid.on('ready', function (version) { console.log('Ready to read RFID card'); rfid.on('read', function(card) { console.log('Card found!'); console.log('uid:', card.uid); console.log("Start auth #1"); var addr = 0x04; // Block address we will write to var auth_key = [0xff,0xff,0xff,0xff,0xff,0xff]; // Authentication key for data block var new_data = [0xa1,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xab,0xac,0xad,0xae,0xaf,0xff]; // New data to write to block var authType = 0; // Authorization type - 0 for A, 1 for B - A is the most common rfid.setPollPeriod(1000*60*60, function(err) { // Set the poll period to give us enough time to run read/write commands without interference var afterAuth1 = function(err){ if (err) { console.log("Auth error", err); rfid.setPollPeriod(250); } else { console.log("Read old data"); rfid.mifareClassicReadBlock(addr, afterRead1) // Read the existing data in the block } }; var afterRead1 = function(err, data){ if (err) { console.log("Read error", err); rfid.setPollPeriod(250); } else { console.log("Old data", data); console.log("Start auth #2"); rfid.mifareClassicAuthenticateBlock(card.uid,addr,authType,auth_key,afterAuth2); // Just in case the previous auth has timed out } }; var afterAuth2 = function(err){ if (err) { console.log("Auth error", err); rfid.setPollPeriod(250); } else { console.log('Write new data'); rfid.mifareClassicWriteBlock(addr, new_data, afterWrite); // Write the new data to the block } }; var afterWrite = function(err) { if (err){ console.log("Write error", err); rfid.setPollPeriod(250); } else { console.log("Start auth #3"); rfid.mifareClassicAuthenticateBlock(card.uid,addr,authType,auth_key,afterAuth3); // Just in case the previous auth has timed out } }; var afterAuth3 = function(err){ if (err){ console.log("Auth error", err); rfid.setPollPeriod(250); } else { console.log("Read new data"); rfid.mifareClassicReadBlock(addr, afterRead2); // Read back the new data we just wrote to the block } }; var afterRead2 = function(err, data){ if (err) { console.log("Read error", err); rfid.setPollPeriod(250); } else { console.log("New data", data); rfid.setPollPeriod(250); // Reset the poll period to start listening for other cards } }; rfid.mifareClassicAuthenticateBlock(card.uid,addr,authType,auth_key,afterAuth1); // Authenticate our block for read/write operations }); }); }); rfid.on('error', function (err) { console.log(err); });
Updated mifare example to work without polling period
examples/mifareClassic.js
Updated mifare example to work without polling period
<ide><path>xamples/mifareClassic.js <ide> var tessel = require('tessel'); <ide> var rfidlib = require('../'); // Replace '../' with 'rfid-pn532' in your own code <ide> <del>var rfid = rfidlib.use(tessel.port['A']); <add>var rfid = rfidlib.use(tessel.port['A'], {read: false}); <ide> <ide> <ide> rfid.on('ready', function (version) { <ide> var new_data = [0xa1,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xab,0xac,0xad,0xae,0xaf,0xff]; // New data to write to block <ide> var authType = 0; // Authorization type - 0 for A, 1 for B - A is the most common <ide> <del> rfid.setPollPeriod(1000*60*60, function(err) { // Set the poll period to give us enough time to run read/write commands without interference <del> <del> var afterAuth1 = function(err){ <del> if (err) { <del> console.log("Auth error", err); <del> rfid.setPollPeriod(250); <del> } else { <del> console.log("Read old data"); <del> rfid.mifareClassicReadBlock(addr, afterRead1) // Read the existing data in the block <del> } <del> }; <add> var afterAuth1 = function(err){ <add> if (err) { <add> console.log("Auth error", err); <add> rfid.startListening(); <add> } else { <add> console.log("Read old data"); <add> rfid.mifareClassicReadBlock(addr, afterRead1) // Read the existing data in the block <add> } <add> }; <ide> <del> var afterRead1 = function(err, data){ <del> if (err) { <del> console.log("Read error", err); <del> rfid.setPollPeriod(250); <del> } else { <del> console.log("Old data", data); <del> console.log("Start auth #2"); <del> rfid.mifareClassicAuthenticateBlock(card.uid,addr,authType,auth_key,afterAuth2); // Just in case the previous auth has timed out <del> } <del> }; <add> var afterRead1 = function(err, data){ <add> if (err) { <add> console.log("Read error", err); <add> rfid.startListening(); <add> } else { <add> console.log("Old data", data); <add> console.log("Start auth #2"); <add> rfid.mifareClassicAuthenticateBlock(card.uid,addr,authType,auth_key,afterAuth2); // Just in case the previous auth has timed out <add> } <add> }; <ide> <del> var afterAuth2 = function(err){ <del> if (err) { <del> console.log("Auth error", err); <del> rfid.setPollPeriod(250); <del> } else { <del> console.log('Write new data'); <del> rfid.mifareClassicWriteBlock(addr, new_data, afterWrite); // Write the new data to the block <del> } <del> }; <add> var afterAuth2 = function(err){ <add> if (err) { <add> console.log("Auth error", err); <add> rfid.startListening(); <add> } else { <add> console.log('Write new data'); <add> rfid.mifareClassicWriteBlock(addr, new_data, afterWrite); // Write the new data to the block <add> } <add> }; <ide> <del> var afterWrite = function(err) { <del> if (err){ <del> console.log("Write error", err); <del> rfid.setPollPeriod(250); <del> } else { <del> console.log("Start auth #3"); <del> rfid.mifareClassicAuthenticateBlock(card.uid,addr,authType,auth_key,afterAuth3); // Just in case the previous auth has timed out <del> } <del> }; <add> var afterWrite = function(err) { <add> if (err){ <add> console.log("Write error", err); <add> rfid.startListening(); <add> } else { <add> console.log("Start auth #3"); <add> rfid.mifareClassicAuthenticateBlock(card.uid,addr,authType,auth_key,afterAuth3); // Just in case the previous auth has timed out <add> } <add> }; <ide> <del> var afterAuth3 = function(err){ <del> if (err){ <del> console.log("Auth error", err); <del> rfid.setPollPeriod(250); <del> } else { <del> console.log("Read new data"); <del> rfid.mifareClassicReadBlock(addr, afterRead2); // Read back the new data we just wrote to the block <del> } <del> }; <add> var afterAuth3 = function(err){ <add> if (err){ <add> console.log("Auth error", err); <add> rfid.startListening(); <add> } else { <add> console.log("Read new data"); <add> rfid.mifareClassicReadBlock(addr, afterRead2); // Read back the new data we just wrote to the block <add> } <add> }; <ide> <del> var afterRead2 = function(err, data){ <del> if (err) { <del> console.log("Read error", err); <del> rfid.setPollPeriod(250); <del> } else { <del> console.log("New data", data); <del> rfid.setPollPeriod(250); // Reset the poll period to start listening for other cards <del> } <del> }; <del> <del> rfid.mifareClassicAuthenticateBlock(card.uid,addr,authType,auth_key,afterAuth1); // Authenticate our block for read/write operations <add> var afterRead2 = function(err, data){ <add> if (err) { <add> console.log("Read error", err); <add> rfid.startListening(); <add> } else { <add> console.log("New data", data); <add> setTimeout(function() { <add> rfid.startListening(); <add> }, 2500); // Wait 2.5 seconds and start listening for another card <add> } <add> }; <add> <add> rfid.mifareClassicAuthenticateBlock(card.uid,addr,authType,auth_key,afterAuth1); // Authenticate our block for read/write operations <ide> <del> }); <ide> }); <ide> }); <ide>
Java
apache-2.0
76a81283fa891973b9301d149b04f64028b9214a
0
tabish121/proton4j
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.qpid.proton4j.engine; import java.util.Map; import org.apache.qpid.proton4j.amqp.Symbol; import org.apache.qpid.proton4j.amqp.transport.ErrorCondition; /** * AMQP Connection state container * * TODO - Better Document the Connection APIs */ public interface Connection { /** * Open the end point. */ public void open(); /** * Close the end point */ public void close(); /** * @return the {@link Context} instance that is associated with this {@link Connection} */ Context getContext(); /** * @return the local endpoint state */ public ConnectionState getLocalState(); /** * @return the local endpoint error, or null if there is none */ public ErrorCondition getLocalCondition(); /** * Sets the local {@link ErrorCondition} to be applied to a {@link Connection} close. * * @param condition * The error condition to convey to the remote peer on connection close. */ public void setLocalCondition(ErrorCondition condition); //----- Operations on local end of this Connection /** * Creates a new Session linked to this Connection * * @return a newly created {@link Session} linked to this {@link Connection}. */ Session session(); /** * @return the Container ID assigned to this Connection */ String getContainerId(); /** * Sets the Container Id to be used when opening this Connection. * * @param containerId * The Container Id used for this end of the Connection. * * @throws IllegalStateException if the Connection has already been opened. */ void setContainerId(String containerId); /** * Set the name of the host (either fully qualified or relative) to which * this connection is connecting to. This information may be used by the * remote peer to determine the correct back-end service to connect the * client to. This value will be sent in the Open performative. * * <b>Note that it is illegal to set the hostname to a numeric IP * address or include a port number.</b> * * @param hostname the RFC1035 compliant host name. * * @throws IllegalStateException if the Connection has already been opened. */ public void setHostname(String hostname); /** * @return returns the host name assigned to this Connection. * * @see #setHostname */ public String getHostname(); /** * Set the channel max value for this Connection. * * @param channelMax * The value to set for channel max when opening the connection. * * @throws IllegalStateException if the Connection has already been opened. */ public void setChannelMax(int channelMax); /** * @return the currently configured channel max for this {@link Connection} */ public int getChannelMax(); /** * Set the idle timeout value for this Connection. * * @param idleTimeout * The value to set for the idle timeout when opening the connection. * * @throws IllegalStateException if the Connection has already been opened. */ public void setIdleTimeout(int idleTimeout); /** * @return the currently configured idle timeout for this {@link Connection} */ public int getIdleTimeout(); /** * Sets the capabilities to be offered on to the remote when this Connection is * opened. * * @param capabilities * The capabilities to be offered to the remote when the Connection is opened. * * @throws IllegalStateException if the Connection has already been opened. */ void setOfferedCapabilities(Symbol[] capabilities); /** * @return the configured capabilities that are offered to the remote when the Connection is opened. */ Symbol[] getOfferedCapabilities(); /** * Sets the capabilities that are desired from the remote when this Connection is * opened. * * @param capabilities * The capabilities desired from the remote when the Connection is opened. * * @throws IllegalStateException if the Connection has already been opened. */ void setDesiredCapabilities(Symbol[] capabilities); /** * @return the configured desired capabilities that are sent to the remote when the Connection is opened. */ Symbol[] getDesiredCapabilities(); /** * Sets the properties to be sent to the remote when this Connection is Opened. * * @param properties * The properties that will be sent to the remote when this Connection is opened. * * @throws IllegalStateException if the Connection has already been opened. */ void setProperties(Map<Symbol, Object> properties); /** * @return the configured properties sent to the remote when this Connection is opened. */ Map<Symbol, Object> getProperties(); //----- View state of remote end of this Connection /** * @return the Container Id assigned to the remote end of the Connection. */ String getRemoteContainerId(); /** * @return the host name assigned to the remote end of this Connection. */ String getRemoteHostname(); /** * @return the capabilities offered by the remote when it opened its end of the Connection. */ Symbol[] getRemoteOfferedCapabilities(); /** * @return the capabilities desired by the remote when it opened its end of the Connection. */ Symbol[] getRemoteDesiredCapabilities(); /** * @return the properties sent by the remote when it opened its end of the Connection. */ Map<Symbol, Object> getRemoteProperties(); /** * @return the remote state (as last communicated) */ public ConnectionState getRemoteState(); /** * @return the remote error, or null if there is none */ public ErrorCondition getRemoteCondition(); //----- Remote events for AMQP Connection resources /** * Sets a EventHandler for when an AMQP Open frame is received from the remote peer. * * Used to process remotely initiated Connections. Locally initiated sessions have their own EventHandler * invoked instead. This method is typically used by servers to listen for the remote peer to open its * connection, while a client would listen for the server to open its end of the connection once a local open * has been performed. * * @param remoteOpenEventHandler * the EventHandler that will be signaled when the connection has been remotely opened * * @return this connection */ Connection openEventHandler(EventHandler<AsyncEvent<Connection>> remoteOpenEventHandler); /** * Sets a EventHandler for when an AMQP Close frame is received from the remote peer. * * @param remoteCloseEventHandler * the EventHandler that will be signaled when the connection is remotely closed. * * @return this connection */ Connection closeEventHandler(EventHandler<AsyncEvent<Connection>> remoteCloseEventHandler); /** * Sets a EventHandler for when an AMQP Begin frame is received from the remote peer. * * Used to process remotely initiated Sessions. Locally initiated sessions have their own EventHandler * invoked instead. This method is Typically used by servers to listen for remote Session creation. * * @param remoteSessionOpenEventHandler * the EventHandler that will be signaled when a session is remotely opened. * * @return this connection */ Connection sessionOpenEventHandler(EventHandler<Session> remoteSessionOpenEventHandler); /** * Sets a EventHandler for when an AMQP Attach frame is received from the remote peer for a sending link. * * Used to process remotely initiated sending link. Locally initiated links have their own EventHandler * invoked instead. This method is Typically used by servers to listen for remote Receiver creation. * If an event handler for remote sender open is registered on the Session that the link is owned by then * that handler will be invoked instead of this one. * * @param remoteSenderOpenEventHandler * the EventHandler that will be signaled when a sender link is remotely opened. * * @return this connection */ Connection senderOpenEventHandler(EventHandler<Sender> remoteSenderOpenEventHandler); /** * Sets a EventHandler for when an AMQP Attach frame is received from the remote peer for a receiving link. * * Used to process remotely initiated receiving link. Locally initiated links have their own EventHandler * invoked instead. This method is Typically used by servers to listen for remote Sender creation. * If an event handler for remote receiver open is registered on the Session that the link is owned by then * that handler will be invoked instead of this one. * * @param remoteReceiverOpenEventHandler * the EventHandler that will be signaled when a receiver link is remotely opened. * * @return this connection */ Connection receiverOpenEventHandler(EventHandler<Receiver> remoteReceiverOpenEventHandler); }
qpid-proton4j-engine/src/main/java/org/apache/qpid/proton4j/engine/Connection.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.qpid.proton4j.engine; import java.util.Map; import org.apache.qpid.proton4j.amqp.Symbol; import org.apache.qpid.proton4j.amqp.transport.ErrorCondition; /** * AMQP Connection state container * * TODO - Better Document the Connection APIs */ public interface Connection { /** * Open the end point. */ public void open(); /** * Close the end point */ public void close(); /** * @return the {@link Context} instance that is associated with this {@link Connection} */ Context getContext(); /** * @return the local endpoint state */ public ConnectionState getLocalState(); /** * @return the local endpoint error, or null if there is none */ public ErrorCondition getLocalCondition(); /** * Sets the local {@link ErrorCondition} to be applied to a {@link Connection} close. * * @param condition * The error condition to convey to the remote peer on connection close. */ public void setLocalCondition(ErrorCondition condition); //----- Operations on local end of this Connection /** * Creates a new Session linked to this Connection */ Session session(); /** * @returns the Container ID assigned to this Connection */ String getContainerId(); /** * Sets the Container Id to be used when opening this Connection. * * @param containerId * The Container Id used for this end of the Connection. * * @throws IllegalStateException if the Connection has already been opened. */ void setContainerId(String containerId); /** * Set the name of the host (either fully qualified or relative) to which * this connection is connecting to. This information may be used by the * remote peer to determine the correct back-end service to connect the * client to. This value will be sent in the Open performative. * * <b>Note that it is illegal to set the hostname to a numeric IP * address or include a port number.</b> * * @param hostname the RFC1035 compliant host name. * * @throws IllegalStateException if the Connection has already been opened. */ public void setHostname(String hostname); /** * @return returns the host name assigned to this Connection. * * @see #setHostname */ public String getHostname(); /** * Set the channel max value for this Connection. * * @param channelMax * The value to set for channel max when opening the connection. * * @throws IllegalStateException if the Connection has already been opened. */ public void setChannelMax(int channelMax); /** * @return the currently configured channel max for this {@link Connection} */ public int getChannelMax(); /** * Set the idle timeout value for this Connection. * * @param idleTimeout * The value to set for the idle timeout when opening the connection. * * @throws IllegalStateException if the Connection has already been opened. */ public void setIdleTimeout(int idleTimeout); /** * @return the currently configured idle timeout for this {@link Connection} */ public int getIdleTimeout(); /** * Sets the capabilities to be offered on to the remote when this Connection is * opened. * * @param capabilities * The capabilities to be offered to the remote when the Connection is opened. * * @throws IllegalStateException if the Connection has already been opened. */ void setOfferedCapabilities(Symbol[] capabilities); /** * @return the configured capabilities that are offered to the remote when the Connection is opened. */ Symbol[] getOfferedCapabilities(); /** * Sets the capabilities that are desired from the remote when this Connection is * opened. * * @param capabilities * The capabilities desired from the remote when the Connection is opened. * * @throws IllegalStateException if the Connection has already been opened. */ void setDesiredCapabilities(Symbol[] capabilities); /** * @return the configured desired capabilities that are sent to the remote when the Connection is opened. */ Symbol[] getDesiredCapabilities(); /** * Sets the properties to be sent to the remote when this Connection is Opened. * * @param properties * The properties that will be sent to the remote when this Connection is opened. * * @throws IllegalStateException if the Connection has already been opened. */ void setProperties(Map<Symbol, Object> properties); /** * @return the configured properties sent to the remote when this Connection is opened. */ Map<Symbol, Object> getProperties(); //----- View state of remote end of this Connection /** * @return the Container Id assigned to the remote end of the Connection. */ String getRemoteContainerId(); /** * @return the host name assigned to the remote end of this Connection. */ String getRemoteHostname(); /** * @return the capabilities offered by the remote when it opened its end of the Connection. */ Symbol[] getRemoteOfferedCapabilities(); /** * @return the capabilities desired by the remote when it opened its end of the Connection. */ Symbol[] getRemoteDesiredCapabilities(); /** * @return the properties sent by the remote when it opened its end of the Connection. */ Map<Symbol, Object> getRemoteProperties(); /** * @return the remote state (as last communicated) */ public ConnectionState getRemoteState(); /** * @return the remote error, or null if there is none */ public ErrorCondition getRemoteCondition(); //----- Remote events for AMQP Connection resources /** * Sets a EventHandler for when an AMQP Open frame is received from the remote peer. * * Used to process remotely initiated Connections. Locally initiated sessions have their own EventHandler * invoked instead. This method is typically used by servers to listen for the remote peer to open its * connection, while a client would listen for the server to open its end of the connection once a local open * has been performed. * * @param remoteOpenEventHandler * the EventHandler that will be signaled when the connection has been remotely opened * * @return this connection */ Connection openEventHandler(EventHandler<AsyncEvent<Connection>> remoteOpenEventHandler); /** * Sets a EventHandler for when an AMQP Close frame is received from the remote peer. * * @param remoteCloseEventHandler * the EventHandler that will be signaled when the connection is remotely closed. * * @return this connection */ Connection closeEventHandler(EventHandler<AsyncEvent<Connection>> remoteCloseEventHandler); /** * Sets a EventHandler for when an AMQP Begin frame is received from the remote peer. * * Used to process remotely initiated Sessions. Locally initiated sessions have their own EventHandler * invoked instead. This method is Typically used by servers to listen for remote Session creation. * * @param remoteSessionOpenEventHandler * the EventHandler that will be signaled when a session is remotely opened. * * @return this connection */ Connection sessionOpenEventHandler(EventHandler<Session> remoteSessionOpenEventHandler); /** * Sets a EventHandler for when an AMQP Attach frame is received from the remote peer for a sending link. * * Used to process remotely initiated sending link. Locally initiated links have their own EventHandler * invoked instead. This method is Typically used by servers to listen for remote Receiver creation. * If an event handler for remote sender open is registered on the Session that the link is owned by then * that handler will be invoked instead of this one. * * @param remoteSenderOpenEventHandler * the EventHandler that will be signaled when a sender link is remotely opened. * * @return this connection */ Connection senderOpenEventHandler(EventHandler<Sender> remoteSenderOpenEventHandler); /** * Sets a EventHandler for when an AMQP Attach frame is received from the remote peer for a receiving link. * * Used to process remotely initiated receiving link. Locally initiated links have their own EventHandler * invoked instead. This method is Typically used by servers to listen for remote Sender creation. * If an event handler for remote receiver open is registered on the Session that the link is owned by then * that handler will be invoked instead of this one. * * @param remoteReceiverOpenEventHandler * the EventHandler that will be signaled when a receiver link is remotely opened. * * @return this connection */ Connection receiverOpenEventHandler(EventHandler<Receiver> remoteReceiverOpenEventHandler); }
Fix some javadocs
qpid-proton4j-engine/src/main/java/org/apache/qpid/proton4j/engine/Connection.java
Fix some javadocs
<ide><path>pid-proton4j-engine/src/main/java/org/apache/qpid/proton4j/engine/Connection.java <ide> <ide> /** <ide> * Creates a new Session linked to this Connection <add> * <add> * @return a newly created {@link Session} linked to this {@link Connection}. <ide> */ <ide> Session session(); <ide> <ide> /** <del> * @returns the Container ID assigned to this Connection <add> * @return the Container ID assigned to this Connection <ide> */ <ide> String getContainerId(); <ide>
Java
cc0-1.0
c01e33f32b3ca77c34d830a20ad7671d6b39fffb
0
cattaka/AdapterToolbox,cattaka/AdapterToolbox
package net.cattaka.android.adaptertoolbox.adapter.listener; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.widget.AdapterView; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.SeekBar; import android.widget.TextView; /** * Created by cattaka on 2016/05/12. */ public class ForwardingListener<A extends RecyclerView.Adapter<? extends VH>, VH extends RecyclerView.ViewHolder> implements IForwardingListener<A, VH, ListenerRelay<A, VH>>, View.OnClickListener, View.OnLongClickListener, RadioGroup.OnCheckedChangeListener, CompoundButton.OnCheckedChangeListener, SeekBar.OnSeekBarChangeListener, AdapterView.OnItemSelectedListener, TextView.OnEditorActionListener { private IProvider<A, VH> mProvider; private ListenerRelay<A, VH> mListenerRelay; public ForwardingListener() { } @Override public void setListenerRelay(@Nullable ListenerRelay<A, VH> listenerRelay) { mListenerRelay = listenerRelay; } @Override public void setProvider(@NonNull IProvider<A, VH> provider) { mProvider = provider; } /** * @see android.view.View.OnClickListener */ @Override public void onClick(View view) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, view) : null); if (vh != null) { mListenerRelay.onClick(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, view); } } } /** * @see android.view.View.OnLongClickListener */ @Override public boolean onLongClick(View view) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, view) : null); if (vh != null) { return mListenerRelay.onLongClick(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, view); } } return false; } /** * @see android.widget.RadioGroup.OnCheckedChangeListener */ @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, group) : null); if (vh != null) { mListenerRelay.onCheckedChanged(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, group, checkedId); } } } /** * @see android.widget.CompoundButton.OnCheckedChangeListener */ @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, buttonView) : null); if (vh != null) { mListenerRelay.onCheckedChanged(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, buttonView, isChecked); } } } /** * @see android.widget.SeekBar.OnSeekBarChangeListener */ @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, seekBar) : null); if (vh != null) { mListenerRelay.onProgressChanged(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, seekBar, progress, fromUser); } } } /** * @see android.widget.SeekBar.OnSeekBarChangeListener */ @Override public void onStartTrackingTouch(SeekBar seekBar) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, seekBar) : null); if (vh != null) { mListenerRelay.onStartTrackingTouch(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, seekBar); } } } /** * @see android.widget.SeekBar.OnSeekBarChangeListener */ @Override public void onStopTrackingTouch(SeekBar seekBar) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, seekBar) : null); if (vh != null) { mListenerRelay.onStopTrackingTouch(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, seekBar); } } } /** * @see android.widget.AdapterView.OnItemSelectedListener */ @Override public void onNothingSelected(AdapterView<?> parent) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, parent) : null); if (vh != null) { mListenerRelay.onNothingSelected(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, parent); } } } /** * @see android.widget.AdapterView.OnItemSelectedListener */ @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, parent) : null); if (vh != null) { mListenerRelay.onItemSelected(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, parent, view, position, id); } } } /** * @see android.widget.TextView.OnEditorActionListener */ @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, v) : null); if (vh != null) { return mListenerRelay.onEditorAction(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, v, actionId, event); } } return false; } /** * @see TextWatcher */ public void addTextChangedListener(@NonNull final EditText target) { target.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, target) : null); if (vh != null) { mListenerRelay.beforeTextChanged(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, target, s, start, count, after); } } } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, target) : null); if (vh != null) { mListenerRelay.onTextChanged(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, target, s, start, count, count); } } } @Override public void afterTextChanged(Editable s) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, target) : null); if (vh != null) { mListenerRelay.afterTextChanged(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, target, s); } } } }); } @Nullable public static RecyclerView.ViewHolder findContainingViewHolder(RecyclerView recyclerView, View view) { View v = view; while (v != null && v.getParent() instanceof View) { if (v.getParent() == recyclerView) { return recyclerView.getChildViewHolder(v); } v = (View) v.getParent(); } return null; } }
adapter-toolbox/src/main/java/net/cattaka/android/adaptertoolbox/adapter/listener/ForwardingListener.java
package net.cattaka.android.adaptertoolbox.adapter.listener; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.widget.AdapterView; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.SeekBar; import android.widget.TextView; /** * Created by cattaka on 2016/05/12. */ public class ForwardingListener<A extends RecyclerView.Adapter<? extends VH>, VH extends RecyclerView.ViewHolder> implements IForwardingListener<A, VH, ListenerRelay<A, VH>>, View.OnClickListener, View.OnLongClickListener, RadioGroup.OnCheckedChangeListener, CompoundButton.OnCheckedChangeListener, SeekBar.OnSeekBarChangeListener, AdapterView.OnItemSelectedListener, TextView.OnEditorActionListener { private IProvider<A, VH> mProvider; private ListenerRelay<A, VH> mListenerRelay; public ForwardingListener() { } @Override public void setListenerRelay(@Nullable ListenerRelay<A, VH> listenerRelay) { mListenerRelay = listenerRelay; } @Override public void setProvider(@NonNull IProvider<A, VH> provider) { mProvider = provider; } /** * @see android.view.View.OnClickListener */ @Override public void onClick(View view) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(view) : null); if (vh != null) { mListenerRelay.onClick(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, view); } } } /** * @see android.view.View.OnLongClickListener */ @Override public boolean onLongClick(View view) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(view) : null); if (vh != null) { return mListenerRelay.onLongClick(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, view); } } return false; } /** * @see android.widget.RadioGroup.OnCheckedChangeListener */ @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(group) : null); if (vh != null) { mListenerRelay.onCheckedChanged(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, group, checkedId); } } } /** * @see android.widget.CompoundButton.OnCheckedChangeListener */ @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(buttonView) : null); if (vh != null) { mListenerRelay.onCheckedChanged(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, buttonView, isChecked); } } } /** * @see android.widget.SeekBar.OnSeekBarChangeListener */ @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(seekBar) : null); if (vh != null) { mListenerRelay.onProgressChanged(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, seekBar, progress, fromUser); } } } /** * @see android.widget.SeekBar.OnSeekBarChangeListener */ @Override public void onStartTrackingTouch(SeekBar seekBar) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(seekBar) : null); if (vh != null) { mListenerRelay.onStartTrackingTouch(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, seekBar); } } } /** * @see android.widget.SeekBar.OnSeekBarChangeListener */ @Override public void onStopTrackingTouch(SeekBar seekBar) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(seekBar) : null); if (vh != null) { mListenerRelay.onStopTrackingTouch(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, seekBar); } } } /** * @see android.widget.AdapterView.OnItemSelectedListener */ @Override public void onNothingSelected(AdapterView<?> parent) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(parent) : null); if (vh != null) { mListenerRelay.onNothingSelected(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, parent); } } } /** * @see android.widget.AdapterView.OnItemSelectedListener */ @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(parent) : null); if (vh != null) { mListenerRelay.onItemSelected(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, parent, view, position, id); } } } /** * @see android.widget.TextView.OnEditorActionListener */ @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(v) : null); if (vh != null) { return mListenerRelay.onEditorAction(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, v, actionId, event); } } return false; } /** * @see TextWatcher */ public void addTextChangedListener(@NonNull final EditText target) { target.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(target) : null); if (vh != null) { mListenerRelay.beforeTextChanged(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, target, s, start, count, after); } } } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(target) : null); if (vh != null) { mListenerRelay.onTextChanged(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, target, s, start, count, count); } } } @Override public void afterTextChanged(Editable s) { if (mListenerRelay != null) { RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); @SuppressWarnings("unchecked") VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(target) : null); if (vh != null) { mListenerRelay.afterTextChanged(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, target, s); } } } }); } }
Step back RecyclerView version to support old one
adapter-toolbox/src/main/java/net/cattaka/android/adaptertoolbox/adapter/listener/ForwardingListener.java
Step back RecyclerView version to support old one
<ide><path>dapter-toolbox/src/main/java/net/cattaka/android/adaptertoolbox/adapter/listener/ForwardingListener.java <ide> if (mListenerRelay != null) { <ide> RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); <ide> @SuppressWarnings("unchecked") <del> VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(view) : null); <add> VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, view) : null); <ide> if (vh != null) { <ide> mListenerRelay.onClick(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, view); <ide> } <ide> if (mListenerRelay != null) { <ide> RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); <ide> @SuppressWarnings("unchecked") <del> VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(view) : null); <add> VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, view) : null); <ide> if (vh != null) { <ide> return mListenerRelay.onLongClick(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, view); <ide> } <ide> if (mListenerRelay != null) { <ide> RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); <ide> @SuppressWarnings("unchecked") <del> VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(group) : null); <add> VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, group) : null); <ide> if (vh != null) { <ide> mListenerRelay.onCheckedChanged(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, group, checkedId); <ide> } <ide> if (mListenerRelay != null) { <ide> RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); <ide> @SuppressWarnings("unchecked") <del> VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(buttonView) : null); <add> VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, buttonView) : null); <ide> if (vh != null) { <ide> mListenerRelay.onCheckedChanged(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, buttonView, isChecked); <ide> } <ide> if (mListenerRelay != null) { <ide> RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); <ide> @SuppressWarnings("unchecked") <del> VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(seekBar) : null); <add> VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, seekBar) : null); <ide> if (vh != null) { <ide> mListenerRelay.onProgressChanged(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, seekBar, progress, fromUser); <ide> } <ide> if (mListenerRelay != null) { <ide> RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); <ide> @SuppressWarnings("unchecked") <del> VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(seekBar) : null); <add> VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, seekBar) : null); <ide> if (vh != null) { <ide> mListenerRelay.onStartTrackingTouch(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, seekBar); <ide> } <ide> if (mListenerRelay != null) { <ide> RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); <ide> @SuppressWarnings("unchecked") <del> VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(seekBar) : null); <add> VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, seekBar) : null); <ide> if (vh != null) { <ide> mListenerRelay.onStopTrackingTouch(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, seekBar); <ide> } <ide> if (mListenerRelay != null) { <ide> RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); <ide> @SuppressWarnings("unchecked") <del> VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(parent) : null); <add> VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, parent) : null); <ide> if (vh != null) { <ide> mListenerRelay.onNothingSelected(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, parent); <ide> } <ide> if (mListenerRelay != null) { <ide> RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); <ide> @SuppressWarnings("unchecked") <del> VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(parent) : null); <add> VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, parent) : null); <ide> if (vh != null) { <ide> mListenerRelay.onItemSelected(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, parent, view, position, id); <ide> } <ide> if (mListenerRelay != null) { <ide> RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); <ide> @SuppressWarnings("unchecked") <del> VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(v) : null); <add> VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, v) : null); <ide> if (vh != null) { <ide> return mListenerRelay.onEditorAction(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, v, actionId, event); <ide> } <ide> if (mListenerRelay != null) { <ide> RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); <ide> @SuppressWarnings("unchecked") <del> VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(target) : null); <add> VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, target) : null); <ide> if (vh != null) { <ide> mListenerRelay.beforeTextChanged(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, target, s, start, count, after); <ide> } <ide> if (mListenerRelay != null) { <ide> RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); <ide> @SuppressWarnings("unchecked") <del> VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(target) : null); <add> VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, target) : null); <ide> if (vh != null) { <ide> mListenerRelay.onTextChanged(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, target, s, start, count, count); <ide> } <ide> if (mListenerRelay != null) { <ide> RecyclerView recyclerView = mProvider.getAttachedRecyclerView(); <ide> @SuppressWarnings("unchecked") <del> VH vh = (VH) (recyclerView != null ? recyclerView.findContainingViewHolder(target) : null); <add> VH vh = (VH) (recyclerView != null ? findContainingViewHolder(recyclerView, target) : null); <ide> if (vh != null) { <ide> mListenerRelay.afterTextChanged(mProvider.getAttachedRecyclerView(), mProvider.getAdapter(), vh, target, s); <ide> } <ide> } <ide> }); <ide> } <add> <add> @Nullable <add> public static RecyclerView.ViewHolder findContainingViewHolder(RecyclerView recyclerView, View view) { <add> View v = view; <add> while (v != null && v.getParent() instanceof View) { <add> if (v.getParent() == recyclerView) { <add> return recyclerView.getChildViewHolder(v); <add> } <add> v = (View) v.getParent(); <add> } <add> return null; <add> } <ide> }
Java
apache-2.0
bd048edb3d7dfba3ccb466171f6ee9889b59413c
0
izumin5210/Bletia
package info.izumin.android.bletia; /** * Created by izumin on 9/10/15. */ public interface BletiaListener { void onConnect(); void onDisconnect(); void onError(BletiaException exception); }
Bletia/src/main/java/info/izumin/android/bletia/BletiaListener.java
package info.izumin.android.bletia; /** * Created by izumin on 9/10/15. */ public interface BletiaListener { void onConnect(); void onDisconnect(); void onError(BleStatus status); }
Change argument type of BletiaListener#onError() to BletiaException
Bletia/src/main/java/info/izumin/android/bletia/BletiaListener.java
Change argument type of BletiaListener#onError() to BletiaException
<ide><path>letia/src/main/java/info/izumin/android/bletia/BletiaListener.java <ide> public interface BletiaListener { <ide> void onConnect(); <ide> void onDisconnect(); <del> void onError(BleStatus status); <add> void onError(BletiaException exception); <ide> }
Java
apache-2.0
e3b728cc9aa93436dae019799fc0503ffb334599
0
rwinch/spring-security,izeye/spring-security,liuguohua/spring-security,hippostar/spring-security,adairtaosy/spring-security,ajdinhedzic/spring-security,eddumelendez/spring-security,mrkingybc/spring-security,chinazhaoht/spring-security,diegofernandes/spring-security,pkdevbox/spring-security,liuguohua/spring-security,cyratech/spring-security,djechelon/spring-security,fhanik/spring-security,adairtaosy/spring-security,fhanik/spring-security,Krasnyanskiy/spring-security,wilkinsona/spring-security,thomasdarimont/spring-security,mparaz/spring-security,mparaz/spring-security,jmnarloch/spring-security,fhanik/spring-security,diegofernandes/spring-security,olezhuravlev/spring-security,eddumelendez/spring-security,wkorando/spring-security,wilkinsona/spring-security,follow99/spring-security,raindev/spring-security,zgscwjm/spring-security,zshift/spring-security,zshift/spring-security,ractive/spring-security,thomasdarimont/spring-security,jgrandja/spring-security,likaiwalkman/spring-security,zhaoqin102/spring-security,cyratech/spring-security,zhaoqin102/spring-security,forestqqqq/spring-security,olezhuravlev/spring-security,rwinch/spring-security,yinhe402/spring-security,mdeinum/spring-security,yinhe402/spring-security,mrkingybc/spring-security,MatthiasWinzeler/spring-security,zgscwjm/spring-security,liuguohua/spring-security,ractive/spring-security,driftman/spring-security,forestqqqq/spring-security,jgrandja/spring-security,vitorgv/spring-security,ajdinhedzic/spring-security,zhaoqin102/spring-security,thomasdarimont/spring-security,dsyer/spring-security,Krasnyanskiy/spring-security,panchenko/spring-security,jgrandja/spring-security,cyratech/spring-security,zshift/spring-security,pwheel/spring-security,rwinch/spring-security,kazuki43zoo/spring-security,eddumelendez/spring-security,zshift/spring-security,follow99/spring-security,tekul/spring-security,Peter32/spring-security,cyratech/spring-security,ajdinhedzic/spring-security,mrkingybc/spring-security,pwheel/spring-security,fhanik/spring-security,spring-projects/spring-security,kazuki43zoo/spring-security,Peter32/spring-security,likaiwalkman/spring-security,spring-projects/spring-security,chinazhaoht/spring-security,yinhe402/spring-security,Xcorpio/spring-security,wkorando/spring-security,ractive/spring-security,caiwenshu/spring-security,pkdevbox/spring-security,xingguang2013/spring-security,jmnarloch/spring-security,hippostar/spring-security,forestqqqq/spring-security,likaiwalkman/spring-security,rwinch/spring-security,xingguang2013/spring-security,Xcorpio/spring-security,pkdevbox/spring-security,MatthiasWinzeler/spring-security,olezhuravlev/spring-security,pwheel/spring-security,diegofernandes/spring-security,mparaz/spring-security,forestqqqq/spring-security,eddumelendez/spring-security,liuguohua/spring-security,fhanik/spring-security,tekul/spring-security,mparaz/spring-security,tekul/spring-security,dsyer/spring-security,raindev/spring-security,zgscwjm/spring-security,djechelon/spring-security,justinedelson/spring-security,caiwenshu/spring-security,spring-projects/spring-security,djechelon/spring-security,diegofernandes/spring-security,mounb/spring-security,Peter32/spring-security,izeye/spring-security,djechelon/spring-security,zgscwjm/spring-security,caiwenshu/spring-security,vitorgv/spring-security,ollie314/spring-security,mdeinum/spring-security,mdeinum/spring-security,jgrandja/spring-security,jmnarloch/spring-security,raindev/spring-security,dsyer/spring-security,panchenko/spring-security,wilkinsona/spring-security,SanjayUser/SpringSecurityPro,Xcorpio/spring-security,panchenko/spring-security,follow99/spring-security,Krasnyanskiy/spring-security,kazuki43zoo/spring-security,xingguang2013/spring-security,raindev/spring-security,yinhe402/spring-security,fhanik/spring-security,thomasdarimont/spring-security,likaiwalkman/spring-security,mounb/spring-security,spring-projects/spring-security,adairtaosy/spring-security,djechelon/spring-security,driftman/spring-security,spring-projects/spring-security,panchenko/spring-security,xingguang2013/spring-security,hippostar/spring-security,pwheel/spring-security,SanjayUser/SpringSecurityPro,justinedelson/spring-security,ollie314/spring-security,mdeinum/spring-security,olezhuravlev/spring-security,chinazhaoht/spring-security,driftman/spring-security,driftman/spring-security,SanjayUser/SpringSecurityPro,Xcorpio/spring-security,eddumelendez/spring-security,spring-projects/spring-security,caiwenshu/spring-security,vitorgv/spring-security,SanjayUser/SpringSecurityPro,thomasdarimont/spring-security,pwheel/spring-security,mrkingybc/spring-security,kazuki43zoo/spring-security,pkdevbox/spring-security,kazuki43zoo/spring-security,rwinch/spring-security,izeye/spring-security,zhaoqin102/spring-security,ajdinhedzic/spring-security,olezhuravlev/spring-security,ollie314/spring-security,wilkinsona/spring-security,mounb/spring-security,rwinch/spring-security,izeye/spring-security,follow99/spring-security,justinedelson/spring-security,jgrandja/spring-security,mounb/spring-security,ractive/spring-security,jmnarloch/spring-security,SanjayUser/SpringSecurityPro,dsyer/spring-security,dsyer/spring-security,hippostar/spring-security,MatthiasWinzeler/spring-security,MatthiasWinzeler/spring-security,wkorando/spring-security,ollie314/spring-security,tekul/spring-security,jgrandja/spring-security,Peter32/spring-security,spring-projects/spring-security,wkorando/spring-security,vitorgv/spring-security,adairtaosy/spring-security,justinedelson/spring-security,chinazhaoht/spring-security,Krasnyanskiy/spring-security
/* Copyright 2004, 2005 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.acegisecurity; /** * Thrown if an authentication request is rejected because the credentials are * not sufficiently trusted. * * <p> * {@link org.acegisecurity.vote.AccessDecisionVoter}s will typically throw * this exception if they are dissatisfied with the level of the * authentication, such as if performed using a remember-me mechanism or * anonymously. The commonly used {@link * org.acegisecurity.intercept.web.SecurityEnforcementFilter} will thus * cause the <code>AuthenticationEntryPoint</code> to be called, allowing the * principal to authenticate with a stronger level of authentication. * </p> * * @author Ben Alex * @version $Id$ */ public class InsufficientAuthenticationException extends AuthenticationException { //~ Constructors =========================================================== /** * Constructs an <code>InsufficientAuthenticationException</code> with the * specified message. * * @param msg the detail message */ public InsufficientAuthenticationException(String msg) { super(msg); } /** * Constructs an <code>InsufficientAuthenticationException</code> with the * specified message and root cause. * * @param msg the detail message * @param t root cause */ public InsufficientAuthenticationException(String msg, Throwable t) { super(msg, t); } }
core/src/main/java/org/acegisecurity/InsufficientAuthenticationException.java
/* Copyright 2004, 2005 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.acegisecurity; /** * Thrown if an authentication request is rejected because the credentials are * not sufficiently trusted. * * <p> * {{@link org.acegisecurity.vote.AccessDecisionVoter}s will typically throw * this exception if they are dissatisfied with the level of the * authentication, such as if performed using a remember-me mechnanism or * anonymously. The commonly used {@link * org.acegisecurity.intercept.web.SecurityEnforcementFilter} will thus * cause the <code>AuthenticationEntryPoint</code> to be called, allowing the * principal to authenticate with a stronger level of authentication. } * </p> * * @author Ben Alex * @version $Id$ */ public class InsufficientAuthenticationException extends AuthenticationException { //~ Constructors =========================================================== /** * Constructs an <code>InsufficientAuthenticationException</code> with the * specified message. * * @param msg the detail message */ public InsufficientAuthenticationException(String msg) { super(msg); } /** * Constructs an <code>InsufficientAuthenticationException</code> with the * specified message and root cause. * * @param msg the detail message * @param t root cause */ public InsufficientAuthenticationException(String msg, Throwable t) { super(msg, t); } }
Javadoc typos.
core/src/main/java/org/acegisecurity/InsufficientAuthenticationException.java
Javadoc typos.
<ide><path>ore/src/main/java/org/acegisecurity/InsufficientAuthenticationException.java <ide> * not sufficiently trusted. <ide> * <ide> * <p> <del> * {{@link org.acegisecurity.vote.AccessDecisionVoter}s will typically throw <add> * {@link org.acegisecurity.vote.AccessDecisionVoter}s will typically throw <ide> * this exception if they are dissatisfied with the level of the <del> * authentication, such as if performed using a remember-me mechnanism or <add> * authentication, such as if performed using a remember-me mechanism or <ide> * anonymously. The commonly used {@link <ide> * org.acegisecurity.intercept.web.SecurityEnforcementFilter} will thus <ide> * cause the <code>AuthenticationEntryPoint</code> to be called, allowing the <del> * principal to authenticate with a stronger level of authentication. } <add> * principal to authenticate with a stronger level of authentication. <ide> * </p> <ide> * <ide> * @author Ben Alex
Java
mit
b2f82359d7d280d9f2a7c2d9f4582ec3065955cd
0
nallar/TickThreading
package nallar.tickthreading.patcher; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import com.google.common.io.Files; import javassist.CannotCompileException; import javassist.ClassLoaderPool; import javassist.ClassPool; import javassist.CtBehavior; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtMethod; import javassist.NotFoundException; import nallar.tickthreading.PatchLog; import nallar.tickthreading.mappings.ClassDescription; import nallar.tickthreading.mappings.FieldDescription; import nallar.tickthreading.mappings.MCPMappings; import nallar.tickthreading.mappings.Mappings; import nallar.tickthreading.mappings.MethodDescription; import nallar.tickthreading.util.CollectionsUtil; import nallar.tickthreading.util.DomUtil; import nallar.unsafe.UnsafeUtil; import net.minecraft.launchwrapper.LaunchClassLoader; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.*; import java.lang.annotation.*; import java.lang.reflect.*; import java.util.*; public class Patcher { private final ClassPool classPool; private final ClassPool preSrgClassPool; private final Mappings mappings; private final Mappings preSrgMappings; private static final boolean DEBUG_PATCHED_OUTPUT = true; private Object patchClassInstance; private Object preSrgPatchClassInstance; private Map<String, PatchMethodDescriptor> patchMethods = new HashMap<String, PatchMethodDescriptor>(); private Map<String, PatchGroup> classToPatchGroup = new HashMap<String, PatchGroup>(); public Patcher(InputStream config, Class<?> patchesClass) { for (Method method : patchesClass.getDeclaredMethods()) { for (Annotation annotation : method.getDeclaredAnnotations()) { if (annotation instanceof Patch) { PatchMethodDescriptor patchMethodDescriptor = new PatchMethodDescriptor(method, (Patch) annotation); patchMethods.put(patchMethodDescriptor.name, patchMethodDescriptor); } } } classPool = new ClassLoaderPool(false); preSrgClassPool = new ClassLoaderPool(true); try { mappings = new MCPMappings(true); preSrgMappings = new MCPMappings(false); } catch (IOException e) { throw new RuntimeException("Failed to load mappings", e); } try { patchClassInstance = patchesClass.getDeclaredConstructors()[0].newInstance(classPool, mappings); preSrgPatchClassInstance = patchesClass.getDeclaredConstructors()[0].newInstance(preSrgClassPool, preSrgMappings); } catch (Exception e) { PatchLog.severe("Failed to instantiate patch class", e); } try { readPatchesFromXmlDocument(DomUtil.readDocumentFromInputStream(config)); } catch (Throwable t) { throw UnsafeUtil.throwIgnoreChecked(t); } } private String env = null; private String getEnv() { String env = this.env; if (env != null) { return env; } try { if (LaunchClassLoader.instance.getClassBytes("za.co.mcportcentral.MCPCConfig") == null) { throw new IOException(); } env = "mcpc"; } catch (IOException e) { env = "forge"; } return this.env = env; } private void readPatchesFromXmlDocument(Document document) { List<Element> patchGroupElements = DomUtil.elementList(document.getDocumentElement().getChildNodes()); for (Element patchGroupElement : patchGroupElements) { new PatchGroup(patchGroupElement); } } public synchronized byte[] preSrgTransformation(String name, String transformedName, byte[] originalBytes) { PatchGroup patchGroup = getPatchGroup(name); if (patchGroup != null && patchGroup.preSrg) { return patchGroup.getClassBytes(name, originalBytes); } return originalBytes; } public synchronized byte[] postSrgTransformation(String name, String transformedName, byte[] originalBytes) { PatchGroup patchGroup = getPatchGroup(transformedName); if (patchGroup != null && !patchGroup.preSrg) { return patchGroup.getClassBytes(transformedName, originalBytes); } return originalBytes; } private PatchGroup getPatchGroup(String name) { return classToPatchGroup.get(name); } private static final Splitter idSplitter = Splitter.on(" ").trimResults().omitEmptyStrings(); private class PatchGroup { public final String name; public final boolean preSrg; public final boolean onDemand; public final ClassPool classPool; public final Mappings mappings; private final Map<String, ClassPatchDescriptor> patches; private final Map<String, byte[]> patchedBytes = new HashMap<String, byte[]>(); private final List<ClassPatchDescriptor> classPatchDescriptors = new ArrayList<ClassPatchDescriptor>(); private boolean ranPatches = false; private PatchGroup(Element element) { Map<String, String> attributes = DomUtil.getAttributes(element); name = element.getTagName(); preSrg = attributes.containsKey("preSrg"); if (preSrg) { classPool = preSrgClassPool; mappings = preSrgMappings; } else { classPool = Patcher.this.classPool; mappings = Patcher.this.mappings; } obfuscateAttributesAndTextContent(element); onDemand = attributes.containsKey("onDemand"); patches = onDemand ? new HashMap<String, ClassPatchDescriptor>() : null; for (Element classElement : DomUtil.elementList(element.getChildNodes())) { ClassPatchDescriptor classPatchDescriptor; try { classPatchDescriptor = new ClassPatchDescriptor(classElement); } catch (Throwable t) { throw new RuntimeException("Failed to create class patch for " + classElement.getAttribute("id"), t); } classPatchDescriptors.add(classPatchDescriptor); classToPatchGroup.put(classPatchDescriptor.name, this); if (onDemand) { if (patches.put(classPatchDescriptor.name, classPatchDescriptor) != null) { throw new Error("Duplicate class patch for " + classPatchDescriptor.name + ", but onDemand is set."); } } } } private void obfuscateAttributesAndTextContent(Element root) { for (Element classElement : DomUtil.elementList(root.getChildNodes())) { String env = classElement.getAttribute("env"); if (env != null && !env.isEmpty()) { if (!env.equals(getEnv())) { root.removeChild(classElement); } } } for (Element element : DomUtil.elementList(root.getChildNodes())) { if (!DomUtil.elementList(element.getChildNodes()).isEmpty()) { obfuscateAttributesAndTextContent(element); } else if (element.getTextContent() != null && !element.getTextContent().isEmpty()) { element.setTextContent(mappings.obfuscate(element.getTextContent())); } Map<String, String> attributes = DomUtil.getAttributes(element); for (Map.Entry<String, String> attributeEntry : attributes.entrySet()) { element.setAttribute(attributeEntry.getKey(), mappings.obfuscate(attributeEntry.getValue())); } } for (Element classElement : DomUtil.elementList(root.getChildNodes())) { String id = classElement.getAttribute("id"); ArrayList<String> list = Lists.newArrayList(idSplitter.split(id)); if (list.size() > 1) { for (String className : list) { Element newClassElement = (Element) classElement.cloneNode(true); newClassElement.setAttribute("id", className.trim()); classElement.getParentNode().insertBefore(newClassElement, classElement); } classElement.getParentNode().removeChild(classElement); } } } private void saveByteCode(byte[] bytes, String name) { if (DEBUG_PATCHED_OUTPUT) { name = name.replace('.', '/') + ".class"; File file = new File("./TTpatched/" + name); file.getParentFile().mkdirs(); try { Files.write(bytes, file); } catch (IOException e) { PatchLog.severe("Failed to save patched bytes for " + name, e); } } } public byte[] getClassBytes(String name, byte[] originalBytes) { if (onDemand) { try { byte[] bytes = patches.get(name).runPatches().toBytecode(); saveByteCode(bytes, name); PatchLog.flush(); return bytes; } catch (Throwable t) { PatchLog.severe("Failed to patch " + name + " in patch group " + name + '.', t); return originalBytes; } } runPatchesIfNeeded(); byte[] bytes = patchedBytes.get(name); if (bytes == null) { PatchLog.severe("Got no patched bytes for " + name); return originalBytes; } return bytes; } private void runPatchesIfNeeded() { if (ranPatches) { return; } ranPatches = true; Set<CtClass> patchedClasses = new HashSet<CtClass>(); for (ClassPatchDescriptor classPatchDescriptor : classPatchDescriptors) { try { patchedClasses.add(classPatchDescriptor.runPatches()); } catch (Throwable t) { PatchLog.severe("Failed to patch " + classPatchDescriptor.name + " in patch group " + name + '.', t); } } for (CtClass ctClass : patchedClasses) { if (!ctClass.isModified()) { PatchLog.severe("Failed to get patched bytes for " + ctClass.getName() + " as it was never modified in patch group " + name + '.'); continue; } try { patchedBytes.put(ctClass.getName(), ctClass.toBytecode()); } catch (Throwable t) { PatchLog.severe("Failed to get patched bytes for " + ctClass.getName() + " in patch group " + name + '.', t); } } PatchLog.flush(); } private class ClassPatchDescriptor { private final Map<String, String> attributes; public final String name; public final List<PatchDescriptor> patches = new ArrayList<PatchDescriptor>(); private ClassPatchDescriptor(Element element) { attributes = DomUtil.getAttributes(element); ClassDescription deobfuscatedClass = new ClassDescription(attributes.get("id")); ClassDescription obfuscatedClass = mappings.map(deobfuscatedClass); name = obfuscatedClass == null ? deobfuscatedClass.name : obfuscatedClass.name; for (Element patchElement : DomUtil.elementList(element.getChildNodes())) { PatchDescriptor patchDescriptor = new PatchDescriptor(patchElement); patches.add(patchDescriptor); List<MethodDescription> methodDescriptionList = MethodDescription.fromListString(deobfuscatedClass.name, patchDescriptor.getMethods()); if (!patchDescriptor.getMethods().isEmpty()) { patchDescriptor.set("deobf", methodDescriptionList.get(0).getShortName()); //noinspection unchecked patchDescriptor.setMethods(MethodDescription.toListString((List<MethodDescription>) mappings.map(methodDescriptionList))); } String field = patchDescriptor.get("field"), prefix = ""; if (field != null && !field.isEmpty()) { if (field.startsWith("this.")) { field = field.substring("this.".length()); prefix = "this."; } String after = "", type = name; if (field.indexOf('.') != -1) { after = field.substring(field.indexOf('.')); field = field.substring(0, field.indexOf('.')); if (!field.isEmpty() && (field.charAt(0) == '$') && prefix.isEmpty()) { ArrayList<String> parameterList = new ArrayList<String>(); for (MethodDescription methodDescriptionOriginal : methodDescriptionList) { MethodDescription methodDescription = mappings.rmap(mappings.map(methodDescriptionOriginal)); methodDescription = methodDescription == null ? methodDescriptionOriginal : methodDescription; int i = 0; for (String parameter : methodDescription.getParameterList()) { if (parameterList.size() <= i) { parameterList.add(parameter); } else if (!parameterList.get(i).equals(parameter)) { parameterList.set(i, null); } i++; } } int parameterIndex = Integer.valueOf(field.substring(1)) - 1; if (parameterIndex >= parameterList.size()) { if (!parameterList.isEmpty()) { PatchLog.severe("Can not obfuscate parameter field " + patchDescriptor.get("field") + ", index: " + parameterIndex + " but parameter list is: " + CollectionsUtil.join(parameterList)); } break; } type = parameterList.get(parameterIndex); if (type == null) { PatchLog.severe("Can not obfuscate parameter field " + patchDescriptor.get("field") + " automatically as this parameter does not have a single type across the methods used in this patch."); break; } prefix = field + '.'; field = after.substring(1); after = ""; } } FieldDescription obfuscatedField = mappings.map(new FieldDescription(type, field)); if (obfuscatedField != null) { patchDescriptor.set("field", prefix + obfuscatedField.name + after); } } } } public CtClass runPatches() throws NotFoundException { CtClass ctClass = classPool.get(name); for (PatchDescriptor patchDescriptor : patches) { PatchMethodDescriptor patchMethodDescriptor = patchMethods.get(patchDescriptor.getPatch()); Object result = patchMethodDescriptor.run(patchDescriptor, ctClass, preSrg ? preSrgPatchClassInstance : patchClassInstance); if (result instanceof CtClass) { ctClass = (CtClass) result; } } return ctClass; } } } private static class PatchDescriptor { private final Map<String, String> attributes; private String methods; private final String patch; PatchDescriptor(Element element) { attributes = DomUtil.getAttributes(element); methods = element.getTextContent().trim(); patch = element.getTagName(); } public String set(String name, String value) { return attributes.put(name, value); } public String get(String name) { return attributes.get(name); } public Map<String, String> getAttributes() { return attributes; } public String getMethods() { return methods; } public String getPatch() { return patch; } public void setMethods(String methods) { this.methods = methods; } } public static class PatchMethodDescriptor { public final String name; public final List<String> requiredAttributes; public final Method patchMethod; public final boolean isClassPatch; public final boolean emptyConstructor; public PatchMethodDescriptor(Method method, Patch patch) { String name = patch.name(); if (Arrays.asList(method.getParameterTypes()).contains(Map.class)) { this.requiredAttributes = CollectionsUtil.split(patch.requiredAttributes()); } else { this.requiredAttributes = null; } if (name == null || name.isEmpty()) { name = method.getName(); } this.name = name; emptyConstructor = patch.emptyConstructor(); isClassPatch = method.getParameterTypes()[0].equals(CtClass.class); patchMethod = method; } public Object run(PatchDescriptor patchDescriptor, CtClass ctClass, Object patchClassInstance) { String methods = patchDescriptor.getMethods(); Map<String, String> attributes = patchDescriptor.getAttributes(); Map<String, String> attributesClean = new HashMap<String, String>(attributes); attributesClean.remove("code"); PatchLog.fine("Patching " + ctClass.getName() + " with " + this.name + '(' + CollectionsUtil.joinMap(attributesClean) + ')' + (methods.isEmpty() ? "" : " {" + methods + '}')); if (requiredAttributes != null && !attributes.keySet().containsAll(requiredAttributes)) { PatchLog.severe("Missing required attributes " + requiredAttributes.toString() + " when patching " + ctClass.getName()); return null; } if ("^all^".equals(methods)) { patchDescriptor.set("silent", "true"); List<CtBehavior> ctBehaviors = new ArrayList<CtBehavior>(); Collections.addAll(ctBehaviors, ctClass.getDeclaredMethods()); Collections.addAll(ctBehaviors, ctClass.getDeclaredConstructors()); CtBehavior initializer = ctClass.getClassInitializer(); if (initializer != null) { ctBehaviors.add(initializer); } for (CtBehavior ctBehavior : ctBehaviors) { run(ctBehavior, attributes, patchClassInstance); } } else if (isClassPatch || (!emptyConstructor && methods.isEmpty())) { return run(ctClass, attributes, patchClassInstance); } else if (methods.isEmpty()) { for (CtConstructor ctConstructor : ctClass.getDeclaredConstructors()) { run(ctConstructor, attributes, patchClassInstance); } } else if ("^static^".equals(methods)) { CtConstructor ctBehavior = ctClass.getClassInitializer(); if (ctBehavior == null) { PatchLog.severe("No static initializer found patching " + ctClass.getName() + " with " + toString()); } else { run(ctBehavior, attributes, patchClassInstance); } } else { List<MethodDescription> methodDescriptions = MethodDescription.fromListString(ctClass.getName(), methods); for (MethodDescription methodDescription : methodDescriptions) { CtMethod ctMethod; try { ctMethod = methodDescription.inClass(ctClass); } catch (Throwable t) { if (!attributes.containsKey("allowMissing")) { PatchLog.warning("", t); } continue; } run(ctMethod, attributes, patchClassInstance); } } return null; } private Object run(CtClass ctClass, Map<String, String> attributes, Object patchClassInstance) { try { if (requiredAttributes == null) { return patchMethod.invoke(patchClassInstance, ctClass); } else { return patchMethod.invoke(patchClassInstance, ctClass, attributes); } } catch (Throwable t) { if (t instanceof InvocationTargetException) { t = t.getCause(); } if (t instanceof CannotCompileException && attributes.containsKey("code")) { PatchLog.severe("Code: " + attributes.get("code")); } PatchLog.severe("Error patching " + ctClass.getName() + " with " + toString(), t); return null; } } private Object run(CtBehavior ctBehavior, Map<String, String> attributes, Object patchClassInstance) { try { if (requiredAttributes == null) { return patchMethod.invoke(patchClassInstance, ctBehavior); } else { return patchMethod.invoke(patchClassInstance, ctBehavior, attributes); } } catch (Throwable t) { if (t instanceof InvocationTargetException) { t = t.getCause(); } if (t instanceof CannotCompileException && attributes.containsKey("code")) { PatchLog.severe("Code: " + attributes.get("code")); } PatchLog.severe("Error patching " + ctBehavior.getName() + " in " + ctBehavior.getDeclaringClass().getName() + " with " + toString(), t); return null; } } @Override public String toString() { return name; } } }
src/main/java/nallar/tickthreading/patcher/Patcher.java
package nallar.tickthreading.patcher; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import com.google.common.io.Files; import javassist.CannotCompileException; import javassist.ClassLoaderPool; import javassist.ClassPool; import javassist.CtBehavior; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtMethod; import javassist.NotFoundException; import nallar.tickthreading.PatchLog; import nallar.tickthreading.mappings.ClassDescription; import nallar.tickthreading.mappings.FieldDescription; import nallar.tickthreading.mappings.MCPMappings; import nallar.tickthreading.mappings.Mappings; import nallar.tickthreading.mappings.MethodDescription; import nallar.tickthreading.util.CollectionsUtil; import nallar.tickthreading.util.DomUtil; import nallar.unsafe.UnsafeUtil; import net.minecraft.launchwrapper.LaunchClassLoader; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.*; import java.lang.annotation.*; import java.lang.reflect.*; import java.util.*; public class Patcher { private final ClassPool classPool; private final ClassPool preSrgClassPool; private final Mappings mappings; private final Mappings preSrgMappings; private static final boolean DEBUG_PATCHED_OUTPUT = true; private Object patchClassInstance; private Object preSrgPatchClassInstance; private Map<String, PatchMethodDescriptor> patchMethods = new HashMap<String, PatchMethodDescriptor>(); private Map<String, PatchGroup> classToPatchGroup = new HashMap<String, PatchGroup>(); public Patcher(InputStream config, Class<?> patchesClass) { for (Method method : patchesClass.getDeclaredMethods()) { for (Annotation annotation : method.getDeclaredAnnotations()) { if (annotation instanceof Patch) { PatchMethodDescriptor patchMethodDescriptor = new PatchMethodDescriptor(method, (Patch) annotation); patchMethods.put(patchMethodDescriptor.name, patchMethodDescriptor); } } } classPool = new ClassLoaderPool(false); preSrgClassPool = new ClassLoaderPool(true); try { mappings = new MCPMappings(true); preSrgMappings = new MCPMappings(false); } catch (IOException e) { throw new RuntimeException("Failed to load mappings", e); } try { patchClassInstance = patchesClass.getDeclaredConstructors()[0].newInstance(classPool, mappings); preSrgPatchClassInstance = patchesClass.getDeclaredConstructors()[0].newInstance(preSrgClassPool, preSrgMappings); } catch (Exception e) { PatchLog.severe("Failed to instantiate patch class", e); } try { readPatchesFromXmlDocument(DomUtil.readDocumentFromInputStream(config)); } catch (Throwable t) { throw UnsafeUtil.throwIgnoreChecked(t); } } private String env = null; private String getEnv() { String env = this.env; if (env != null) { return env; } try { if (LaunchClassLoader.instance.getClassBytes("za.co.mcportcentral.MCPCConfig") == null) { throw new IOException(); } env = "mcpc"; } catch (IOException e) { env = "forge"; } return this.env = env; } private void readPatchesFromXmlDocument(Document document) { List<Element> patchGroupElements = DomUtil.elementList(document.getDocumentElement().getChildNodes()); for (Element patchGroupElement : patchGroupElements) { new PatchGroup(patchGroupElement); } } public synchronized byte[] preSrgTransformation(String name, String transformedName, byte[] originalBytes) { PatchGroup patchGroup = getPatchGroup(name); if (patchGroup != null && patchGroup.preSrg) { return patchGroup.getClassBytes(name, originalBytes); } return originalBytes; } public synchronized byte[] postSrgTransformation(String name, String transformedName, byte[] originalBytes) { PatchGroup patchGroup = getPatchGroup(transformedName); if (patchGroup != null && !patchGroup.preSrg) { return patchGroup.getClassBytes(transformedName, originalBytes); } return originalBytes; } private PatchGroup getPatchGroup(String name) { return classToPatchGroup.get(name); } private static final Splitter idSplitter = Splitter.on(" ").trimResults().omitEmptyStrings(); private class PatchGroup { public final String name; public final boolean preSrg; public final boolean onDemand; public final ClassPool classPool; public final Mappings mappings; private final Map<String, ClassPatchDescriptor> patches; private final Map<String, byte[]> patchedBytes = new HashMap<String, byte[]>(); private final List<ClassPatchDescriptor> classPatchDescriptors = new ArrayList<ClassPatchDescriptor>(); private boolean ranPatches = false; private PatchGroup(Element element) { Map<String, String> attributes = DomUtil.getAttributes(element); name = element.getTagName(); preSrg = attributes.containsKey("preSrg"); if (preSrg) { classPool = preSrgClassPool; mappings = preSrgMappings; } else { classPool = Patcher.this.classPool; mappings = Patcher.this.mappings; } obfuscateAttributesAndTextContent(element); onDemand = attributes.containsKey("onDemand"); patches = onDemand ? new HashMap<String, ClassPatchDescriptor>() : null; for (Element classElement : DomUtil.elementList(element.getChildNodes())) { ClassPatchDescriptor classPatchDescriptor; try { classPatchDescriptor = new ClassPatchDescriptor(classElement); } catch (Throwable t) { throw new RuntimeException("Failed to create class patch for " + classElement.getAttribute("id"), t); } classPatchDescriptors.add(classPatchDescriptor); classToPatchGroup.put(classPatchDescriptor.name, this); if (onDemand) { if (patches.put(classPatchDescriptor.name, classPatchDescriptor) != null) { throw new Error("Duplicate class patch for " + classPatchDescriptor.name + ", but onDemand is set."); } } } } private void obfuscateAttributesAndTextContent(Element root) { for (Element element : DomUtil.elementList(root.getChildNodes())) { if (!DomUtil.elementList(element.getChildNodes()).isEmpty()) { obfuscateAttributesAndTextContent(element); } else if (element.getTextContent() != null && !element.getTextContent().isEmpty()) { element.setTextContent(mappings.obfuscate(element.getTextContent())); } Map<String, String> attributes = DomUtil.getAttributes(element); for (Map.Entry<String, String> attributeEntry : attributes.entrySet()) { element.setAttribute(attributeEntry.getKey(), mappings.obfuscate(attributeEntry.getValue())); } } for (Element classElement : DomUtil.elementList(root.getChildNodes())) { String id = classElement.getAttribute("id"); ArrayList<String> list = Lists.newArrayList(idSplitter.split(id)); if (list.size() > 1) { for (String className : list) { Element newClassElement = (Element) classElement.cloneNode(true); newClassElement.setAttribute("id", className.trim()); classElement.getParentNode().insertBefore(newClassElement, classElement); } classElement.getParentNode().removeChild(classElement); } } } private void saveByteCode(byte[] bytes, String name) { if (DEBUG_PATCHED_OUTPUT) { name = name.replace('.', '/') + ".class"; File file = new File("./TTpatched/" + name); file.getParentFile().mkdirs(); try { Files.write(bytes, file); } catch (IOException e) { PatchLog.severe("Failed to save patched bytes for " + name, e); } } } public byte[] getClassBytes(String name, byte[] originalBytes) { if (onDemand) { try { byte[] bytes = patches.get(name).runPatches().toBytecode(); saveByteCode(bytes, name); PatchLog.flush(); return bytes; } catch (Throwable t) { PatchLog.severe("Failed to patch " + name + " in patch group " + name + '.', t); return originalBytes; } } runPatchesIfNeeded(); byte[] bytes = patchedBytes.get(name); if (bytes == null) { PatchLog.severe("Got no patched bytes for " + name); return originalBytes; } return bytes; } private void runPatchesIfNeeded() { if (ranPatches) { return; } ranPatches = true; Set<CtClass> patchedClasses = new HashSet<CtClass>(); for (ClassPatchDescriptor classPatchDescriptor : classPatchDescriptors) { String env = classPatchDescriptor.attributes.get("env"); if (env != null && !env.isEmpty()) { if (!env.equals(getEnv())) { continue; } } try { patchedClasses.add(classPatchDescriptor.runPatches()); } catch (Throwable t) { PatchLog.severe("Failed to patch " + classPatchDescriptor.name + " in patch group " + name + '.', t); } } for (CtClass ctClass : patchedClasses) { if (!ctClass.isModified()) { PatchLog.severe("Failed to get patched bytes for " + ctClass.getName() + " as it was never modified in patch group " + name + '.'); continue; } try { patchedBytes.put(ctClass.getName(), ctClass.toBytecode()); } catch (Throwable t) { PatchLog.severe("Failed to get patched bytes for " + ctClass.getName() + " in patch group " + name + '.', t); } } PatchLog.flush(); } private class ClassPatchDescriptor { private final Map<String, String> attributes; public final String name; public final List<PatchDescriptor> patches = new ArrayList<PatchDescriptor>(); private ClassPatchDescriptor(Element element) { attributes = DomUtil.getAttributes(element); ClassDescription deobfuscatedClass = new ClassDescription(attributes.get("id")); ClassDescription obfuscatedClass = mappings.map(deobfuscatedClass); name = obfuscatedClass == null ? deobfuscatedClass.name : obfuscatedClass.name; for (Element patchElement : DomUtil.elementList(element.getChildNodes())) { PatchDescriptor patchDescriptor = new PatchDescriptor(patchElement); patches.add(patchDescriptor); List<MethodDescription> methodDescriptionList = MethodDescription.fromListString(deobfuscatedClass.name, patchDescriptor.getMethods()); if (!patchDescriptor.getMethods().isEmpty()) { patchDescriptor.set("deobf", methodDescriptionList.get(0).getShortName()); //noinspection unchecked patchDescriptor.setMethods(MethodDescription.toListString((List<MethodDescription>) mappings.map(methodDescriptionList))); } String field = patchDescriptor.get("field"), prefix = ""; if (field != null && !field.isEmpty()) { if (field.startsWith("this.")) { field = field.substring("this.".length()); prefix = "this."; } String after = "", type = name; if (field.indexOf('.') != -1) { after = field.substring(field.indexOf('.')); field = field.substring(0, field.indexOf('.')); if (!field.isEmpty() && (field.charAt(0) == '$') && prefix.isEmpty()) { ArrayList<String> parameterList = new ArrayList<String>(); for (MethodDescription methodDescriptionOriginal : methodDescriptionList) { MethodDescription methodDescription = mappings.rmap(mappings.map(methodDescriptionOriginal)); methodDescription = methodDescription == null ? methodDescriptionOriginal : methodDescription; int i = 0; for (String parameter : methodDescription.getParameterList()) { if (parameterList.size() <= i) { parameterList.add(parameter); } else if (!parameterList.get(i).equals(parameter)) { parameterList.set(i, null); } i++; } } int parameterIndex = Integer.valueOf(field.substring(1)) - 1; if (parameterIndex >= parameterList.size()) { if (!parameterList.isEmpty()) { PatchLog.severe("Can not obfuscate parameter field " + patchDescriptor.get("field") + ", index: " + parameterIndex + " but parameter list is: " + CollectionsUtil.join(parameterList)); } break; } type = parameterList.get(parameterIndex); if (type == null) { PatchLog.severe("Can not obfuscate parameter field " + patchDescriptor.get("field") + " automatically as this parameter does not have a single type across the methods used in this patch."); break; } prefix = field + '.'; field = after.substring(1); after = ""; } } FieldDescription obfuscatedField = mappings.map(new FieldDescription(type, field)); if (obfuscatedField != null) { patchDescriptor.set("field", prefix + obfuscatedField.name + after); } } } } public CtClass runPatches() throws NotFoundException { CtClass ctClass = classPool.get(name); for (PatchDescriptor patchDescriptor : patches) { PatchMethodDescriptor patchMethodDescriptor = patchMethods.get(patchDescriptor.getPatch()); Object result = patchMethodDescriptor.run(patchDescriptor, ctClass, preSrg ? preSrgPatchClassInstance : patchClassInstance); if (result instanceof CtClass) { ctClass = (CtClass) result; } } return ctClass; } } } private static class PatchDescriptor { private final Map<String, String> attributes; private String methods; private final String patch; PatchDescriptor(Element element) { attributes = DomUtil.getAttributes(element); methods = element.getTextContent().trim(); patch = element.getTagName(); } public String set(String name, String value) { return attributes.put(name, value); } public String get(String name) { return attributes.get(name); } public Map<String, String> getAttributes() { return attributes; } public String getMethods() { return methods; } public String getPatch() { return patch; } public void setMethods(String methods) { this.methods = methods; } } public static class PatchMethodDescriptor { public final String name; public final List<String> requiredAttributes; public final Method patchMethod; public final boolean isClassPatch; public final boolean emptyConstructor; public PatchMethodDescriptor(Method method, Patch patch) { String name = patch.name(); if (Arrays.asList(method.getParameterTypes()).contains(Map.class)) { this.requiredAttributes = CollectionsUtil.split(patch.requiredAttributes()); } else { this.requiredAttributes = null; } if (name == null || name.isEmpty()) { name = method.getName(); } this.name = name; emptyConstructor = patch.emptyConstructor(); isClassPatch = method.getParameterTypes()[0].equals(CtClass.class); patchMethod = method; } public Object run(PatchDescriptor patchDescriptor, CtClass ctClass, Object patchClassInstance) { String methods = patchDescriptor.getMethods(); Map<String, String> attributes = patchDescriptor.getAttributes(); Map<String, String> attributesClean = new HashMap<String, String>(attributes); attributesClean.remove("code"); PatchLog.fine("Patching " + ctClass.getName() + " with " + this.name + '(' + CollectionsUtil.joinMap(attributesClean) + ')' + (methods.isEmpty() ? "" : " {" + methods + '}')); if (requiredAttributes != null && !attributes.keySet().containsAll(requiredAttributes)) { PatchLog.severe("Missing required attributes " + requiredAttributes.toString() + " when patching " + ctClass.getName()); return null; } if ("^all^".equals(methods)) { patchDescriptor.set("silent", "true"); List<CtBehavior> ctBehaviors = new ArrayList<CtBehavior>(); Collections.addAll(ctBehaviors, ctClass.getDeclaredMethods()); Collections.addAll(ctBehaviors, ctClass.getDeclaredConstructors()); CtBehavior initializer = ctClass.getClassInitializer(); if (initializer != null) { ctBehaviors.add(initializer); } for (CtBehavior ctBehavior : ctBehaviors) { run(ctBehavior, attributes, patchClassInstance); } } else if (isClassPatch || (!emptyConstructor && methods.isEmpty())) { return run(ctClass, attributes, patchClassInstance); } else if (methods.isEmpty()) { for (CtConstructor ctConstructor : ctClass.getDeclaredConstructors()) { run(ctConstructor, attributes, patchClassInstance); } } else if ("^static^".equals(methods)) { CtConstructor ctBehavior = ctClass.getClassInitializer(); if (ctBehavior == null) { PatchLog.severe("No static initializer found patching " + ctClass.getName() + " with " + toString()); } else { run(ctBehavior, attributes, patchClassInstance); } } else { List<MethodDescription> methodDescriptions = MethodDescription.fromListString(ctClass.getName(), methods); for (MethodDescription methodDescription : methodDescriptions) { CtMethod ctMethod; try { ctMethod = methodDescription.inClass(ctClass); } catch (Throwable t) { if (!attributes.containsKey("allowMissing")) { PatchLog.warning("", t); } continue; } run(ctMethod, attributes, patchClassInstance); } } return null; } private Object run(CtClass ctClass, Map<String, String> attributes, Object patchClassInstance) { try { if (requiredAttributes == null) { return patchMethod.invoke(patchClassInstance, ctClass); } else { return patchMethod.invoke(patchClassInstance, ctClass, attributes); } } catch (Throwable t) { if (t instanceof InvocationTargetException) { t = t.getCause(); } if (t instanceof CannotCompileException && attributes.containsKey("code")) { PatchLog.severe("Code: " + attributes.get("code")); } PatchLog.severe("Error patching " + ctClass.getName() + " with " + toString(), t); return null; } } private Object run(CtBehavior ctBehavior, Map<String, String> attributes, Object patchClassInstance) { try { if (requiredAttributes == null) { return patchMethod.invoke(patchClassInstance, ctBehavior); } else { return patchMethod.invoke(patchClassInstance, ctBehavior, attributes); } } catch (Throwable t) { if (t instanceof InvocationTargetException) { t = t.getCause(); } if (t instanceof CannotCompileException && attributes.containsKey("code")) { PatchLog.severe("Code: " + attributes.get("code")); } PatchLog.severe("Error patching " + ctBehavior.getName() + " in " + ctBehavior.getDeclaringClass().getName() + " with " + toString(), t); return null; } } @Override public String toString() { return name; } } }
Don't make ClassPatchDescriptors for classes in wrong enviromnet - improves patcher speed, fixes warnings about no patched bytes being available. Signed-off-by: Ross Allan <[email protected]>
src/main/java/nallar/tickthreading/patcher/Patcher.java
Don't make ClassPatchDescriptors for classes in wrong enviromnet - improves patcher speed, fixes warnings about no patched bytes being available.
<ide><path>rc/main/java/nallar/tickthreading/patcher/Patcher.java <ide> } <ide> <ide> private void obfuscateAttributesAndTextContent(Element root) { <add> for (Element classElement : DomUtil.elementList(root.getChildNodes())) { <add> String env = classElement.getAttribute("env"); <add> if (env != null && !env.isEmpty()) { <add> if (!env.equals(getEnv())) { <add> root.removeChild(classElement); <add> } <add> } <add> } <ide> for (Element element : DomUtil.elementList(root.getChildNodes())) { <ide> if (!DomUtil.elementList(element.getChildNodes()).isEmpty()) { <ide> obfuscateAttributesAndTextContent(element); <ide> ranPatches = true; <ide> Set<CtClass> patchedClasses = new HashSet<CtClass>(); <ide> for (ClassPatchDescriptor classPatchDescriptor : classPatchDescriptors) { <del> String env = classPatchDescriptor.attributes.get("env"); <del> if (env != null && !env.isEmpty()) { <del> if (!env.equals(getEnv())) { <del> continue; <del> } <del> } <ide> try { <ide> patchedClasses.add(classPatchDescriptor.runPatches()); <ide> } catch (Throwable t) {
JavaScript
mit
efa633712031191d650e8594144ea55427631fbb
0
phetsims/scenery-phet,phetsims/scenery-phet,phetsims/scenery-phet
// Copyright 2002-2013, University of Colorado Boulder /** * A drag handler for something has a location and is constrained to some (optional) bounds. * * @author Chris Malley (PixelZoom, Inc.) */ define( function( require ) { 'use strict'; // modules var Bounds2 = require( 'DOT/Bounds2' ); var inherit = require( 'PHET_CORE/inherit' ); var ModelViewTransform2 = require( 'PHETCOMMON/view/ModelViewTransform2' ); var SimpleDragHandler = require( 'SCENERY/input/SimpleDragHandler' ); var Events = require( 'AXON/Events' ); /** * @param {Property.<Vector2>} locationProperty - in model coordinate frame * OR {get:...,set:...}, used in Bending Light's PrismNode as somewhat of a hack. * @param {Object} [options] * @constructor */ function MovableDragHandler( locationProperty, options ) { var self = this; // Events for signifying when processing callbacks starts/ends this.events = new Events(); options = _.extend( { dragBounds: Bounds2.EVERYTHING, // {Bounds2} dragging will be constrained to these bounds, in model coordinate frame modelViewTransform: ModelViewTransform2.createIdentity(), // {ModelViewTransform2} defaults to identity startDrag: function( event ) {}, // use this to do something at the start of dragging, like moving a node to the foreground endDrag: function( event ) {}, // use this to do something at the end of dragging, like 'snapping' onDrag: function( event ) {} // use this to do something every time drag is called, such as notify that a user has modified the position }, options ); this.locationProperty = locationProperty; // @private this._dragBounds = options.dragBounds.copy(); // @private this._modelViewTransform = options.modelViewTransform; // @private var startOffset; // where the drag started relative to locationProperty, in parent view coordinates // @private - note where the drag started this.movableDragHandlerStart = function( event ) { self.events.trigger1( 'startedCallbacksForDragStarted', locationProperty.get() ); options.startDrag( event ); // Note the options.startDrag can change the locationProperty, so read it again above, see https://github.com/phetsims/scenery-phet/issues/157 var location = self._modelViewTransform.modelToViewPosition( locationProperty.get() ); startOffset = event.currentTarget.globalToParentPoint( event.pointer.point ).minus( location ); self.events.trigger0( 'endedCallbacksForDragStarted' ); }; // @private - change the location, adjust for starting offset, constrain to drag bounds this.movableDragHandlerDrag = function( event ) { var parentPoint = event.currentTarget.globalToParentPoint( event.pointer.point ).minus( startOffset ); var location = self._modelViewTransform.viewToModelPosition( parentPoint ); location = self._dragBounds.closestPointTo( location ); self.events.trigger1( 'startedCallbacksForDragged', location ); locationProperty.set( location ); options.onDrag( event ); self.events.trigger0( 'endedCallbacksForDragged' ); }; // @private this.movableDragHandlerEnd = function( event ) { self.events.trigger1( 'startedCallbacksForDragEnded', locationProperty.get() ); options.endDrag( event ); self.events.trigger0( 'endedCallbacksForDragEnded' ); }; SimpleDragHandler.call( this, { allowTouchSnag: true, start: this.movableDragHandlerStart, drag: this.movableDragHandlerDrag, end: this.movableDragHandlerEnd } ); } return inherit( SimpleDragHandler, MovableDragHandler, { /** * Sets the dragBounds. * In addition, it forces the location to be within the bounds. * @param {Bounds2} dragBounds */ setDragBounds: function( dragBounds ) { this._dragBounds = dragBounds.copy(); this.locationProperty.set( this._dragBounds.closestPointTo( this.locationProperty.get() ) ); }, set dragBounds( value ) { this.setDragBounds( value ); }, /** * Gets the dragBounds. Clients should not mutate the value returned. * @returns {Bounds2} */ getDragBounds: function() { return this._dragBounds; }, get dragBounds() { return this.getDragBounds(); }, /** * Sets the modelViewTransform. * @param {ModelViewTransform2} modelViewTransform */ setModelViewTransform: function( modelViewTransform ) { this._modelViewTransform = modelViewTransform; }, set modelViewTransform( modelViewTransform ) { this._modelViewTransform = modelViewTransform; }, /** * Gets the modelViewTransform. Clients should not mutate the value returned. * @returns {ModelViewTransform2} */ getModelViewTransform: function() { return this._modelViewTransform; }, get modelViewTransform() { return this._modelViewTransform; }, /** * Forward an event from another listener to this one, useful when dragging an icon from the toolbox. * @param event */ forwardStartEvent: function( event ) { this.movableDragHandlerStart( event ); }, /** * Forward an event from another listener to this one, useful when dragging an icon from the toolbox. * @param event */ forwardDragEvent: function( event ) { this.movableDragHandlerDrag( event ); }, /** * Forward an event from another listener to this one, useful when dragging an icon from the toolbox. * @param event */ forwardEndEvent: function( event ) { this.movableDragHandlerEnd( event ); } } ); } );
js/input/MovableDragHandler.js
// Copyright 2002-2013, University of Colorado Boulder /** * A drag handler for something has a location and is constrained to some (optional) bounds. * * @author Chris Malley (PixelZoom, Inc.) */ define( function( require ) { 'use strict'; // modules var Bounds2 = require( 'DOT/Bounds2' ); var inherit = require( 'PHET_CORE/inherit' ); var ModelViewTransform2 = require( 'PHETCOMMON/view/ModelViewTransform2' ); var SimpleDragHandler = require( 'SCENERY/input/SimpleDragHandler' ); var Events = require( 'AXON/Events' ); /** * @param {Property.<Vector2>} locationProperty - in model coordinate frame * @param {Object} [options] * @constructor */ function MovableDragHandler( locationProperty, options ) { var self = this; // Events for signifying when processing callbacks starts/ends this.events = new Events(); options = _.extend( { dragBounds: Bounds2.EVERYTHING, // {Bounds2} dragging will be constrained to these bounds, in model coordinate frame modelViewTransform: ModelViewTransform2.createIdentity(), // {ModelViewTransform2} defaults to identity startDrag: function( event ) {}, // use this to do something at the start of dragging, like moving a node to the foreground endDrag: function( event ) {}, // use this to do something at the end of dragging, like 'snapping' onDrag: function( event ) {} // use this to do something every time drag is called, such as notify that a user has modified the position }, options ); this.locationProperty = locationProperty; // @private this._dragBounds = options.dragBounds.copy(); // @private this._modelViewTransform = options.modelViewTransform; // @private var startOffset; // where the drag started relative to locationProperty, in parent view coordinates // @private - note where the drag started this.movableDragHandlerStart = function( event ) { self.events.trigger1( 'startedCallbacksForDragStarted', locationProperty.get() ); options.startDrag( event ); // Note the options.startDrag can change the locationProperty, so read it again above, see https://github.com/phetsims/scenery-phet/issues/157 var location = self._modelViewTransform.modelToViewPosition( locationProperty.get() ); startOffset = event.currentTarget.globalToParentPoint( event.pointer.point ).minus( location ); self.events.trigger0( 'endedCallbacksForDragStarted' ); }; // @private - change the location, adjust for starting offset, constrain to drag bounds this.movableDragHandlerDrag = function( event ) { var parentPoint = event.currentTarget.globalToParentPoint( event.pointer.point ).minus( startOffset ); var location = self._modelViewTransform.viewToModelPosition( parentPoint ); location = self._dragBounds.closestPointTo( location ); self.events.trigger1( 'startedCallbacksForDragged', location ); locationProperty.set( location ); options.onDrag( event ); self.events.trigger0( 'endedCallbacksForDragged' ); }; // @private this.movableDragHandlerEnd = function( event ) { self.events.trigger1( 'startedCallbacksForDragEnded', locationProperty.get() ); options.endDrag( event ); self.events.trigger0( 'endedCallbacksForDragEnded' ); }; SimpleDragHandler.call( this, { allowTouchSnag: true, start: this.movableDragHandlerStart, drag: this.movableDragHandlerDrag, end: this.movableDragHandlerEnd } ); } return inherit( SimpleDragHandler, MovableDragHandler, { /** * Sets the dragBounds. * In addition, it forces the location to be within the bounds. * @param {Bounds2} dragBounds */ setDragBounds: function( dragBounds ) { this._dragBounds = dragBounds.copy(); this.locationProperty.set( this._dragBounds.closestPointTo( this.locationProperty.value ) ); }, set dragBounds( value ) { this.setDragBounds( value ); }, /** * Gets the dragBounds. Clients should not mutate the value returned. * @returns {Bounds2} */ getDragBounds: function() { return this._dragBounds; }, get dragBounds() { return this.getDragBounds(); }, /** * Sets the modelViewTransform. * @param {ModelViewTransform2} modelViewTransform */ setModelViewTransform: function( modelViewTransform ) { this._modelViewTransform = modelViewTransform; }, set modelViewTransform( modelViewTransform ) { this._modelViewTransform = modelViewTransform; }, /** * Gets the modelViewTransform. Clients should not mutate the value returned. * @returns {ModelViewTransform2} */ getModelViewTransform: function() { return this._modelViewTransform; }, get modelViewTransform() { return this._modelViewTransform; }, /** * Forward an event from another listener to this one, useful when dragging an icon from the toolbox. * @param event */ forwardStartEvent: function( event ) { this.movableDragHandlerStart( event ); }, /** * Forward an event from another listener to this one, useful when dragging an icon from the toolbox. * @param event */ forwardDragEvent: function( event ) { this.movableDragHandlerDrag( event ); }, /** * Forward an event from another listener to this one, useful when dragging an icon from the toolbox. * @param event */ forwardEndEvent: function( event ) { this.movableDragHandlerEnd( event ); } } ); } );
Use Property.get() instead of Property.value and added docs
js/input/MovableDragHandler.js
Use Property.get() instead of Property.value and added docs
<ide><path>s/input/MovableDragHandler.js <ide> <ide> /** <ide> * @param {Property.<Vector2>} locationProperty - in model coordinate frame <add> * OR {get:...,set:...}, used in Bending Light's PrismNode as somewhat of a hack. <ide> * @param {Object} [options] <ide> * @constructor <ide> */ <ide> */ <ide> setDragBounds: function( dragBounds ) { <ide> this._dragBounds = dragBounds.copy(); <del> this.locationProperty.set( this._dragBounds.closestPointTo( this.locationProperty.value ) ); <add> this.locationProperty.set( this._dragBounds.closestPointTo( this.locationProperty.get() ) ); <ide> }, <ide> set dragBounds( value ) { this.setDragBounds( value ); }, <ide>
JavaScript
apache-2.0
57f1ff7cbcab1e755d1f7b2fdcad917f72d957b2
0
bbreck3/dsp-core,neroxing/dsp-core,billappleton/dsp-core,billappleton/dsp-core,billappleton/dsp-core,bbreck3/dsp-core,neroxing/dsp-core,neroxing/dsp-core,bbreck3/dsp-core,billappleton/dsp-core,bbreck3/dsp-core,neroxing/dsp-core
/** * Created with JetBrains PhpStorm. * User: jasonsykes * Date: 1/28/13 * Time: 12:17 PM * To change this template use File | Settings | File Templates. */ var AdminApp = angular.module("AdminApp", ["ngResource", "ngGrid"]). config(function ($routeProvider) { $routeProvider.when('/app', { controller:AppCtrl, templateUrl:'applications.html' }); $routeProvider.when('/user', { controller:UserCtrl, templateUrl:'users.html' }); $routeProvider.when('/role', { controller:RoleCtrl, templateUrl:'roles.html' }); $routeProvider.when('/group', { controller:GroupCtrl, templateUrl:'groups.html' }); $routeProvider.when('/schema', { controller:SchemaCtrl, templateUrl:'schema.html' }); $routeProvider.when('/service', { controller:ServiceCtrl, templateUrl:'services.html' }); $routeProvider.when('/import', { controller:FileCtrl, templateUrl:'import.html' }); }). directive('uiValidateEquals', function() { return { require: 'ngModel', link: function(scope, elm, attrs, ctrl) { function validateEqual(myValue, otherValue) { if (myValue === otherValue) { ctrl.$setValidity('equal', true); return myValue; } else { ctrl.$setValidity('equal', false); return undefined; } } scope.$watch(attrs.uiValidateEquals, function(otherModelValue) { validateEqual(ctrl.$viewValue, otherModelValue); }); ctrl.$parsers.unshift(function(viewValue) { return validateEqual(viewValue, scope.$eval(attrs.uiValidateEquals)); }); ctrl.$formatters.unshift(function(modelValue) { return validateEqual(modelValue, scope.$eval(attrs.uiValidateEquals)); }); } }; }); AdminApp.factory('AppsRelated', function ($resource) { return $resource('/rest/system/app/:id/?app_name=admin&fields=*&related=roles', {}, { update:{ method:'PUT' }, query:{ method:'GET', isArray:false } }); }); AdminApp.factory('App', function ($resource) { return $resource('/rest/system/app/:id/?app_name=admin&fields=*', {}, { update:{ method:'PUT' }, query:{ method:'GET', isArray:false } }); }); AdminApp.factory('User', function ($resource) { return $resource('/rest/system/user/:id/?app_name=admin&fields=*', {}, { update:{ method:'PUT' }, query:{ method:'GET', isArray:false } }); }); AdminApp.factory('Role', function ($resource) { return $resource('/rest/system/role/:id/?app_name=admin&fields=*', {}, { update:{ method:'PUT' }, query:{ method:'GET', isArray:false } }); }); AdminApp.factory('RolesRelated', function ($resource) { return $resource('/rest/system/role/:id/?app_name=admin&fields=*&related=users,apps,role_service_accesses', {}, { update:{ method:'PUT' }, query:{ method:'GET', isArray:false } }); }); AdminApp.factory('Service', function ($resource) { return $resource('/rest/system/service/:id/?app_name=admin&fields=*', {}, { update:{ method:'PUT' }, query:{ method:'GET', isArray:false } }); }); AdminApp.factory('Schema', function ($resource) { return $resource('/rest/schema/:name/?app_name=admin&fields=*', {}, { update:{ method:'PUT' }, query:{ method:'GET', isArray:false } }); }); AdminApp.factory('DB', function ($resource) { return $resource('/rest/db/:name/?app_name=admin&fields=*', {}, { update:{ method:'PUT' }, query:{ method:'GET', isArray:false } }); }); AdminApp.factory('Group', function ($resource) { return $resource('/rest/system/app_group/:id/?app_name=admin&fields=*&related=apps', {}, { update:{ method:'PUT' }, query:{ method:'GET', isArray:false } }); }); AdminApp.factory('Group', function ($resource) { return $resource('/rest/system/app_group/:id/?app_name=admin&fields=*&related=apps', {}, { update:{ method:'PUT' }, query:{ method:'GET', isArray:false } }); }); var setCurrentApp = function(currentApp){ $('.active').removeClass('active'); $("#nav_" + currentApp).addClass("active"); }; $(document).ready(function () { $('#app-container').css('height', ($(window).height()-44)); // $('#grid-table').css('max-height', ($(window).height()-56)).css('height', ($(window).height()-56)); $(window).resize(function () { $('#app-container').css('height', ($(window).height()-44)); // $('#grid-table').css('max-height', ($(window).height()-56)).css('height', ($(window).height()-56)); }); });
js/app.js
/** * Created with JetBrains PhpStorm. * User: jasonsykes * Date: 1/28/13 * Time: 12:17 PM * To change this template use File | Settings | File Templates. */ var AdminApp = angular.module("AdminApp", ["ngResource", "ngGrid"]). config(function ($routeProvider) { $routeProvider.when('/app', { controller:AppCtrl, templateUrl:'applications.html' }); $routeProvider.when('/user', { controller:UserCtrl, templateUrl:'users.html' }); $routeProvider.when('/role', { controller:RoleCtrl, templateUrl:'roles.html' }); $routeProvider.when('/group', { controller:GroupCtrl, templateUrl:'groups.html' }); $routeProvider.when('/schema', { controller:SchemaCtrl, templateUrl:'schema.html' }); $routeProvider.when('/service', { controller:ServiceCtrl, templateUrl:'services.html' }); $routeProvider.when('/import', { controller:FileCtrl, templateUrl:'import.html' }); }); AdminApp.factory('AppsRelated', function ($resource) { return $resource('/rest/system/app/:id/?app_name=admin&fields=*&related=roles', {}, { update:{ method:'PUT' }, query:{ method:'GET', isArray:false } }); }); AdminApp.factory('App', function ($resource) { return $resource('/rest/system/app/:id/?app_name=admin&fields=*', {}, { update:{ method:'PUT' }, query:{ method:'GET', isArray:false } }); }); AdminApp.factory('User', function ($resource) { return $resource('/rest/system/user/:id/?app_name=admin&fields=*', {}, { update:{ method:'PUT' }, query:{ method:'GET', isArray:false } }); }); AdminApp.factory('Role', function ($resource) { return $resource('/rest/system/role/:id/?app_name=admin&fields=*', {}, { update:{ method:'PUT' }, query:{ method:'GET', isArray:false } }); }); AdminApp.factory('RolesRelated', function ($resource) { return $resource('/rest/system/role/:id/?app_name=admin&fields=*&related=users,apps,role_service_accesses', {}, { update:{ method:'PUT' }, query:{ method:'GET', isArray:false } }); }); AdminApp.factory('Service', function ($resource) { return $resource('/rest/system/service/:id/?app_name=admin&fields=*', {}, { update:{ method:'PUT' }, query:{ method:'GET', isArray:false } }); }); AdminApp.factory('Schema', function ($resource) { return $resource('/rest/schema/:name/?app_name=admin&fields=*', {}, { update:{ method:'PUT' }, query:{ method:'GET', isArray:false } }); }); AdminApp.factory('DB', function ($resource) { return $resource('/rest/db/:name/?app_name=admin&fields=*', {}, { update:{ method:'PUT' }, query:{ method:'GET', isArray:false } }); }); AdminApp.factory('Group', function ($resource) { return $resource('/rest/system/app_group/:id/?app_name=admin&fields=*&related=apps', {}, { update:{ method:'PUT' }, query:{ method:'GET', isArray:false } }); }); AdminApp.factory('Group', function ($resource) { return $resource('/rest/system/app_group/:id/?app_name=admin&fields=*&related=apps', {}, { update:{ method:'PUT' }, query:{ method:'GET', isArray:false } }); }); var setCurrentApp = function(currentApp){ $('.active').removeClass('active'); $("#nav_" + currentApp).addClass("active"); }; $(document).ready(function () { $('#app-container').css('height', ($(window).height()-44)); // $('#grid-table').css('max-height', ($(window).height()-56)).css('height', ($(window).height()-56)); $(window).resize(function () { $('#app-container').css('height', ($(window).height()-44)); // $('#grid-table').css('max-height', ($(window).height()-56)).css('height', ($(window).height()-56)); }); });
Restore directive that was overwritten.
js/app.js
Restore directive that was overwritten.
<ide><path>s/app.js <ide> $routeProvider.when('/service', { controller:ServiceCtrl, templateUrl:'services.html' }); <ide> $routeProvider.when('/import', { controller:FileCtrl, templateUrl:'import.html' }); <ide> <add> }). <add> directive('uiValidateEquals', function() { <add> <add> return { <add> require: 'ngModel', <add> link: function(scope, elm, attrs, ctrl) { <add> <add> function validateEqual(myValue, otherValue) { <add> if (myValue === otherValue) { <add> ctrl.$setValidity('equal', true); <add> return myValue; <add> } else { <add> ctrl.$setValidity('equal', false); <add> return undefined; <add> } <add> } <add> <add> scope.$watch(attrs.uiValidateEquals, function(otherModelValue) { <add> validateEqual(ctrl.$viewValue, otherModelValue); <add> }); <add> <add> ctrl.$parsers.unshift(function(viewValue) { <add> return validateEqual(viewValue, scope.$eval(attrs.uiValidateEquals)); <add> }); <add> <add> ctrl.$formatters.unshift(function(modelValue) { <add> return validateEqual(modelValue, scope.$eval(attrs.uiValidateEquals)); <add> }); <add> } <add> }; <ide> }); <ide> AdminApp.factory('AppsRelated', function ($resource) { <ide> return $resource('/rest/system/app/:id/?app_name=admin&fields=*&related=roles', {}, { update:{ method:'PUT' }, query:{
JavaScript
isc
e3aef580a2879a7ae94a5a6dc0dcf957757ffaa3
0
thics/ripple-client-desktop,yongsoo/ripple-client-desktop,wangbibo/ripple-client,darkdarkdragon/ripple-client-desktop,mrajvanshy/ripple-client,yxxyun/ripple-client,xdv/giving-client,resilience-me/DEPRICATED_ripple-client,yongsoo/ripple-client,MatthewPhinney/ripple-client-desktop,ripple/ripple-client-desktop,arturomc/ripple-client,MatthewPhinney/ripple-client,MatthewPhinney/ripple-client,Madsn/ripple-client,yxxyun/ripple-client,mrajvanshy/ripple-client,ripple/ripple-client,yongsoo/ripple-client,mrajvanshy/ripple-client,darkdarkdragon/ripple-client,h0vhannes/ripple-client,ripple/ripple-client,xdv/ripple-client-desktop,h0vhannes/ripple-client,resilience-me/DEPRICATED_ripple-client,darkdarkdragon/ripple-client-desktop,Madsn/ripple-client,MatthewPhinney/ripple-client-desktop,darkdarkdragon/ripple-client,vhpoet/ripple-client-desktop,ripple/ripple-client,bankonme/ripple-client-desktop,h0vhannes/ripple-client,Madsn/ripple-client,wangbibo/ripple-client,wangbibo/ripple-client,xdv/ripple-client,yxxyun/ripple-client-desktop,xdv/giving-client,bsteinlo/ripple-client,dncohen/ripple-client-desktop,MatthewPhinney/ripple-client,vhpoet/ripple-client,mrajvanshy/ripple-client-desktop,yxxyun/ripple-client,xdv/ripple-client,ripple/ripple-client,vhpoet/ripple-client,darkdarkdragon/ripple-client,yongsoo/ripple-client,h0vhannes/ripple-client,MatthewPhinney/ripple-client,xdv/giving-client,Madsn/ripple-client,yongsoo/ripple-client,mrajvanshy/ripple-client-desktop,arturomc/ripple-client,arturomc/ripple-client,darkdarkdragon/ripple-client,thics/ripple-client-desktop,yxxyun/ripple-client-desktop,xdv/ripple-client-desktop,xdv/ripple-client-desktop,xdv/ripple-client,bsteinlo/ripple-client,arturomc/ripple-client,xdv/ripple-client,yongsoo/ripple-client-desktop,yxxyun/ripple-client,ripple/giving-client,mrajvanshy/ripple-client,dncohen/ripple-client-desktop,wangbibo/ripple-client,vhpoet/ripple-client,vhpoet/ripple-client,bankonme/ripple-client-desktop,ripple/ripple-client-desktop,ripple/giving-client,vhpoet/ripple-client-desktop
var util = require('util'); var webutil = require('../util/web'); var Tab = require('../client/tabmanager').Tab; var Amount = ripple.Amount; var TradeTab = function () { Tab.call(this); }; util.inherits(TradeTab, Tab); TradeTab.prototype.parent = 'advanced'; TradeTab.prototype.generateHtml = function () { return require('../../jade/tabs/trade.jade')(); }; TradeTab.prototype.angularDeps = Tab.prototype.angularDeps.concat(['ledger']); TradeTab.prototype.angular = function(module) { var self = this; var app = this.app; module.controller('TradeCtrl', ['rpLedger', '$scope', function (ledger, $scope) { $scope.mode = "confirm"; $scope.orders = []; var pairs = require('../data/pairs'); $scope.pairs_query = webutil.queryFromOptions(pairs); $scope.reset = function (keepPair) { var pair = keepPair ? $scope.order.currency_pair : pairs[0].name; var fIssuer= keepPair ? $scope.order.first_issuer : app.id.account; var sIssuer= keepPair ? $scope.order.second_issuer : app.id.account; if ($scope.orderForm) $scope.orderForm.$setPristine(); $scope.mode = "trade"; $scope.order = { type: 'buy', first: '', price: '', second: '', currency_pair: pair, first_currency: pair.slice(0, 3), second_currency: pair.slice(4, 7), first_issuer: fIssuer, second_issuer: sIssuer, listing: 'my', // This variable is true if both the pair and the issuers are set to // valid values. It is used to enable or disable all the functionality // on the page. valid_settings: false }; updateSettings(); }; $scope.back = function () { $scope.mode = "trade"; }; $scope.place_order = function () { $scope.mode = "confirm"; if ($scope.order.type === 'buy') { $scope.order.sell_amount = $scope.order.second_amount; $scope.order.buy_amount = $scope.order.first_amount; } else { $scope.order.sell_amount = $scope.order.first_amount; $scope.order.buy_amount = $scope.order.second_amount; } }; $scope.cancel_order = function () { var tx = app.net.remote.transaction(); tx.offer_cancel(app.id.account, this.entry.seq); tx.on('success', function () { }); tx.on('error', function () { $scope.mode = "error"; $scope.$digest(); }); tx.submit(); this.cancelled = true; }; $scope.order_confirmed = function () { var tx = app.net.remote.transaction(); tx.offer_create(app.id.account, $scope.order.buy_amount, $scope.order.sell_amount); tx.on('success', function (res) { setEngineStatus(res, false); $scope.done(this.hash); $scope.$digest(); }); tx.on('error', function () { $scope.mode = "error"; $scope.$digest(); }); tx.submit(); $scope.mode = "sending"; }; $scope.done = function (hash) { console.log('done'); $scope.mode = "done"; app.net.remote.on('account', handleAccountEvent); function handleAccountEvent(e) { console.log('got event'); if (e.transaction.hash === hash) { console.log('into hash'); setEngineStatus(e, true); $scope.$digest(); app.net.remote.removeListener('account', handleAccountEvent); } } }; function setEngineStatus(res, accepted) { $scope.engine_result = res.engine_result; $scope.engine_result_message = res.engine_result_message; switch (res.engine_result.slice(0, 3)) { case 'tes': $scope.tx_result = accepted ? "cleared" : "pending"; break; case 'tem': $scope.tx_result = "malformed"; break; case 'ter': $scope.tx_result = "failed"; break; case 'tec': $scope.tx_result = "claim"; break; case 'tep': console.warn("Unhandled engine status encountered!"); } } $scope.$watch('order.currency_pair', function (pair) { updateSettings(); resetIssuers(true); }, true); $scope.$watch('order.first', function (amount_str) { $scope.update_first(); }, true); $scope.$watch('order.price', function (amount_str) { $scope.update_price(); }, true); $scope.$watch('order.second', function (amount_str) { $scope.update_second(); }, true); $scope.update_first = function () { var first_currency = $scope.order.first_currency || "XRP"; var formatted = "" + $scope.order.first + " " + first_currency; $scope.order.first_amount = ripple.Amount.from_human(formatted); if (first_currency !== 'XRP') $scope.order.first_amount.set_issuer($scope.order.first_issuer); }; $scope.update_price = function () { var second_currency = $scope.order.second_currency || "XRP"; var formatted = "" + $scope.order.price + " " + second_currency; $scope.order.price_amount = ripple.Amount.from_human(formatted); if (second_currency !== 'XRP') $scope.order.price_amount.set_issuer($scope.order.second_issuer); }; $scope.update_second = function () { var second_currency = $scope.order.second_currency || "XRP"; var formatted = "" + $scope.order.second + " " + second_currency; $scope.order.second_amount = ripple.Amount.from_human(formatted); if (second_currency !== 'XRP') $scope.order.second_amount.set_issuer($scope.order.second_issuer); }; $scope.calc_second = function () { $scope.update_first(); $scope.update_price(); if ($scope.order.price_amount && $scope.order.price_amount.is_valid() && $scope.order.first_amount && $scope.order.first_amount.is_valid()) { $scope.order.second_amount = $scope.order.price_amount.product_human($scope.order.first_amount); $scope.order.second = +$scope.order.second_amount.to_human({group_sep: false}); } }; $scope.calc_first = function () { $scope.update_second(); $scope.update_price(); if ($scope.order.price_amount && $scope.order.price_amount.is_valid() && $scope.order.second_amount && $scope.order.second_amount.is_valid()) { $scope.order.first_amount = $scope.order.second_amount.ratio_human($scope.order.price_amount); $scope.order.first = +$scope.order.first_amount.to_human({group_sep: false}); } }; // This functions is called whenever the settings, specifically the pair and // the issuer(s) have been modified. It checks the new configuration and // sets $scope.valid_settings. function updateSettings() { console.log("updateSettings"); var pair = $scope.order.currency_pair; if ("string" !== typeof pair || !pair.match(/^[a-z]{3}\/[a-z]{3}$/i)) { $scope.order.first_currency = 'XRP'; $scope.order.second_currency = 'XRP'; $scope.order.valid_settings = false; return; } var first_currency = $scope.order.first_currency = pair.slice(0, 3); var second_currency = $scope.order.second_currency = pair.slice(4, 7); var first_issuer = ripple.UInt160.from_json($scope.order.first_issuer); var second_issuer = ripple.UInt160.from_json($scope.order.second_issuer); if ((first_currency !== 'XRP' && !first_issuer.is_valid()) || (second_currency !== 'XRP' && !second_issuer.is_valid())) { $scope.order.valid_settings = false; return; } if ($scope.order.type === "buy") { $scope.order.sell_currency = $scope.order.second_currency; $scope.order.buy_currency = $scope.order.first_currency; $scope.order.sell_issuer = $scope.order.second_issuer; $scope.order.buy_issuer = $scope.order.first_issuer; } else { $scope.order.sell_currency = $scope.order.first_currency; $scope.order.buy_currency = $scope.order.second_currency; $scope.order.sell_issuer = $scope.order.first_issuer; $scope.order.buy_issuer = $scope.order.second_issuer; } $scope.order.valid_settings = true; updateTicker(); } function updateTicker() { $scope.bid_price = ripple.Amount.NaN(); $scope.ask_price = ripple.Amount.NaN(); $scope.spread = ripple.Amount.NaN(); var first_currency = $scope.order.first_currency || "XRP"; var second_currency = $scope.order.second_currency || "XRP"; var first_issuer = $scope.order.first_issuer; var second_issuer = $scope.order.second_issuer; var orders = ledger.getOrders(first_currency, second_currency, first_issuer, second_issuer); var bestBid = orders.bids[0]; if (bestBid) $scope.bid_price = bestBid.o.amount.ratio_human(bestBid.i.amount); var bestAsk = orders.asks[0]; if (bestAsk) $scope.ask_price = bestAsk.o.amount.ratio_human(bestAsk.i.amount); if ($scope.bid_price.is_valid() && $scope.ask_price.is_valid()) { $scope.spread = $scope.ask_price.add($scope.bid_price.negate()); } $scope.bids = orders.bids; $scope.asks = orders.asks; } function guessIssuer(currency) { var guess; // First guess: An explicit issuer preference setting in the user's blob try { guess = $scope.userBlob.data.preferred_issuer[currency]; if (guess) return guess; } catch (e) {} // Second guess: The user's highest trust line in this currency try { guess = $scope.balances[currency].highest_issuer; if (guess) return guess; } catch (e) {} // We found nothing return null; } function resetIssuers(force) { var guess; if (force) { $scope.order.first_issuer = null; $scope.order.second_issuer = null; } if (!$scope.order.first_issuer && $scope.order.first_currency && $scope.order.first_currency !== 'XRP' && (guess = guessIssuer($scope.order.first_currency))) { $scope.order.first_issuer = guess; } if (!$scope.order.second_issuer && $scope.order.second_currency && $scope.order.second_currency !== 'XRP' && (guess = guessIssuer($scope.order.second_currency))) { $scope.order.second_issuer = guess; } } $scope.edit_first_issuer = function () { $scope.show_issuer_form = 'first'; $scope.order.first_issuer_edit = $scope.order.first_issuer; }; $scope.edit_second_issuer = function () { $scope.show_issuer_form = 'second'; $scope.order.second_issuer_edit = $scope.order.second_issuer; }; $scope.save_first_issuer = function () { $scope.order.first_issuer = $scope.order.first_issuer_edit; $scope.show_issuer_form = false; // Persist issuer setting if ($scope.order.valid_settings && $scope.order.first_currency !== 'XRP') { $scope.userBlob.data.preferred_issuer[$scope.order.first_currency] = $scope.order.first_issuer; } }; $scope.save_second_issuer = function () { $scope.order.second_issuer = $scope.order.second_issuer_edit; $scope.show_issuer_form = false; // Persist issuer setting if ($scope.order.valid_settings && $scope.order.second_currency !== 'XRP') { $scope.userBlob.data.preferred_issuer[$scope.order.second_currency] = $scope.order.second_issuer; } }; $scope.ledger = ledger; $scope.$watch('ledger.offers', function (offers) { updateTicker(); }, true); $scope.$watch('order.first_issuer', function (issuer) { updateSettings(); }); $scope.$watch('order.second_issuer', function (issuer) { updateSettings(); }); $scope.$watch('balances', function () { resetIssuers(false); }, true); $scope.reset(); }]); }; module.exports = TradeTab;
src/js/tabs/trade.js
var util = require('util'); var webutil = require('../util/web'); var Tab = require('../client/tabmanager').Tab; var Amount = ripple.Amount; var TradeTab = function () { Tab.call(this); }; util.inherits(TradeTab, Tab); TradeTab.prototype.parent = 'advanced'; TradeTab.prototype.generateHtml = function () { return require('../../jade/tabs/trade.jade')(); }; TradeTab.prototype.angularDeps = Tab.prototype.angularDeps.concat(['ledger']); TradeTab.prototype.angular = function(module) { var self = this; var app = this.app; module.controller('TradeCtrl', ['rpLedger', '$scope', function (ledger, $scope) { $scope.mode = "confirm"; $scope.orders = []; var pairs = require('../data/pairs'); $scope.pairs_query = webutil.queryFromOptions(pairs); $scope.reset = function (keepPair) { var pair = keepPair ? $scope.order.currency_pair : pairs[0].name; if ($scope.orderForm) $scope.orderForm.$setPristine(); $scope.mode = "trade"; $scope.order = { type: 'buy', first: '', price: '', second: '', currency_pair: pair, first_currency: pair.slice(0, 3), second_currency: pair.slice(4, 7), first_issuer: app.id.account, second_issuer: app.id.account, listing: 'my', // This variable is true if both the pair and the issuers are set to // valid values. It is used to enable or disable all the functionality // on the page. valid_settings: false }; updateSettings(); }; $scope.back = function () { $scope.mode = "trade"; }; $scope.place_order = function () { $scope.mode = "confirm"; if ($scope.order.type === 'buy') { $scope.order.sell_amount = $scope.order.second_amount; $scope.order.buy_amount = $scope.order.first_amount; } else { $scope.order.sell_amount = $scope.order.first_amount; $scope.order.buy_amount = $scope.order.second_amount; } }; $scope.cancel_order = function () { var tx = app.net.remote.transaction(); tx.offer_cancel(app.id.account, this.entry.seq); tx.on('success', function () { }); tx.on('error', function () { $scope.mode = "error"; $scope.$digest(); }); tx.submit(); this.cancelled = true; }; $scope.order_confirmed = function () { var tx = app.net.remote.transaction(); tx.offer_create(app.id.account, $scope.order.buy_amount, $scope.order.sell_amount); tx.on('success', function (res) { setEngineStatus(res, false); $scope.done(this.hash); $scope.$digest(); }); tx.on('error', function () { $scope.mode = "error"; $scope.$digest(); }); tx.submit(); $scope.mode = "sending"; }; $scope.done = function (hash) { console.log('done'); $scope.mode = "done"; app.net.remote.on('account', handleAccountEvent); function handleAccountEvent(e) { console.log('got event'); if (e.transaction.hash === hash) { console.log('into hash'); setEngineStatus(e, true); $scope.$digest(); app.net.remote.removeListener('account', handleAccountEvent); } } }; function setEngineStatus(res, accepted) { $scope.engine_result = res.engine_result; $scope.engine_result_message = res.engine_result_message; switch (res.engine_result.slice(0, 3)) { case 'tes': $scope.tx_result = accepted ? "cleared" : "pending"; break; case 'tem': $scope.tx_result = "malformed"; break; case 'ter': $scope.tx_result = "failed"; break; case 'tec': $scope.tx_result = "claim"; break; case 'tep': console.warn("Unhandled engine status encountered!"); } } $scope.$watch('order.currency_pair', function (pair) { updateSettings(); resetIssuers(true); }, true); $scope.$watch('order.first', function (amount_str) { $scope.update_first(); }, true); $scope.$watch('order.price', function (amount_str) { $scope.update_price(); }, true); $scope.$watch('order.second', function (amount_str) { $scope.update_second(); }, true); $scope.update_first = function () { var first_currency = $scope.order.first_currency || "XRP"; var formatted = "" + $scope.order.first + " " + first_currency; $scope.order.first_amount = ripple.Amount.from_human(formatted); if (first_currency !== 'XRP') $scope.order.first_amount.set_issuer($scope.order.first_issuer); }; $scope.update_price = function () { var second_currency = $scope.order.second_currency || "XRP"; var formatted = "" + $scope.order.price + " " + second_currency; $scope.order.price_amount = ripple.Amount.from_human(formatted); if (second_currency !== 'XRP') $scope.order.price_amount.set_issuer($scope.order.second_issuer); }; $scope.update_second = function () { var second_currency = $scope.order.second_currency || "XRP"; var formatted = "" + $scope.order.second + " " + second_currency; $scope.order.second_amount = ripple.Amount.from_human(formatted); if (second_currency !== 'XRP') $scope.order.second_amount.set_issuer($scope.order.second_issuer); }; $scope.calc_second = function () { $scope.update_first(); $scope.update_price(); if ($scope.order.price_amount && $scope.order.price_amount.is_valid() && $scope.order.first_amount && $scope.order.first_amount.is_valid()) { $scope.order.second_amount = $scope.order.price_amount.product_human($scope.order.first_amount); $scope.order.second = +$scope.order.second_amount.to_human({group_sep: false}); } }; $scope.calc_first = function () { $scope.update_second(); $scope.update_price(); if ($scope.order.price_amount && $scope.order.price_amount.is_valid() && $scope.order.second_amount && $scope.order.second_amount.is_valid()) { $scope.order.first_amount = $scope.order.second_amount.ratio_human($scope.order.price_amount); $scope.order.first = +$scope.order.first_amount.to_human({group_sep: false}); } }; // This functions is called whenever the settings, specifically the pair and // the issuer(s) have been modified. It checks the new configuration and // sets $scope.valid_settings. function updateSettings() { var pair = $scope.order.currency_pair; if ("string" !== typeof pair || !pair.match(/^[a-z]{3}\/[a-z]{3}$/i)) { $scope.order.first_currency = 'XRP'; $scope.order.second_currency = 'XRP'; $scope.order.valid_settings = false; return; } var first_currency = $scope.order.first_currency = pair.slice(0, 3); var second_currency = $scope.order.second_currency = pair.slice(4, 7); var first_issuer = ripple.UInt160.from_json($scope.order.first_issuer); var second_issuer = ripple.UInt160.from_json($scope.order.second_issuer); if ((first_currency !== 'XRP' && !first_issuer.is_valid()) || (second_currency !== 'XRP' && !second_issuer.is_valid())) { $scope.order.valid_settings = false; return; } if ($scope.order.type === "buy") { $scope.order.sell_currency = $scope.order.second_currency; $scope.order.buy_currency = $scope.order.first_currency; $scope.order.sell_issuer = $scope.order.second_issuer; $scope.order.buy_issuer = $scope.order.first_issuer; } else { $scope.order.sell_currency = $scope.order.first_currency; $scope.order.buy_currency = $scope.order.second_currency; $scope.order.sell_issuer = $scope.order.first_issuer; $scope.order.buy_issuer = $scope.order.second_issuer; } $scope.order.valid_settings = true; updateTicker(); } function updateTicker() { $scope.bid_price = ripple.Amount.NaN(); $scope.ask_price = ripple.Amount.NaN(); $scope.spread = ripple.Amount.NaN(); var first_currency = $scope.order.first_currency || "XRP"; var second_currency = $scope.order.second_currency || "XRP"; var first_issuer = $scope.order.first_issuer; var second_issuer = $scope.order.second_issuer; var orders = ledger.getOrders(first_currency, second_currency, first_issuer, second_issuer); var bestBid = orders.bids[0]; if (bestBid) $scope.bid_price = bestBid.o.amount.ratio_human(bestBid.i.amount); var bestAsk = orders.asks[0]; if (bestAsk) $scope.ask_price = bestAsk.o.amount.ratio_human(bestAsk.i.amount); if ($scope.bid_price.is_valid() && $scope.ask_price.is_valid()) { $scope.spread = $scope.ask_price.add($scope.bid_price.negate()); } $scope.bids = orders.bids; $scope.asks = orders.asks; } function guessIssuer(currency) { var guess; // First guess: An explicit issuer preference setting in the user's blob try { guess = $scope.userBlob.data.preferred_issuer[currency]; if (guess) return guess; } catch (e) {} // Second guess: The user's highest trust line in this currency try { guess = $scope.balances[currency].highest_issuer; if (guess) return guess; } catch (e) {} // We found nothing return null; } function resetIssuers(force) { var guess; if (force) { $scope.order.first_issuer = null; $scope.order.second_issuer = null; } if (!$scope.order.first_issuer && $scope.order.first_currency && $scope.order.first_currency !== 'XRP' && (guess = guessIssuer($scope.order.first_currency))) { $scope.order.first_issuer = guess; } if (!$scope.order.second_issuer && $scope.order.second_currency && $scope.order.second_currency !== 'XRP' && (guess = guessIssuer($scope.order.second_currency))) { $scope.order.second_issuer = guess; } } $scope.edit_first_issuer = function () { $scope.show_issuer_form = 'first'; $scope.order.first_issuer_edit = $scope.order.first_issuer; }; $scope.edit_second_issuer = function () { $scope.show_issuer_form = 'second'; $scope.order.second_issuer_edit = $scope.order.second_issuer; }; $scope.save_first_issuer = function () { $scope.order.first_issuer = $scope.order.first_issuer_edit; $scope.show_issuer_form = false; // Persist issuer setting if ($scope.order.valid_settings && $scope.order.first_currency !== 'XRP') { $scope.userBlob.data.preferred_issuer[$scope.order.first_currency] = $scope.order.first_issuer; } }; $scope.save_second_issuer = function () { $scope.order.second_issuer = $scope.order.second_issuer_edit; $scope.show_issuer_form = false; // Persist issuer setting if ($scope.order.valid_settings && $scope.order.second_currency !== 'XRP') { $scope.userBlob.data.preferred_issuer[$scope.order.second_currency] = $scope.order.second_issuer; } }; $scope.ledger = ledger; $scope.$watch('ledger.offers', function (offers) { updateTicker(); }, true); $scope.$watch('order.first_issuer', function (issuer) { updateSettings(); }); $scope.$watch('order.second_issuer', function (issuer) { updateSettings(); }); $scope.$watch('balances', function () { resetIssuers(false); }, true); $scope.reset(); }]); }; module.exports = TradeTab;
fix #141
src/js/tabs/trade.js
fix #141
<ide><path>rc/js/tabs/trade.js <ide> <ide> $scope.reset = function (keepPair) { <ide> var pair = keepPair ? $scope.order.currency_pair : pairs[0].name; <add> var fIssuer= keepPair ? $scope.order.first_issuer : app.id.account; <add> var sIssuer= keepPair ? $scope.order.second_issuer : app.id.account; <ide> if ($scope.orderForm) $scope.orderForm.$setPristine(); <ide> $scope.mode = "trade"; <ide> $scope.order = { <ide> currency_pair: pair, <ide> first_currency: pair.slice(0, 3), <ide> second_currency: pair.slice(4, 7), <del> first_issuer: app.id.account, <del> second_issuer: app.id.account, <add> first_issuer: fIssuer, <add> second_issuer: sIssuer, <ide> listing: 'my', <ide> <ide> // This variable is true if both the pair and the issuers are set to <ide> <ide> updateSettings(); <ide> }; <add> <add> <ide> <ide> $scope.back = function () { <ide> $scope.mode = "trade"; <ide> // the issuer(s) have been modified. It checks the new configuration and <ide> // sets $scope.valid_settings. <ide> function updateSettings() { <add> console.log("updateSettings"); <add> <ide> var pair = $scope.order.currency_pair; <ide> if ("string" !== typeof pair || <ide> !pair.match(/^[a-z]{3}\/[a-z]{3}$/i)) { <ide> <ide> function guessIssuer(currency) { <ide> var guess; <del> <add> <ide> // First guess: An explicit issuer preference setting in the user's blob <ide> try { <ide> guess = $scope.userBlob.data.preferred_issuer[currency]; <ide> <ide> function resetIssuers(force) { <ide> var guess; <del> <add> <ide> if (force) { <ide> $scope.order.first_issuer = null; <ide> $scope.order.second_issuer = null;
Java
apache-2.0
e74a2a75a08938044681f8c240cba7ca53351d04
0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
/* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.shardingjdbc.orchestration.internal.datasource; import com.google.common.base.Preconditions; import com.google.common.eventbus.Subscribe; import io.shardingsphere.api.ConfigMapContext; import io.shardingsphere.api.config.ShardingRuleConfiguration; import io.shardingsphere.orchestration.config.OrchestrationConfiguration; import io.shardingsphere.orchestration.internal.OrchestrationFacade; import io.shardingsphere.orchestration.internal.config.ConfigurationService; import io.shardingsphere.orchestration.internal.event.config.ShardingConfigurationEventBusEvent; import io.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource; import io.shardingsphere.shardingjdbc.orchestration.internal.circuit.datasource.CircuitBreakerDataSource; import io.shardingsphere.orchestration.internal.rule.OrchestrationShardingRule; import java.sql.Connection; import java.sql.SQLException; import java.util.LinkedHashMap; /** * Orchestration sharding datasource. * * @author panjuan */ public class OrchestrationShardingDataSource extends AbstractOrchestrationDataSource { private ShardingDataSource dataSource; public OrchestrationShardingDataSource(final ShardingDataSource shardingDataSource, final OrchestrationConfiguration orchestrationConfig) throws SQLException { super(new OrchestrationFacade(orchestrationConfig), shardingDataSource.getDataSourceMap()); dataSource = new ShardingDataSource(shardingDataSource.getDataSourceMap(), new OrchestrationShardingRule(shardingDataSource.getShardingContext().getShardingRule().getShardingRuleConfig(), shardingDataSource.getDataSourceMap().keySet()), ConfigMapContext.getInstance().getShardingConfig(), shardingDataSource.getShardingProperties().getProps()); initOrchestrationFacade(dataSource); } public OrchestrationShardingDataSource(final OrchestrationConfiguration orchestrationConfig) throws SQLException { super(new OrchestrationFacade(orchestrationConfig)); ConfigurationService configService = getOrchestrationFacade().getConfigService(); ShardingRuleConfiguration shardingRuleConfig = configService.loadShardingRuleConfiguration(); Preconditions.checkState(null != shardingRuleConfig && !shardingRuleConfig.getTableRuleConfigs().isEmpty(), "Missing the sharding rule configuration on register center"); dataSource = new ShardingDataSource(configService.loadDataSourceMap(), new OrchestrationShardingRule(shardingRuleConfig, configService.loadDataSourceMap().keySet()), configService.loadShardingConfigMap(), configService.loadShardingProperties()); initOrchestrationFacade(dataSource); } private void initOrchestrationFacade(final ShardingDataSource shardingDataSource) { getOrchestrationFacade().init(shardingDataSource.getDataSourceMap(), shardingDataSource.getShardingContext().getShardingRule().getShardingRuleConfig(), ConfigMapContext.getInstance().getShardingConfig(), shardingDataSource.getShardingProperties().getProps()); } @Override public final Connection getConnection() { if (isCircuitBreak()) { return new CircuitBreakerDataSource().getConnection(); } return dataSource.getConnection(); } @Override public final void close() { dataSource.close(); getOrchestrationFacade().close(); } /** * Renew sharding data source. * * @param shardingEvent sharding configuration event bus event. * @throws SQLException SQL exception */ @Subscribe public void renew(final ShardingConfigurationEventBusEvent shardingEvent) throws SQLException { dataSource = new ShardingDataSource(shardingEvent.getDataSourceMap(), shardingEvent.getShardingRule(), new LinkedHashMap<String, Object>(), shardingEvent.getProps()); } }
sharding-jdbc/sharding-jdbc-orchestration/src/main/java/io/shardingsphere/shardingjdbc/orchestration/internal/datasource/OrchestrationShardingDataSource.java
/* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.shardingjdbc.orchestration.internal.datasource; import com.google.common.base.Preconditions; import com.google.common.eventbus.Subscribe; import io.shardingsphere.api.ConfigMapContext; import io.shardingsphere.api.config.ShardingRuleConfiguration; import io.shardingsphere.orchestration.config.OrchestrationConfiguration; import io.shardingsphere.orchestration.internal.OrchestrationFacade; import io.shardingsphere.orchestration.internal.config.ConfigurationService; import io.shardingsphere.orchestration.internal.event.config.ShardingConfigurationEventBusEvent; import io.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource; import io.shardingsphere.shardingjdbc.orchestration.internal.circuit.datasource.CircuitBreakerDataSource; import io.shardingsphere.shardingjdbc.orchestration.internal.rule.OrchestrationShardingRule; import java.sql.Connection; import java.sql.SQLException; import java.util.LinkedHashMap; /** * Orchestration sharding datasource. * * @author panjuan */ public class OrchestrationShardingDataSource extends AbstractOrchestrationDataSource { private ShardingDataSource dataSource; public OrchestrationShardingDataSource(final ShardingDataSource shardingDataSource, final OrchestrationConfiguration orchestrationConfig) throws SQLException { super(new OrchestrationFacade(orchestrationConfig), shardingDataSource.getDataSourceMap()); dataSource = new ShardingDataSource(shardingDataSource.getDataSourceMap(), new OrchestrationShardingRule(shardingDataSource.getShardingContext().getShardingRule().getShardingRuleConfig(), shardingDataSource.getDataSourceMap().keySet()), ConfigMapContext.getInstance().getShardingConfig(), shardingDataSource.getShardingProperties().getProps()); initOrchestrationFacade(dataSource); } public OrchestrationShardingDataSource(final OrchestrationConfiguration orchestrationConfig) throws SQLException { super(new OrchestrationFacade(orchestrationConfig)); ConfigurationService configService = getOrchestrationFacade().getConfigService(); ShardingRuleConfiguration shardingRuleConfig = configService.loadShardingRuleConfiguration(); Preconditions.checkState(null != shardingRuleConfig && !shardingRuleConfig.getTableRuleConfigs().isEmpty(), "Missing the sharding rule configuration on register center"); dataSource = new ShardingDataSource(configService.loadDataSourceMap(), new OrchestrationShardingRule(shardingRuleConfig, configService.loadDataSourceMap().keySet()), configService.loadShardingConfigMap(), configService.loadShardingProperties()); initOrchestrationFacade(dataSource); } private void initOrchestrationFacade(final ShardingDataSource shardingDataSource) { getOrchestrationFacade().init(shardingDataSource.getDataSourceMap(), shardingDataSource.getShardingContext().getShardingRule().getShardingRuleConfig(), ConfigMapContext.getInstance().getShardingConfig(), shardingDataSource.getShardingProperties().getProps()); } @Override public final Connection getConnection() { if (isCircuitBreak()) { return new CircuitBreakerDataSource().getConnection(); } return dataSource.getConnection(); } @Override public final void close() { dataSource.close(); getOrchestrationFacade().close(); } /** * Renew sharding data source. * * @param shardingEvent sharding configuration event bus event. * @throws SQLException SQL exception */ @Subscribe public void renew(final ShardingConfigurationEventBusEvent shardingEvent) throws SQLException { dataSource = new ShardingDataSource(shardingEvent.getDataSourceMap(), shardingEvent.getShardingRule(), new LinkedHashMap<String, Object>(), shardingEvent.getProps()); } }
change import
sharding-jdbc/sharding-jdbc-orchestration/src/main/java/io/shardingsphere/shardingjdbc/orchestration/internal/datasource/OrchestrationShardingDataSource.java
change import
<ide><path>harding-jdbc/sharding-jdbc-orchestration/src/main/java/io/shardingsphere/shardingjdbc/orchestration/internal/datasource/OrchestrationShardingDataSource.java <ide> import io.shardingsphere.orchestration.internal.event.config.ShardingConfigurationEventBusEvent; <ide> import io.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource; <ide> import io.shardingsphere.shardingjdbc.orchestration.internal.circuit.datasource.CircuitBreakerDataSource; <del>import io.shardingsphere.shardingjdbc.orchestration.internal.rule.OrchestrationShardingRule; <add>import io.shardingsphere.orchestration.internal.rule.OrchestrationShardingRule; <ide> <ide> import java.sql.Connection; <ide> import java.sql.SQLException;
Java
isc
a5daa04c77233d832d53c5d95c665ccf72b80b7c
0
rchodava/jdbc-driver
package foundation.stack.jdbc; import com.google.common.base.Strings; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.ConfigConstants; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URL; import java.security.CodeSource; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Ravi Chodavarapu ([email protected]) */ public class NameGenerator { private static final Logger logger = Logger.getLogger(DelegatingDriver.class.getName()); private static final String APPLICATION_NAME = "applicationName"; private final static String GENERATED_APP_NAME = "APP-NAME-%s"; private static File findGitRoot(File file) { while (file != null) { File gitDirectory = new File(file, ".git"); if (gitDirectory.exists() && gitDirectory.isDirectory()) { return gitDirectory; } file = file.getParentFile(); } return null; } private static String findCodePathOfClass(Class<?> clazz) { CodeSource codeSource = clazz.getProtectionDomain().getCodeSource(); if (codeSource != null) { URL codeLocation = codeSource.getLocation(); if (codeLocation != null) { return codeLocation.getPath(); } } return null; } private static File findGitRootOfClassSource(Class<?> clazz) { String codePath = findCodePathOfClass(clazz); if (codePath != null) { File codeFile = new File(codePath); if (codeFile.exists() && codeFile.isDirectory()) { // Running from a class file (probably an IDE) return findGitRoot(codeFile); } else if (codeFile.exists()) { // Running from a JAR (maybe Maven?) return findGitRoot(codeFile.getParentFile()); } } return null; } private static String determineGitBranch(File gitRoot) { try (Repository gitRepository = FileRepositoryBuilder.create(gitRoot)) { String fullBranch = getHeadBranch(gitRepository); if (fullBranch != null) return fullBranch; } catch (IOException e) { } return null; } private static String getHeadBranch(Repository gitRepository) throws IOException { String fullBranch = gitRepository.getFullBranch(); if (fullBranch != null && fullBranch.startsWith(Constants.R_HEADS)) { return fullBranch.substring(Constants.R_HEADS.length()); } return null; } private static File findGitRootInStack() { File gitRoot = null; StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); int index = stackTrace.length; while (gitRoot == null && index > 1) { Class<?> callerClass; try { callerClass = getCallerClassForName(stackTrace[--index].getClassName()); gitRoot = findGitRootOfClassSource(callerClass); } catch (ClassNotFoundException e) { } } if (gitRoot != null) { logger.log(Level.FINE, "Found git root on {0}", gitRoot.getAbsolutePath()); } else { logger.log(Level.FINE, "Could not find git root"); } return gitRoot; } private static Class<?> getCallerClassForName(String className) throws ClassNotFoundException { if (className != null) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (classLoader == null) { classLoader = DockerDatabaseServerPerApplicationConnectionLookup.class.getClassLoader(); } return Class.forName(className, true, classLoader); } return null; } private static String determineRemoteUri(File gitRoot) { if (gitRoot != null) { try (Repository gitRepository = FileRepositoryBuilder.create(gitRoot)) { return getRemoteUri(gitRepository, getHeadBranch(gitRepository)); } catch (IOException e) { } } return null; } private static String getRemoteUri(Repository gitRepository, String branchName) { Config configuration = gitRepository.getConfig(); String remote = configuration.getString( ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REMOTE); if (remote == null) { remote = Constants.DEFAULT_REMOTE_NAME; } if (!remote.equals(".")) { String remoteUri = configuration.getString( ConfigConstants.CONFIG_REMOTE_SECTION, remote, ConfigConstants.CONFIG_KEY_URL); return remoteUri; } return null; } private static String generateApplicationNameFromGitRemoteUri(String gitUri) { StringBuilder applicationName = new StringBuilder(); String[] segments = gitUri.split("/"); if (segments.length > 0) { for (int i = 0; i < segments.length; i++) { String segment = segments[i]; if (segment.endsWith(".git")) { segment = segment.substring(0, segment.length() - 4); } if (!segment.isEmpty()) { applicationName.append(segment); if (i + 1 < segments.length) { applicationName.append('-'); } } } } else { return null; } return applicationName.toString(); } public static String generateContextApplicationName() { String applicationName = getApplicationName(); if (Strings.isNullOrEmpty(applicationName)) { File gitRoot = findGitRootInStack(); if (gitRoot != null) { String remoteUri = determineRemoteUri(gitRoot); String path = URI.create(remoteUri).getPath(); if (path != null) { applicationName = generateApplicationNameFromGitRemoteUri(path); if (applicationName != null) { logger.log(Level.FINE, "Derived application {0} name from git ", applicationName); return applicationName; } } } } if (Strings.isNullOrEmpty(applicationName)) { String generatedName = generateRandomApplicationName(); logger.log(Level.FINE, "Using generated application name {0}", generatedName); return generatedName; } logger.log(Level.FINE, "Using user provided application name {0}", applicationName); return applicationName; } private static String generateRandomApplicationName() { return String.format(GENERATED_APP_NAME, UUID.randomUUID().toString()); } private static String getApplicationName() { return System.getProperty(APPLICATION_NAME); } public static String generateDatabaseName() { File gitRoot = findGitRootInStack(); if (gitRoot != null) { return determineGitBranch(gitRoot); } return "master"; } }
src/main/java/foundation/stack/jdbc/NameGenerator.java
package foundation.stack.jdbc; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.ConfigConstants; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URL; import java.security.CodeSource; /** * @author Ravi Chodavarapu ([email protected]) */ public class NameGenerator { private static String getCallerClassName() { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); if (stackTrace != null && stackTrace.length > 0) { int index = stackTrace.length == 1 ? 0 : stackTrace.length - 1; return stackTrace[index].getClassName(); } return null; } private static Class<?> getCallerClass() throws ClassNotFoundException { String className = getCallerClassName(); if (className != null) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (classLoader == null) { classLoader = DockerDatabaseServerPerApplicationConnectionLookup.class.getClassLoader(); } return Class.forName(className, true, classLoader); } return null; } private static File findGitRoot(File file) { while (file != null) { File gitDirectory = new File(file, ".git"); if (gitDirectory.exists() && gitDirectory.isDirectory()) { return gitDirectory; } file = file.getParentFile(); } return null; } private static String findCodePathOfClass(Class<?> clazz) { CodeSource codeSource = clazz.getProtectionDomain().getCodeSource(); if (codeSource != null) { URL codeLocation = codeSource.getLocation(); if (codeLocation != null) { return codeLocation.getPath(); } } return null; } private static File findGitRootOfClassSource(Class<?> clazz) { String codePath = findCodePathOfClass(clazz); if (codePath != null) { File codeFile = new File(codePath); if (codeFile.exists() && codeFile.isDirectory()) { // Running from a class file (probably an IDE) return findGitRoot(codeFile); } else if (codeFile.exists()) { // Running from a JAR (maybe Maven?) return findGitRoot(codeFile.getParentFile()); } } return null; } private static String determineGitBranch(File gitRoot) { try (Repository gitRepository = FileRepositoryBuilder.create(gitRoot)) { String fullBranch = getHeadBranch(gitRepository); if (fullBranch != null) return fullBranch; } catch (IOException e) { } return null; } private static String getHeadBranch(Repository gitRepository) throws IOException { String fullBranch = gitRepository.getFullBranch(); if (fullBranch != null && fullBranch.startsWith(Constants.R_HEADS)) { return fullBranch.substring(Constants.R_HEADS.length()); } return null; } private static File findGitRootOfCallerClass() { Class<?> callerClass = null; try { callerClass = getCallerClass(); } catch (ClassNotFoundException e) { } if (callerClass != null) { return findGitRootOfClassSource(callerClass); } return null; } private static String determineRemoteUri() { File gitRoot = findGitRootOfCallerClass(); if (gitRoot != null) { try (Repository gitRepository = FileRepositoryBuilder.create(gitRoot)) { return getRemoteUri(gitRepository, getHeadBranch(gitRepository)); } catch (IOException e) { } } return null; } private static String getRemoteUri(Repository gitRepository, String branchName) { Config configuration = gitRepository.getConfig(); String remote = configuration.getString( ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REMOTE); if (remote == null) { remote = Constants.DEFAULT_REMOTE_NAME; } if (!remote.equals(".")) { String remoteUri = configuration.getString( ConfigConstants.CONFIG_REMOTE_SECTION, remote, ConfigConstants.CONFIG_KEY_URL); return remoteUri; } return null; } private static String generateApplicationNameFromCodeLocation() { Class<?> callerClass = null; try { callerClass = getCallerClass(); } catch (ClassNotFoundException e) { } if (callerClass != null) { String codePath = findCodePathOfClass(callerClass); if (codePath != null) { return new File(codePath).getName(); } } return null; } private static String generateApplicationNameFromGitRemoteUri(String gitUri) { StringBuilder applicationName = new StringBuilder(); String[] segments = gitUri.split("/"); if (segments.length > 0) { for (int i = 0; i < segments.length; i++) { String segment = segments[i]; if (segment.endsWith(".git")) { segment = segment.substring(0, segment.length() - 4); } if (!segment.isEmpty()) { applicationName.append(segment); if (i + 1 < segments.length) { applicationName.append('-'); } } } } else { return null; } return applicationName.toString(); } public static String generateContextApplicationName() { File gitRoot = findGitRootOfCallerClass(); if (gitRoot != null) { String remoteUri = determineRemoteUri(); String path = URI.create(remoteUri).getPath(); if (path != null) { String applicationName = generateApplicationNameFromGitRemoteUri(path); if (applicationName != null) { return applicationName; } } } String applicationName = generateApplicationNameFromCodeLocation(); if (applicationName != null) { return applicationName; } return getCallerClassName(); } public static String generateDatabaseName() { File gitRoot = findGitRootOfCallerClass(); if (gitRoot != null) { return determineGitBranch(gitRoot); } return "master"; } }
Changed logic to name generation. Will use system property, or will try to infer it from git, or will use a randomly generated one.
src/main/java/foundation/stack/jdbc/NameGenerator.java
Changed logic to name generation. Will use system property, or will try to infer it from git, or will use a randomly generated one.
<ide><path>rc/main/java/foundation/stack/jdbc/NameGenerator.java <ide> package foundation.stack.jdbc; <ide> <add>import com.google.common.base.Strings; <ide> import org.eclipse.jgit.lib.Config; <ide> import org.eclipse.jgit.lib.ConfigConstants; <ide> import org.eclipse.jgit.lib.Constants; <ide> import java.net.URI; <ide> import java.net.URL; <ide> import java.security.CodeSource; <add>import java.util.UUID; <add>import java.util.logging.Level; <add>import java.util.logging.Logger; <ide> <ide> /** <ide> * @author Ravi Chodavarapu ([email protected]) <ide> */ <ide> public class NameGenerator { <del> <del> private static String getCallerClassName() { <del> StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); <del> if (stackTrace != null && stackTrace.length > 0) { <del> int index = stackTrace.length == 1 ? 0 : stackTrace.length - 1; <del> return stackTrace[index].getClassName(); <del> } <del> <del> return null; <del> } <del> <del> private static Class<?> getCallerClass() throws ClassNotFoundException { <del> String className = getCallerClassName(); <del> if (className != null) { <del> ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); <del> if (classLoader == null) { <del> classLoader = DockerDatabaseServerPerApplicationConnectionLookup.class.getClassLoader(); <del> } <del> <del> return Class.forName(className, true, classLoader); <del> } <del> <del> return null; <del> } <del> <del> private static File findGitRoot(File file) { <add> private static final Logger logger = Logger.getLogger(DelegatingDriver.class.getName()); <add> <add> private static final String APPLICATION_NAME = "applicationName"; <add> private final static String GENERATED_APP_NAME = "APP-NAME-%s"; <add> <add> private static File findGitRoot(File file) { <ide> while (file != null) { <ide> File gitDirectory = new File(file, ".git"); <ide> if (gitDirectory.exists() && gitDirectory.isDirectory()) { <ide> return null; <ide> } <ide> <del> private static File findGitRootOfCallerClass() { <del> Class<?> callerClass = null; <del> try { <del> callerClass = getCallerClass(); <del> } catch (ClassNotFoundException e) { <del> } <del> <del> if (callerClass != null) { <del> return findGitRootOfClassSource(callerClass); <del> } <del> <del> return null; <del> } <del> <del> private static String determineRemoteUri() { <del> File gitRoot = findGitRootOfCallerClass(); <add> private static File findGitRootInStack() { <add> File gitRoot = null; <add> StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); <add> int index = stackTrace.length; <add> while (gitRoot == null && index > 1) { <add> Class<?> callerClass; <add> try { <add> callerClass = getCallerClassForName(stackTrace[--index].getClassName()); <add> gitRoot = findGitRootOfClassSource(callerClass); <add> } catch (ClassNotFoundException e) { <add> } <add> } <add> if (gitRoot != null) { <add> logger.log(Level.FINE, "Found git root on {0}", gitRoot.getAbsolutePath()); <add> } <add> else { <add> logger.log(Level.FINE, "Could not find git root"); <add> } <add> <add> return gitRoot; <add> } <add> <add> private static Class<?> getCallerClassForName(String className) throws ClassNotFoundException { <add> if (className != null) { <add> ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); <add> if (classLoader == null) { <add> classLoader = DockerDatabaseServerPerApplicationConnectionLookup.class.getClassLoader(); <add> } <add> <add> return Class.forName(className, true, classLoader); <add> } <add> <add> return null; <add> } <add> <add> <add> private static String determineRemoteUri(File gitRoot) { <ide> if (gitRoot != null) { <ide> try (Repository gitRepository = FileRepositoryBuilder.create(gitRoot)) { <ide> return getRemoteUri(gitRepository, getHeadBranch(gitRepository)); <ide> ConfigConstants.CONFIG_KEY_URL); <ide> <ide> return remoteUri; <del> } <del> <del> return null; <del> } <del> <del> private static String generateApplicationNameFromCodeLocation() { <del> Class<?> callerClass = null; <del> try { <del> callerClass = getCallerClass(); <del> } catch (ClassNotFoundException e) { <del> } <del> <del> if (callerClass != null) { <del> String codePath = findCodePathOfClass(callerClass); <del> if (codePath != null) { <del> return new File(codePath).getName(); <del> } <ide> } <ide> <ide> return null; <ide> } <ide> <ide> public static String generateContextApplicationName() { <del> File gitRoot = findGitRootOfCallerClass(); <del> if (gitRoot != null) { <del> String remoteUri = determineRemoteUri(); <del> String path = URI.create(remoteUri).getPath(); <del> if (path != null) { <del> String applicationName = generateApplicationNameFromGitRemoteUri(path); <del> if (applicationName != null) { <del> return applicationName; <del> } <del> } <del> } <del> <del> String applicationName = generateApplicationNameFromCodeLocation(); <del> if (applicationName != null) { <del> return applicationName; <del> } <del> <del> return getCallerClassName(); <del> } <del> <del> public static String generateDatabaseName() { <del> File gitRoot = findGitRootOfCallerClass(); <add> String applicationName = getApplicationName(); <add> <add> if (Strings.isNullOrEmpty(applicationName)) { <add> File gitRoot = findGitRootInStack(); <add> if (gitRoot != null) { <add> String remoteUri = determineRemoteUri(gitRoot); <add> String path = URI.create(remoteUri).getPath(); <add> if (path != null) { <add> applicationName = generateApplicationNameFromGitRemoteUri(path); <add> if (applicationName != null) { <add> logger.log(Level.FINE, "Derived application {0} name from git ", applicationName); <add> return applicationName; <add> } <add> } <add> } <add> } <add> <add> if (Strings.isNullOrEmpty(applicationName)) { <add> String generatedName = generateRandomApplicationName(); <add> logger.log(Level.FINE, "Using generated application name {0}", generatedName); <add> return generatedName; <add> } <add> <add> logger.log(Level.FINE, "Using user provided application name {0}", applicationName); <add> return applicationName; <add> } <add> <add> private static String generateRandomApplicationName() { <add> return String.format(GENERATED_APP_NAME, UUID.randomUUID().toString()); <add> } <add> <add> private static String getApplicationName() { <add> return System.getProperty(APPLICATION_NAME); <add> } <add> <add> public static String generateDatabaseName() { <add> File gitRoot = findGitRootInStack(); <ide> if (gitRoot != null) { <ide> return determineGitBranch(gitRoot); <ide> }
Java
apache-2.0
c947e57d5e4dda8682a6ec1c6bc6850a65ab912e
0
mans2singh/nifi,alopresto/nifi,jtstorck/nifi,aperepel/nifi,bbende/nifi,aperepel/nifi,jfrazee/nifi,jfrazee/nifi,ijokarumawak/nifi,patricker/nifi,jfrazee/nifi,aperepel/nifi,mans2singh/nifi,patricker/nifi,ijokarumawak/nifi,mattyb149/nifi,aperepel/nifi,jtstorck/nifi,MikeThomsen/nifi,mcgilman/nifi,trixpan/nifi,alopresto/nifi,ijokarumawak/nifi,patricker/nifi,mcgilman/nifi,trixpan/nifi,mattyb149/nifi,mattyb149/nifi,mattyb149/nifi,mcgilman/nifi,m-hogue/nifi,YolandaMDavis/nifi,MikeThomsen/nifi,mattyb149/nifi,pvillard31/nifi,m-hogue/nifi,bbende/nifi,YolandaMDavis/nifi,mans2singh/nifi,jtstorck/nifi,pvillard31/nifi,MikeThomsen/nifi,m-hogue/nifi,ijokarumawak/nifi,trixpan/nifi,alopresto/nifi,pvillard31/nifi,jfrazee/nifi,pvillard31/nifi,patricker/nifi,bbende/nifi,alopresto/nifi,pvillard31/nifi,alopresto/nifi,mans2singh/nifi,YolandaMDavis/nifi,patricker/nifi,mcgilman/nifi,MikeThomsen/nifi,MikeThomsen/nifi,bbende/nifi,YolandaMDavis/nifi,mans2singh/nifi,ijokarumawak/nifi,YolandaMDavis/nifi,MikeThomsen/nifi,MikeThomsen/nifi,m-hogue/nifi,jtstorck/nifi,mcgilman/nifi,mcgilman/nifi,jfrazee/nifi,trixpan/nifi,m-hogue/nifi,aperepel/nifi,alopresto/nifi,bbende/nifi,mcgilman/nifi,jfrazee/nifi,patricker/nifi,YolandaMDavis/nifi,patricker/nifi,m-hogue/nifi,mattyb149/nifi,jtstorck/nifi,jfrazee/nifi,bbende/nifi,mattyb149/nifi,YolandaMDavis/nifi,jtstorck/nifi,pvillard31/nifi,jtstorck/nifi,m-hogue/nifi,pvillard31/nifi,aperepel/nifi,mans2singh/nifi,trixpan/nifi,jfrazee/nifi,alopresto/nifi,ijokarumawak/nifi,trixpan/nifi,pvillard31/nifi
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.web.api.dto; import io.swagger.annotations.ApiModelProperty; import org.apache.nifi.web.api.dto.util.TimestampAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.util.Date; import java.util.List; public abstract class AsynchronousRequestDTO<T extends UpdateStepDTO> { private String requestId; private String uri; private Date submissionTime; private Date lastUpdated; private boolean complete = false; private String failureReason; private int percentCompleted; private String state; private List<T> updateSteps; @ApiModelProperty(value = "The ID of the request", readOnly = true) public String getRequestId() { return requestId; } public void setRequestId(final String requestId) { this.requestId = requestId; } @ApiModelProperty(value = "The URI for the request", readOnly = true) public String getUri() { return uri; } public void setUri(final String uri) { this.uri = uri; } @XmlJavaTypeAdapter(TimestampAdapter.class) @ApiModelProperty(value = "The timestamp of when the request was submitted", readOnly = true) public Date getSubmissionTime() { return submissionTime; } public void setSubmissionTime(final Date submissionTime) { this.submissionTime = submissionTime; } @XmlJavaTypeAdapter(TimestampAdapter.class) @ApiModelProperty(value = "The timestamp of when the request was last updated", readOnly = true) public Date getLastUpdated() { return lastUpdated; } public void setLastUpdated(final Date lastUpdated) { this.lastUpdated = lastUpdated; } @ApiModelProperty(value = "Whether or not the request is completed", readOnly = true) public boolean isComplete() { return complete; } public void setComplete(final boolean complete) { this.complete = complete; } @ApiModelProperty(value = "The reason for the request failing, or null if the request has not failed", readOnly = true) public String getFailureReason() { return failureReason; } public void setFailureReason(final String failureReason) { this.failureReason = failureReason; } @ApiModelProperty(value = "A value between 0 and 100 (inclusive) indicating how close the request is to completion", readOnly = true) public int getPercentCompleted() { return percentCompleted; } public void setPercentCompleted(final int percentCompleted) { this.percentCompleted = percentCompleted; } @ApiModelProperty(value = "A description of the current state of the request", readOnly = true) public String getState() { return state; } public void setState(final String state) { this.state = state; } @ApiModelProperty(value = "The steps that are required in order to complete the request, along with the status of each", readOnly = true) public List<T> getUpdateSteps() { return updateSteps; } public void setUpdateSteps(List<T> updateSteps) { this.updateSteps = updateSteps; } }
nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/AsynchronousRequestDTO.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.web.api.dto; import io.swagger.annotations.ApiModelProperty; import java.util.Date; import java.util.List; public abstract class AsynchronousRequestDTO<T extends UpdateStepDTO> { private String requestId; private String uri; private Date submissionTime; private Date lastUpdated; private boolean complete = false; private String failureReason; private int percentCompleted; private String state; private List<T> updateSteps; @ApiModelProperty(value = "The ID of the request", readOnly = true) public String getRequestId() { return requestId; } public void setRequestId(final String requestId) { this.requestId = requestId; } @ApiModelProperty(value = "The URI for the request", readOnly = true) public String getUri() { return uri; } public void setUri(final String uri) { this.uri = uri; } @ApiModelProperty(value = "The timestamp of when the request was submitted", readOnly = true) public Date getSubmissionTime() { return submissionTime; } public void setSubmissionTime(final Date submissionTime) { this.submissionTime = submissionTime; } @ApiModelProperty(value = "The timestamp of when the request was last updated", readOnly = true) public Date getLastUpdated() { return lastUpdated; } public void setLastUpdated(final Date lastUpdated) { this.lastUpdated = lastUpdated; } @ApiModelProperty(value = "Whether or not the request is completed", readOnly = true) public boolean isComplete() { return complete; } public void setComplete(final boolean complete) { this.complete = complete; } @ApiModelProperty(value = "The reason for the request failing, or null if the request has not failed", readOnly = true) public String getFailureReason() { return failureReason; } public void setFailureReason(final String failureReason) { this.failureReason = failureReason; } @ApiModelProperty(value = "A value between 0 and 100 (inclusive) indicating how close the request is to completion", readOnly = true) public int getPercentCompleted() { return percentCompleted; } public void setPercentCompleted(final int percentCompleted) { this.percentCompleted = percentCompleted; } @ApiModelProperty(value = "A description of the current state of the request", readOnly = true) public String getState() { return state; } public void setState(final String state) { this.state = state; } @ApiModelProperty(value = "The steps that are required in order to complete the request, along with the status of each", readOnly = true) public List<T> getUpdateSteps() { return updateSteps; } public void setUpdateSteps(List<T> updateSteps) { this.updateSteps = updateSteps; } }
NIFI-6814: - Restored JAXB Adapter This closes #3880
nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/AsynchronousRequestDTO.java
NIFI-6814: - Restored JAXB Adapter
<ide><path>ifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/AsynchronousRequestDTO.java <ide> package org.apache.nifi.web.api.dto; <ide> <ide> import io.swagger.annotations.ApiModelProperty; <add>import org.apache.nifi.web.api.dto.util.TimestampAdapter; <ide> <add>import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; <ide> import java.util.Date; <ide> import java.util.List; <ide> <ide> this.uri = uri; <ide> } <ide> <add> @XmlJavaTypeAdapter(TimestampAdapter.class) <ide> @ApiModelProperty(value = "The timestamp of when the request was submitted", readOnly = true) <ide> public Date getSubmissionTime() { <ide> return submissionTime; <ide> this.submissionTime = submissionTime; <ide> } <ide> <add> @XmlJavaTypeAdapter(TimestampAdapter.class) <ide> @ApiModelProperty(value = "The timestamp of when the request was last updated", readOnly = true) <ide> public Date getLastUpdated() { <ide> return lastUpdated;
JavaScript
mit
7fe6c49bee28bedab0d3cd43ac9d0b955bf4f954
0
MischievousBoys/WikiPoetry,MischievousBoys/WikiPoetry
var React = require('react'); var API = require('../../api/wikiApi'); var WikiPoetryStore = require('../../stores/WikiPoetryStore'); var WikiPoetryActionCreators = require('../../actions/WikiPoetryActionCreators'); var ReactRouter = require('react-router'); var Edit = require('../edit/Edit.react'); var Save = require('../edit/Save.react'); function getArticleContent() { return WikiPoetryStore.getArticle(); } var ArticleSubsection = React.createClass({ mixins: [ReactRouter.History], getInitialState: function () { return { type: WikiPoetryStore.getType(), editMode: WikiPoetryStore.getMode(), } }, componentDidMount: function () { WikiPoetryStore.addArticleListener(this._onChange); WikiPoetryStore.addEditListener(this._onEdit); WikiPoetryStore.addEditListener(this._onSave); }, componentWillUnMount: function () { WikiPoetryStore.removeArticleListener(this._onChange); WikiPoetryStore.removeEditListener(this._onEdit); WikiPoetryStore.removeEditListener(this._onSave); }, handleClick: function (event, word) { event.preventDefault(); WikiPoetryActionCreators.submitSearch(word); if (this.state.type === 'user') { WikiPoetryActionCreators.getUserPoem(word); } else { WikiPoetryActionCreators.getArticleContent(this.state.type, word); } }, linkifyArticle: function (content, links) { var words = content.split(' '); var index; var spaced = []; var linkedArray = words.map(function(word, i) { if (links.indexOf(word) !== -1) { index = links.indexOf(word); var linkedWord = React.createElement("a", {key: i, href: '#', onClick: function(e){this.handleClick(e, word)}.bind(this), activeClassName: "link-active"}, word); return linkedWord; } else { return word; } }.bind(this)); linkedArray.forEach(function(strOrObj) { spaced.push(strOrObj); spaced.push(' '); }); return spaced; }, editText: function (event) { this.setState({value: event.target.value}); }, render: function () { var content = this.props.poem ? this.props.poem.poem : 'Please wait'; var links = this.props.poem ? this.props.poem.replaced : []; var load = this.props.load; var linkedArticle; var displayPoem; var userTextArea; var button; var editing = this.state.editMode.editing; var poemKey; var wholeArticle = this.props.wholeArticle; if (content && !editing) { linkedArticle = this.linkifyArticle(content, links); } if (editing) { console.log('editing'); userTextArea = <textarea id="userPoem" name="userPoem" defaultValue={content} onChange={this.editText}></textarea> var userPoem = this.state.value; button = <Save keyIndex={this.props.keyIndex} wholeArticle={this.props.wholeArticle} userPoem={userPoem}/> displayPoem = ''; } /*else if (!editing && !load) { }*/ else { console.log('not editing'); displayPoem = linkedArticle; button = <Edit keyIndex={this.props.keyIndex}/> } return ( <div className="subsection"> <div className="input">{this.props.error}</div> <h4 className="subheading"> {this.props.subheading} {button} </h4> <p className="subcontent">{linkedArticle}</p> <div>{userTextArea}</div> </div> ); }, _onChange: function () { console.log('article content: ',getArticleContent()); if (this.state.term) { this.history.pushState(getArticleContent(), '/Article/' + this.state.term, null); } }, _onEdit: function () { if (this.state.editMode.key === this.props.keyIndex) { this.setState({ editMode: WikiPoetryStore.getMode() }); } }, _onSave: function () { if (this.state.editMode.key === this.props.keyIndex) { this.setState({ editMode: WikiPoetryStore.getMode() }); } } }); module.exports = ArticleSubsection;
client/app/components/article/ArticleSubsection.react.js
var React = require('react'); var API = require('../../api/wikiApi'); var WikiPoetryStore = require('../../stores/WikiPoetryStore'); var WikiPoetryActionCreators = require('../../actions/WikiPoetryActionCreators'); var ReactRouter = require('react-router'); var Edit = require('../edit/Edit.react'); var Save = require('../edit/Save.react'); function getArticleContent() { return WikiPoetryStore.getArticle(); } var ArticleSubsection = React.createClass({ mixins: [ReactRouter.History], getInitialState: function () { return { type: WikiPoetryStore.getType(), editMode: WikiPoetryStore.getMode(), } }, componentDidMount: function () { WikiPoetryStore.addArticleListener(this._onChange); WikiPoetryStore.addEditListener(this._onEdit); WikiPoetryStore.addEditListener(this._onSave); }, componentWillUnMount: function () { WikiPoetryStore.removeArticleListener(this._onChange); WikiPoetryStore.removeEditListener(this._onEdit); WikiPoetryStore.removeEditListener(this._onSave); }, handleClick: function (event, word) { event.preventDefault(); WikiPoetryActionCreators.submitSearch(word); if (this.state.type === 'user') { WikiPoetryActionCreators.getUserPoem(word); } else { WikiPoetryActionCreators.getArticleContent(this.state.type, word); } }, linkifyArticle: function (content, links) { var words = content.split(' '); var index; var spaced = []; var linkedArray = words.map(function(word, i) { if (links.indexOf(word) !== -1) { index = links.indexOf(word); var linkedWord = React.createElement("a", {key: i, href: '#', onClick: function(e){this.handleClick(e, word)}.bind(this), activeClassName: "link-active"}, word); return linkedWord; } else { return word; } }.bind(this)); linkedArray.forEach(function(strOrObj) { spaced.push(strOrObj); spaced.push(' '); }); return spaced; }, editText: function (event) { this.setState({value: event.target.value}); }, render: function () { var content = this.props.poem ? this.props.poem.poem : 'Please wait'; var links = this.props.poem ? this.props.poem.replaced : []; var load = this.props.load; var linkedArticle; var displayPoem; var userTextArea; var button; var editing = this.state.editMode.editing; var poemKey; var wholeArticle = this.props.wholeArticle; if (content && !editing) { linkedArticle = this.linkifyArticle(content, links); } if (editing) { console.log('editing'); userTextArea = <textarea id="userPoem" name="userPoem" defaultValue={content} onChange={this.editText}></textarea> var userPoem = this.state.value; button = <Save keyIndex={this.props.keyIndex} wholeArticle={this.props.wholeArticle} userPoem={userPoem}/> displayPoem = ''; } /*else if (!editing && !load) { }*/ else { console.log('not editing'); displayPoem = linkedArticle; button = <Edit keyIndex={this.props.keyIndex}/> } return ( <div className="subsection"> <div className="input">{this.props.error}</div> <h4 className="subheading"> {this.props.subheading} {button} </h4> <p className="subcontent">{displayPoem}</p> <div>{userTextArea}</div> </div> ); }, _onChange: function () { console.log('article content: ',getArticleContent()); if (this.state.term) { this.history.pushState(getArticleContent(), '/Article/' + this.state.term, null); } }, _onEdit: function () { if (this.state.editMode.key === this.props.keyIndex) { this.setState({ editMode: WikiPoetryStore.getMode() }); } }, _onSave: function () { if (this.state.editMode.key === this.props.keyIndex) { this.setState({ editMode: WikiPoetryStore.getMode() }); } } }); module.exports = ArticleSubsection;
(bug) Fixes more edit button rendering issues
client/app/components/article/ArticleSubsection.react.js
(bug) Fixes more edit button rendering issues
<ide><path>lient/app/components/article/ArticleSubsection.react.js <ide> {this.props.subheading} <ide> {button} <ide> </h4> <del> <p className="subcontent">{displayPoem}</p> <add> <p className="subcontent">{linkedArticle}</p> <ide> <div>{userTextArea}</div> <ide> </div> <ide> );
Java
bsd-3-clause
ab5a699bd9b8a845a08e0e7ea54f4e4fb5df6fc4
0
kleingeist/xtreemfs,jswrenn/xtreemfs,kleingeist/xtreemfs,rbaerzib/xtreemfs,harnesscloud/xtreemfs,rbaerzib/xtreemfs,kleingeist/xtreemfs,jswrenn/xtreemfs,harnesscloud/xtreemfs,jswrenn/xtreemfs,rbaerzib/xtreemfs,kleingeist/xtreemfs,rbaerzib/xtreemfs,jswrenn/xtreemfs,harnesscloud/xtreemfs,jswrenn/xtreemfs,harnesscloud/xtreemfs,jswrenn/xtreemfs,rbaerzib/xtreemfs,harnesscloud/xtreemfs,jswrenn/xtreemfs,kleingeist/xtreemfs,jswrenn/xtreemfs,kleingeist/xtreemfs,harnesscloud/xtreemfs,rbaerzib/xtreemfs,harnesscloud/xtreemfs,rbaerzib/xtreemfs,harnesscloud/xtreemfs,kleingeist/xtreemfs,rbaerzib/xtreemfs,kleingeist/xtreemfs
/* * Copyright (c) 2010-2011 by Bjoern Kolbeck, * Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ package org.xtreemfs.osd.rwre; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; import org.xtreemfs.common.uuids.ServiceUUID; import org.xtreemfs.common.uuids.UnknownUUIDException; import org.xtreemfs.common.xloc.XLocations; import org.xtreemfs.foundation.SSLOptions; import org.xtreemfs.foundation.buffer.ASCIIString; import org.xtreemfs.foundation.buffer.BufferPool; import org.xtreemfs.foundation.buffer.ReusableBuffer; import org.xtreemfs.foundation.flease.Flease; import org.xtreemfs.foundation.flease.FleaseConfig; import org.xtreemfs.foundation.flease.FleaseMessageSenderInterface; import org.xtreemfs.foundation.flease.FleaseStage; import org.xtreemfs.foundation.flease.FleaseStatusListener; import org.xtreemfs.foundation.flease.FleaseViewChangeListenerInterface; import org.xtreemfs.foundation.flease.comm.FleaseMessage; import org.xtreemfs.foundation.flease.proposer.FleaseException; import org.xtreemfs.foundation.flease.proposer.FleaseListener; import org.xtreemfs.foundation.logging.Logging; import org.xtreemfs.foundation.logging.Logging.Category; import org.xtreemfs.foundation.pbrpc.client.PBRPCException; import org.xtreemfs.foundation.pbrpc.client.RPCAuthentication; import org.xtreemfs.foundation.pbrpc.client.RPCNIOSocketClient; import org.xtreemfs.foundation.pbrpc.client.RPCResponse; import org.xtreemfs.foundation.pbrpc.client.RPCResponseAvailableListener; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.ErrorType; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.POSIXErrno; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.RPCHeader.ErrorResponse; import org.xtreemfs.foundation.pbrpc.utils.ErrorUtils; import org.xtreemfs.osd.InternalObjectData; import org.xtreemfs.osd.OSDRequest; import org.xtreemfs.osd.OSDRequestDispatcher; import org.xtreemfs.osd.operations.EventRWRStatus; import org.xtreemfs.osd.operations.OSDOperation; import org.xtreemfs.osd.rwre.ReplicatedFileState.ReplicaState; import org.xtreemfs.osd.stages.PreprocStage.InstallXLocSetCallback; import org.xtreemfs.osd.stages.PreprocStage.InvalidateXLocSetCallback; import org.xtreemfs.osd.stages.Stage; import org.xtreemfs.osd.stages.StorageStage.DeleteObjectsCallback; import org.xtreemfs.osd.stages.StorageStage.InternalGetMaxObjectNoCallback; import org.xtreemfs.osd.stages.StorageStage.WriteObjectCallback; import org.xtreemfs.osd.storage.CowPolicy; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.FileCredentials; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.OSDWriteResponse; import org.xtreemfs.pbrpc.generatedinterfaces.OSD.AuthoritativeReplicaState; import org.xtreemfs.pbrpc.generatedinterfaces.OSD.ObjectData; import org.xtreemfs.pbrpc.generatedinterfaces.OSD.ObjectVersion; import org.xtreemfs.pbrpc.generatedinterfaces.OSD.ObjectVersionMapping; import org.xtreemfs.pbrpc.generatedinterfaces.OSD.ReplicaStatus; import org.xtreemfs.pbrpc.generatedinterfaces.OSD.XLocSetVersionState; import org.xtreemfs.pbrpc.generatedinterfaces.OSDServiceClient; /** * * @author bjko */ public class RWReplicationStage extends Stage implements FleaseMessageSenderInterface { public static final int STAGEOP_REPLICATED_WRITE = 1; public static final int STAGEOP_CLOSE = 2; public static final int STAGEOP_PROCESS_FLEASE_MSG = 3; public static final int STAGEOP_PREPAREOP = 5; public static final int STAGEOP_TRUNCATE = 6; public static final int STAGEOP_GETSTATUS = 7; public static final int STAGEOP_INTERNAL_AUTHSTATE = 10; public static final int STAGEOP_INTERNAL_OBJFETCHED = 11; public static final int STAGEOP_LEASE_STATE_CHANGED = 13; public static final int STAGEOP_INTERNAL_STATEAVAIL = 14; public static final int STAGEOP_INTERNAL_DELETE_COMPLETE = 15; public static final int STAGEOP_FORCE_RESET = 16; public static final int STAGEOP_INTERNAL_MAXOBJ_AVAIL = 17; public static final int STAGEOP_INTERNAL_BACKUP_AUTHSTATE = 18; public static final int STAGEOP_SETVIEW = 21; public static final int STAGEOP_INVALIDATEVIEW = 22; public static enum Operation { READ, WRITE, TRUNCATE, INTERNAL_UPDATE, INTERNAL_TRUNCATE }; private final RPCNIOSocketClient client; private final OSDServiceClient osdClient; private final Map<String,ReplicatedFileState> files; private final Map<ASCIIString,String> cellToFileId; private final OSDRequestDispatcher master; private final FleaseStage fstage; private final RPCNIOSocketClient fleaseClient; private final OSDServiceClient fleaseOsdClient; private final ASCIIString localID; private int numObjsInFlight; private static final int MAX_OBJS_IN_FLIGHT = 10; private static final int MAX_PENDING_PER_FILE = 10; private static final int MAX_EXTERNAL_REQUESTS_IN_Q = 250; private final Queue<ReplicatedFileState> filesInReset; private final FleaseMasterEpochThread masterEpochThread; private final AtomicInteger externalRequestsInQueue; public RWReplicationStage(OSDRequestDispatcher master, SSLOptions sslOpts, int maxRequestsQueueLength) throws IOException { super("RWReplSt", maxRequestsQueueLength); this.master = master; client = new RPCNIOSocketClient(sslOpts, 15000, 60000*5, "RWReplicationStage"); fleaseClient = new RPCNIOSocketClient(sslOpts, 15000, 60000*5, "RWReplicationStage (flease)"); osdClient = new OSDServiceClient(client,null); fleaseOsdClient = new OSDServiceClient(fleaseClient,null); files = new HashMap<String, ReplicatedFileState>(); cellToFileId = new HashMap<ASCIIString,String>(); numObjsInFlight = 0; filesInReset = new LinkedList(); externalRequestsInQueue = new AtomicInteger(0); localID = new ASCIIString(master.getConfig().getUUID().toString()); masterEpochThread = new FleaseMasterEpochThread(master.getStorageStage().getStorageLayout(), maxRequestsQueueLength); FleaseConfig fcfg = new FleaseConfig(master.getConfig().getFleaseLeaseToMS(), master.getConfig().getFleaseDmaxMS(), master.getConfig().getFleaseMsgToMS(), null, localID.toString(), master.getConfig().getFleaseRetries()); fstage = new FleaseStage(fcfg, master.getConfig().getObjDir()+"/", this, false, new FleaseViewChangeListenerInterface() { @Override public void viewIdChangeEvent(ASCIIString cellId, int viewId) { throw new UnsupportedOperationException("Not supported yet."); } }, new FleaseStatusListener() { @Override public void statusChanged(ASCIIString cellId, Flease lease) { //FIXME: change state eventLeaseStateChanged(cellId, lease, null); } @Override public void leaseFailed(ASCIIString cellID, FleaseException error) { //change state //flush pending requests eventLeaseStateChanged(cellID, null, error); } }, masterEpochThread); fstage.setLifeCycleListener(master); } @Override public void start() { masterEpochThread.start(); client.start(); fleaseClient.start(); fstage.start(); super.start(); } @Override public void shutdown() { client.shutdown(); fleaseClient.shutdown(); fstage.shutdown(); masterEpochThread.shutdown(); super.shutdown(); } @Override public void waitForStartup() throws Exception { masterEpochThread.waitForStartup(); client.waitForStartup(); fleaseClient.waitForStartup(); fstage.waitForStartup(); super.waitForStartup(); } @Override public void waitForShutdown() throws Exception { client.waitForShutdown(); fleaseClient.waitForShutdown(); fstage.waitForShutdown(); masterEpochThread.waitForShutdown(); super.waitForShutdown(); } public void eventReplicaStateAvailable(String fileId, ReplicaStatus localState, ErrorResponse error) { this.enqueueOperation(STAGEOP_INTERNAL_STATEAVAIL, new Object[]{fileId,localState,error}, null, null); } public void eventForceReset(FileCredentials credentials, XLocations xloc) { this.enqueueOperation(STAGEOP_FORCE_RESET, new Object[]{credentials, xloc}, null, null); } public void eventDeleteObjectsComplete(String fileId, ErrorResponse error) { this.enqueueOperation(STAGEOP_INTERNAL_DELETE_COMPLETE, new Object[]{fileId,error}, null, null); } void eventObjectFetched(String fileId, ObjectVersionMapping object, InternalObjectData data, ErrorResponse error) { this.enqueueOperation(STAGEOP_INTERNAL_OBJFETCHED, new Object[]{fileId,object,data,error}, null, null); } void eventSetAuthState(String fileId, AuthoritativeReplicaState authState, ReplicaStatus localState, ErrorResponse error) { this.enqueueOperation(STAGEOP_INTERNAL_AUTHSTATE, new Object[]{fileId,authState, localState, error}, null, null); } void eventLeaseStateChanged(ASCIIString cellId, Flease lease, FleaseException error) { this.enqueueOperation(STAGEOP_LEASE_STATE_CHANGED, new Object[]{cellId,lease,error}, null, null); } void eventMaxObjAvail(String fileId, long maxObjVer, long fileSize, long truncateEpoch, ErrorResponse error) { this.enqueueOperation(STAGEOP_INTERNAL_MAXOBJ_AVAIL, new Object[]{fileId,maxObjVer,error}, null, null); } public void eventBackupReplicaReset(String fileId, AuthoritativeReplicaState authState, ReplicaStatus localState, FileCredentials credentials, XLocations xloc) { this.enqueueOperation(STAGEOP_INTERNAL_BACKUP_AUTHSTATE, new Object[]{fileId,authState, localState, credentials, xloc}, null, null); } private void executeSetAuthState(final ReplicaStatus localState, final AuthoritativeReplicaState authState, ReplicatedFileState state, final String fileId) { // Calculate what we need to do locally based on the local state. boolean resetRequired = localState.getTruncateEpoch() < authState.getTruncateEpoch(); // Create a list of missing objects. Map<Long, Long> objectsToBeDeleted = new HashMap(); for (ObjectVersion localObject : localState.getObjectVersionsList()) { // Never delete any object which is newer than auth state! if (localObject.getObjectVersion() <= authState.getMaxObjVersion()) { objectsToBeDeleted.put(localObject.getObjectNumber(), localObject.getObjectVersion()); } } // Delete everything that is older or not part of the authoritative state. for (ObjectVersionMapping authObject : authState.getObjectVersionsList()) { Long version = objectsToBeDeleted.get(authObject.getObjectNumber()); if ((version != null) && (version == authObject.getObjectVersion())) { objectsToBeDeleted.remove(authObject.getObjectNumber()); } } Map<Long, ObjectVersionMapping> missingObjects = new HashMap(); for (ObjectVersionMapping authObject : authState.getObjectVersionsList()) { missingObjects.put(authObject.getObjectNumber(), authObject); } for (ObjectVersion localObject : localState.getObjectVersionsList()) { ObjectVersionMapping object = missingObjects.get(localObject.getObjectNumber()); if ((object != null) && (localObject.getObjectVersion() >= object.getObjectVersion())) { missingObjects.remove(localObject.getObjectNumber()); } } if (!missingObjects.isEmpty() || !objectsToBeDeleted.isEmpty() || (localState.getTruncateEpoch() < authState.getTruncateEpoch())) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this, "(R:%s) replica RESET required updates for: %s", localID, state.getFileId()); } state.setObjectsToFetch(new LinkedList(missingObjects.values())); filesInReset.add(state); // Start by deleting the old objects. master.getStorageStage().deleteObjects(fileId, state.getsPolicy(), authState.getTruncateEpoch(), objectsToBeDeleted, new DeleteObjectsCallback() { @Override public void deleteObjectsComplete(ErrorResponse error) { eventDeleteObjectsComplete(fileId, error); } }); } else { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this, "(R:%s) replica RESET finished (replica is up-to-date): %s", localID, state.getFileId()); } doOpen(state); } } private void processLeaseStateChanged(StageRequest method) { try { final ASCIIString cellId = (ASCIIString) method.getArgs()[0]; final Flease lease = (Flease) method.getArgs()[1]; final FleaseException error = (FleaseException) method.getArgs()[2]; if (error == null) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) lease change event: %s, %s",localID, cellId, lease); } } else { // Logging.logMessage(Logging.LEVEL_WARN, Category.replication, this,"(R:%s) lease error in cell %s: %s cell debug: %s",localID, cellId, error, error.getFleaseCellDebugString()); Logging.logMessage(Logging.LEVEL_WARN, Category.replication, this,"(R:%s) lease error in cell %s: %s",localID, cellId, error); } final String fileId = cellToFileId.get(cellId); if (fileId != null) { ReplicatedFileState state = files.get(fileId); assert(state != null); boolean leaseOk = false; if (error == null) { boolean localIsPrimary = (lease.getLeaseHolder() != null) && (lease.getLeaseHolder().equals(localID)); ReplicaState oldState = state.getState(); state.setLocalIsPrimary(localIsPrimary); state.setLease(lease); // Error handling for timeouts on the primary. if (oldState == ReplicaState.PRIMARY &&lease.getLeaseHolder() == null && lease.getLeaseTimeout_ms() == 0) { Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this,"(R:%s) was primary, lease error in cell %s, restarting replication: %s",localID, cellId,lease,error); failed(state, ErrorUtils.getInternalServerError(new IOException(fileId +": lease timed out, renew failed")), "processLeaseStateChanged"); } else { if ( (state.getState() == ReplicaState.BACKUP) || (state.getState() == ReplicaState.PRIMARY) || (state.getState() == ReplicaState.WAITING_FOR_LEASE) ) { if (localIsPrimary) { //notify onPrimary if (oldState != ReplicaState.PRIMARY) { state.setMasterEpoch(lease.getMasterEpochNumber()); doPrimary(state); } } else { if (oldState != ReplicaState.BACKUP) { state.setMasterEpoch(FleaseMessage.IGNORE_MASTER_EPOCH); doBackup(state); } } } } } else { failed(state, ErrorUtils.getInternalServerError(error), "processLeaseStateChanged (error != null)"); } } } catch (Exception ex) { Logging.logMessage(Logging.LEVEL_ERROR, this, "Exception was thrown and caught while processing the change of the lease state." + " This is an error in the code. Please report it! Caught exception: "); Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void processBackupAuthoritativeState(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; final AuthoritativeReplicaState authState = (AuthoritativeReplicaState) method.getArgs()[1]; final ReplicaStatus localState = (ReplicaStatus) method.getArgs()[2]; final FileCredentials credentials = (FileCredentials) method.getArgs()[3]; final XLocations loc = (XLocations) method.getArgs()[4]; ReplicatedFileState state = getState(credentials, loc, true); switch (state.getState()) { case INITIALIZING: case OPEN: case WAITING_FOR_LEASE: { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) enqueued backup reset for file %s",localID, fileId); state.addPendingRequest(method); break; } case BACKUP: { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) backup reset triggered by AUTHSTATE request for file %s",localID, fileId); state.setState(ReplicaState.RESET); executeSetAuthState(localState, authState, state, fileId); break; } case RESET: default: { // Ignore. Logging.logMessage(Logging.LEVEL_WARN, Category.replication, this,"(R:%s) auth state ignored, already in reset for file %s",localID, fileId); } } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void processSetAuthoritativeState(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; final AuthoritativeReplicaState authState = (AuthoritativeReplicaState) method.getArgs()[1]; final ReplicaStatus localState = (ReplicaStatus) method.getArgs()[2]; final ErrorResponse error = (ErrorResponse) method.getArgs()[3]; ReplicatedFileState state = files.get(fileId); if (state == null) { Logging.logMessage(Logging.LEVEL_WARN, Category.replication, this,"(R:%s) set AUTH for unknown file: %s",localID, fileId); return; } if (error != null) { failed(state, error, "processSetAuthoritativeState"); } else { executeSetAuthState(localState, authState, state, fileId); } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void processDeleteObjectsComplete(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; final ErrorResponse error = (ErrorResponse) method.getArgs()[1]; ReplicatedFileState state = files.get(fileId); if (state != null) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) deleted all objects requested by RESET for %s with %s",localID,state.getFileId(), ErrorUtils.formatError(error)); } if (error != null) { failed(state, error, "processDeleteObjectsComplete"); } else { fetchObjects(); } } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void fetchObjects() { while (numObjsInFlight < MAX_OBJS_IN_FLIGHT) { ReplicatedFileState file = filesInReset.poll(); if (file == null) break; if (!file.getObjectsToFetch().isEmpty()) { ObjectVersionMapping o = file.getObjectsToFetch().remove(0); file.setNumObjectsPending(file.getNumObjectsPending()+1); numObjsInFlight++; fetchObject(file.getFileId(), o); } if (!file.getObjectsToFetch().isEmpty()) { filesInReset.add(file); } } } private void fetchObject(final String fileId, final ObjectVersionMapping record) { ReplicatedFileState state = files.get(fileId); if (state == null) { return; } try { final ServiceUUID osd = new ServiceUUID(record.getOsdUuidsList().get(0)); //fetch that object if (Logging.isDebug()) Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) file %s, fetch object %d (version %d) from %s", localID, fileId,record.getObjectNumber(),record.getObjectVersion(),osd); RPCResponse r = osdClient.xtreemfs_rwr_fetch(osd.getAddress(), RPCAuthentication.authNone, RPCAuthentication.userService, state.getCredentials(), fileId, record.getObjectNumber(), record.getObjectVersion()); r.registerListener(new RPCResponseAvailableListener() { @Override public void responseAvailable(RPCResponse r) { try { ObjectData metadata = (ObjectData) r.get(); InternalObjectData data = new InternalObjectData(metadata, r.getData()); eventObjectFetched(fileId, record, data, null); } catch (PBRPCException ex) { // Transform exception into correct ErrorResponse. // TODO(mberlin): Generalize this functionality by returning "Throwable" instead of // "ErrorResponse" to the event* functions. // The "ErrorResponse" shall be created in the last 'step' at the // invocation of failed(). eventObjectFetched(fileId, record, null, ErrorUtils.getErrorResponse(ex.getErrorType(), ex.getPOSIXErrno(), ex.toString(), ex)); } catch (Exception ex) { eventObjectFetched(fileId, record, null, ErrorUtils.getErrorResponse(ErrorType.IO_ERROR, POSIXErrno.POSIX_ERROR_NONE, ex.toString(), ex)); } finally { r.freeBuffers(); } } }); } catch (IOException ex) { eventObjectFetched(fileId, record, null, ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO, ex.toString(), ex)); } } private void processObjectFetched(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; final ObjectVersionMapping record = (ObjectVersionMapping) method.getArgs()[1]; final InternalObjectData data = (InternalObjectData) method.getArgs()[2]; final ErrorResponse error = (ErrorResponse) method.getArgs()[3]; ReplicatedFileState state = files.get(fileId); if (state != null) { if (error != null) { numObjsInFlight--; fetchObjects(); failed(state, error, "processObjectFetched"); } else if (data.getData() == null) { // data is null if object was deleted meanwhile. numObjsInFlight--; fetchObjects(); ErrorResponse generatedError = ErrorResponse.newBuilder().setErrorType(RPC.ErrorType.INTERNAL_SERVER_ERROR).setErrorMessage("Fetching a missing object failed because no data was returned. The object was probably deleted meanwhile.").build(); failed(state, generatedError, "processObjectFetched"); } else { final int bytes = data.getData().remaining(); master.getStorageStage().writeObjectWithoutGMax(fileId, record.getObjectNumber(), state.getsPolicy(), 0, data.getData(), CowPolicy.PolicyNoCow, null, false, record.getObjectVersion(), null, new WriteObjectCallback() { @Override public void writeComplete(OSDWriteResponse result, ErrorResponse error) { if (error != null) { Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this,"cannot write object locally: %s",ErrorUtils.formatError(error)); } } }); master.getPreprocStage().pingFile(fileId); master.objectReplicated(); master.replicatedDataReceived(bytes); numObjsInFlight--; final int numPendingFile = state.getNumObjectsPending()-1; state.setNumObjectsPending(numPendingFile); state.getPolicy().objectFetched(record.getObjectVersion()); if (Logging.isDebug()) Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) fetched object for replica, file %s, remaining %d",localID, fileId,numPendingFile); fetchObjects(); if (numPendingFile == 0) { //reset complete! Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) RESET complete for file %s",localID, fileId); doOpen(state); } } } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void doReset(final ReplicatedFileState file, long updateObjVer) { if (file.getState() == ReplicaState.RESET) { if (Logging.isDebug()) Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"file %s is already in RESET",file.getFileId()); return; } if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) replica state changed for %s from %s to %s",localID, file.getFileId(),file.getState(),ReplicaState.RESET); } file.setState(ReplicaState.RESET); if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) replica RESET started: %s (update objVer=%d)",localID, file.getFileId(),updateObjVer); } OSDOperation op = master.getInternalEvent(EventRWRStatus.class); op.startInternalEvent(new Object[]{file.getFileId(),file.getsPolicy()}); } private void processReplicaStateAvailExecReset(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; final ReplicaStatus localReplicaState = (ReplicaStatus) method.getArgs()[1]; final ErrorResponse error = (ErrorResponse) method.getArgs()[2]; final ReplicatedFileState state = files.get(fileId); if (state != null) { if (error != null) { Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this,"local state for %s failed: %s", state.getFileId(), error); failed(state, error, "processReplicaStateAvailExecReset"); } else { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) local state for %s available.", localID, state.getFileId()); } state.getPolicy().executeReset(state.getCredentials(), localReplicaState, new ReplicaUpdatePolicy.ExecuteResetCallback() { @Override public void finished(AuthoritativeReplicaState authState) { eventSetAuthState(state.getFileId(), authState, localReplicaState, null); } @Override public void failed(ErrorResponse error) { eventSetAuthState(state.getFileId(), null, null, error); } }); } } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void processForceReset(StageRequest method) { try { final FileCredentials credentials = (FileCredentials) method.getArgs()[0]; final XLocations loc = (XLocations) method.getArgs()[1]; ReplicatedFileState state = getState(credentials, loc, true); if (!state.isForceReset()) { state.setForceReset(true); } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void doWaitingForLease(final ReplicatedFileState file) { if (file.getPolicy().requiresLease()) { if (file.isCellOpen()) { if (file.isLocalIsPrimary()) { doPrimary(file); } else { doBackup(file); } } else { file.setCellOpen(true); if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) replica state changed for %s from %s to %s", localID,file.getFileId(),file.getState(),ReplicaState.WAITING_FOR_LEASE); } try { file.setState(ReplicaState.WAITING_FOR_LEASE); List<InetSocketAddress> osdAddresses = new ArrayList(); for (ServiceUUID osd : file.getPolicy().getRemoteOSDUUIDs()) { osdAddresses.add(osd.getAddress()); } fstage.openCell(file.getPolicy().getCellId(), osdAddresses, true); //wait for lease... } catch (UnknownUUIDException ex) { failed(file, ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO, ex.toString(), ex), "doWaitingForLease"); } } } else { //become primary immediately doPrimary(file); } } private void doOpen(final ReplicatedFileState file) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, this,"(R:%s) replica state changed for %s from %s to %s",localID, file.getFileId(),file.getState(),ReplicaState.OPEN); } file.setState(ReplicaState.OPEN); if (file.getPendingRequests().size() > 0) { doWaitingForLease(file); } } private void doPrimary(final ReplicatedFileState file) { assert(file.isLocalIsPrimary()); try { if (file.getPolicy().onPrimary((int)file.getMasterEpoch()) && !file.isPrimaryReset()) { file.setPrimaryReset(true); doReset(file,ReplicaUpdatePolicy.UNLIMITED_RESET); } else { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) replica state changed for %s from %s to %s", localID, file.getFileId(),file.getState(),ReplicaState.PRIMARY); } file.setPrimaryReset(false); file.setState(ReplicaState.PRIMARY); while (!file.getPendingRequests().isEmpty()) { StageRequest m = file.getPendingRequests().remove(0); enqueuePrioritized(m); } } } catch (IOException ex) { failed(file, ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO, ex.toString(), ex), "doPrimary"); } } private void doBackup(final ReplicatedFileState file) { assert(!file.isLocalIsPrimary()); //try { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) replica state changed for %s from %s to %s", localID, file.getFileId(),file.getState(),ReplicaState.BACKUP); } file.setPrimaryReset(false); file.setState(ReplicaState.BACKUP); while (!file.getPendingRequests().isEmpty()) { StageRequest m = file.getPendingRequests().remove(0); enqueuePrioritized(m); } /*} catch (IOException ex) { failed(file, ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO, ex.toString(), ex)); }*/ } private void failed(ReplicatedFileState file, ErrorResponse ex, String methodName) { Logging.logMessage(Logging.LEVEL_WARN, Category.replication, this,"(R:%s) replica for file %s failed (in method: %s): %s", localID, file.getFileId(), methodName, ErrorUtils.formatError(ex)); file.setPrimaryReset(false); file.setState(ReplicaState.OPEN); file.setCellOpen(false); fstage.closeCell(file.getPolicy().getCellId(), false); for (StageRequest rq : file.getPendingRequests()) { RWReplicationCallback callback = (RWReplicationCallback) rq.getCallback(); if (callback != null) { callback.failed(ex); } } file.getPendingRequests().clear(); } private void enqueuePrioritized(StageRequest rq) { while (!q.offer(rq)) { StageRequest otherRq = q.poll(); otherRq.sendInternalServerError(new IllegalStateException("internal queue overflow, cannot enqueue operation for processing.")); Logging.logMessage(Logging.LEVEL_DEBUG, this, "Dropping request from rwre queue due to overload"); } } public static interface RWReplicationCallback { public void success(long newObjectVersion); public void redirect(String redirectTo); public void failed(ErrorResponse ex); } /*public void openFile(FileCredentials credentials, XLocations locations, boolean forceReset, RWReplicationCallback callback, OSDRequest request) { this.enqueueOperation(STAGEOP_OPEN, new Object[]{credentials,locations,forceReset}, request, callback); }*/ protected void enqueueExternalOperation(int stageOp, Object[] arguments, OSDRequest request, ReusableBuffer createdViewBuffer, Object callback) { if (externalRequestsInQueue.get() >= MAX_EXTERNAL_REQUESTS_IN_Q) { Logging.logMessage(Logging.LEVEL_WARN, this, "RW replication stage is overloaded, request %d for %s dropped", request.getRequestId(), request.getFileId()); request.sendInternalServerError(new IllegalStateException("RW replication stage is overloaded, request dropped")); // Make sure that the data buffer is returned to the pool if // necessary, as some operations create view buffers on the // data. Otherwise, a 'finalized but not freed before' warning // may occur. if (createdViewBuffer != null) { assert (createdViewBuffer.getRefCount() >= 2); BufferPool.free(createdViewBuffer); } } else { externalRequestsInQueue.incrementAndGet(); this.enqueueOperation(stageOp, arguments, request, createdViewBuffer, callback); } } public void prepareOperation(FileCredentials credentials, XLocations xloc, long objNo, long objVersion, Operation op, RWReplicationCallback callback, OSDRequest request) { this.enqueueExternalOperation(STAGEOP_PREPAREOP, new Object[]{credentials,xloc,objNo,objVersion,op}, request, null, callback); } public void replicatedWrite(FileCredentials credentials, XLocations xloc, long objNo, long objVersion, InternalObjectData data, ReusableBuffer createdViewBuffer, RWReplicationCallback callback, OSDRequest request) { this.enqueueExternalOperation(STAGEOP_REPLICATED_WRITE, new Object[]{credentials,xloc,objNo,objVersion,data}, request, createdViewBuffer, callback); } public void replicateTruncate(FileCredentials credentials, XLocations xloc, long newFileSize, long newObjectVersion, RWReplicationCallback callback, OSDRequest request) { this.enqueueExternalOperation(STAGEOP_TRUNCATE, new Object[]{credentials,xloc,newFileSize,newObjectVersion}, request, null, callback); } public void fileClosed(String fileId) { this.enqueueOperation(STAGEOP_CLOSE, new Object[]{fileId}, null, null); } public void receiveFleaseMessage(ReusableBuffer message, InetSocketAddress sender) { //this.enqueueOperation(STAGEOP_PROCESS_FLEASE_MSG, new Object[]{message,sender}, null, null); try { FleaseMessage msg = new FleaseMessage(message); BufferPool.free(message); msg.setSender(sender); fstage.receiveMessage(msg); } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } public void getStatus(StatusCallback callback) { this.enqueueOperation(STAGEOP_GETSTATUS, new Object[]{}, null, callback); } public static interface StatusCallback { public void statusComplete(Map<String,Map<String,String>> status); } public void setFleaseView(String fileId, XLocSetVersionState versionState) { enqueueOperation(STAGEOP_SETVIEW, new Object[] { fileId, versionState }, null, null); } public void setFleaseView(String fileId, XLocSetVersionState versionState, InstallXLocSetCallback callback) { enqueueOperation(STAGEOP_SETVIEW, new Object[] { fileId, versionState }, null, callback); } public void invalidateView(String fileId, XLocSetVersionState versionState, InvalidateXLocSetCallback callback) { enqueueOperation(STAGEOP_INVALIDATEVIEW, new Object[] { fileId, versionState }, null, callback); } @Override public void sendMessage(FleaseMessage message, InetSocketAddress recipient) { ReusableBuffer data = BufferPool.allocate(message.getSize()); message.serialize(data); data.flip(); try { RPCResponse r = fleaseOsdClient.xtreemfs_rwr_flease_msg(recipient, RPCAuthentication.authNone, RPCAuthentication.userService, master.getHostName(),master.getConfig().getPort(),data); r.registerListener(new RPCResponseAvailableListener() { @Override public void responseAvailable(RPCResponse r) { r.freeBuffers(); } }); } catch (IOException ex) { Logging.logError(Logging.LEVEL_ERROR, this, ex); } } @Override protected void processMethod(StageRequest method) { switch (method.getStageMethod()) { case STAGEOP_REPLICATED_WRITE : { externalRequestsInQueue.decrementAndGet(); processReplicatedWrite(method); break; } case STAGEOP_TRUNCATE : { externalRequestsInQueue.decrementAndGet(); processReplicatedTruncate(method); break; } case STAGEOP_CLOSE : processFileClosed(method); break; case STAGEOP_PROCESS_FLEASE_MSG : processFleaseMessage(method); break; case STAGEOP_PREPAREOP : { externalRequestsInQueue.decrementAndGet(); processPrepareOp(method); break; } case STAGEOP_INTERNAL_AUTHSTATE : processSetAuthoritativeState(method); break; case STAGEOP_LEASE_STATE_CHANGED : processLeaseStateChanged(method); break; case STAGEOP_INTERNAL_OBJFETCHED : processObjectFetched(method); break; case STAGEOP_INTERNAL_STATEAVAIL : processReplicaStateAvailExecReset(method); break; case STAGEOP_INTERNAL_DELETE_COMPLETE : processDeleteObjectsComplete(method); break; case STAGEOP_INTERNAL_MAXOBJ_AVAIL : processMaxObjAvail(method); break; case STAGEOP_INTERNAL_BACKUP_AUTHSTATE: processBackupAuthoritativeState(method); break; case STAGEOP_FORCE_RESET : processForceReset(method); break; case STAGEOP_GETSTATUS : processGetStatus(method); break; case STAGEOP_SETVIEW: processSetFleaseView(method); break; case STAGEOP_INVALIDATEVIEW: processInvalidateView(method); break; default : throw new IllegalArgumentException("no such stageop"); } } private void processFleaseMessage(StageRequest method) { try { final ReusableBuffer data = (ReusableBuffer) method.getArgs()[0]; final InetSocketAddress sender = (InetSocketAddress) method.getArgs()[1]; FleaseMessage msg = new FleaseMessage(data); BufferPool.free(data); msg.setSender(sender); fstage.receiveMessage(msg); } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void processFileClosed(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; ReplicatedFileState state = files.remove(fileId); if (state != null) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"closing file %s",fileId); } state.getPolicy().closeFile(); if (state.getPolicy().requiresLease()) fstage.closeCell(state.getPolicy().getCellId(), false); cellToFileId.remove(state.getPolicy().getCellId()); } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private ReplicatedFileState getState(FileCredentials credentials, XLocations loc, boolean forceReset) throws IOException { final String fileId = credentials.getXcap().getFileId(); ReplicatedFileState state = files.get(fileId); if (state == null) { if (Logging.isDebug()) Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"open file: "+fileId); //"open" file state = new ReplicatedFileState(fileId,loc, master.getConfig().getUUID(), fstage, osdClient); files.put(fileId,state); state.setCredentials(credentials); state.setForceReset(forceReset); cellToFileId.put(state.getPolicy().getCellId(),fileId); assert(state.getState() == ReplicaState.INITIALIZING); master.getStorageStage().internalGetMaxObjectNo(fileId, loc.getLocalReplica().getStripingPolicy(), new InternalGetMaxObjectNoCallback() { @Override public void maxObjectNoCompleted(long maxObjNo, long fileSize, long truncateEpoch, ErrorResponse error) { eventMaxObjAvail(fileId, maxObjNo, fileSize, truncateEpoch, error); } }); } return state; } private void processMaxObjAvail(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; final Long maxObjVersion = (Long) method.getArgs()[1]; final ErrorResponse error = (ErrorResponse) method.getArgs()[2]; if (Logging.isDebug()) Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) max obj avail for file: "+fileId+" max="+maxObjVersion, localID); ReplicatedFileState state = files.get(fileId); if (state == null) { Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this,"received maxObjAvail event for unknow file: %s",fileId); return; } if(state.getState() == ReplicaState.INITIALIZING) { state.getPolicy().setLocalObjectVersion(maxObjVersion); doOpen(state); } else { Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this, "ReplicaState is %s instead of INITIALIZING, maxObjectVersion=%d", state.getState().name(), maxObjVersion); return; } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this, ex); } } private void processReplicatedWrite(StageRequest method) { final RWReplicationCallback callback = (RWReplicationCallback) method.getCallback(); try { final FileCredentials credentials = (FileCredentials) method.getArgs()[0]; final XLocations loc = (XLocations) method.getArgs()[1]; final Long objNo = (Long) method.getArgs()[2]; final Long objVersion = (Long) method.getArgs()[3]; final InternalObjectData objData = (InternalObjectData) method.getArgs()[4]; final String fileId = credentials.getXcap().getFileId(); ReplicatedFileState state = files.get(fileId); if (state == null) { BufferPool.free(objData.getData()); callback.failed(ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_EIO, "file is not open!")); return; } state.setCredentials(credentials); state.getPolicy().executeWrite(credentials, objNo, objVersion, objData, new ReplicaUpdatePolicy.ClientOperationCallback() { @Override public void finsihed() { callback.success(objVersion); } @Override public void failed(ErrorResponse error) { callback.failed(error); } }); } catch (Exception ex) { ex.printStackTrace(); callback.failed(ErrorUtils.getInternalServerError(ex)); } } private void processReplicatedTruncate(StageRequest method) { final RWReplicationCallback callback = (RWReplicationCallback) method.getCallback(); try { final FileCredentials credentials = (FileCredentials) method.getArgs()[0]; final XLocations loc = (XLocations) method.getArgs()[1]; final Long newFileSize = (Long) method.getArgs()[2]; final Long newObjVersion = (Long) method.getArgs()[3]; final String fileId = credentials.getXcap().getFileId(); ReplicatedFileState state = files.get(fileId); if (state == null) { callback.failed(ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_EIO, "file is not open!")); return; } state.setCredentials(credentials); state.getPolicy().executeTruncate(credentials, newFileSize, newObjVersion, new ReplicaUpdatePolicy.ClientOperationCallback() { @Override public void finsihed() { callback.success(newObjVersion); } @Override public void failed(ErrorResponse error) { callback.failed(error); } }); } catch (Exception ex) { ex.printStackTrace(); callback.failed(ErrorUtils.getInternalServerError(ex)); } } private void processPrepareOp(StageRequest method) { final RWReplicationCallback callback = (RWReplicationCallback)method.getCallback(); try { final FileCredentials credentials = (FileCredentials) method.getArgs()[0]; final XLocations loc = (XLocations) method.getArgs()[1]; final Long objVersion = (Long) method.getArgs()[3]; final Operation op = (Operation) method.getArgs()[4]; final String fileId = credentials.getXcap().getFileId(); ReplicatedFileState state = getState(credentials, loc, false); if ((op == Operation.INTERNAL_UPDATE) || (op == Operation.INTERNAL_TRUNCATE)) { switch (state.getState()) { case WAITING_FOR_LEASE: case INITIALIZING: case RESET: case OPEN: { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"enqeue update for %s (state is %s)",fileId,state.getState()); } if (state.getPendingRequests().size() > MAX_PENDING_PER_FILE) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, this, "rejecting request: too many requests (is: %d, max %d) in queue for file %s", state.getPendingRequests().size(), MAX_PENDING_PER_FILE, fileId); } callback.failed(ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_NONE, "too many requests in queue for file")); return; } else { state.getPendingRequests().add(method); } if (state.getState() == ReplicaState.OPEN) { //immediately change to backup mode...no need to check the lease doWaitingForLease(state); } return; } } if (!state.getPolicy().acceptRemoteUpdate(objVersion)) { Logging.logMessage( Logging.LEVEL_WARN, Category.replication, this, "received outdated object version %d for file %s", objVersion, fileId); callback.failed(ErrorUtils.getErrorResponse( ErrorType.IO_ERROR, POSIXErrno.POSIX_ERROR_EIO, "outdated object version for update rejected")); return; } boolean needsReset = state.getPolicy().onRemoteUpdate(objVersion, state.getState()); if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"%s needs reset: %s",fileId,needsReset); } if (needsReset) { state.getPendingRequests().add(method); doReset(state,objVersion); } else { callback.success(0); } } else { state.setCredentials(credentials); switch (state.getState()) { case WAITING_FOR_LEASE: case INITIALIZING: case RESET : { if (state.getPendingRequests().size() > MAX_PENDING_PER_FILE) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, this, "rejecting request: too many requests (is: %d, max %d) in queue for file %s", state.getPendingRequests().size(), MAX_PENDING_PER_FILE, fileId); } callback.failed(ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_NONE, "too many requests in queue for file")); } else { state.getPendingRequests().add(method); } return; } case OPEN : { if (state.getPendingRequests().size() > MAX_PENDING_PER_FILE) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, this, "rejecting request: too many requests (is: %d, max %d) in queue for file %s", state.getPendingRequests().size(), MAX_PENDING_PER_FILE, fileId); } callback.failed(ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_NONE, "too many requests in queue for file")); return; } else { state.getPendingRequests().add(method); } doWaitingForLease(state); return; } } try { long newVersion = state.getPolicy().onClientOperation(op,objVersion,state.getState(),state.getLease()); callback.success(newVersion); } catch (RedirectToMasterException ex) { callback.redirect(ex.getMasterUUID()); } catch (RetryException ex) { final ErrorResponse err = ErrorUtils.getInternalServerError(ex); failed(state, err, "processPrepareOp"); if (state.getState() == ReplicaState.BACKUP || state.getState() == ReplicaState.PRIMARY) { // Request is not in queue, we must notify // callback. callback.failed(err); } } } } catch (Exception ex) { ex.printStackTrace(); callback.failed(ErrorUtils.getInternalServerError(ex)); } } private void processGetStatus(StageRequest method) { final StatusCallback callback = (StatusCallback)method.getCallback(); try { Map<String,Map<String,String>> status = new HashMap(); Map<ASCIIString,FleaseMessage> fleaseState = fstage.getLocalState(); for (String fileId : this.files.keySet()) { Map<String,String> fStatus = new HashMap(); final ReplicatedFileState fState = files.get(fileId); final ASCIIString cellId = fState.getPolicy().getCellId(); fStatus.put("policy",fState.getPolicy().getClass().getSimpleName()); fStatus.put("peers (OSDs)",fState.getPolicy().getRemoteOSDUUIDs().toString()); fStatus.put("pending requests", fState.getPendingRequests() == null ? "0" : ""+fState.getPendingRequests().size()); fStatus.put("cellId", cellId.toString()); String primary = "unknown"; if ((fState.getLease() != null) && (!fState.getLease().isEmptyLease())) { if (fState.getLease().isValid()) { if (fState.isLocalIsPrimary()) { primary = "primary"; } else { primary = "backup ( primary is "+fState.getLease().getLeaseHolder()+")"; } } else { primary = "outdated lease: "+fState.getLease().getLeaseHolder(); } } fStatus.put("role", primary); status.put(fileId,fStatus); } callback.statusComplete(status); } catch (Exception ex) { ex.printStackTrace(); callback.statusComplete(null); } } public String getPrimary(final String fileId) { String primary = null; final ReplicatedFileState fState = files.get(fileId); if ((fState != null) && (fState.getLease() != null) && (!fState.getLease().isEmptyLease())) { if (fState.getLease().isValid()) { primary = "" + fState.getLease().getLeaseHolder(); } else { // outdated lease } } return primary; } private void processSetFleaseView(StageRequest method) { final Object[] args = method.getArgs(); final String fileId = (String) args[0]; final XLocSetVersionState versionState = (XLocSetVersionState) args[1]; final InstallXLocSetCallback callback = (InstallXLocSetCallback) method.getCallback(); // TODO (jdillmann): check if file exists and files.get() != null final ASCIIString cellId = files.get(fileId).getPolicy().getCellId(); int viewId; if (versionState.getInvalidated()) { viewId = FleaseMessage.VIEW_ID_INVALIDATED; } else { viewId = versionState.getVersion(); } fstage.setViewId(cellId, viewId, new FleaseListener() { @Override public void proposalResult(ASCIIString cellId, ASCIIString leaseHolder, long leaseTimeout_ms, long masterEpochNumber) { if (callback != null) { callback.installComplete(fileId, versionState.getVersion(), null); } } @Override public void proposalFailed(ASCIIString cellId, Throwable cause) { if (callback != null) { callback.installComplete(fileId, versionState.getVersion(), ErrorUtils.getInternalServerError(cause)); } } }); } private void processInvalidateView(StageRequest method) { final Object[] args = method.getArgs(); final String fileId = (String) args[0]; final XLocSetVersionState versionState = (XLocSetVersionState) args[1]; final InvalidateXLocSetCallback callback = (InvalidateXLocSetCallback) method.getCallback(); // TODO (jdillmann): check if file exists and files.get() != null final ReplicatedFileState fState = files.get(fileId); final ASCIIString cellId = fState.getPolicy().getCellId(); final boolean isPrimary = (fState != null && fState.isLocalIsPrimary()); fstage.setViewId(cellId, FleaseMessage.VIEW_ID_INVALIDATED, new FleaseListener() { @Override public void proposalResult(ASCIIString cellId, ASCIIString leaseHolder, long leaseTimeout_ms, long masterEpochNumber) { callback.invalidateComplete(fileId, versionState.getVersion(), isPrimary, null); } @Override public void proposalFailed(ASCIIString cellId, Throwable cause) { callback.invalidateComplete(fileId, versionState.getVersion(), isPrimary, ErrorUtils.getInternalServerError(cause)); } }); } }
java/servers/src/org/xtreemfs/osd/rwre/RWReplicationStage.java
/* * Copyright (c) 2010-2011 by Bjoern Kolbeck, * Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ package org.xtreemfs.osd.rwre; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; import org.xtreemfs.common.uuids.ServiceUUID; import org.xtreemfs.common.uuids.UnknownUUIDException; import org.xtreemfs.common.xloc.XLocations; import org.xtreemfs.foundation.SSLOptions; import org.xtreemfs.foundation.buffer.ASCIIString; import org.xtreemfs.foundation.buffer.BufferPool; import org.xtreemfs.foundation.buffer.ReusableBuffer; import org.xtreemfs.foundation.flease.Flease; import org.xtreemfs.foundation.flease.FleaseConfig; import org.xtreemfs.foundation.flease.FleaseMessageSenderInterface; import org.xtreemfs.foundation.flease.FleaseStage; import org.xtreemfs.foundation.flease.FleaseStatusListener; import org.xtreemfs.foundation.flease.FleaseViewChangeListenerInterface; import org.xtreemfs.foundation.flease.comm.FleaseMessage; import org.xtreemfs.foundation.flease.proposer.FleaseException; import org.xtreemfs.foundation.flease.proposer.FleaseListener; import org.xtreemfs.foundation.logging.Logging; import org.xtreemfs.foundation.logging.Logging.Category; import org.xtreemfs.foundation.pbrpc.client.PBRPCException; import org.xtreemfs.foundation.pbrpc.client.RPCAuthentication; import org.xtreemfs.foundation.pbrpc.client.RPCNIOSocketClient; import org.xtreemfs.foundation.pbrpc.client.RPCResponse; import org.xtreemfs.foundation.pbrpc.client.RPCResponseAvailableListener; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.ErrorType; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.POSIXErrno; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.RPCHeader.ErrorResponse; import org.xtreemfs.foundation.pbrpc.utils.ErrorUtils; import org.xtreemfs.osd.InternalObjectData; import org.xtreemfs.osd.OSDRequest; import org.xtreemfs.osd.OSDRequestDispatcher; import org.xtreemfs.osd.operations.EventRWRStatus; import org.xtreemfs.osd.operations.OSDOperation; import org.xtreemfs.osd.rwre.ReplicatedFileState.ReplicaState; import org.xtreemfs.osd.stages.PreprocStage.InstallXLocSetCallback; import org.xtreemfs.osd.stages.PreprocStage.InvalidateXLocSetCallback; import org.xtreemfs.osd.stages.Stage; import org.xtreemfs.osd.stages.StorageStage.DeleteObjectsCallback; import org.xtreemfs.osd.stages.StorageStage.InternalGetMaxObjectNoCallback; import org.xtreemfs.osd.stages.StorageStage.WriteObjectCallback; import org.xtreemfs.osd.storage.CowPolicy; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.FileCredentials; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.OSDWriteResponse; import org.xtreemfs.pbrpc.generatedinterfaces.OSD.AuthoritativeReplicaState; import org.xtreemfs.pbrpc.generatedinterfaces.OSD.ObjectData; import org.xtreemfs.pbrpc.generatedinterfaces.OSD.ObjectVersion; import org.xtreemfs.pbrpc.generatedinterfaces.OSD.ObjectVersionMapping; import org.xtreemfs.pbrpc.generatedinterfaces.OSD.ReplicaStatus; import org.xtreemfs.pbrpc.generatedinterfaces.OSD.XLocSetVersionState; import org.xtreemfs.pbrpc.generatedinterfaces.OSDServiceClient; /** * * @author bjko */ public class RWReplicationStage extends Stage implements FleaseMessageSenderInterface { public static final int STAGEOP_REPLICATED_WRITE = 1; public static final int STAGEOP_CLOSE = 2; public static final int STAGEOP_PROCESS_FLEASE_MSG = 3; public static final int STAGEOP_PREPAREOP = 5; public static final int STAGEOP_TRUNCATE = 6; public static final int STAGEOP_GETSTATUS = 7; public static final int STAGEOP_INTERNAL_AUTHSTATE = 10; public static final int STAGEOP_INTERNAL_OBJFETCHED = 11; public static final int STAGEOP_LEASE_STATE_CHANGED = 13; public static final int STAGEOP_INTERNAL_STATEAVAIL = 14; public static final int STAGEOP_INTERNAL_DELETE_COMPLETE = 15; public static final int STAGEOP_FORCE_RESET = 16; public static final int STAGEOP_INTERNAL_MAXOBJ_AVAIL = 17; public static final int STAGEOP_INTERNAL_BACKUP_AUTHSTATE = 18; public static final int STAGEOP_SETVIEW = 21; public static final int STAGEOP_INVALIDATEVIEW = 22; public static enum Operation { READ, WRITE, TRUNCATE, INTERNAL_UPDATE, INTERNAL_TRUNCATE }; private final RPCNIOSocketClient client; private final OSDServiceClient osdClient; private final Map<String,ReplicatedFileState> files; private final Map<ASCIIString,String> cellToFileId; private final OSDRequestDispatcher master; private final FleaseStage fstage; private final RPCNIOSocketClient fleaseClient; private final OSDServiceClient fleaseOsdClient; private final ASCIIString localID; private int numObjsInFlight; private static final int MAX_OBJS_IN_FLIGHT = 10; private static final int MAX_PENDING_PER_FILE = 10; private static final int MAX_EXTERNAL_REQUESTS_IN_Q = 250; private final Queue<ReplicatedFileState> filesInReset; private final FleaseMasterEpochThread masterEpochThread; private final AtomicInteger externalRequestsInQueue; public RWReplicationStage(OSDRequestDispatcher master, SSLOptions sslOpts, int maxRequestsQueueLength) throws IOException { super("RWReplSt", maxRequestsQueueLength); this.master = master; client = new RPCNIOSocketClient(sslOpts, 15000, 60000*5, "RWReplicationStage"); fleaseClient = new RPCNIOSocketClient(sslOpts, 15000, 60000*5, "RWReplicationStage (flease)"); osdClient = new OSDServiceClient(client,null); fleaseOsdClient = new OSDServiceClient(fleaseClient,null); files = new HashMap<String, ReplicatedFileState>(); cellToFileId = new HashMap<ASCIIString,String>(); numObjsInFlight = 0; filesInReset = new LinkedList(); externalRequestsInQueue = new AtomicInteger(0); localID = new ASCIIString(master.getConfig().getUUID().toString()); masterEpochThread = new FleaseMasterEpochThread(master.getStorageStage().getStorageLayout(), maxRequestsQueueLength); FleaseConfig fcfg = new FleaseConfig(master.getConfig().getFleaseLeaseToMS(), master.getConfig().getFleaseDmaxMS(), master.getConfig().getFleaseMsgToMS(), null, localID.toString(), master.getConfig().getFleaseRetries()); fstage = new FleaseStage(fcfg, master.getConfig().getObjDir()+"/", this, false, new FleaseViewChangeListenerInterface() { @Override public void viewIdChangeEvent(ASCIIString cellId, int viewId) { throw new UnsupportedOperationException("Not supported yet."); } }, new FleaseStatusListener() { @Override public void statusChanged(ASCIIString cellId, Flease lease) { //FIXME: change state eventLeaseStateChanged(cellId, lease, null); } @Override public void leaseFailed(ASCIIString cellID, FleaseException error) { //change state //flush pending requests eventLeaseStateChanged(cellID, null, error); } }, masterEpochThread); fstage.setLifeCycleListener(master); } @Override public void start() { masterEpochThread.start(); client.start(); fleaseClient.start(); fstage.start(); super.start(); } @Override public void shutdown() { client.shutdown(); fleaseClient.shutdown(); fstage.shutdown(); masterEpochThread.shutdown(); super.shutdown(); } @Override public void waitForStartup() throws Exception { masterEpochThread.waitForStartup(); client.waitForStartup(); fleaseClient.waitForStartup(); fstage.waitForStartup(); super.waitForStartup(); } public void waitForShutdown() throws Exception { client.waitForShutdown(); fleaseClient.waitForShutdown(); fstage.waitForShutdown(); masterEpochThread.waitForShutdown(); super.waitForShutdown(); } public void eventReplicaStateAvailable(String fileId, ReplicaStatus localState, ErrorResponse error) { this.enqueueOperation(STAGEOP_INTERNAL_STATEAVAIL, new Object[]{fileId,localState,error}, null, null); } public void eventForceReset(FileCredentials credentials, XLocations xloc) { this.enqueueOperation(STAGEOP_FORCE_RESET, new Object[]{credentials, xloc}, null, null); } public void eventDeleteObjectsComplete(String fileId, ErrorResponse error) { this.enqueueOperation(STAGEOP_INTERNAL_DELETE_COMPLETE, new Object[]{fileId,error}, null, null); } void eventObjectFetched(String fileId, ObjectVersionMapping object, InternalObjectData data, ErrorResponse error) { this.enqueueOperation(STAGEOP_INTERNAL_OBJFETCHED, new Object[]{fileId,object,data,error}, null, null); } void eventSetAuthState(String fileId, AuthoritativeReplicaState authState, ReplicaStatus localState, ErrorResponse error) { this.enqueueOperation(STAGEOP_INTERNAL_AUTHSTATE, new Object[]{fileId,authState, localState, error}, null, null); } void eventLeaseStateChanged(ASCIIString cellId, Flease lease, FleaseException error) { this.enqueueOperation(STAGEOP_LEASE_STATE_CHANGED, new Object[]{cellId,lease,error}, null, null); } void eventMaxObjAvail(String fileId, long maxObjVer, long fileSize, long truncateEpoch, ErrorResponse error) { this.enqueueOperation(STAGEOP_INTERNAL_MAXOBJ_AVAIL, new Object[]{fileId,maxObjVer,error}, null, null); } public void eventBackupReplicaReset(String fileId, AuthoritativeReplicaState authState, ReplicaStatus localState, FileCredentials credentials, XLocations xloc) { this.enqueueOperation(STAGEOP_INTERNAL_BACKUP_AUTHSTATE, new Object[]{fileId,authState, localState, credentials, xloc}, null, null); } private void executeSetAuthState(final ReplicaStatus localState, final AuthoritativeReplicaState authState, ReplicatedFileState state, final String fileId) { // Calculate what we need to do locally based on the local state. boolean resetRequired = localState.getTruncateEpoch() < authState.getTruncateEpoch(); // Create a list of missing objects. Map<Long, Long> objectsToBeDeleted = new HashMap(); for (ObjectVersion localObject : localState.getObjectVersionsList()) { // Never delete any object which is newer than auth state! if (localObject.getObjectVersion() <= authState.getMaxObjVersion()) { objectsToBeDeleted.put(localObject.getObjectNumber(), localObject.getObjectVersion()); } } // Delete everything that is older or not part of the authoritative state. for (ObjectVersionMapping authObject : authState.getObjectVersionsList()) { Long version = objectsToBeDeleted.get(authObject.getObjectNumber()); if ((version != null) && (version == authObject.getObjectVersion())) { objectsToBeDeleted.remove(authObject.getObjectNumber()); } } Map<Long, ObjectVersionMapping> missingObjects = new HashMap(); for (ObjectVersionMapping authObject : authState.getObjectVersionsList()) { missingObjects.put(authObject.getObjectNumber(), authObject); } for (ObjectVersion localObject : localState.getObjectVersionsList()) { ObjectVersionMapping object = missingObjects.get(localObject.getObjectNumber()); if ((object != null) && (localObject.getObjectVersion() >= object.getObjectVersion())) { missingObjects.remove(localObject.getObjectNumber()); } } if (!missingObjects.isEmpty() || !objectsToBeDeleted.isEmpty() || (localState.getTruncateEpoch() < authState.getTruncateEpoch())) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this, "(R:%s) replica RESET required updates for: %s", localID, state.getFileId()); } state.setObjectsToFetch(new LinkedList(missingObjects.values())); filesInReset.add(state); // Start by deleting the old objects. master.getStorageStage().deleteObjects(fileId, state.getsPolicy(), authState.getTruncateEpoch(), objectsToBeDeleted, new DeleteObjectsCallback() { @Override public void deleteObjectsComplete(ErrorResponse error) { eventDeleteObjectsComplete(fileId, error); } }); } else { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this, "(R:%s) replica RESET finished (replica is up-to-date): %s", localID, state.getFileId()); } doOpen(state); } } private void processLeaseStateChanged(StageRequest method) { try { final ASCIIString cellId = (ASCIIString) method.getArgs()[0]; final Flease lease = (Flease) method.getArgs()[1]; final FleaseException error = (FleaseException) method.getArgs()[2]; if (error == null) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) lease change event: %s, %s",localID, cellId, lease); } } else { // Logging.logMessage(Logging.LEVEL_WARN, Category.replication, this,"(R:%s) lease error in cell %s: %s cell debug: %s",localID, cellId, error, error.getFleaseCellDebugString()); Logging.logMessage(Logging.LEVEL_WARN, Category.replication, this,"(R:%s) lease error in cell %s: %s",localID, cellId, error); } final String fileId = cellToFileId.get(cellId); if (fileId != null) { ReplicatedFileState state = files.get(fileId); assert(state != null); boolean leaseOk = false; if (error == null) { boolean localIsPrimary = (lease.getLeaseHolder() != null) && (lease.getLeaseHolder().equals(localID)); ReplicaState oldState = state.getState(); state.setLocalIsPrimary(localIsPrimary); state.setLease(lease); // Error handling for timeouts on the primary. if (oldState == ReplicaState.PRIMARY &&lease.getLeaseHolder() == null && lease.getLeaseTimeout_ms() == 0) { Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this,"(R:%s) was primary, lease error in cell %s, restarting replication: %s",localID, cellId,lease,error); failed(state, ErrorUtils.getInternalServerError(new IOException(fileId +": lease timed out, renew failed")), "processLeaseStateChanged"); } else { if ( (state.getState() == ReplicaState.BACKUP) || (state.getState() == ReplicaState.PRIMARY) || (state.getState() == ReplicaState.WAITING_FOR_LEASE) ) { if (localIsPrimary) { //notify onPrimary if (oldState != ReplicaState.PRIMARY) { state.setMasterEpoch(lease.getMasterEpochNumber()); doPrimary(state); } } else { if (oldState != ReplicaState.BACKUP) { state.setMasterEpoch(FleaseMessage.IGNORE_MASTER_EPOCH); doBackup(state); } } } } } else { failed(state, ErrorUtils.getInternalServerError(error), "processLeaseStateChanged (error != null)"); } } } catch (Exception ex) { Logging.logMessage(Logging.LEVEL_ERROR, this, "Exception was thrown and caught while processing the change of the lease state." + " This is an error in the code. Please report it! Caught exception: "); Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void processBackupAuthoritativeState(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; final AuthoritativeReplicaState authState = (AuthoritativeReplicaState) method.getArgs()[1]; final ReplicaStatus localState = (ReplicaStatus) method.getArgs()[2]; final FileCredentials credentials = (FileCredentials) method.getArgs()[3]; final XLocations loc = (XLocations) method.getArgs()[4]; ReplicatedFileState state = getState(credentials, loc, true); switch (state.getState()) { case INITIALIZING: case OPEN: case WAITING_FOR_LEASE: { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) enqueued backup reset for file %s",localID, fileId); state.addPendingRequest(method); break; } case BACKUP: { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) backup reset triggered by AUTHSTATE request for file %s",localID, fileId); state.setState(ReplicaState.RESET); executeSetAuthState(localState, authState, state, fileId); break; } case RESET: default: { // Ignore. Logging.logMessage(Logging.LEVEL_WARN, Category.replication, this,"(R:%s) auth state ignored, already in reset for file %s",localID, fileId); } } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void processSetAuthoritativeState(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; final AuthoritativeReplicaState authState = (AuthoritativeReplicaState) method.getArgs()[1]; final ReplicaStatus localState = (ReplicaStatus) method.getArgs()[2]; final ErrorResponse error = (ErrorResponse) method.getArgs()[3]; ReplicatedFileState state = files.get(fileId); if (state == null) { Logging.logMessage(Logging.LEVEL_WARN, Category.replication, this,"(R:%s) set AUTH for unknown file: %s",localID, fileId); return; } if (error != null) { failed(state, error, "processSetAuthoritativeState"); } else { executeSetAuthState(localState, authState, state, fileId); } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void processDeleteObjectsComplete(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; final ErrorResponse error = (ErrorResponse) method.getArgs()[1]; ReplicatedFileState state = files.get(fileId); if (state != null) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) deleted all objects requested by RESET for %s with %s",localID,state.getFileId(), ErrorUtils.formatError(error)); } if (error != null) { failed(state, error, "processDeleteObjectsComplete"); } else { fetchObjects(); } } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void fetchObjects() { while (numObjsInFlight < MAX_OBJS_IN_FLIGHT) { ReplicatedFileState file = filesInReset.poll(); if (file == null) break; if (!file.getObjectsToFetch().isEmpty()) { ObjectVersionMapping o = file.getObjectsToFetch().remove(0); file.setNumObjectsPending(file.getNumObjectsPending()+1); numObjsInFlight++; fetchObject(file.getFileId(), o); } if (!file.getObjectsToFetch().isEmpty()) { filesInReset.add(file); } } } private void fetchObject(final String fileId, final ObjectVersionMapping record) { ReplicatedFileState state = files.get(fileId); if (state == null) { return; } try { final ServiceUUID osd = new ServiceUUID(record.getOsdUuidsList().get(0)); //fetch that object if (Logging.isDebug()) Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) file %s, fetch object %d (version %d) from %s", localID, fileId,record.getObjectNumber(),record.getObjectVersion(),osd); RPCResponse r = osdClient.xtreemfs_rwr_fetch(osd.getAddress(), RPCAuthentication.authNone, RPCAuthentication.userService, state.getCredentials(), fileId, record.getObjectNumber(), record.getObjectVersion()); r.registerListener(new RPCResponseAvailableListener() { @Override public void responseAvailable(RPCResponse r) { try { ObjectData metadata = (ObjectData) r.get(); InternalObjectData data = new InternalObjectData(metadata, r.getData()); eventObjectFetched(fileId, record, data, null); } catch (PBRPCException ex) { // Transform exception into correct ErrorResponse. // TODO(mberlin): Generalize this functionality by returning "Throwable" instead of // "ErrorResponse" to the event* functions. // The "ErrorResponse" shall be created in the last 'step' at the // invocation of failed(). eventObjectFetched(fileId, record, null, ErrorUtils.getErrorResponse(ex.getErrorType(), ex.getPOSIXErrno(), ex.toString(), ex)); } catch (Exception ex) { eventObjectFetched(fileId, record, null, ErrorUtils.getErrorResponse(ErrorType.IO_ERROR, POSIXErrno.POSIX_ERROR_NONE, ex.toString(), ex)); } finally { r.freeBuffers(); } } }); } catch (IOException ex) { eventObjectFetched(fileId, record, null, ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO, ex.toString(), ex)); } } private void processObjectFetched(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; final ObjectVersionMapping record = (ObjectVersionMapping) method.getArgs()[1]; final InternalObjectData data = (InternalObjectData) method.getArgs()[2]; final ErrorResponse error = (ErrorResponse) method.getArgs()[3]; ReplicatedFileState state = files.get(fileId); if (state != null) { if (error != null) { numObjsInFlight--; fetchObjects(); failed(state, error, "processObjectFetched"); } else { final int bytes = data.getData().remaining(); master.getStorageStage().writeObjectWithoutGMax(fileId, record.getObjectNumber(), state.getsPolicy(), 0, data.getData(), CowPolicy.PolicyNoCow, null, false, record.getObjectVersion(), null, new WriteObjectCallback() { @Override public void writeComplete(OSDWriteResponse result, ErrorResponse error) { if (error != null) { Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this,"cannot write object locally: %s",ErrorUtils.formatError(error)); } } }); master.getPreprocStage().pingFile(fileId); master.objectReplicated(); master.replicatedDataReceived(bytes); numObjsInFlight--; final int numPendingFile = state.getNumObjectsPending()-1; state.setNumObjectsPending(numPendingFile); state.getPolicy().objectFetched(record.getObjectVersion()); if (Logging.isDebug()) Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) fetched object for replica, file %s, remaining %d",localID, fileId,numPendingFile); fetchObjects(); if (numPendingFile == 0) { //reset complete! Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) RESET complete for file %s",localID, fileId); doOpen(state); } } } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void doReset(final ReplicatedFileState file, long updateObjVer) { if (file.getState() == ReplicaState.RESET) { if (Logging.isDebug()) Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"file %s is already in RESET",file.getFileId()); return; } if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) replica state changed for %s from %s to %s",localID, file.getFileId(),file.getState(),ReplicaState.RESET); } file.setState(ReplicaState.RESET); if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) replica RESET started: %s (update objVer=%d)",localID, file.getFileId(),updateObjVer); } OSDOperation op = master.getInternalEvent(EventRWRStatus.class); op.startInternalEvent(new Object[]{file.getFileId(),file.getsPolicy()}); } private void processReplicaStateAvailExecReset(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; final ReplicaStatus localReplicaState = (ReplicaStatus) method.getArgs()[1]; final ErrorResponse error = (ErrorResponse) method.getArgs()[2]; final ReplicatedFileState state = files.get(fileId); if (state != null) { if (error != null) { Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this,"local state for %s failed: %s", state.getFileId(), error); failed(state, error, "processReplicaStateAvailExecReset"); } else { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) local state for %s available.", localID, state.getFileId()); } state.getPolicy().executeReset(state.getCredentials(), localReplicaState, new ReplicaUpdatePolicy.ExecuteResetCallback() { @Override public void finished(AuthoritativeReplicaState authState) { eventSetAuthState(state.getFileId(), authState, localReplicaState, null); } @Override public void failed(ErrorResponse error) { eventSetAuthState(state.getFileId(), null, null, error); } }); } } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void processForceReset(StageRequest method) { try { final FileCredentials credentials = (FileCredentials) method.getArgs()[0]; final XLocations loc = (XLocations) method.getArgs()[1]; ReplicatedFileState state = getState(credentials, loc, true); if (!state.isForceReset()) { state.setForceReset(true); } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void doWaitingForLease(final ReplicatedFileState file) { if (file.getPolicy().requiresLease()) { if (file.isCellOpen()) { if (file.isLocalIsPrimary()) { doPrimary(file); } else { doBackup(file); } } else { file.setCellOpen(true); if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) replica state changed for %s from %s to %s", localID,file.getFileId(),file.getState(),ReplicaState.WAITING_FOR_LEASE); } try { file.setState(ReplicaState.WAITING_FOR_LEASE); List<InetSocketAddress> osdAddresses = new ArrayList(); for (ServiceUUID osd : file.getPolicy().getRemoteOSDUUIDs()) { osdAddresses.add(osd.getAddress()); } fstage.openCell(file.getPolicy().getCellId(), osdAddresses, true); //wait for lease... } catch (UnknownUUIDException ex) { failed(file, ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO, ex.toString(), ex), "doWaitingForLease"); } } } else { //become primary immediately doPrimary(file); } } private void doOpen(final ReplicatedFileState file) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, this,"(R:%s) replica state changed for %s from %s to %s",localID, file.getFileId(),file.getState(),ReplicaState.OPEN); } file.setState(ReplicaState.OPEN); if (file.getPendingRequests().size() > 0) { doWaitingForLease(file); } } private void doPrimary(final ReplicatedFileState file) { assert(file.isLocalIsPrimary()); try { if (file.getPolicy().onPrimary((int)file.getMasterEpoch()) && !file.isPrimaryReset()) { file.setPrimaryReset(true); doReset(file,ReplicaUpdatePolicy.UNLIMITED_RESET); } else { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) replica state changed for %s from %s to %s", localID, file.getFileId(),file.getState(),ReplicaState.PRIMARY); } file.setPrimaryReset(false); file.setState(ReplicaState.PRIMARY); while (!file.getPendingRequests().isEmpty()) { StageRequest m = file.getPendingRequests().remove(0); enqueuePrioritized(m); } } } catch (IOException ex) { failed(file, ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO, ex.toString(), ex), "doPrimary"); } } private void doBackup(final ReplicatedFileState file) { assert(!file.isLocalIsPrimary()); //try { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) replica state changed for %s from %s to %s", localID, file.getFileId(),file.getState(),ReplicaState.BACKUP); } file.setPrimaryReset(false); file.setState(ReplicaState.BACKUP); while (!file.getPendingRequests().isEmpty()) { StageRequest m = file.getPendingRequests().remove(0); enqueuePrioritized(m); } /*} catch (IOException ex) { failed(file, ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO, ex.toString(), ex)); }*/ } private void failed(ReplicatedFileState file, ErrorResponse ex, String methodName) { Logging.logMessage(Logging.LEVEL_WARN, Category.replication, this,"(R:%s) replica for file %s failed (in method: %s): %s", localID, file.getFileId(), methodName, ErrorUtils.formatError(ex)); file.setPrimaryReset(false); file.setState(ReplicaState.OPEN); file.setCellOpen(false); fstage.closeCell(file.getPolicy().getCellId(), false); for (StageRequest rq : file.getPendingRequests()) { RWReplicationCallback callback = (RWReplicationCallback) rq.getCallback(); if (callback != null) { callback.failed(ex); } } file.getPendingRequests().clear(); } private void enqueuePrioritized(StageRequest rq) { while (!q.offer(rq)) { StageRequest otherRq = q.poll(); otherRq.sendInternalServerError(new IllegalStateException("internal queue overflow, cannot enqueue operation for processing.")); Logging.logMessage(Logging.LEVEL_DEBUG, this, "Dropping request from rwre queue due to overload"); } } public static interface RWReplicationCallback { public void success(long newObjectVersion); public void redirect(String redirectTo); public void failed(ErrorResponse ex); } /*public void openFile(FileCredentials credentials, XLocations locations, boolean forceReset, RWReplicationCallback callback, OSDRequest request) { this.enqueueOperation(STAGEOP_OPEN, new Object[]{credentials,locations,forceReset}, request, callback); }*/ protected void enqueueExternalOperation(int stageOp, Object[] arguments, OSDRequest request, ReusableBuffer createdViewBuffer, Object callback) { if (externalRequestsInQueue.get() >= MAX_EXTERNAL_REQUESTS_IN_Q) { Logging.logMessage(Logging.LEVEL_WARN, this, "RW replication stage is overloaded, request %d for %s dropped", request.getRequestId(), request.getFileId()); request.sendInternalServerError(new IllegalStateException("RW replication stage is overloaded, request dropped")); // Make sure that the data buffer is returned to the pool if // necessary, as some operations create view buffers on the // data. Otherwise, a 'finalized but not freed before' warning // may occur. if (createdViewBuffer != null) { assert (createdViewBuffer.getRefCount() >= 2); BufferPool.free(createdViewBuffer); } } else { externalRequestsInQueue.incrementAndGet(); this.enqueueOperation(stageOp, arguments, request, createdViewBuffer, callback); } } public void prepareOperation(FileCredentials credentials, XLocations xloc, long objNo, long objVersion, Operation op, RWReplicationCallback callback, OSDRequest request) { this.enqueueExternalOperation(STAGEOP_PREPAREOP, new Object[]{credentials,xloc,objNo,objVersion,op}, request, null, callback); } public void replicatedWrite(FileCredentials credentials, XLocations xloc, long objNo, long objVersion, InternalObjectData data, ReusableBuffer createdViewBuffer, RWReplicationCallback callback, OSDRequest request) { this.enqueueExternalOperation(STAGEOP_REPLICATED_WRITE, new Object[]{credentials,xloc,objNo,objVersion,data}, request, createdViewBuffer, callback); } public void replicateTruncate(FileCredentials credentials, XLocations xloc, long newFileSize, long newObjectVersion, RWReplicationCallback callback, OSDRequest request) { this.enqueueExternalOperation(STAGEOP_TRUNCATE, new Object[]{credentials,xloc,newFileSize,newObjectVersion}, request, null, callback); } public void fileClosed(String fileId) { this.enqueueOperation(STAGEOP_CLOSE, new Object[]{fileId}, null, null); } public void receiveFleaseMessage(ReusableBuffer message, InetSocketAddress sender) { //this.enqueueOperation(STAGEOP_PROCESS_FLEASE_MSG, new Object[]{message,sender}, null, null); try { FleaseMessage msg = new FleaseMessage(message); BufferPool.free(message); msg.setSender(sender); fstage.receiveMessage(msg); } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } public void getStatus(StatusCallback callback) { this.enqueueOperation(STAGEOP_GETSTATUS, new Object[]{}, null, callback); } public static interface StatusCallback { public void statusComplete(Map<String,Map<String,String>> status); } public void setFleaseView(String fileId, XLocSetVersionState versionState) { enqueueOperation(STAGEOP_SETVIEW, new Object[] { fileId, versionState }, null, null); } public void setFleaseView(String fileId, XLocSetVersionState versionState, InstallXLocSetCallback callback) { enqueueOperation(STAGEOP_SETVIEW, new Object[] { fileId, versionState }, null, callback); } public void invalidateView(String fileId, XLocSetVersionState versionState, InvalidateXLocSetCallback callback) { enqueueOperation(STAGEOP_INVALIDATEVIEW, new Object[] { fileId, versionState }, null, callback); } @Override public void sendMessage(FleaseMessage message, InetSocketAddress recipient) { ReusableBuffer data = BufferPool.allocate(message.getSize()); message.serialize(data); data.flip(); try { RPCResponse r = fleaseOsdClient.xtreemfs_rwr_flease_msg(recipient, RPCAuthentication.authNone, RPCAuthentication.userService, master.getHostName(),master.getConfig().getPort(),data); r.registerListener(new RPCResponseAvailableListener() { @Override public void responseAvailable(RPCResponse r) { r.freeBuffers(); } }); } catch (IOException ex) { Logging.logError(Logging.LEVEL_ERROR, this, ex); } } @Override protected void processMethod(StageRequest method) { switch (method.getStageMethod()) { case STAGEOP_REPLICATED_WRITE : { externalRequestsInQueue.decrementAndGet(); processReplicatedWrite(method); break; } case STAGEOP_TRUNCATE : { externalRequestsInQueue.decrementAndGet(); processReplicatedTruncate(method); break; } case STAGEOP_CLOSE : processFileClosed(method); break; case STAGEOP_PROCESS_FLEASE_MSG : processFleaseMessage(method); break; case STAGEOP_PREPAREOP : { externalRequestsInQueue.decrementAndGet(); processPrepareOp(method); break; } case STAGEOP_INTERNAL_AUTHSTATE : processSetAuthoritativeState(method); break; case STAGEOP_LEASE_STATE_CHANGED : processLeaseStateChanged(method); break; case STAGEOP_INTERNAL_OBJFETCHED : processObjectFetched(method); break; case STAGEOP_INTERNAL_STATEAVAIL : processReplicaStateAvailExecReset(method); break; case STAGEOP_INTERNAL_DELETE_COMPLETE : processDeleteObjectsComplete(method); break; case STAGEOP_INTERNAL_MAXOBJ_AVAIL : processMaxObjAvail(method); break; case STAGEOP_INTERNAL_BACKUP_AUTHSTATE: processBackupAuthoritativeState(method); break; case STAGEOP_FORCE_RESET : processForceReset(method); break; case STAGEOP_GETSTATUS : processGetStatus(method); break; case STAGEOP_SETVIEW: processSetFleaseView(method); break; case STAGEOP_INVALIDATEVIEW: processInvalidateView(method); break; default : throw new IllegalArgumentException("no such stageop"); } } private void processFleaseMessage(StageRequest method) { try { final ReusableBuffer data = (ReusableBuffer) method.getArgs()[0]; final InetSocketAddress sender = (InetSocketAddress) method.getArgs()[1]; FleaseMessage msg = new FleaseMessage(data); BufferPool.free(data); msg.setSender(sender); fstage.receiveMessage(msg); } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private void processFileClosed(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; ReplicatedFileState state = files.remove(fileId); if (state != null) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"closing file %s",fileId); } state.getPolicy().closeFile(); if (state.getPolicy().requiresLease()) fstage.closeCell(state.getPolicy().getCellId(), false); cellToFileId.remove(state.getPolicy().getCellId()); } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this,ex); } } private ReplicatedFileState getState(FileCredentials credentials, XLocations loc, boolean forceReset) throws IOException { final String fileId = credentials.getXcap().getFileId(); ReplicatedFileState state = files.get(fileId); if (state == null) { if (Logging.isDebug()) Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"open file: "+fileId); //"open" file state = new ReplicatedFileState(fileId,loc, master.getConfig().getUUID(), fstage, osdClient); files.put(fileId,state); state.setCredentials(credentials); state.setForceReset(forceReset); cellToFileId.put(state.getPolicy().getCellId(),fileId); assert(state.getState() == ReplicaState.INITIALIZING); master.getStorageStage().internalGetMaxObjectNo(fileId, loc.getLocalReplica().getStripingPolicy(), new InternalGetMaxObjectNoCallback() { @Override public void maxObjectNoCompleted(long maxObjNo, long fileSize, long truncateEpoch, ErrorResponse error) { eventMaxObjAvail(fileId, maxObjNo, fileSize, truncateEpoch, error); } }); } return state; } private void processMaxObjAvail(StageRequest method) { try { final String fileId = (String) method.getArgs()[0]; final Long maxObjVersion = (Long) method.getArgs()[1]; final ErrorResponse error = (ErrorResponse) method.getArgs()[2]; if (Logging.isDebug()) Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) max obj avail for file: "+fileId+" max="+maxObjVersion, localID); ReplicatedFileState state = files.get(fileId); if (state == null) { Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this,"received maxObjAvail event for unknow file: %s",fileId); return; } if(state.getState() == ReplicaState.INITIALIZING) { state.getPolicy().setLocalObjectVersion(maxObjVersion); doOpen(state); } else { Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this, "ReplicaState is %s instead of INITIALIZING, maxObjectVersion=%d", state.getState().name(), maxObjVersion); return; } } catch (Exception ex) { Logging.logError(Logging.LEVEL_ERROR, this, ex); } } private void processReplicatedWrite(StageRequest method) { final RWReplicationCallback callback = (RWReplicationCallback) method.getCallback(); try { final FileCredentials credentials = (FileCredentials) method.getArgs()[0]; final XLocations loc = (XLocations) method.getArgs()[1]; final Long objNo = (Long) method.getArgs()[2]; final Long objVersion = (Long) method.getArgs()[3]; final InternalObjectData objData = (InternalObjectData) method.getArgs()[4]; final String fileId = credentials.getXcap().getFileId(); ReplicatedFileState state = files.get(fileId); if (state == null) { BufferPool.free(objData.getData()); callback.failed(ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_EIO, "file is not open!")); return; } state.setCredentials(credentials); state.getPolicy().executeWrite(credentials, objNo, objVersion, objData, new ReplicaUpdatePolicy.ClientOperationCallback() { @Override public void finsihed() { callback.success(objVersion); } @Override public void failed(ErrorResponse error) { callback.failed(error); } }); } catch (Exception ex) { ex.printStackTrace(); callback.failed(ErrorUtils.getInternalServerError(ex)); } } private void processReplicatedTruncate(StageRequest method) { final RWReplicationCallback callback = (RWReplicationCallback) method.getCallback(); try { final FileCredentials credentials = (FileCredentials) method.getArgs()[0]; final XLocations loc = (XLocations) method.getArgs()[1]; final Long newFileSize = (Long) method.getArgs()[2]; final Long newObjVersion = (Long) method.getArgs()[3]; final String fileId = credentials.getXcap().getFileId(); ReplicatedFileState state = files.get(fileId); if (state == null) { callback.failed(ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_EIO, "file is not open!")); return; } state.setCredentials(credentials); state.getPolicy().executeTruncate(credentials, newFileSize, newObjVersion, new ReplicaUpdatePolicy.ClientOperationCallback() { @Override public void finsihed() { callback.success(newObjVersion); } @Override public void failed(ErrorResponse error) { callback.failed(error); } }); } catch (Exception ex) { ex.printStackTrace(); callback.failed(ErrorUtils.getInternalServerError(ex)); } } private void processPrepareOp(StageRequest method) { final RWReplicationCallback callback = (RWReplicationCallback)method.getCallback(); try { final FileCredentials credentials = (FileCredentials) method.getArgs()[0]; final XLocations loc = (XLocations) method.getArgs()[1]; final Long objVersion = (Long) method.getArgs()[3]; final Operation op = (Operation) method.getArgs()[4]; final String fileId = credentials.getXcap().getFileId(); ReplicatedFileState state = getState(credentials, loc, false); if ((op == Operation.INTERNAL_UPDATE) || (op == Operation.INTERNAL_TRUNCATE)) { switch (state.getState()) { case WAITING_FOR_LEASE: case INITIALIZING: case RESET: case OPEN: { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"enqeue update for %s (state is %s)",fileId,state.getState()); } if (state.getPendingRequests().size() > MAX_PENDING_PER_FILE) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, this, "rejecting request: too many requests (is: %d, max %d) in queue for file %s", state.getPendingRequests().size(), MAX_PENDING_PER_FILE, fileId); } callback.failed(ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_NONE, "too many requests in queue for file")); return; } else { state.getPendingRequests().add(method); } if (state.getState() == ReplicaState.OPEN) { //immediately change to backup mode...no need to check the lease doWaitingForLease(state); } return; } } if (!state.getPolicy().acceptRemoteUpdate(objVersion)) { Logging.logMessage( Logging.LEVEL_WARN, Category.replication, this, "received outdated object version %d for file %s", objVersion, fileId); callback.failed(ErrorUtils.getErrorResponse( ErrorType.IO_ERROR, POSIXErrno.POSIX_ERROR_EIO, "outdated object version for update rejected")); return; } boolean needsReset = state.getPolicy().onRemoteUpdate(objVersion, state.getState()); if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"%s needs reset: %s",fileId,needsReset); } if (needsReset) { state.getPendingRequests().add(method); doReset(state,objVersion); } else { callback.success(0); } } else { state.setCredentials(credentials); switch (state.getState()) { case WAITING_FOR_LEASE: case INITIALIZING: case RESET : { if (state.getPendingRequests().size() > MAX_PENDING_PER_FILE) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, this, "rejecting request: too many requests (is: %d, max %d) in queue for file %s", state.getPendingRequests().size(), MAX_PENDING_PER_FILE, fileId); } callback.failed(ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_NONE, "too many requests in queue for file")); } else { state.getPendingRequests().add(method); } return; } case OPEN : { if (state.getPendingRequests().size() > MAX_PENDING_PER_FILE) { if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, this, "rejecting request: too many requests (is: %d, max %d) in queue for file %s", state.getPendingRequests().size(), MAX_PENDING_PER_FILE, fileId); } callback.failed(ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_NONE, "too many requests in queue for file")); return; } else { state.getPendingRequests().add(method); } doWaitingForLease(state); return; } } try { long newVersion = state.getPolicy().onClientOperation(op,objVersion,state.getState(),state.getLease()); callback.success(newVersion); } catch (RedirectToMasterException ex) { callback.redirect(ex.getMasterUUID()); } catch (RetryException ex) { final ErrorResponse err = ErrorUtils.getInternalServerError(ex); failed(state, err, "processPrepareOp"); if (state.getState() == ReplicaState.BACKUP || state.getState() == ReplicaState.PRIMARY) { // Request is not in queue, we must notify // callback. callback.failed(err); } } } } catch (Exception ex) { ex.printStackTrace(); callback.failed(ErrorUtils.getInternalServerError(ex)); } } private void processGetStatus(StageRequest method) { final StatusCallback callback = (StatusCallback)method.getCallback(); try { Map<String,Map<String,String>> status = new HashMap(); Map<ASCIIString,FleaseMessage> fleaseState = fstage.getLocalState(); for (String fileId : this.files.keySet()) { Map<String,String> fStatus = new HashMap(); final ReplicatedFileState fState = files.get(fileId); final ASCIIString cellId = fState.getPolicy().getCellId(); fStatus.put("policy",fState.getPolicy().getClass().getSimpleName()); fStatus.put("peers (OSDs)",fState.getPolicy().getRemoteOSDUUIDs().toString()); fStatus.put("pending requests", fState.getPendingRequests() == null ? "0" : ""+fState.getPendingRequests().size()); fStatus.put("cellId", cellId.toString()); String primary = "unknown"; if ((fState.getLease() != null) && (!fState.getLease().isEmptyLease())) { if (fState.getLease().isValid()) { if (fState.isLocalIsPrimary()) { primary = "primary"; } else { primary = "backup ( primary is "+fState.getLease().getLeaseHolder()+")"; } } else { primary = "outdated lease: "+fState.getLease().getLeaseHolder(); } } fStatus.put("role", primary); status.put(fileId,fStatus); } callback.statusComplete(status); } catch (Exception ex) { ex.printStackTrace(); callback.statusComplete(null); } } public String getPrimary(final String fileId) { String primary = null; final ReplicatedFileState fState = files.get(fileId); if ((fState != null) && (fState.getLease() != null) && (!fState.getLease().isEmptyLease())) { if (fState.getLease().isValid()) { primary = "" + fState.getLease().getLeaseHolder(); } else { // outdated lease } } return primary; } private void processSetFleaseView(StageRequest method) { final Object[] args = method.getArgs(); final String fileId = (String) args[0]; final XLocSetVersionState versionState = (XLocSetVersionState) args[1]; final InstallXLocSetCallback callback = (InstallXLocSetCallback) method.getCallback(); // TODO (jdillmann): check if file exists and files.get() != null final ASCIIString cellId = files.get(fileId).getPolicy().getCellId(); int viewId; if (versionState.getInvalidated()) { viewId = FleaseMessage.VIEW_ID_INVALIDATED; } else { viewId = versionState.getVersion(); } fstage.setViewId(cellId, viewId, new FleaseListener() { @Override public void proposalResult(ASCIIString cellId, ASCIIString leaseHolder, long leaseTimeout_ms, long masterEpochNumber) { if (callback != null) { callback.installComplete(fileId, versionState.getVersion(), null); } } @Override public void proposalFailed(ASCIIString cellId, Throwable cause) { if (callback != null) { callback.installComplete(fileId, versionState.getVersion(), ErrorUtils.getInternalServerError(cause)); } } }); } private void processInvalidateView(StageRequest method) { final Object[] args = method.getArgs(); final String fileId = (String) args[0]; final XLocSetVersionState versionState = (XLocSetVersionState) args[1]; final InvalidateXLocSetCallback callback = (InvalidateXLocSetCallback) method.getCallback(); // TODO (jdillmann): check if file exists and files.get() != null final ReplicatedFileState fState = files.get(fileId); final ASCIIString cellId = fState.getPolicy().getCellId(); final boolean isPrimary = (fState != null && fState.isLocalIsPrimary()); fstage.setViewId(cellId, FleaseMessage.VIEW_ID_INVALIDATED, new FleaseListener() { @Override public void proposalResult(ASCIIString cellId, ASCIIString leaseHolder, long leaseTimeout_ms, long masterEpochNumber) { callback.invalidateComplete(fileId, versionState.getVersion(), isPrimary, null); } @Override public void proposalFailed(ASCIIString cellId, Throwable cause) { callback.invalidateComplete(fileId, versionState.getVersion(), isPrimary, ErrorUtils.getInternalServerError(cause)); } }); } }
servers: views: Fixed some auto-merge errors
java/servers/src/org/xtreemfs/osd/rwre/RWReplicationStage.java
servers: views: Fixed some auto-merge errors
<ide><path>ava/servers/src/org/xtreemfs/osd/rwre/RWReplicationStage.java <ide> import org.xtreemfs.foundation.pbrpc.client.RPCNIOSocketClient; <ide> import org.xtreemfs.foundation.pbrpc.client.RPCResponse; <ide> import org.xtreemfs.foundation.pbrpc.client.RPCResponseAvailableListener; <add>import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC; <ide> import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.ErrorType; <ide> import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.POSIXErrno; <ide> import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.RPCHeader.ErrorResponse; <ide> super.waitForStartup(); <ide> } <ide> <add> @Override <ide> public void waitForShutdown() throws Exception { <ide> client.waitForShutdown(); <ide> fleaseClient.waitForShutdown(); <ide> if (error != null) { <ide> numObjsInFlight--; <ide> fetchObjects(); <add> <ide> failed(state, error, "processObjectFetched"); <add> } else if (data.getData() == null) { <add> // data is null if object was deleted meanwhile. <add> numObjsInFlight--; <add> fetchObjects(); <add> <add> ErrorResponse generatedError = ErrorResponse.newBuilder().setErrorType(RPC.ErrorType.INTERNAL_SERVER_ERROR).setErrorMessage("Fetching a missing object failed because no data was returned. The object was probably deleted meanwhile.").build(); <add> failed(state, generatedError, "processObjectFetched"); <ide> } else { <ide> final int bytes = data.getData().remaining(); <ide> master.getStorageStage().writeObjectWithoutGMax(fileId, record.getObjectNumber(),
Java
mit
8e962160e222a7eff364515287e4f31910749d77
0
teshi04/Justaway-for-Android-Original,s-aska/Justaway-for-Android-Original,nirvash/Justaway-for-Android-Original
package info.justaway; import android.R.color; import android.app.ActionBar; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.Typeface; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import info.justaway.adapter.MainPagerAdapter; import info.justaway.fragment.main.BaseFragment; import info.justaway.fragment.main.DirectMessagesFragment; import info.justaway.fragment.main.InteractionsFragment; import info.justaway.fragment.main.TimelineFragment; import info.justaway.fragment.main.UserListFragment; import info.justaway.model.Row; import info.justaway.task.DestroyDirectMessageTask; import info.justaway.task.ReFetchFavoriteStatus; import twitter4j.ConnectionLifeCycleListener; import twitter4j.DirectMessage; import twitter4j.Status; import twitter4j.StatusDeletionNotice; import twitter4j.StatusUpdate; import twitter4j.TwitterException; import twitter4j.TwitterStream; import twitter4j.User; import twitter4j.UserStreamAdapter; /** * @author aska */ public class MainActivity extends FragmentActivity { private JustawayApplication mApplication; private TwitterStream mTwitterStream; private MainPagerAdapter mMainPagerAdapter; private ViewPager mViewPager; private ProgressDialog mProgressDialog; ActionBar mActionBar; private TextView mTitle; private TextView mSignalButton; private static final int REQUEST_CHOOSE_USER_LIST = 100; private static final int REQUEST_ACCOUNT_SETTING = 200; private static final int ERROR_CODE_DUPLICATE_STATUS = 187; private static final int TAB_ID_TIMELINE = -1; private static final int TAB_ID_INTERACTIONS = -2; private static final int TAB_ID_DIRECT_MESSAGE = -3; private Long mInReplyToStatusId; public Long getInReplyToStatusId() { return mInReplyToStatusId; } public void setInReplyToStatusId(Long inReplyToStatusId) { this.mInReplyToStatusId = inReplyToStatusId; } /** * ActionBarでCustomView使ってるので自分で再実装 */ @Override public void setTitle(CharSequence title) { if (mTitle != null) { mTitle.setText(title); } } @Override public void setTitle(int titleId) { setTitle(getString(titleId)); } @SuppressWarnings("MagicConstant") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // クイックモード時に起動と同時にキーボードが出現するのを抑止 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); mActionBar = getActionBar(); if (mActionBar != null) { int options = mActionBar.getDisplayOptions(); if ((options & ActionBar.DISPLAY_SHOW_CUSTOM) == ActionBar.DISPLAY_SHOW_CUSTOM) { mActionBar.setDisplayOptions(options ^ ActionBar.DISPLAY_SHOW_CUSTOM); } else { mActionBar.setDisplayOptions(options | ActionBar.DISPLAY_SHOW_CUSTOM); if (mActionBar.getCustomView() == null) { mActionBar.setCustomView(R.layout.action_bar); ViewGroup group = (ViewGroup) mActionBar.getCustomView(); mTitle = (TextView) group.findViewById(R.id.title); mSignalButton = (TextView) group.findViewById(R.id.signal); mSignalButton.setTypeface(JustawayApplication.getFontello()); mSignalButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (mApplication.getStreamingMode()) { DialogFragment dialog = new DialogFragment() { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.confirm_destroy_streaming); builder.setPositiveButton(getString(R.string.button_ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mApplication.setStreamingMode(false); if (mTwitterStream != null) { mTwitterStream.cleanUp(); mTwitterStream.shutdown(); } JustawayApplication.showToast(R.string.toast_destroy_streaming); dismiss(); } }); builder.setNegativeButton(getString(R.string.button_cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismiss(); } }); return builder.create(); } }; dialog.show(getSupportFragmentManager(), "dialog"); } else { DialogFragment dialog = new DialogFragment() { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.confirm_create_streaming); builder.setPositiveButton(getString(R.string.button_ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mApplication.setStreamingMode(true); setupStream(); JustawayApplication.showToast(R.string.toast_create_streaming); dismiss(); } }); builder.setNegativeButton(getString(R.string.button_cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismiss(); } }); return builder.create(); } }; dialog.show(getSupportFragmentManager(), "dialog"); } } }); } } } setContentView(R.layout.activity_main); setTitle(R.string.title_main); // クイックモード時に起動と同時に入力エリアにフォーカスするのを抑止 findViewById(R.id.main).requestFocus(); mApplication = JustawayApplication.getApplication(); // アクセストークンがない場合に認証用のアクティビティを起動する if (!mApplication.hasAccessToken()) { Intent intent = new Intent(this, SignInActivity.class); startActivity(intent); finish(); return; } setup(); /** * 違うタブだったら移動、同じタブだったら最上部にスクロールという美しい実装 * ActionBarのタブに頼っていない為、自力でsetCurrentItemでタブを動かしている * タブの切替がスワイプだけで良い場合はこの処理すら不要 */ Typeface fontello = JustawayApplication.getFontello(); Button home = (Button) findViewById(R.id.action_timeline); Button interactions = (Button) findViewById(R.id.action_interactions); Button directMessage = (Button) findViewById(R.id.action_direct_message); Button tweet = (Button) findViewById(R.id.action_tweet); Button send = (Button) findViewById(R.id.send); findViewById(R.id.action_timeline).setSelected(true); home.setTypeface(fontello); interactions.setTypeface(fontello); directMessage.setTypeface(fontello); tweet.setTypeface(fontello); send.setTypeface(fontello); home.setOnClickListener(tabMenuOnClickListener(0)); interactions.setOnClickListener(tabMenuOnClickListener(1)); directMessage.setOnClickListener(tabMenuOnClickListener(2)); tweet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), PostActivity.class); if (findViewById(R.id.quick_tweet_layout).getVisibility() == View.VISIBLE) { EditText status = (EditText) findViewById(R.id.quick_tweet_edit); if (status == null) { return; } String msg = status.getText() != null ? status.getText().toString() : null; if (msg != null && msg.length() > 0) { Long inReplyToStatusId = getInReplyToStatusId(); intent.putExtra("status", msg); intent.putExtra("selection", msg.length()); if (inReplyToStatusId != null && inReplyToStatusId > 0) { intent.putExtra("inReplyToStatusId", inReplyToStatusId); } status.setText(""); status.clearFocus(); } } startActivity(intent); } }); tweet.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { if (findViewById(R.id.quick_tweet_layout).getVisibility() == View.VISIBLE) { hideQuickPanel(); } else { showQuickPanel(); } return true; } }); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText status = (EditText) findViewById(R.id.quick_tweet_edit); String msg = status.getText() != null ? status.getText().toString() : null; if (msg != null && msg.length() > 0) { showProgressDialog(getString(R.string.progress_sending)); StatusUpdate super_sugoi = new StatusUpdate(msg); Long inReplyToStatusId = getInReplyToStatusId(); if (inReplyToStatusId != null && inReplyToStatusId > 0) { super_sugoi.setInReplyToStatusId(inReplyToStatusId); setInReplyToStatusId((long) 0); } new UpdateStatusTask().execute(super_sugoi); } } }); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } @SuppressWarnings("NullableProblems") @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); } public void showQuickPanel() { findViewById(R.id.quick_tweet_layout).setVisibility(View.VISIBLE); EditText editStatus = (EditText) findViewById(R.id.quick_tweet_edit); editStatus.setFocusable(true); editStatus.setFocusableInTouchMode(true); editStatus.setEnabled(true); mApplication.setQuickMod(true); } public void hideQuickPanel() { EditText editStatus = (EditText) findViewById(R.id.quick_tweet_edit); editStatus.setFocusable(false); editStatus.setFocusableInTouchMode(false); editStatus.setEnabled(false); editStatus.clearFocus(); findViewById(R.id.quick_tweet_layout).setVisibility(View.GONE); setInReplyToStatusId((long) 0); mApplication.setQuickMod(false); } public void setupTab() { LinearLayout tab_menus = (LinearLayout) findViewById(R.id.tab_menus); int count = tab_menus.getChildCount(); // 4つめ以降のタブを消す if (count > 3) { for (int position = count - 1; position > 2; position--) { View view = tab_menus.getChildAt(position); if (view != null) { tab_menus.removeView(view); } mMainPagerAdapter.removeTab(position); } } Typeface fontello = JustawayApplication.getFontello(); ArrayList<JustawayApplication.Tab> tabs = mApplication.loadTabs(); if (tabs.size() > 3) { int position = 2; for (JustawayApplication.Tab tab : tabs) { // 標準のタブを動的に生成する時に実装する if (tab.id > 0) { Button button = new Button(this); button.setWidth(60); button.setTypeface(fontello); button.setTextSize(22); button.setBackgroundResource(R.drawable.tab_stateful); button.setText(R.string.fontello_list); button.setOnClickListener(tabMenuOnClickListener(++position)); tab_menus.addView(button); Bundle args = new Bundle(); args.putInt("userListId", tab.id); mMainPagerAdapter.addTab(UserListFragment.class, args, tab.name, tab.id); } } } mMainPagerAdapter.notifyDataSetChanged(); } @Override protected void onStart() { super.onStart(); // 前回バグで強制終了した場合はダイアログ表示、Yesでレポート送信 MyUncaughtExceptionHandler.showBugReportDialogIfExist(this); // スリープさせない指定 if (JustawayApplication.getApplication().getKeepScreenOn()) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } else { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } mApplication.resetDisplaySettings(); // フォントサイズの変更や他のアクティビティでのfav/RTを反映 mMainPagerAdapter.notifyDataSetChanged(); } @Override protected void onResume() { super.onResume(); } @Override protected void onDestroy() { super.onDestroy(); if (mTwitterStream != null) { mTwitterStream.cleanUp(); mTwitterStream.shutdown(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_CHOOSE_USER_LIST: if (resultCode == RESULT_OK) { Bundle bundle = data.getExtras(); if (bundle == null) { return; } ArrayList<Integer> lists = bundle.getIntegerArrayList("lists"); ArrayList<Integer> tabs = new ArrayList<Integer>(); // 後々タブ設定画面に標準のタブを含める tabs.add(-1); tabs.add(-2); tabs.add(-3); tabs.addAll(lists); mApplication.saveTabs(tabs); setupTab(); if (lists != null && lists.size() > 0) { JustawayApplication.showToast(R.string.toast_register_list_for_tab); } } else { /** * リストの削除を検出してタブを再構成 */ ArrayList<JustawayApplication.Tab> tabs = mApplication.loadTabs(); ArrayList<Integer> new_tabs = new ArrayList<Integer>(); for (JustawayApplication.Tab tab : tabs) { if (tab.id > 0 && mApplication.getUserList(tab.id) == null) { continue; } new_tabs.add(tab.id); } if (tabs.size() != new_tabs.size()) { mApplication.saveTabs(new_tabs); setupTab(); } } break; case REQUEST_ACCOUNT_SETTING: if (mTwitterStream != null) { mTwitterStream.cleanUp(); mTwitterStream.shutdown(); } setupTab(); int count = mMainPagerAdapter.getCount(); for (int id = 0; id < count; id++) { BaseFragment fragment = mMainPagerAdapter .findFragmentByPosition(id); if (fragment != null) { fragment.getListAdapter().clear(); fragment.reload(); } } default: break; } } private View.OnClickListener tabMenuOnClickListener(final int position) { return new View.OnClickListener() { @Override public void onClick(View v) { BaseFragment f = mMainPagerAdapter.findFragmentByPosition(position); if (f == null) { return; } int id = mViewPager.getCurrentItem(); if (id != position) { mViewPager.setCurrentItem(position); if (f.isTop()) { showTopView(); } } else { f.goToTop(); } } }; } public void setup() { /** * スワイプで動かせるタブを実装するのに最低限必要な実装 */ mViewPager = (ViewPager) findViewById(R.id.pager); mMainPagerAdapter = new MainPagerAdapter(this, mViewPager); mMainPagerAdapter.addTab(TimelineFragment.class, null, getString(R.string.title_main), TAB_ID_TIMELINE); mMainPagerAdapter.addTab(InteractionsFragment.class, null, getString(R.string.title_interactions), TAB_ID_INTERACTIONS); mMainPagerAdapter.addTab(DirectMessagesFragment.class, null, getString(R.string.title_direct_messages), TAB_ID_DIRECT_MESSAGE); setupTab(); findViewById(R.id.footer).setVisibility(View.VISIBLE); /** * タブは前後タブまでは状態が保持されるがそれ以上離れるとViewが破棄されてしまう、 * あまりに使いづらいの上限を増やしている、指定値+前後のタブまでが保持されるようになる * デフォルト値は1(表示しているタブの前後までしか保持されない) */ mViewPager.setOffscreenPageLimit(10); /** * スワイプ移動でも移動先が未読アプしている場合、アピ解除判定を行う */ mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { BaseFragment f = mMainPagerAdapter.findFragmentByPosition(position); if (f.isTop()) { showTopView(); } LinearLayout tab_menus = (LinearLayout) findViewById(R.id.tab_menus); int count = tab_menus.getChildCount(); for (int i = 0; i < count; i++) { Button button = (Button) tab_menus.getChildAt(i); if (button == null) { continue; } if (i == position) { button.setSelected(true); } else { button.setSelected(false); } } setTitle(mMainPagerAdapter.getPageTitle(position)); } }); if (mApplication.getQuickMode()) { showQuickPanel(); } } public void setupStream() { if (!mApplication.getStreamingMode()) { return; } if (mTwitterStream != null) { mTwitterStream.cleanUp(); mTwitterStream.shutdown(); mTwitterStream.setOAuthAccessToken(mApplication.getAccessToken()); } else { mTwitterStream = mApplication.getTwitterStream(); mTwitterStream.addListener(getUserStreamAdapter()); mTwitterStream.addConnectionLifeCycleListener(new ConnectionLifeCycleListener() { @Override public void onConnect() { if (mSignalButton != null) { mSignalButton.post(new Runnable() { @Override public void run() { mSignalButton.setTextColor(getResources().getColor(R.color.holo_green_light)); } }); } } @Override public void onDisconnect() { if (mSignalButton != null) { mSignalButton.post(new Runnable() { @Override public void run() { if (mApplication.getStreamingMode()) { mSignalButton.setTextColor(getResources().getColor(R.color.holo_red_light)); } else { mSignalButton.setTextColor(Color.WHITE); } } }); } } @Override public void onCleanUp() { if (mSignalButton != null) { mSignalButton.post(new Runnable() { @Override public void run() { if (mApplication.getStreamingMode()) { mSignalButton.setTextColor(getResources().getColor(R.color.holo_orange_light)); } else { mSignalButton.setTextColor(Color.WHITE); } } }); } } }); mSignalButton.setTextColor(getResources().getColor(R.color.holo_blue_light)); } mTwitterStream.user(); } /** * 新しいツイートが来たアピ */ public void onNewTimeline(Boolean autoScroll) { // 表示中のタブかつ自動スクロール時はハイライトしない if (mViewPager.getCurrentItem() == 0 && autoScroll) { return; } Button button = (Button) findViewById(R.id.action_timeline); button.setTextColor(getResources().getColor(color.holo_blue_bright)); } /** * 新しいリプが来たアピ */ public void onNewInteractions(Boolean autoScroll) { // 表示中のタブかつ自動スクロール時はハイライトしない if (mViewPager.getCurrentItem() == 1 && autoScroll) { return; } Button button = (Button) findViewById(R.id.action_interactions); button.setTextColor(getResources().getColor(color.holo_blue_bright)); } /** * 新しいDMが来たアピ */ public void onNewDirectMessage(Boolean autoScroll) { // 表示中のタブかつ自動スクロール時はハイライトしない if (mViewPager.getCurrentItem() == 2 && autoScroll) { return; } Button button = (Button) findViewById(R.id.action_direct_message); button.setTextColor(getResources().getColor(color.holo_blue_bright)); } /** * 新しいツイートが来たアピ */ public void onNewListStatus(int listId, Boolean autoScroll) { // 表示中のタブかつ自動スクロール時はハイライトしない int position = mMainPagerAdapter.findPositionById(listId); if (mViewPager.getCurrentItem() == position && autoScroll) { return; } if (position >= 0) { LinearLayout tab_menus = (LinearLayout) findViewById(R.id.tab_menus); Button button = (Button) tab_menus.getChildAt(position); if (button != null) { button.setTextColor(getResources().getColor(color.holo_blue_bright)); } } } /** * 新しいレコードを見たアピ */ public void showTopView() { LinearLayout tab_menus = (LinearLayout) findViewById(R.id.tab_menus); Button button = (Button) tab_menus.getChildAt(mViewPager.getCurrentItem()); if (button != null) { button.setTextColor(getResources().getColor(color.white)); } } /** * 弄らないとアプリをバックボタンで閉じる度にタイムラインが初期化されてしまう(アクティビティがfinishされる) * moveTaskToBackはホームボタンを押した時と同じ動き */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { EditText editText = (EditText) findViewById(R.id.quick_tweet_edit); if (editText != null && editText.getText() != null && editText.getText().length() > 0) { editText.setText(""); setInReplyToStatusId((long) 0); return false; } finish(); } return false; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.profile) { /** * screenNameは変更可能なのでuserIdを使う */ Intent intent = new Intent(this, ProfileActivity.class); intent.putExtra("userId", mApplication.getUserId()); startActivity(intent); } else if (itemId == R.id.user_list) { Intent intent = new Intent(this, ChooseUserListsActivity.class); startActivityForResult(intent, REQUEST_CHOOSE_USER_LIST); } else if (itemId == R.id.search) { Intent intent = new Intent(this, SearchActivity.class); startActivity(intent); } else if (itemId == R.id.settings) { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); } else if (itemId == R.id.official_website) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.official_website))); startActivity(intent); } else if (itemId == R.id.feedback) { View singleLineTweet = findViewById(R.id.quick_tweet_layout); if (singleLineTweet != null && singleLineTweet.getVisibility() == View.VISIBLE) { EditText editStatus = (EditText) findViewById(R.id.quick_tweet_edit); editStatus.setText(" #justaway"); editStatus.requestFocus(); mApplication.showKeyboard(editStatus); return true; } Intent intent = new Intent(this, PostActivity.class); intent.putExtra("status", " #justaway"); startActivity(intent); } else if (itemId == R.id.account) { Intent intent = new Intent(this, AccountSettingActivity.class); startActivityForResult(intent, REQUEST_ACCOUNT_SETTING); } return true; } /** * ストリーミング受信時の処理 */ private UserStreamAdapter getUserStreamAdapter() { final View view = findViewById(R.id.action_interactions); return new UserStreamAdapter() { @Override public void onStatus(Status status) { /** * ツイートを表示するかどうかはFragmentに任せる */ int count = mMainPagerAdapter.getCount(); for (int id = 0; id < count; id++) { BaseFragment fragment = mMainPagerAdapter .findFragmentByPosition(id); if (fragment != null) { fragment.add(Row.newStatus(status)); } } } @Override public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { super.onDeletionNotice(statusDeletionNotice); int count = mMainPagerAdapter.getCount(); for (int id = 0; id < count; id++) { BaseFragment fragment = mMainPagerAdapter .findFragmentByPosition(id); if (fragment != null) { fragment.removeStatus(statusDeletionNotice.getStatusId()); } } } @Override public void onFavorite(User source, User target, Status status) { // 自分の fav を反映 if (source.getId() == mApplication.getUserId()) { mApplication.setFav(status.getId()); return; } Row row = Row.newFavorite(source, target, status); BaseFragment fragment = mMainPagerAdapter .findFragmentById(TAB_ID_INTERACTIONS); new ReFetchFavoriteStatus(fragment).execute(row); } @Override public void onUnfavorite(User arg0, User arg1, Status arg2) { final User source = arg0; final Status status = arg2; // 自分の unfav を反映 if (source.getId() == mApplication.getUserId()) { mApplication.removeFav(status.getId()); return; } view.post(new Runnable() { @Override public void run() { JustawayApplication.showToast(source.getScreenName() + " unfav " + status.getText()); } }); } @Override public void onDirectMessage(DirectMessage directMessage) { super.onDirectMessage(directMessage); BaseFragment fragment = mMainPagerAdapter .findFragmentById(TAB_ID_DIRECT_MESSAGE); if (fragment != null) { fragment.add(Row.newDirectMessage(directMessage)); } } @Override public void onDeletionNotice(long directMessageId, long userId) { super.onDeletionNotice(directMessageId, userId); DirectMessagesFragment fragment = (DirectMessagesFragment) mMainPagerAdapter .findFragmentById(TAB_ID_DIRECT_MESSAGE); if (fragment != null) { fragment.remove(directMessageId); } } }; } public class UpdateStatusTask extends AsyncTask<StatusUpdate, Void, TwitterException> { @Override protected TwitterException doInBackground(StatusUpdate... params) { StatusUpdate superSugoi = params[0]; try { mApplication.getTwitter().updateStatus(superSugoi); return null; } catch (TwitterException e) { e.printStackTrace(); return e; } } @Override protected void onPostExecute(TwitterException e) { dismissProgressDialog(); if (e == null) { EditText status = (EditText) findViewById(R.id.quick_tweet_edit); status.setText(""); } else if (e.getErrorCode() == ERROR_CODE_DUPLICATE_STATUS) { JustawayApplication.showToast(getString(R.string.toast_update_status_already)); } else { JustawayApplication.showToast(R.string.toast_update_status_failure); } } } private void showProgressDialog(String message) { mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage(message); mProgressDialog.show(); } private void dismissProgressDialog() { if (mProgressDialog != null) mProgressDialog.dismiss(); } public void notifyDataSetChanged() { /** * 重く同期で処理すると一瞬画面が固まる */ new Handler().post(new Runnable() { @Override public void run() { int count = mMainPagerAdapter.getCount(); for (int id = 0; id < count; id++) { BaseFragment fragment = mMainPagerAdapter.findFragmentByPosition(id); if (fragment != null) { fragment.getListAdapter().notifyDataSetChanged(); } } } }); } public void doDestroyDirectMessage(Long id) { new DestroyDirectMessageTask().execute(id); // 自分宛のDMを消してもStreaming APIで拾えないで自力で消す DirectMessagesFragment fragment = (DirectMessagesFragment) mMainPagerAdapter .findFragmentById(TAB_ID_DIRECT_MESSAGE); if (fragment != null) { fragment.remove(id); } } }
src/info/justaway/MainActivity.java
package info.justaway; import android.R.color; import android.app.ActionBar; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.Typeface; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import info.justaway.adapter.MainPagerAdapter; import info.justaway.fragment.main.BaseFragment; import info.justaway.fragment.main.DirectMessagesFragment; import info.justaway.fragment.main.InteractionsFragment; import info.justaway.fragment.main.TimelineFragment; import info.justaway.fragment.main.UserListFragment; import info.justaway.model.Row; import info.justaway.task.DestroyDirectMessageTask; import info.justaway.task.ReFetchFavoriteStatus; import twitter4j.ConnectionLifeCycleListener; import twitter4j.DirectMessage; import twitter4j.Status; import twitter4j.StatusDeletionNotice; import twitter4j.StatusUpdate; import twitter4j.TwitterException; import twitter4j.TwitterStream; import twitter4j.User; import twitter4j.UserStreamAdapter; /** * @author aska */ public class MainActivity extends FragmentActivity { private JustawayApplication mApplication; private TwitterStream mTwitterStream; private MainPagerAdapter mMainPagerAdapter; private ViewPager mViewPager; private ProgressDialog mProgressDialog; ActionBar mActionBar; private TextView mTitle; private TextView mSignalButton; private static final int REQUEST_CHOOSE_USER_LIST = 100; private static final int REQUEST_ACCOUNT_SETTING = 200; private static final int ERROR_CODE_DUPLICATE_STATUS = 187; private static final int TAB_ID_TIMELINE = -1; private static final int TAB_ID_INTERACTIONS = -2; private static final int TAB_ID_DIRECT_MESSAGE = -3; private Long mInReplyToStatusId; public Long getInReplyToStatusId() { return mInReplyToStatusId; } public void setInReplyToStatusId(Long inReplyToStatusId) { this.mInReplyToStatusId = inReplyToStatusId; } /** * ActionBarでCustomView使ってるので自分で再実装 */ @Override public void setTitle(CharSequence title) { if (mTitle != null) { mTitle.setText(title); } } @Override public void setTitle(int titleId) { setTitle(getString(titleId)); } @SuppressWarnings("MagicConstant") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // クイックモード時に起動と同時にキーボードが出現するのを抑止 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); mActionBar = getActionBar(); if (mActionBar != null) { int options = mActionBar.getDisplayOptions(); if ((options & ActionBar.DISPLAY_SHOW_CUSTOM) == ActionBar.DISPLAY_SHOW_CUSTOM) { mActionBar.setDisplayOptions(options ^ ActionBar.DISPLAY_SHOW_CUSTOM); } else { mActionBar.setDisplayOptions(options | ActionBar.DISPLAY_SHOW_CUSTOM); if (mActionBar.getCustomView() == null) { mActionBar.setCustomView(R.layout.action_bar); ViewGroup group = (ViewGroup) mActionBar.getCustomView(); mTitle = (TextView) group.findViewById(R.id.title); mSignalButton = (TextView) group.findViewById(R.id.signal); mSignalButton.setTypeface(JustawayApplication.getFontello()); mSignalButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (mApplication.getStreamingMode()) { DialogFragment dialog = new DialogFragment() { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.confirm_destroy_streaming); builder.setPositiveButton(getString(R.string.button_ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mApplication.setStreamingMode(false); if (mTwitterStream != null) { mTwitterStream.cleanUp(); mTwitterStream.shutdown(); } JustawayApplication.showToast(R.string.toast_destroy_streaming); dismiss(); } }); builder.setNegativeButton(getString(R.string.button_cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismiss(); } }); return builder.create(); } }; dialog.show(getSupportFragmentManager(), "dialog"); } else { DialogFragment dialog = new DialogFragment() { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.confirm_create_streaming); builder.setPositiveButton(getString(R.string.button_ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mApplication.setStreamingMode(true); setupStream(); JustawayApplication.showToast(R.string.toast_create_streaming); dismiss(); } }); builder.setNegativeButton(getString(R.string.button_cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismiss(); } }); return builder.create(); } }; dialog.show(getSupportFragmentManager(), "dialog"); } } }); } } } setContentView(R.layout.activity_main); setTitle(R.string.title_main); // クイックモード時に起動と同時に入力エリアにフォーカスするのを抑止 findViewById(R.id.main).requestFocus(); mApplication = JustawayApplication.getApplication(); // アクセストークンがない場合に認証用のアクティビティを起動する if (!mApplication.hasAccessToken()) { Intent intent = new Intent(this, SignInActivity.class); startActivity(intent); finish(); return; } setup(); /** * 違うタブだったら移動、同じタブだったら最上部にスクロールという美しい実装 * ActionBarのタブに頼っていない為、自力でsetCurrentItemでタブを動かしている * タブの切替がスワイプだけで良い場合はこの処理すら不要 */ Typeface fontello = JustawayApplication.getFontello(); Button home = (Button) findViewById(R.id.action_timeline); Button interactions = (Button) findViewById(R.id.action_interactions); Button directMessage = (Button) findViewById(R.id.action_direct_message); Button tweet = (Button) findViewById(R.id.action_tweet); Button send = (Button) findViewById(R.id.send); findViewById(R.id.action_timeline).setSelected(true); home.setTypeface(fontello); interactions.setTypeface(fontello); directMessage.setTypeface(fontello); tweet.setTypeface(fontello); send.setTypeface(fontello); home.setOnClickListener(tabMenuOnClickListener(0)); interactions.setOnClickListener(tabMenuOnClickListener(1)); directMessage.setOnClickListener(tabMenuOnClickListener(2)); tweet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), PostActivity.class); if (findViewById(R.id.quick_tweet_layout).getVisibility() == View.VISIBLE) { EditText status = (EditText) findViewById(R.id.quick_tweet_edit); if (status == null) { return; } String msg = status.getText() != null ? status.getText().toString() : null; if (msg != null && msg.length() > 0) { Long inReplyToStatusId = getInReplyToStatusId(); intent.putExtra("status", msg); intent.putExtra("selection", msg.length()); if (inReplyToStatusId != null && inReplyToStatusId > 0) { intent.putExtra("inReplyToStatusId", inReplyToStatusId); } status.setText(""); status.clearFocus(); } } startActivity(intent); } }); tweet.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { if (findViewById(R.id.quick_tweet_layout).getVisibility() == View.VISIBLE) { hideQuickPanel(); } else { showQuickPanel(); } return true; } }); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText status = (EditText) findViewById(R.id.quick_tweet_edit); String msg = status.getText() != null ? status.getText().toString() : null; if (msg != null && msg.length() > 0) { showProgressDialog(getString(R.string.progress_sending)); StatusUpdate super_sugoi = new StatusUpdate(msg); Long inReplyToStatusId = getInReplyToStatusId(); if (inReplyToStatusId != null && inReplyToStatusId > 0) { super_sugoi.setInReplyToStatusId(inReplyToStatusId); setInReplyToStatusId((long) 0); } new UpdateStatusTask().execute(super_sugoi); } } }); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } @SuppressWarnings("NullableProblems") @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); } public void showQuickPanel() { findViewById(R.id.quick_tweet_layout).setVisibility(View.VISIBLE); EditText editStatus = (EditText) findViewById(R.id.quick_tweet_edit); editStatus.setFocusable(true); editStatus.setFocusableInTouchMode(true); editStatus.setEnabled(true); mApplication.setQuickMod(true); } public void hideQuickPanel() { EditText editStatus = (EditText) findViewById(R.id.quick_tweet_edit); editStatus.setFocusable(false); editStatus.setFocusableInTouchMode(false); editStatus.setEnabled(false); editStatus.clearFocus(); findViewById(R.id.quick_tweet_layout).setVisibility(View.GONE); setInReplyToStatusId((long) 0); mApplication.setQuickMod(false); } public void setupTab() { LinearLayout tab_menus = (LinearLayout) findViewById(R.id.tab_menus); int count = tab_menus.getChildCount(); // 4つめ以降のタブを消す if (count > 3) { for (int position = count - 1; position > 2; position--) { View view = tab_menus.getChildAt(position); if (view != null) { tab_menus.removeView(view); } mMainPagerAdapter.removeTab(position); } } Typeface fontello = JustawayApplication.getFontello(); ArrayList<JustawayApplication.Tab> tabs = mApplication.loadTabs(); if (tabs.size() > 3) { int position = 2; for (JustawayApplication.Tab tab : tabs) { // 標準のタブを動的に生成する時に実装する if (tab.id > 0) { Button button = new Button(this); button.setWidth(60); button.setTypeface(fontello); button.setTextSize(22); button.setBackgroundResource(R.drawable.tab_stateful); button.setText(R.string.fontello_list); button.setOnClickListener(tabMenuOnClickListener(++position)); tab_menus.addView(button); Bundle args = new Bundle(); args.putInt("userListId", tab.id); mMainPagerAdapter.addTab(UserListFragment.class, args, tab.name, tab.id); } } } mMainPagerAdapter.notifyDataSetChanged(); } @Override protected void onStart() { super.onStart(); // 前回バグで強制終了した場合はダイアログ表示、Yesでレポート送信 MyUncaughtExceptionHandler.showBugReportDialogIfExist(this); // スリープさせない指定 if (JustawayApplication.getApplication().getKeepScreenOn()) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } else { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } mApplication.resetDisplaySettings(); // フォントサイズの変更や他のアクティビティでのfav/RTを反映 mMainPagerAdapter.notifyDataSetChanged(); } @Override protected void onResume() { super.onResume(); } @Override protected void onDestroy() { super.onDestroy(); if (mTwitterStream != null) { mTwitterStream.cleanUp(); mTwitterStream.shutdown(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_CHOOSE_USER_LIST: if (resultCode == RESULT_OK) { Bundle bundle = data.getExtras(); if (bundle == null) { return; } ArrayList<Integer> lists = bundle.getIntegerArrayList("lists"); ArrayList<Integer> tabs = new ArrayList<Integer>(); // 後々タブ設定画面に標準のタブを含める tabs.add(-1); tabs.add(-2); tabs.add(-3); tabs.addAll(lists); mApplication.saveTabs(tabs); setupTab(); if (lists != null && lists.size() > 0) { JustawayApplication.showToast(R.string.toast_register_list_for_tab); } } else { /** * リストの削除を検出してタブを再構成 */ ArrayList<JustawayApplication.Tab> tabs = mApplication.loadTabs(); ArrayList<Integer> new_tabs = new ArrayList<Integer>(); for (JustawayApplication.Tab tab : tabs) { if (tab.id > 0 && mApplication.getUserList(tab.id) == null) { continue; } new_tabs.add(tab.id); } if (tabs.size() != new_tabs.size()) { mApplication.saveTabs(new_tabs); setupTab(); } } break; case REQUEST_ACCOUNT_SETTING: if (mTwitterStream != null) { mTwitterStream.cleanUp(); mTwitterStream.shutdown(); } setupTab(); int count = mMainPagerAdapter.getCount(); for (int id = 0; id < count; id++) { BaseFragment fragment = mMainPagerAdapter .findFragmentByPosition(id); if (fragment != null) { fragment.getListAdapter().clear(); fragment.reload(); } } default: break; } } private View.OnClickListener tabMenuOnClickListener(final int position) { return new View.OnClickListener() { @Override public void onClick(View v) { BaseFragment f = mMainPagerAdapter.findFragmentByPosition(position); if (f == null) { return; } int id = mViewPager.getCurrentItem(); if (id != position) { mViewPager.setCurrentItem(position); if (f.isTop()) { showTopView(); } } else { f.goToTop(); } } }; } public void setup() { /** * スワイプで動かせるタブを実装するのに最低限必要な実装 */ mViewPager = (ViewPager) findViewById(R.id.pager); mMainPagerAdapter = new MainPagerAdapter(this, mViewPager); mMainPagerAdapter.addTab(TimelineFragment.class, null, getString(R.string.title_main), TAB_ID_TIMELINE); mMainPagerAdapter.addTab(InteractionsFragment.class, null, getString(R.string.title_interactions), TAB_ID_INTERACTIONS); mMainPagerAdapter.addTab(DirectMessagesFragment.class, null, getString(R.string.title_direct_messages), TAB_ID_DIRECT_MESSAGE); setupTab(); findViewById(R.id.footer).setVisibility(View.VISIBLE); /** * タブは前後タブまでは状態が保持されるがそれ以上離れるとViewが破棄されてしまう、 * あまりに使いづらいの上限を増やしている、指定値+前後のタブまでが保持されるようになる * デフォルト値は1(表示しているタブの前後までしか保持されない) */ mViewPager.setOffscreenPageLimit(10); /** * スワイプ移動でも移動先が未読アプしている場合、アピ解除判定を行う */ mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { BaseFragment f = mMainPagerAdapter.findFragmentByPosition(position); if (f.isTop()) { showTopView(); } LinearLayout tab_menus = (LinearLayout) findViewById(R.id.tab_menus); int count = tab_menus.getChildCount(); for (int i = 0; i < count; i++) { Button button = (Button) tab_menus.getChildAt(i); if (button == null) { continue; } if (i == position) { button.setSelected(true); } else { button.setSelected(false); } } setTitle(mMainPagerAdapter.getPageTitle(position)); } }); if (mApplication.getQuickMode()) { showQuickPanel(); } } public void setupStream() { if (!mApplication.getStreamingMode()) { return; } if (mTwitterStream != null) { mTwitterStream.cleanUp(); mTwitterStream.shutdown(); mTwitterStream.setOAuthAccessToken(mApplication.getAccessToken()); } else { mTwitterStream = mApplication.getTwitterStream(); mTwitterStream.addListener(getUserStreamAdapter()); mTwitterStream.addConnectionLifeCycleListener(new ConnectionLifeCycleListener() { @Override public void onConnect() { if (mSignalButton != null) { mSignalButton.setTextColor(getResources().getColor(R.color.holo_green_light)); } } @Override public void onDisconnect() { if (mSignalButton != null) { if (mApplication.getStreamingMode()) { mSignalButton.setTextColor(getResources().getColor(R.color.holo_red_light)); } else { mSignalButton.setTextColor(Color.WHITE); } } } @Override public void onCleanUp() { if (mSignalButton != null) { if (mApplication.getStreamingMode()) { mSignalButton.setTextColor(getResources().getColor(R.color.holo_orange_light)); } else { mSignalButton.setTextColor(Color.WHITE); } } } }); mSignalButton.setTextColor(getResources().getColor(R.color.holo_blue_light)); } mTwitterStream.user(); } /** * 新しいツイートが来たアピ */ public void onNewTimeline(Boolean autoScroll) { // 表示中のタブかつ自動スクロール時はハイライトしない if (mViewPager.getCurrentItem() == 0 && autoScroll) { return; } Button button = (Button) findViewById(R.id.action_timeline); button.setTextColor(getResources().getColor(color.holo_blue_bright)); } /** * 新しいリプが来たアピ */ public void onNewInteractions(Boolean autoScroll) { // 表示中のタブかつ自動スクロール時はハイライトしない if (mViewPager.getCurrentItem() == 1 && autoScroll) { return; } Button button = (Button) findViewById(R.id.action_interactions); button.setTextColor(getResources().getColor(color.holo_blue_bright)); } /** * 新しいDMが来たアピ */ public void onNewDirectMessage(Boolean autoScroll) { // 表示中のタブかつ自動スクロール時はハイライトしない if (mViewPager.getCurrentItem() == 2 && autoScroll) { return; } Button button = (Button) findViewById(R.id.action_direct_message); button.setTextColor(getResources().getColor(color.holo_blue_bright)); } /** * 新しいツイートが来たアピ */ public void onNewListStatus(int listId, Boolean autoScroll) { // 表示中のタブかつ自動スクロール時はハイライトしない int position = mMainPagerAdapter.findPositionById(listId); if (mViewPager.getCurrentItem() == position && autoScroll) { return; } if (position >= 0) { LinearLayout tab_menus = (LinearLayout) findViewById(R.id.tab_menus); Button button = (Button) tab_menus.getChildAt(position); if (button != null) { button.setTextColor(getResources().getColor(color.holo_blue_bright)); } } } /** * 新しいレコードを見たアピ */ public void showTopView() { LinearLayout tab_menus = (LinearLayout) findViewById(R.id.tab_menus); Button button = (Button) tab_menus.getChildAt(mViewPager.getCurrentItem()); if (button != null) { button.setTextColor(getResources().getColor(color.white)); } } /** * 弄らないとアプリをバックボタンで閉じる度にタイムラインが初期化されてしまう(アクティビティがfinishされる) * moveTaskToBackはホームボタンを押した時と同じ動き */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { EditText editText = (EditText) findViewById(R.id.quick_tweet_edit); if (editText != null && editText.getText() != null && editText.getText().length() > 0) { editText.setText(""); setInReplyToStatusId((long) 0); return false; } finish(); } return false; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.profile) { /** * screenNameは変更可能なのでuserIdを使う */ Intent intent = new Intent(this, ProfileActivity.class); intent.putExtra("userId", mApplication.getUserId()); startActivity(intent); } else if (itemId == R.id.user_list) { Intent intent = new Intent(this, ChooseUserListsActivity.class); startActivityForResult(intent, REQUEST_CHOOSE_USER_LIST); } else if (itemId == R.id.search) { Intent intent = new Intent(this, SearchActivity.class); startActivity(intent); } else if (itemId == R.id.settings) { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); } else if (itemId == R.id.official_website) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.official_website))); startActivity(intent); } else if (itemId == R.id.feedback) { View singleLineTweet = findViewById(R.id.quick_tweet_layout); if (singleLineTweet != null && singleLineTweet.getVisibility() == View.VISIBLE) { EditText editStatus = (EditText) findViewById(R.id.quick_tweet_edit); editStatus.setText(" #justaway"); editStatus.requestFocus(); mApplication.showKeyboard(editStatus); return true; } Intent intent = new Intent(this, PostActivity.class); intent.putExtra("status", " #justaway"); startActivity(intent); } else if (itemId == R.id.account) { Intent intent = new Intent(this, AccountSettingActivity.class); startActivityForResult(intent, REQUEST_ACCOUNT_SETTING); } return true; } /** * ストリーミング受信時の処理 */ private UserStreamAdapter getUserStreamAdapter() { final View view = findViewById(R.id.action_interactions); return new UserStreamAdapter() { @Override public void onStatus(Status status) { /** * ツイートを表示するかどうかはFragmentに任せる */ int count = mMainPagerAdapter.getCount(); for (int id = 0; id < count; id++) { BaseFragment fragment = mMainPagerAdapter .findFragmentByPosition(id); if (fragment != null) { fragment.add(Row.newStatus(status)); } } } @Override public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { super.onDeletionNotice(statusDeletionNotice); int count = mMainPagerAdapter.getCount(); for (int id = 0; id < count; id++) { BaseFragment fragment = mMainPagerAdapter .findFragmentByPosition(id); if (fragment != null) { fragment.removeStatus(statusDeletionNotice.getStatusId()); } } } @Override public void onFavorite(User source, User target, Status status) { // 自分の fav を反映 if (source.getId() == mApplication.getUserId()) { mApplication.setFav(status.getId()); return; } Row row = Row.newFavorite(source, target, status); BaseFragment fragment = mMainPagerAdapter .findFragmentById(TAB_ID_INTERACTIONS); new ReFetchFavoriteStatus(fragment).execute(row); } @Override public void onUnfavorite(User arg0, User arg1, Status arg2) { final User source = arg0; final Status status = arg2; // 自分の unfav を反映 if (source.getId() == mApplication.getUserId()) { mApplication.removeFav(status.getId()); return; } view.post(new Runnable() { @Override public void run() { JustawayApplication.showToast(source.getScreenName() + " unfav " + status.getText()); } }); } @Override public void onDirectMessage(DirectMessage directMessage) { super.onDirectMessage(directMessage); BaseFragment fragment = mMainPagerAdapter .findFragmentById(TAB_ID_DIRECT_MESSAGE); if (fragment != null) { fragment.add(Row.newDirectMessage(directMessage)); } } @Override public void onDeletionNotice(long directMessageId, long userId) { super.onDeletionNotice(directMessageId, userId); DirectMessagesFragment fragment = (DirectMessagesFragment) mMainPagerAdapter .findFragmentById(TAB_ID_DIRECT_MESSAGE); if (fragment != null) { fragment.remove(directMessageId); } } }; } public class UpdateStatusTask extends AsyncTask<StatusUpdate, Void, TwitterException> { @Override protected TwitterException doInBackground(StatusUpdate... params) { StatusUpdate superSugoi = params[0]; try { mApplication.getTwitter().updateStatus(superSugoi); return null; } catch (TwitterException e) { e.printStackTrace(); return e; } } @Override protected void onPostExecute(TwitterException e) { dismissProgressDialog(); if (e == null) { EditText status = (EditText) findViewById(R.id.quick_tweet_edit); status.setText(""); } else if (e.getErrorCode() == ERROR_CODE_DUPLICATE_STATUS) { JustawayApplication.showToast(getString(R.string.toast_update_status_already)); } else { JustawayApplication.showToast(R.string.toast_update_status_failure); } } } private void showProgressDialog(String message) { mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage(message); mProgressDialog.show(); } private void dismissProgressDialog() { if (mProgressDialog != null) mProgressDialog.dismiss(); } public void notifyDataSetChanged() { /** * 重く同期で処理すると一瞬画面が固まる */ new Handler().post(new Runnable() { @Override public void run() { int count = mMainPagerAdapter.getCount(); for (int id = 0; id < count; id++) { BaseFragment fragment = mMainPagerAdapter.findFragmentByPosition(id); if (fragment != null) { fragment.getListAdapter().notifyDataSetChanged(); } } } }); } public void doDestroyDirectMessage(Long id) { new DestroyDirectMessageTask().execute(id); // 自分宛のDMを消してもStreaming APIで拾えないで自力で消す DirectMessagesFragment fragment = (DirectMessagesFragment) mMainPagerAdapter .findFragmentById(TAB_ID_DIRECT_MESSAGE); if (fragment != null) { fragment.remove(id); } } }
Guy to fixed streaming color change bug.
src/info/justaway/MainActivity.java
Guy to fixed streaming color change bug.
<ide><path>rc/info/justaway/MainActivity.java <ide> import android.support.v4.app.DialogFragment; <ide> import android.support.v4.app.FragmentActivity; <ide> import android.support.v4.view.ViewPager; <add>import android.util.Log; <ide> import android.view.KeyEvent; <ide> import android.view.Menu; <ide> import android.view.MenuItem; <ide> @Override <ide> public void onConnect() { <ide> if (mSignalButton != null) { <del> mSignalButton.setTextColor(getResources().getColor(R.color.holo_green_light)); <add> mSignalButton.post(new Runnable() { <add> @Override <add> public void run() { <add> mSignalButton.setTextColor(getResources().getColor(R.color.holo_green_light)); <add> } <add> }); <ide> } <ide> } <ide> <ide> @Override <ide> public void onDisconnect() { <ide> if (mSignalButton != null) { <del> if (mApplication.getStreamingMode()) { <del> mSignalButton.setTextColor(getResources().getColor(R.color.holo_red_light)); <del> } else { <del> mSignalButton.setTextColor(Color.WHITE); <del> } <add> mSignalButton.post(new Runnable() { <add> @Override <add> public void run() { <add> if (mApplication.getStreamingMode()) { <add> mSignalButton.setTextColor(getResources().getColor(R.color.holo_red_light)); <add> } else { <add> mSignalButton.setTextColor(Color.WHITE); <add> } <add> } <add> }); <ide> } <ide> } <ide> <ide> @Override <ide> public void onCleanUp() { <ide> if (mSignalButton != null) { <del> if (mApplication.getStreamingMode()) { <del> mSignalButton.setTextColor(getResources().getColor(R.color.holo_orange_light)); <del> } else { <del> mSignalButton.setTextColor(Color.WHITE); <del> } <add> mSignalButton.post(new Runnable() { <add> @Override <add> public void run() { <add> if (mApplication.getStreamingMode()) { <add> mSignalButton.setTextColor(getResources().getColor(R.color.holo_orange_light)); <add> } else { <add> mSignalButton.setTextColor(Color.WHITE); <add> } <add> } <add> }); <ide> } <ide> } <ide> });
Java
apache-2.0
2ee1cacb9c0a7582bc91075b287a1927563a1033
0
apache/commons-chain,apache/commons-chain,apache/commons-chain
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.chain.generic; import org.apache.commons.chain.Command; import org.apache.commons.chain.Context; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; import java.util.WeakHashMap; /** * An abstract base command which uses introspection to look up a method to execute. * For use by developers who prefer to group related functionality into a single class * rather than an inheritance family. * * @param <C> Type of the context associated with this command * * @since Chain 1.1 */ public abstract class DispatchCommand<C extends Context> implements Command<C> { /** Cache of methods */ private final Map<String, Method> methods = new WeakHashMap<String, Method>(); /** Method name */ private String method = null; /** Method key */ private String methodKey = null; /** * The base implementation expects dispatch methods to take a <code>Context</code> * as their only argument. */ protected static final Class<?>[] DEFAULT_SIGNATURE = new Class<?>[] {Context.class}; /** * Look up the method specified by either "method" or "methodKey" and invoke it, * returning a boolean value as interpreted by <code>evaluateResult</code>. * @param context The Context to be processed by this Command. * @return the result of method being dispatched to. * @throws IllegalStateException if neither 'method' nor 'methodKey' properties are defined * @throws Exception if any is thrown by the invocation. Note that if invoking the method * results in an InvocationTargetException, the cause of that exception is thrown instead of * the exception itself, unless the cause is an <code>Error</code> or other <code>Throwable</code> * which is not an <code>Exception</code>. */ public boolean execute(C context) throws Exception { if (this.getMethod() == null && this.getMethodKey() == null) { throw new IllegalStateException("Neither 'method' nor 'methodKey' properties are defined "); } Method methodObject = extractMethod(context); try { return evaluateResult(methodObject.invoke(this, getArguments(context))); } catch (InvocationTargetException e) { Throwable cause = e.getTargetException(); if (cause instanceof Exception) { throw (Exception)cause; } throw e; } } /** * Extract the dispatch method. The base implementation uses the command's * <code>method</code> property as the name of a method to look up, or, if that is not defined, * looks up the the method name in the Context using the <code>methodKey</code>. * * @param context The Context being processed by this Command. * @return The method to execute * @throws NoSuchMethodException if no method can be found under the specified name. * @throws NullPointerException if no methodName cannot be determined */ protected Method extractMethod(C context) throws NoSuchMethodException { String methodName = this.getMethod(); if (methodName == null) { Object methodContextObj = context.get(this.getMethodKey()); if (methodContextObj == null) { throw new NullPointerException("No value found in context under " + this.getMethodKey()); } methodName = methodContextObj.toString(); } Method theMethod = null; synchronized (methods) { theMethod = methods.get(methodName); if (theMethod == null) { theMethod = getClass().getMethod(methodName, getSignature()); methods.put(methodName, theMethod); } } return theMethod; } /** * Evaluate the result of the method invocation as a boolean value. Base implementation * expects that the invoked method returns boolean true/false, but subclasses might * implement other interpretations. * @param o The result of the methid execution * @return The evaluated result/ */ protected boolean evaluateResult(Object o) { Boolean result = (Boolean) o; return (result != null && result.booleanValue()); } /** * Return a <code>Class[]</code> describing the expected signature of the method. * @return The method signature. */ protected Class<?>[] getSignature() { return DEFAULT_SIGNATURE; } /** * Get the arguments to be passed into the dispatch method. * Default implementation simply returns the context which was passed in, but subclasses * could use this to wrap the context in some other type, or extract key values from the * context to pass in. The length and types of values returned by this must coordinate * with the return value of <code>getSignature()</code> * @param context The Context being processed by this Command. * @return The method arguments. */ protected Object[] getArguments(C context) { return new Object[] {context}; } /** * Return the method name. * @return The method name. */ public String getMethod() { return method; } /** * Return the Context key for the method name. * @return The Context key for the method name. */ public String getMethodKey() { return methodKey; } /** * Set the method name. * @param method The method name. */ public void setMethod(String method) { this.method = method; } /** * Set the Context key for the method name. * @param methodKey The Context key for the method name. */ public void setMethodKey(String methodKey) { this.methodKey = methodKey; } }
src/main/java/org/apache/commons/chain/generic/DispatchCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.chain.generic; import org.apache.commons.chain.Command; import org.apache.commons.chain.Context; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; import java.util.WeakHashMap; /** * An abstract base command which uses introspection to look up a method to execute. * For use by developers who prefer to group related functionality into a single class * rather than an inheritance family. * * @param <C> Type of the context associated with this command * * @since Chain 1.1 */ public abstract class DispatchCommand<C extends Context> implements Command<C> { /** Cache of methods */ private final Map<String, Method> methods = new WeakHashMap<String, Method>(); /** Method name */ private String method = null; /** Method key */ private String methodKey = null; /** * The base implementation expects dispatch methods to take a <code>Context</code> * as their only argument. */ protected static final Class[] DEFAULT_SIGNATURE = new Class[] {Context.class}; /** * Look up the method specified by either "method" or "methodKey" and invoke it, * returning a boolean value as interpreted by <code>evaluateResult</code>. * @param context The Context to be processed by this Command. * @return the result of method being dispatched to. * @throws IllegalStateException if neither 'method' nor 'methodKey' properties are defined * @throws Exception if any is thrown by the invocation. Note that if invoking the method * results in an InvocationTargetException, the cause of that exception is thrown instead of * the exception itself, unless the cause is an <code>Error</code> or other <code>Throwable</code> * which is not an <code>Exception</code>. */ public boolean execute(C context) throws Exception { if (this.getMethod() == null && this.getMethodKey() == null) { throw new IllegalStateException("Neither 'method' nor 'methodKey' properties are defined "); } Method methodObject = extractMethod(context); try { return evaluateResult(methodObject.invoke(this, getArguments(context))); } catch (InvocationTargetException e) { Throwable cause = e.getTargetException(); if (cause instanceof Exception) { throw (Exception)cause; } throw e; } } /** * Extract the dispatch method. The base implementation uses the command's * <code>method</code> property as the name of a method to look up, or, if that is not defined, * looks up the the method name in the Context using the <code>methodKey</code>. * * @param context The Context being processed by this Command. * @return The method to execute * @throws NoSuchMethodException if no method can be found under the specified name. * @throws NullPointerException if no methodName cannot be determined */ protected Method extractMethod(C context) throws NoSuchMethodException { String methodName = this.getMethod(); if (methodName == null) { Object methodContextObj = context.get(this.getMethodKey()); if (methodContextObj == null) { throw new NullPointerException("No value found in context under " + this.getMethodKey()); } methodName = methodContextObj.toString(); } Method theMethod = null; synchronized (methods) { theMethod = methods.get(methodName); if (theMethod == null) { theMethod = getClass().getMethod(methodName, getSignature()); methods.put(methodName, theMethod); } } return theMethod; } /** * Evaluate the result of the method invocation as a boolean value. Base implementation * expects that the invoked method returns boolean true/false, but subclasses might * implement other interpretations. * @param o The result of the methid execution * @return The evaluated result/ */ protected boolean evaluateResult(Object o) { Boolean result = (Boolean) o; return (result != null && result.booleanValue()); } /** * Return a <code>Class[]</code> describing the expected signature of the method. * @return The method signature. */ protected Class[] getSignature() { return DEFAULT_SIGNATURE; } /** * Get the arguments to be passed into the dispatch method. * Default implementation simply returns the context which was passed in, but subclasses * could use this to wrap the context in some other type, or extract key values from the * context to pass in. The length and types of values returned by this must coordinate * with the return value of <code>getSignature()</code> * @param context The Context being processed by this Command. * @return The method arguments. */ protected Object[] getArguments(C context) { return new Object[] {context}; } /** * Return the method name. * @return The method name. */ public String getMethod() { return method; } /** * Return the Context key for the method name. * @return The Context key for the method name. */ public String getMethodKey() { return methodKey; } /** * Set the method name. * @param method The method name. */ public void setMethod(String method) { this.method = method; } /** * Set the Context key for the method name. * @param methodKey The Context key for the method name. */ public void setMethodKey(String methodKey) { this.methodKey = methodKey; } }
fixed generic types warnings git-svn-id: c648d2fd594d54929ed024cccc47021495644b24@1163732 13f79535-47bb-0310-9956-ffa450edef68
src/main/java/org/apache/commons/chain/generic/DispatchCommand.java
fixed generic types warnings
<ide><path>rc/main/java/org/apache/commons/chain/generic/DispatchCommand.java <ide> * The base implementation expects dispatch methods to take a <code>Context</code> <ide> * as their only argument. <ide> */ <del> protected static final Class[] DEFAULT_SIGNATURE = new Class[] {Context.class}; <add> protected static final Class<?>[] DEFAULT_SIGNATURE = new Class<?>[] {Context.class}; <ide> <ide> <ide> /** <ide> * Return a <code>Class[]</code> describing the expected signature of the method. <ide> * @return The method signature. <ide> */ <del> protected Class[] getSignature() { <add> protected Class<?>[] getSignature() { <ide> return DEFAULT_SIGNATURE; <ide> } <ide>
Java
apache-2.0
ea1af9c2947156b66d25f84fbe482a783ee700e5
0
Jukkorsis/Hadrian,Jukkorsis/Hadrian,Jukkorsis/Hadrian
/* * Copyright 2015 Richard Thurston. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.northernwall.hadrian.db; import com.northernwall.hadrian.domain.DataStore; import com.northernwall.hadrian.domain.Vip; import com.northernwall.hadrian.domain.VipRef; import com.northernwall.hadrian.domain.Host; import com.northernwall.hadrian.domain.Service; import com.northernwall.hadrian.domain.ServiceRef; import com.northernwall.hadrian.domain.Team; import com.northernwall.hadrian.domain.WorkItem; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Predicate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Richard Thurston */ public class InMemoryDataAccess implements DataAccess { private final static Logger logger = LoggerFactory.getLogger(InMemoryDataAccess.class); private final Map<String, Team> teams; private final List<Service> services; private final Map<String, Host> hosts; private final Map<String, Vip> vips; private final List<ServiceRef> serviceRefs; private final List<VipRef> vipRefs; private final List<DataStore> dataStores; private final Map<String, WorkItem> workItems; public InMemoryDataAccess() { teams = new ConcurrentHashMap<>(); services = new LinkedList<>(); hosts = new ConcurrentHashMap<>(); vips = new ConcurrentHashMap<>(); serviceRefs = new LinkedList<>(); vipRefs = new LinkedList<>(); dataStores = new LinkedList<>(); workItems = new ConcurrentHashMap<>(); } @Override public List<Team> getTeams() { List<Team> temp = new LinkedList<>(teams.values()); Collections.sort(temp); return temp; } @Override public Team getTeam(String teamId) { return teams.get(teamId); } @Override public void saveTeam(Team team) { teams.put(team.getTeamId(), team); } @Override public List<Service> getServices() { List<Service> temp = services; Collections.sort(temp); return temp; } @Override public List<Service> getServices(String teamId) { List<Service> temp = new LinkedList<>(); for (Service service : services) { if (service.getTeamId().equals(teamId)) { temp.add(service); } } Collections.sort(temp); return temp; } @Override public Service getService(String serviceId) { for (Service service : services) { if (service.getServiceId().equals(serviceId)) { return service; } } return null; } @Override public void saveService(Service service) { services.add(service); } @Override public List<Host> getHosts(String serviceId) { List<Host> temp = new LinkedList<>(); for (Host host : hosts.values()) { if (host.getServiceId().equals(serviceId)) { temp.add(host); } } Collections.sort(temp); return temp; } @Override public Host getHost(String hostId) { return hosts.get(hostId); } @Override public void saveHost(Host host) { hosts.put(host.getHostId(), host); } @Override public void updateHost(Host host) { hosts.put(host.getHostId(), host); } @Override public void deleteHost(String hostId) { hosts.remove(hostId); } @Override public List<Vip> getVips(String serviceId) { List<Vip> temp = new LinkedList<>(); for (Vip vip : vips.values()) { if (vip.getServiceId().equals(serviceId)) { temp.add(vip); } } Collections.sort(temp); return temp; } @Override public Vip getVip(String vipId) { return vips.get(vipId); } @Override public void saveVip(Vip vip) { vips.put(vip.getVipId(), vip); } @Override public void updateVip(Vip vip){ vips.put(vip.getVipId(), vip); } @Override public void deleteVip(String vipId) { vips.remove(vipId); } @Override public List<ServiceRef> getServiceRefs() { return serviceRefs; } @Override public List<ServiceRef> getServiceRefsByClient(String clientServiceId) { List<ServiceRef> temp = new LinkedList<>(); for (ServiceRef serviceRef : serviceRefs) { if (serviceRef.getClientServiceId().equals(clientServiceId)) { temp.add(serviceRef); } } return temp; } @Override public List<ServiceRef> getServiceRefsByServer(String serverServiceId) { List<ServiceRef> temp = new LinkedList<>(); for (ServiceRef serviceRef : serviceRefs) { if (serviceRef.getServerServiceId().equals(serverServiceId)) { temp.add(serviceRef); } } return temp; } @Override public void saveServiceRef(ServiceRef serviceRef) { serviceRefs.add(serviceRef); } @Override public void deleteServiceRef(final String clientId, final String serviceId) { serviceRefs.removeIf(new Predicate<ServiceRef>() { @Override public boolean test(ServiceRef t) { return t.getClientServiceId().equals(clientId) && t.getServerServiceId().equals(serviceId); } }); } @Override public List<VipRef> getVipRefsByHost(String hostId) { List<VipRef> temp = new LinkedList<>(); for (VipRef vipRef : vipRefs) { if (vipRef.getHostId().equals(hostId)) { temp.add(vipRef); } } return temp; } @Override public List<VipRef> getVipRefsByVip(String vipId) { List<VipRef> temp = new LinkedList<>(); for (VipRef vipRef : vipRefs) { if (vipRef.getVipId().equals(vipId)) { temp.add(vipRef); } } return temp; } @Override public VipRef getVipRef(String hostId, String vipId) { for (VipRef vipRef : vipRefs) { if (vipRef.getHostId().equals(hostId) && vipRef.getVipId().equals(vipId)) { return vipRef; } } return null; } @Override public void saveVipRef(VipRef vipRef) { for (VipRef temp : vipRefs) { if (temp.getVipId().equals(vipRef.getVipId()) && temp.getHostId().equals(vipRef.getHostId())) { return; } } vipRefs.add(vipRef); } @Override public void updateVipRef(VipRef vipRef) { for (VipRef temp : vipRefs) { if (temp.getVipId().equals(vipRef.getVipId()) && temp.getHostId().equals(vipRef.getHostId())) { temp.setStatus(vipRef.getStatus()); return; } } } @Override public void deleteVipRef(final String hostId, final String vipId) { vipRefs.removeIf(new Predicate<VipRef>() { @Override public boolean test(VipRef ref) { return ref.getHostId().equals(hostId) && ref.getVipId().equals(vipId); } }); } @Override public void deleteVipRefs(final String vipId) { vipRefs.removeIf(new Predicate<VipRef>() { @Override public boolean test(VipRef ref) { return ref.getVipId().equals(vipId); } }); } @Override public List<DataStore> getDataStores(String teamId) { List<DataStore> temp = new LinkedList<>(); for (DataStore dataStore : dataStores) { if (dataStore.getTeamId().equals(teamId)) { temp.add(dataStore); } } Collections.sort(temp); return temp; } @Override public DataStore getDataStore(String dataStoreId) { for (DataStore dataStore : dataStores) { if (dataStore.getDataStoreId().equals(dataStoreId)) { return dataStore; } } return null; } @Override public void saveDataStore(DataStore dataStore) { dataStores.add(dataStore); } @Override public void saveWorkItem(WorkItem workItem) { workItems.put(workItem.getId(), workItem); } @Override public WorkItem getWorkItem(String id) { return workItems.get(id); } }
src/main/java/com/northernwall/hadrian/db/InMemoryDataAccess.java
/* * Copyright 2015 Richard Thurston. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.northernwall.hadrian.db; import com.northernwall.hadrian.domain.DataStore; import com.northernwall.hadrian.domain.Vip; import com.northernwall.hadrian.domain.VipRef; import com.northernwall.hadrian.domain.Host; import com.northernwall.hadrian.domain.Service; import com.northernwall.hadrian.domain.ServiceRef; import com.northernwall.hadrian.domain.Team; import com.northernwall.hadrian.domain.WorkItem; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Predicate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Richard Thurston */ public class InMemoryDataAccess implements DataAccess { private final static Logger logger = LoggerFactory.getLogger(InMemoryDataAccess.class); private final Map<String, Team> teams; private final List<Service> services; private final Map<String, Host> hosts; private final Map<String, Vip> vips; private final List<ServiceRef> serviceRefs; private final List<VipRef> vipRefs; private final List<DataStore> dataStores; private final Map<String, WorkItem> workItems; public InMemoryDataAccess() { teams = new ConcurrentHashMap<>(); services = new LinkedList<>(); hosts = new ConcurrentHashMap<>(); vips = new ConcurrentHashMap<>(); serviceRefs = new LinkedList<>(); vipRefs = new LinkedList<>(); dataStores = new LinkedList<>(); workItems = new ConcurrentHashMap<>(); } @Override public List<Team> getTeams() { List<Team> temp = new LinkedList<>(teams.values()); Collections.sort(temp); return temp; } @Override public Team getTeam(String teamId) { return teams.get(teamId); } @Override public void saveTeam(Team team) { teams.put(team.getTeamId(), team); } @Override public List<Service> getServices() { List<Service> temp = services; Collections.sort(temp); return temp; } @Override public List<Service> getServices(String teamId) { List<Service> temp = new LinkedList<>(); for (Service service : services) { if (service.getTeamId().equals(teamId)) { temp.add(service); } } Collections.sort(temp); return temp; } @Override public Service getService(String serviceId) { for (Service service : services) { if (service.getServiceId().equals(serviceId)) { return service; } } return null; } @Override public void saveService(Service service) { services.add(service); } @Override public List<Host> getHosts(String serviceId) { List<Host> temp = new LinkedList<>(); for (Host host : hosts.values()) { if (host.getServiceId().equals(serviceId)) { temp.add(host); } } Collections.sort(temp); return temp; } @Override public Host getHost(String hostId) { return hosts.get(hostId); } @Override public void saveHost(Host host) { hosts.put(host.getHostId(), host); } @Override public void updateHost(Host host) { hosts.put(host.getHostId(), host); } @Override public void deleteHost(String hostId) { hosts.remove(hostId); } @Override public List<Vip> getVips(String serviceId) { List<Vip> temp = new LinkedList<>(); for (Vip vip : vips.values()) { if (vip.getServiceId().equals(serviceId)) { temp.add(vip); } } Collections.sort(temp); return temp; } @Override public Vip getVip(String vipId) { return vips.get(vipId); } @Override public void saveVip(Vip vip) { vips.put(vip.getVipId(), vip); } @Override public void updateVip(Vip vip){ vips.put(vip.getVipId(), vip); } @Override public void deleteVip(String vipId) { vips.remove(vipId); } @Override public List<ServiceRef> getServiceRefs() { return serviceRefs; } @Override public List<ServiceRef> getServiceRefsByClient(String clientServiceId) { List<ServiceRef> temp = new LinkedList<>(); for (ServiceRef serviceRef : serviceRefs) { if (serviceRef.getClientServiceId().equals(clientServiceId)) { temp.add(serviceRef); } } return temp; } @Override public List<ServiceRef> getServiceRefsByServer(String serverServiceId) { List<ServiceRef> temp = new LinkedList<>(); for (ServiceRef serviceRef : serviceRefs) { if (serviceRef.getServerServiceId().equals(serverServiceId)) { temp.add(serviceRef); } } return temp; } @Override public void saveServiceRef(ServiceRef serviceRef) { serviceRefs.add(serviceRef); } @Override public List<VipRef> getVipRefsByHost(String hostId) { List<VipRef> temp = new LinkedList<>(); for (VipRef vipRef : vipRefs) { if (vipRef.getHostId().equals(hostId)) { temp.add(vipRef); } } return temp; } @Override public List<VipRef> getVipRefsByVip(String vipId) { List<VipRef> temp = new LinkedList<>(); for (VipRef vipRef : vipRefs) { if (vipRef.getVipId().equals(vipId)) { temp.add(vipRef); } } return temp; } @Override public VipRef getVipRef(String hostId, String vipId) { for (VipRef vipRef : vipRefs) { if (vipRef.getHostId().equals(hostId) && vipRef.getVipId().equals(vipId)) { return vipRef; } } return null; } @Override public void saveVipRef(VipRef vipRef) { for (VipRef temp : vipRefs) { if (temp.getVipId().equals(vipRef.getVipId()) && temp.getHostId().equals(vipRef.getHostId())) { return; } } vipRefs.add(vipRef); } @Override public void updateVipRef(VipRef vipRef) { for (VipRef temp : vipRefs) { if (temp.getVipId().equals(vipRef.getVipId()) && temp.getHostId().equals(vipRef.getHostId())) { temp.setStatus(vipRef.getStatus()); return; } } } @Override public void deleteVipRef(final String hostId, final String vipId) { vipRefs.removeIf(new Predicate<VipRef>() { @Override public boolean test(VipRef ref) { return ref.getHostId().equals(hostId) && ref.getVipId().equals(vipId); } }); } @Override public void deleteVipRefs(final String vipId) { vipRefs.removeIf(new Predicate<VipRef>() { @Override public boolean test(VipRef ref) { return ref.getVipId().equals(vipId); } }); } @Override public List<DataStore> getDataStores(String teamId) { List<DataStore> temp = new LinkedList<>(); for (DataStore dataStore : dataStores) { if (dataStore.getTeamId().equals(teamId)) { temp.add(dataStore); } } Collections.sort(temp); return temp; } @Override public DataStore getDataStore(String dataStoreId) { for (DataStore dataStore : dataStores) { if (dataStore.getDataStoreId().equals(dataStoreId)) { return dataStore; } } return null; } @Override public void saveDataStore(DataStore dataStore) { dataStores.add(dataStore); } @Override public void saveWorkItem(WorkItem workItem) { workItems.put(workItem.getId(), workItem); } @Override public WorkItem getWorkItem(String id) { return workItems.get(id); } }
remove service uses ref
src/main/java/com/northernwall/hadrian/db/InMemoryDataAccess.java
remove service uses ref
<ide><path>rc/main/java/com/northernwall/hadrian/db/InMemoryDataAccess.java <ide> } <ide> <ide> @Override <add> public void deleteServiceRef(final String clientId, final String serviceId) { <add> serviceRefs.removeIf(new Predicate<ServiceRef>() { <add> @Override <add> public boolean test(ServiceRef t) { <add> return t.getClientServiceId().equals(clientId) && t.getServerServiceId().equals(serviceId); <add> } <add> }); <add> } <add> <add> @Override <ide> public List<VipRef> getVipRefsByHost(String hostId) { <ide> List<VipRef> temp = new LinkedList<>(); <ide> for (VipRef vipRef : vipRefs) {
Java
lgpl-2.1
8d24e077f3b3619791ed2ec994a9c442be7899f5
0
xph906/SootNew,anddann/soot,cfallin/soot,anddann/soot,cfallin/soot,mbenz89/soot,mbenz89/soot,xph906/SootNew,plast-lab/soot,xph906/SootNew,cfallin/soot,anddann/soot,mbenz89/soot,cfallin/soot,mbenz89/soot,plast-lab/soot,anddann/soot,plast-lab/soot,xph906/SootNew
package soot.toDex; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; import org.jf.dexlib.AnnotationDirectoryItem; import org.jf.dexlib.AnnotationDirectoryItem.FieldAnnotation; import org.jf.dexlib.AnnotationDirectoryItem.MethodAnnotation; import org.jf.dexlib.AnnotationDirectoryItem.ParameterAnnotation; import org.jf.dexlib.AnnotationItem; import org.jf.dexlib.AnnotationSetItem; import org.jf.dexlib.AnnotationSetRefList; import org.jf.dexlib.AnnotationVisibility; import org.jf.dexlib.ClassDataItem; import org.jf.dexlib.DexFile; import org.jf.dexlib.FieldIdItem; import org.jf.dexlib.MethodIdItem; import org.jf.dexlib.ProtoIdItem; import org.jf.dexlib.StringIdItem; import org.jf.dexlib.TypeIdItem; import org.jf.dexlib.TypeListItem; import org.jf.dexlib.EncodedValue.AnnotationEncodedSubValue; import org.jf.dexlib.EncodedValue.AnnotationEncodedValue; import org.jf.dexlib.EncodedValue.ArrayEncodedValue; import org.jf.dexlib.EncodedValue.BooleanEncodedValue; import org.jf.dexlib.EncodedValue.ByteEncodedValue; import org.jf.dexlib.EncodedValue.CharEncodedValue; import org.jf.dexlib.EncodedValue.DoubleEncodedValue; import org.jf.dexlib.EncodedValue.EncodedValue; import org.jf.dexlib.EncodedValue.EnumEncodedValue; import org.jf.dexlib.EncodedValue.FieldEncodedValue; import org.jf.dexlib.EncodedValue.FloatEncodedValue; import org.jf.dexlib.EncodedValue.IntEncodedValue; import org.jf.dexlib.EncodedValue.LongEncodedValue; import org.jf.dexlib.EncodedValue.MethodEncodedValue; import org.jf.dexlib.EncodedValue.NullEncodedValue; import org.jf.dexlib.EncodedValue.ShortEncodedValue; import org.jf.dexlib.EncodedValue.StringEncodedValue; import org.jf.dexlib.EncodedValue.TypeEncodedValue; import soot.G; import soot.SootClass; import soot.SootField; import soot.SootMethod; import soot.dexpler.DexType; import soot.dexpler.Util; import soot.options.Options; import soot.tagkit.AnnotationAnnotationElem; import soot.tagkit.AnnotationArrayElem; import soot.tagkit.AnnotationBooleanElem; import soot.tagkit.AnnotationClassElem; import soot.tagkit.AnnotationConstants; import soot.tagkit.AnnotationDoubleElem; import soot.tagkit.AnnotationElem; import soot.tagkit.AnnotationEnumElem; import soot.tagkit.AnnotationFloatElem; import soot.tagkit.AnnotationIntElem; import soot.tagkit.AnnotationLongElem; import soot.tagkit.AnnotationStringElem; import soot.tagkit.AnnotationTag; import soot.tagkit.EnclosingMethodTag; import soot.tagkit.InnerClassAttribute; import soot.tagkit.InnerClassTag; import soot.tagkit.SignatureTag; import soot.tagkit.Tag; import soot.tagkit.VisibilityAnnotationTag; import soot.tagkit.VisibilityParameterAnnotationTag; /** * Class to generate Dexlib Annotations from Jimple Annotations * @author alex * */ public class DexAnnotation { DexFile dexFile = null; SootClass currentClass = null; List<AnnotationItem> classAnnotationItems = new ArrayList<AnnotationItem>(); AnnotationSetItem classAnnotations = null; List<FieldAnnotation> fieldAnnotations = null; List<MethodAnnotation> methodAnnotations = null; List<ParameterAnnotation> parameterAnnotations = null; public DexAnnotation(DexFile dexFile, SootClass sc) { this.dexFile = dexFile; this.currentClass = sc; //classAnnotations = new AnnotationSetItem; fieldAnnotations = new ArrayList<FieldAnnotation>(); methodAnnotations = new ArrayList<MethodAnnotation>(); parameterAnnotations = new ArrayList<ParameterAnnotation>(); } /** * Add Annotation Directory to the Dexlib's representation of the target .dex file * @return */ public AnnotationDirectoryItem finish() { classAnnotations = AnnotationSetItem.internAnnotationSetItem(dexFile, classAnnotationItems); Debug.printDbg("add ", classAnnotations.getAnnotations().length , " class annotations, " , fieldAnnotations.size() ," field annotations " , methodAnnotations.size() , " method annotations " , parameterAnnotations.size() , " parameters annotations."); AnnotationDirectoryItem di = AnnotationDirectoryItem.internAnnotationDirectoryItem(dexFile, classAnnotations, fieldAnnotations, methodAnnotations, parameterAnnotations); return di; } /** * Handle Class Annotations * @param c SootClass * @param citem Dexlib class item */ // .annotation "Ldalvik/annotation/AnnotationDefault;" // .annotation "Ldalvik/annotation/EnclosingClass;" // .annotation "Ldalvik/annotation/EnclosingMethod;" // .annotation "Ldalvik/annotation/InnerClass;" // .annotation "Ldalvik/annotation/MemberClasses;" // .annotation "Ldalvik/annotation/Signature;" // .annotation "Ldalvik/annotation/Throws;" public void handleClass(SootClass c, ClassDataItem citem) { Debug.printDbg("1"); // handle inner class tags if (c.hasTag("InnerClassAttribute") && !Options.v().no_output_inner_classes_attribute()){ InnerClassTag innerClass = null; List<InnerClassTag> memberClasses = new ArrayList<InnerClassTag>(); InnerClassAttribute innerClassAttribute = (InnerClassAttribute) c.getTag("InnerClassAttribute"); Debug.printDbg("has tag: class attribute"); // separate inner class from member classes for (Tag t : innerClassAttribute.getSpecs()){ Debug.printDbg("t: ", t); InnerClassTag tag = (InnerClassTag) t; String innerC = tag.getInnerClass(); String innerCSootFormat = innerC.replaceAll("/", "\\."); Debug.printDbg("innercc: ", innerCSootFormat); if (innerCSootFormat.equals(c.toString())) { if (innerClass != null) G.v().out.println("warning: multiple inner class tags!"); innerClass = tag; } else { Debug.printDbg("1 add ", tag); memberClasses.add(tag); } } // inner class if (innerClass != null) { // enclosing class AnnotationItem enclosingItem = makeEnclosingClassAnnotation(innerClass); classAnnotationItems.add(enclosingItem); // inner class AnnotationItem innerItem = makeInnerClassAnnotation(innerClass); classAnnotationItems.add(innerItem); } // member classes if (memberClasses.size() > 0) { Debug.printDbg("here:"); AnnotationItem memberItem = makeMemberClasses(memberClasses); classAnnotationItems.add(memberItem); } } // handle enclosing method tags if (c.hasTag("EnclosingMethodTag")){ EnclosingMethodTag eMethTag = (EnclosingMethodTag)c.getTag("EnclosingMethodTag"); AnnotationItem enclosingMethodItem = makeEnclosingMethod(eMethTag); if (enclosingMethodItem != null) classAnnotationItems.add(enclosingMethodItem); } // handle deprecated tag if (c.hasTag("DeprecatedTag")){ AnnotationItem deprecatedItem = makeDeprecatedItem(); classAnnotationItems.add(deprecatedItem); } // handle visibility annotation tags for (Tag t : c.getTags()){ if (t.getName().equals("VisibilityAnnotationTag")){ Debug.printDbg("class visibility annotation tag: ", t); List<AnnotationItem> visibilityItems = makeVisibilityItem(t); for (AnnotationItem i : visibilityItems) classAnnotationItems.add(i); } } // Debug.printDbg("\n tag: ", t.getName()); // // List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>(); // List<StringIdItem> namesList = new ArrayList<StringIdItem>(); // // VisibilityAnnotationTag vat = (VisibilityAnnotationTag)t; // List<AnnotationTag> atList = vat.getAnnotations(); // for (AnnotationTag at: atList) { // Debug.printDbg("annotation tag name: ", at.getName(), " class: ", at.getClass()); // //String type = soot2DalvikType(at.getType()); // String type = at.getType(); // Debug.printDbg("tag type: ", type); // // for (AnnotationElem ae : at.getElems()) { // EncodedValue value = getAnnotationElement(ae); // encodedValueList.add(value); // namesList.add(StringIdItem.internStringIdItem(dexFile, ae.getName())); // Debug.printDbg("new class annotation: ", value ," ", ae.getName() ," ", at.getName() ," ", ae.getClass()); // } // // TypeIdItem annotationType = TypeIdItem.internTypeIdItem(dexFile, type); // StringIdItem[] names = namesList.toArray(new StringIdItem[namesList.size()]); // EncodedValue[] values = encodedValueList.toArray(new EncodedValue[encodedValueList.size()]); // AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue(annotationType, names, values); // AnnotationItem aItem = AnnotationItem.internAnnotationItem(dexFile, getVisibility(vat.getVisibility()), annotationValue); // classAnnotationItems.add(aItem); // } // // } } /** * Handle Field Annotations * @param sf SootField * @param fid DexLib Field */ private Set<String> alreadyDone = new HashSet<String>(); public void handleField(SootField sf, FieldIdItem fid) { if (!sf.getDeclaringClass().getName().equals(currentClass.getName())) return; if (alreadyDone.contains(sf.getSignature())) return; alreadyDone.add(sf.getSignature()); Debug.printDbg("handle annotations for field: '", sf ,"' current class: ", currentClass); List<AnnotationItem> aList = new ArrayList<AnnotationItem>(); // handle deprecated tag if (sf.hasTag("DeprecatedTag")){ AnnotationItem deprecatedItem = makeDeprecatedItem(); aList.add(deprecatedItem); } // handle signature tag if (sf.hasTag("SignatureTag")){ SignatureTag tag = (SignatureTag)sf.getTag("SignatureTag"); AnnotationItem deprecatedItem = makeSignatureItem(tag); aList.add(deprecatedItem); } // handle visibility annotation tags for (Tag t : sf.getTags()){ if (t.getName().equals("VisibilityAnnotationTag")){ Debug.printDbg("field visibility annotation tag: ", t); List<AnnotationItem> visibilityItems = makeVisibilityItem(t); for (AnnotationItem ai : visibilityItems) aList.add(ai); } } // // handle constant tag // int cst = 0; // for (Tag t : sf.getTags()) { // if (t instanceof ConstantValueTag) { // cst++; // if (cst > 1) // G.v().out.println("warning: more than one constant tag for field: "+ sf); // AnnotationItem ai = makeConstantItem(t); // aList.add(ai); // } // } AnnotationSetItem set = AnnotationSetItem.internAnnotationSetItem(dexFile, aList); FieldAnnotation fa = new FieldAnnotation(fid, set); fieldAnnotations.add(fa); } private Set<SootMethod> alreadyDoneMethods = new HashSet<SootMethod>(); /** * Handles Method and Parameter Annotations * @param sm SootMethod * @param mid Dexlib Method Item */ public void handleMethod(SootMethod sm, MethodIdItem mid) { if (!sm.getDeclaringClass().getName().equals(currentClass.getName())) return; if (!alreadyDoneMethods.add(sm)) return; Debug.printDbg("handle annotations for method: '", sm ,"' current class: ", currentClass); List<AnnotationItem> aList = new ArrayList<AnnotationItem>(); List<AnnotationSetItem> setList = new ArrayList<AnnotationSetItem>(); Set<String> skipList = new HashSet<String>(); if (sm.hasTag("DeprecatedTag")){ AnnotationItem deprecatedItem = makeDeprecatedItem(); aList.add(deprecatedItem); skipList.add("Ljava/lang/Deprecated;"); } if (sm.hasTag("SignatureTag")){ SignatureTag tag = (SignatureTag)sm.getTag("SignatureTag"); AnnotationItem signatureItem = makeSignatureItem(tag); aList.add(signatureItem); skipList.add("Ldalvik/annotation/Signature;"); } if (sm.hasTag("AnnotationDefaultTag")){ // AnnotationDefaultTag tag = (AnnotationDefaultTag)sm.getTag("AnnotationDefaultTag"); Debug.printDbg("TODO"); } for (Tag t : sm.getTags()) { if (t.getName().equals("VisibilityAnnotationTag")){ VisibilityAnnotationTag vat = (VisibilityAnnotationTag)t; aList.addAll(handleMethodTag(vat, mid, skipList)); } if (t.getName().equals("VisibilityParameterAnnotationTag")){ VisibilityParameterAnnotationTag vat = (VisibilityParameterAnnotationTag)t; setList.addAll(handleMethodParamTag(vat, mid, Collections.<String>emptySet())); } } // Sort the annotation list Collections.sort(aList, new Comparator<AnnotationItem>() { @Override public int compare(AnnotationItem o1, AnnotationItem o2) { int idx1 = o1.getEncodedAnnotation().annotationType.getIndex(); int idx2 = o2.getEncodedAnnotation().annotationType.getIndex(); int res = idx1 - idx2; // Check that our generated APK file will not be broken if (res == 0 && !(idx1 == -1 && idx2 == -1)) throw new RuntimeException("Duplicate annotation type:" + o1); if (o1.getEncodedAnnotation().annotationType.getTypeDescriptor().equals (o2.getEncodedAnnotation().annotationType.getTypeDescriptor())) throw new RuntimeException("Duplicate annotation type:" + o1); return res; } }); AnnotationSetItem set = AnnotationSetItem.internAnnotationSetItem(dexFile, aList); MethodAnnotation ma = new MethodAnnotation(mid, set); methodAnnotations.add(ma); AnnotationSetRefList asrList = AnnotationSetRefList.internAnnotationSetRefList(dexFile, setList); ParameterAnnotation pa = new ParameterAnnotation(mid, asrList); parameterAnnotations.add(pa); } /** * Handle Method Annotations * @param vat * @param mid * @return */ private List<AnnotationItem> handleMethodTag(VisibilityAnnotationTag vat, MethodIdItem mid, Set<String> skipList) { List<AnnotationTag> atList = vat.getAnnotations(); List<AnnotationItem> aList = new ArrayList<AnnotationItem>(); for (AnnotationTag at: atList) { //String type = soot2DalvikType(at.getType()); String type = at.getType(); if (skipList.contains(type)) continue; List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>(); List<StringIdItem> namesList = new ArrayList<StringIdItem>(); for (AnnotationElem ae : at.getElems()) { EncodedValue value = getAnnotationElement(ae); encodedValueList.add(value); namesList.add(StringIdItem.internStringIdItem(dexFile, ae.getName())); Debug.printDbg("new method annotation: ", value ," ", ae.getName()); } TypeIdItem annotationType = TypeIdItem.internTypeIdItem(dexFile, type); StringIdItem[] names = namesList.toArray(new StringIdItem[namesList.size()]); EncodedValue[] values = encodedValueList.toArray(new EncodedValue[encodedValueList.size()]); AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue(annotationType, names, values); AnnotationItem a = AnnotationItem.internAnnotationItem(dexFile, getVisibility(vat.getVisibility()), annotationValue); aList.add(a); } return aList; } /** * Handle (Method) Parameter Annotations * @param vat1 * @param mid * @return */ private List<AnnotationSetItem> handleMethodParamTag(VisibilityParameterAnnotationTag vat1, MethodIdItem mid, Set<String> skipList) { List<VisibilityAnnotationTag> vatList = vat1.getVisibilityAnnotations(); if (vatList == null) return Collections.emptyList(); List<AnnotationSetItem> setList = new ArrayList<AnnotationSetItem>(); for (VisibilityAnnotationTag vat: vatList) { if (vat == null) continue; List<AnnotationItem> aList = new ArrayList<AnnotationItem>(); if (vat.getAnnotations() != null) for (AnnotationTag at: vat.getAnnotations()) { List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>(); List<StringIdItem> namesList = new ArrayList<StringIdItem>(); for (AnnotationElem ae : at.getElems()) { EncodedValue value = getAnnotationElement(ae); encodedValueList.add(value); namesList.add(StringIdItem.internStringIdItem(dexFile, ae.getName())); Debug.printDbg("new annotation: ", value ," ", ae.getName()); } //String type = soot2DalvikType(at.getType()); String type = at.getType(); if (skipList.contains(type)) continue; TypeIdItem annotationType = TypeIdItem.internTypeIdItem(dexFile, type); StringIdItem[] names = namesList.toArray(new StringIdItem[namesList.size()]); EncodedValue[] values = encodedValueList.toArray(new EncodedValue[encodedValueList.size()]); AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue(annotationType, names, values); AnnotationItem a = AnnotationItem.internAnnotationItem(dexFile, getVisibility(vat.getVisibility()), annotationValue); aList.add(a); } AnnotationSetItem annotationSets = AnnotationSetItem.internAnnotationSetItem(dexFile, aList); setList.add(annotationSets); } return setList; } /** * Encodes Annotations Elements from Jimple to Dexlib * @param elem Jimple Element * @return Dexlib encoded element */ private EncodedValue getAnnotationElement(AnnotationElem elem){ EncodedValue v = null; Debug.printDbg("annotation kind: ", elem.getKind()); switch (elem.getKind()) { case 'Z': { if (elem instanceof AnnotationIntElem) { AnnotationIntElem e = (AnnotationIntElem)elem; if (e.getValue() == 0) { v = BooleanEncodedValue.FalseValue; } else if (e.getValue() == 1) { v = BooleanEncodedValue.TrueValue; } else { throw new RuntimeException("error: boolean value from int with value != 0 or 1."); } } else if (elem instanceof AnnotationBooleanElem) { AnnotationBooleanElem e = (AnnotationBooleanElem) elem; if (e.getValue()) v = BooleanEncodedValue.TrueValue; else v = BooleanEncodedValue.FalseValue; } else throw new RuntimeException("Annotation type incompatible with target type boolean"); break; } case 'S': { AnnotationIntElem e = (AnnotationIntElem)elem; ShortEncodedValue a = new ShortEncodedValue((short)e.getValue()); v = a; break; } case 'B': { AnnotationIntElem e = (AnnotationIntElem)elem; ByteEncodedValue a = new ByteEncodedValue((byte)e.getValue()); v = a; break; } case 'C': { AnnotationIntElem e = (AnnotationIntElem)elem; CharEncodedValue a = new CharEncodedValue((char)e.getValue()); v = a; break; } case 'I': { AnnotationIntElem e = (AnnotationIntElem)elem; IntEncodedValue a = new IntEncodedValue(e.getValue()); v = a; break; } case 'J': { AnnotationLongElem e = (AnnotationLongElem)elem; LongEncodedValue a = new LongEncodedValue(e.getValue()); v = a; break; } case 'F': { AnnotationFloatElem e = (AnnotationFloatElem)elem; FloatEncodedValue a = new FloatEncodedValue(e.getValue()); v = a; break; } case 'D': { AnnotationDoubleElem e = (AnnotationDoubleElem)elem; DoubleEncodedValue a = new DoubleEncodedValue(e.getValue()); v = a; break; } case 's': { AnnotationStringElem e = (AnnotationStringElem)elem; StringIdItem string = StringIdItem.internStringIdItem(dexFile, e.getValue()); StringEncodedValue a = new StringEncodedValue(string); v = a; break; } case 'e': { AnnotationEnumElem e = (AnnotationEnumElem)elem; String classT = soot2DalvikType(e.getTypeName()); String fieldT = soot2DalvikType(e.getTypeName()); String fieldNameString = e.getName(); TypeIdItem classType = TypeIdItem.internTypeIdItem(dexFile, classT); TypeIdItem fieldType = TypeIdItem.internTypeIdItem(dexFile, fieldT); StringIdItem fieldName = StringIdItem.internStringIdItem(dexFile, fieldNameString); FieldIdItem fId = FieldIdItem.internFieldIdItem(dexFile, classType, fieldType, fieldName); EnumEncodedValue a = new EnumEncodedValue(fId); v = a; break; } case 'c': { AnnotationClassElem e = (AnnotationClassElem)elem; String type = soot2DalvikType(e.getDesc()); StringIdItem strId = StringIdItem.internStringIdItem(dexFile, type); TypeIdItem typeId = TypeIdItem.internTypeIdItem(dexFile, strId); TypeEncodedValue a = new TypeEncodedValue(typeId); v = a; break; } case '[': { AnnotationArrayElem e = (AnnotationArrayElem)elem; List<EncodedValue> valueList = new ArrayList<EncodedValue>(); for (int i = 0; i < e.getNumValues(); i++){ EncodedValue val = getAnnotationElement(e.getValueAt(i)); valueList.add(val); } ArrayEncodedValue a = new ArrayEncodedValue(valueList.toArray( new EncodedValue[valueList.size()])); v = a; break; } case '@': { AnnotationAnnotationElem e = (AnnotationAnnotationElem)elem; List<StringIdItem> nameList = new ArrayList<StringIdItem>(); List<EncodedValue> valueList = new ArrayList<EncodedValue>(); for (AnnotationElem ae : e.getValue().getElems()){ EncodedValue val = getAnnotationElement(ae); valueList.add(val); nameList.add(StringIdItem.internStringIdItem(dexFile, ae.getName())); } //String type = soot2DalvikType(e.getValue().getType()); String type = e.getValue().getType(); TypeIdItem annotationType = TypeIdItem.internTypeIdItem(dexFile, type); StringIdItem[] names = nameList.toArray(new StringIdItem[nameList.size()]); EncodedValue[] values = valueList.toArray(new EncodedValue[valueList.size()]); AnnotationEncodedValue a = new AnnotationEncodedValue(annotationType, names, values); v = a; break; } case 'f': { // field (Dalvik specific?) AnnotationStringElem e = (AnnotationStringElem)elem; String fSig = e.getValue(); String[] sp = fSig.split(" "); String classString = soot2DalvikType(sp[0].split(":")[0]); String typeString = soot2DalvikType(sp[1]); String fieldName = sp[2]; StringIdItem ctypeDescriptor = StringIdItem.internStringIdItem(dexFile, classString); StringIdItem ftypeDescriptor = StringIdItem.internStringIdItem(dexFile, typeString); StringIdItem fieldNameItem = StringIdItem.internStringIdItem(dexFile, fieldName); Debug.printDbg("field item: ", classString ," ", typeString, " ", fieldName); TypeIdItem classType = TypeIdItem.internTypeIdItem(dexFile, ctypeDescriptor); TypeIdItem fieldType = TypeIdItem.internTypeIdItem(dexFile, ftypeDescriptor); FieldIdItem fId = FieldIdItem.internFieldIdItem(dexFile, classType, fieldType, fieldNameItem); FieldEncodedValue a = new FieldEncodedValue(fId); v = a; break; } case 'M': { // method (Dalvik specific?) AnnotationStringElem e = (AnnotationStringElem)elem; String mSig = e.getValue(); Debug.printDbg("msig: ", mSig); // String[] sp = mSig.split(" "); String classString = soot2DalvikType(sp[0].split(":")[0]); String returnType = soot2DalvikType(sp[1]); String[] sp2 = sp[2].split("\\("); String methodNameString = sp2[0]; String parameters = sp2[1].replaceAll("\\)", ""); Debug.printDbg("parameters: '", parameters ,"'"); List<String> paramTypeList = new ArrayList<String>(); if (parameters.length() > 0) for (String p: parameters.split(",")) { String type = soot2DalvikType(p); paramTypeList.add(type); } // StringIdItem ctypeDescriptor = StringIdItem.internStringIdItem(dexFile, classString); StringIdItem returnDescriptor = StringIdItem.internStringIdItem(dexFile, returnType); List<TypeIdItem> parametersItemList = new ArrayList<TypeIdItem>(); for (String p: paramTypeList) { StringIdItem t = StringIdItem.internStringIdItem(dexFile, p); parametersItemList.add(TypeIdItem.internTypeIdItem(dexFile, t)); } // TypeIdItem classType = TypeIdItem.internTypeIdItem(dexFile, ctypeDescriptor); TypeIdItem returnTypeItem = TypeIdItem.internTypeIdItem(dexFile, returnDescriptor); TypeListItem parametersItem = TypeListItem.internTypeListItem(dexFile, parametersItemList); ProtoIdItem methodPrototype = ProtoIdItem.internProtoIdItem(dexFile, returnTypeItem, parametersItem); StringIdItem methodName = StringIdItem.internStringIdItem(dexFile, methodNameString); MethodIdItem mId = MethodIdItem.internMethodIdItem(dexFile, classType, methodPrototype, methodName); MethodEncodedValue a = new MethodEncodedValue(mId); v = a; break; } case 'N': { // null (Dalvik specific?) NullEncodedValue a = NullEncodedValue.NullValue; v = a; break; } default : { throw new RuntimeException("Unknown Elem Attr Kind: "+elem.getKind()); } } return v; } private AnnotationItem makeEnclosingClassAnnotation(InnerClassTag tag) { String outerClass = tag.getOuterClass(); TypeIdItem string = TypeIdItem.internTypeIdItem(dexFile, "L" + outerClass + ";"); TypeEncodedValue a = new TypeEncodedValue(string); TypeIdItem annotationType = TypeIdItem.internTypeIdItem( dexFile, "Ldalvik/annotation/EnclosingClass;"); List<StringIdItem> namesList = new ArrayList<StringIdItem>(); List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>(); namesList.add(StringIdItem.internStringIdItem(dexFile, "value")); encodedValueList.add(a); StringIdItem[] names = namesList.toArray( new StringIdItem[namesList.size()]); EncodedValue[] values = encodedValueList.toArray( new EncodedValue[encodedValueList.size()]); AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue( annotationType, names, values); AnnotationItem aItem = AnnotationItem.internAnnotationItem( dexFile, AnnotationVisibility.SYSTEM, annotationValue); return aItem; } private AnnotationItem makeInnerClassAnnotation(InnerClassTag tag) { IntEncodedValue flags = new IntEncodedValue(tag.getAccessFlags()); TypeIdItem annotationType = TypeIdItem.internTypeIdItem( dexFile, "Ldalvik/annotation/InnerClass;"); List<StringIdItem> namesList = new ArrayList<StringIdItem>(); List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>(); namesList.add(StringIdItem.internStringIdItem(dexFile, "accessFlags")); encodedValueList.add(flags); if (tag.getShortName() != null) { StringIdItem nameId = StringIdItem.internStringIdItem(dexFile, tag.getShortName()); StringEncodedValue nameV = new StringEncodedValue(nameId); namesList.add(StringIdItem.internStringIdItem(dexFile, "name")); encodedValueList.add(nameV); } StringIdItem[] names = namesList.toArray( new StringIdItem[namesList.size()]); EncodedValue[] values = encodedValueList.toArray( new EncodedValue[encodedValueList.size()]); AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue( annotationType, names, values); AnnotationItem aItem = AnnotationItem.internAnnotationItem( dexFile, AnnotationVisibility.SYSTEM, annotationValue); return aItem; } private AnnotationItem makeMemberClasses(List<InnerClassTag> tags) { TypeIdItem annotationType = TypeIdItem.internTypeIdItem( dexFile, "Ldalvik/annotation/MemberClasses;"); List<StringIdItem> namesList = new ArrayList<StringIdItem>(); List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>(); namesList.add(StringIdItem.internStringIdItem(dexFile, "value")); List<EncodedValue> valueList = new ArrayList<EncodedValue>(); for (InnerClassTag t : tags) { TypeIdItem memberType = TypeIdItem.internTypeIdItem(dexFile, "L" + t.getInnerClass() + ";"); TypeEncodedValue memberEv = new TypeEncodedValue(memberType); valueList.add(memberEv); } ArrayEncodedValue a = new ArrayEncodedValue(valueList.toArray( new EncodedValue[valueList.size()])); encodedValueList.add(a); StringIdItem[] names = namesList.toArray( new StringIdItem[namesList.size()]); EncodedValue[] values = encodedValueList.toArray( new EncodedValue[encodedValueList.size()]); AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue( annotationType, names, values); AnnotationItem aItem = AnnotationItem.internAnnotationItem( dexFile, AnnotationVisibility.SYSTEM, annotationValue); return aItem; } private AnnotationItem makeEnclosingMethod(EnclosingMethodTag tag) { TypeIdItem annotationType = TypeIdItem.internTypeIdItem( dexFile, "Ldalvik/annotation/EnclosingMethod;"); String enclosingClass = DexType.toDalvikICAT(tag.getEnclosingClass()); TypeIdItem classType = TypeIdItem.internTypeIdItem(dexFile, enclosingClass); String enclosingMethod = tag.getEnclosingMethod(); String methodSig = tag.getEnclosingMethodSig(); // Sometimes we don't have an enclosing method if (methodSig == null || methodSig.isEmpty()) return null; String[] split1 = methodSig.split("\\)"); String parametersS = split1[0].replaceAll("\\(", ""); String returnTypeS = split1[1]; TypeIdItem returnType = TypeIdItem.internTypeIdItem(dexFile, returnTypeS); List<TypeIdItem> typeList = new ArrayList<TypeIdItem>(); Debug.printDbg("parameters:", parametersS); if (!parametersS.equals("")) { for (String p : Util.splitParameters(parametersS)) { if (p.equals("")) continue; Debug.printDbg("parametr: ", p); TypeIdItem i = TypeIdItem.internTypeIdItem(dexFile, p); typeList.add(i); } } TypeListItem parameters = TypeListItem.internTypeListItem(dexFile, typeList); ProtoIdItem methodPrototype = ProtoIdItem.internProtoIdItem(dexFile, returnType, parameters); StringIdItem methodName = StringIdItem.internStringIdItem(dexFile, enclosingMethod); MethodIdItem methodId = MethodIdItem.internMethodIdItem(dexFile, classType, methodPrototype, methodName); MethodEncodedValue a = new MethodEncodedValue(methodId); List<StringIdItem> namesList = new ArrayList<StringIdItem>(); List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>(); namesList.add(StringIdItem.internStringIdItem(dexFile, "value")); encodedValueList.add(a); StringIdItem[] names = namesList.toArray( new StringIdItem[namesList.size()]); EncodedValue[] values = encodedValueList.toArray( new EncodedValue[encodedValueList.size()]); AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue( annotationType, names, values); AnnotationItem aItem = AnnotationItem.internAnnotationItem( dexFile, AnnotationVisibility.SYSTEM, annotationValue); return aItem; } private AnnotationItem makeDeprecatedItem() { TypeIdItem annotationType = TypeIdItem.internTypeIdItem( dexFile, "Ljava/lang/Deprecated;"); List<StringIdItem> namesList = new ArrayList<StringIdItem>(); List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>();; StringIdItem[] names = namesList.toArray( new StringIdItem[namesList.size()]); EncodedValue[] values = encodedValueList.toArray( new EncodedValue[encodedValueList.size()]); AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue( annotationType, names, values); AnnotationItem aItem = AnnotationItem.internAnnotationItem( dexFile, AnnotationVisibility.SYSTEM, annotationValue); return aItem; } private AnnotationItem makeSignatureItem(SignatureTag t) { TypeIdItem annotationType = TypeIdItem.internTypeIdItem( dexFile, "Ldalvik/annotation/Signature;"); List<StringIdItem> namesList = new ArrayList<StringIdItem>(); List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>(); namesList.add(StringIdItem.internStringIdItem(dexFile, "value")); List<EncodedValue> valueList = new ArrayList<EncodedValue>(); for (String s : t.getSignature().split(" ")) { StringIdItem member = StringIdItem.internStringIdItem(dexFile, s); StringEncodedValue memberEv = new StringEncodedValue(member); //TypeEncodedValue memberEv = new TypeEncodedValue(memberType); valueList.add(memberEv); } ArrayEncodedValue a = new ArrayEncodedValue(valueList.toArray( new EncodedValue[valueList.size()])); encodedValueList.add(a); StringIdItem[] names = namesList.toArray( new StringIdItem[namesList.size()]); EncodedValue[] values = encodedValueList.toArray( new EncodedValue[encodedValueList.size()]); AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue( annotationType, names, values); AnnotationItem aItem = AnnotationItem.internAnnotationItem( dexFile, AnnotationVisibility.SYSTEM, annotationValue); return aItem; } private List<AnnotationItem> makeVisibilityItem(Tag t) { List<AnnotationItem> aList = new ArrayList<AnnotationItem>(); if (!(t instanceof VisibilityAnnotationTag)) return aList; VisibilityAnnotationTag vat = (VisibilityAnnotationTag)t; List<AnnotationTag> atList = vat.getAnnotations(); for (AnnotationTag at: atList) { List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>(); List<StringIdItem> namesList = new ArrayList<StringIdItem>(); for (AnnotationElem ae : at.getElems()) { EncodedValue value = getAnnotationElement(ae); encodedValueList.add(value); namesList.add(StringIdItem.internStringIdItem(dexFile, ae.getName())); Debug.printDbg("new annotation: ", value ," ", ae.getName() ," type: ", value.getClass()); } String type = at.getType(); Debug.printDbg(" annotation type: ", type); TypeIdItem annotationType = TypeIdItem.internTypeIdItem(dexFile, type); StringIdItem[] names = namesList.toArray(new StringIdItem[namesList.size()]); EncodedValue[] values = encodedValueList.toArray(new EncodedValue[encodedValueList.size()]); AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue(annotationType, names, values); AnnotationItem a = AnnotationItem.internAnnotationItem(dexFile, getVisibility(vat.getVisibility()), annotationValue); aList.add(a); } return aList; } // private AnnotationItem makeConstantItem(Tag t) { // if (!(t instanceof ConstantValueTag)) // throw new RuntimeException("error: t not ConstantValueTag."); // return null; // } /** * Converts type such as "a.b.c[][]" to "[[a/b/c". * * @param sootType Soot type to convert to Dexlib type. * @return String representation of the Dexlib type */ public static String soot2DalvikType(String sootType) { return sootType; // if (sootType.startsWith("L") || sootType.startsWith("[")) { // throw new RuntimeException("error: wrong type format: "+ sootType); // } // // int arraySize = 0; // while (sootType.endsWith("[]")) { // arraySize++; // sootType = sootType.replaceFirst("\\[\\]", ""); // } // String type = ""; // if (sootType.equals("int")) { // type = "I"; // } else if (sootType.equals("float")) { // type = "F"; // } else if (sootType.equals("long")) { // type = "J"; // } else if (sootType.equals("double")) { // type = "D"; // } else if (sootType.equals("char")) { // type = "C"; // } else if (sootType.equals("boolean")) { // type = "Z"; // } else if (sootType.equals("byte")) { // type = "B"; // } else if (sootType.equals("void")) { // type = "V"; // } else { // type = "L"+ sootType.replaceAll("\\.", "/") +";"; // } // // if (type.startsWith("LL")) { // throw new RuntimeException("error: wrong type format: "+ type); // } // // for (int i = 0; i< arraySize; i++) // type = "[" + type; // return type; } /** * Converts Jimple visibility to Dexlib visibility * @param visibility Jimple visibility * @return Dexlib visibility */ private static AnnotationVisibility getVisibility(int visibility) { if (visibility == AnnotationConstants.RUNTIME_VISIBLE) // 0 return AnnotationVisibility.RUNTIME; // 1 if (visibility == AnnotationConstants.RUNTIME_INVISIBLE) // 1 return AnnotationVisibility.BUILD; // 0 if (visibility == AnnotationConstants.SOURCE_VISIBLE) // 2 return AnnotationVisibility.SYSTEM; // 2 throw new RuntimeException("Unknown annotation visibility: '"+ visibility +"'"); } }
src/soot/toDex/DexAnnotation.java
package soot.toDex; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; import org.jf.dexlib.AnnotationDirectoryItem; import org.jf.dexlib.AnnotationDirectoryItem.FieldAnnotation; import org.jf.dexlib.AnnotationDirectoryItem.MethodAnnotation; import org.jf.dexlib.AnnotationDirectoryItem.ParameterAnnotation; import org.jf.dexlib.AnnotationItem; import org.jf.dexlib.AnnotationSetItem; import org.jf.dexlib.AnnotationSetRefList; import org.jf.dexlib.AnnotationVisibility; import org.jf.dexlib.ClassDataItem; import org.jf.dexlib.DexFile; import org.jf.dexlib.FieldIdItem; import org.jf.dexlib.MethodIdItem; import org.jf.dexlib.ProtoIdItem; import org.jf.dexlib.StringIdItem; import org.jf.dexlib.TypeIdItem; import org.jf.dexlib.TypeListItem; import org.jf.dexlib.EncodedValue.AnnotationEncodedSubValue; import org.jf.dexlib.EncodedValue.AnnotationEncodedValue; import org.jf.dexlib.EncodedValue.ArrayEncodedValue; import org.jf.dexlib.EncodedValue.BooleanEncodedValue; import org.jf.dexlib.EncodedValue.ByteEncodedValue; import org.jf.dexlib.EncodedValue.CharEncodedValue; import org.jf.dexlib.EncodedValue.DoubleEncodedValue; import org.jf.dexlib.EncodedValue.EncodedValue; import org.jf.dexlib.EncodedValue.EnumEncodedValue; import org.jf.dexlib.EncodedValue.FieldEncodedValue; import org.jf.dexlib.EncodedValue.FloatEncodedValue; import org.jf.dexlib.EncodedValue.IntEncodedValue; import org.jf.dexlib.EncodedValue.LongEncodedValue; import org.jf.dexlib.EncodedValue.MethodEncodedValue; import org.jf.dexlib.EncodedValue.NullEncodedValue; import org.jf.dexlib.EncodedValue.ShortEncodedValue; import org.jf.dexlib.EncodedValue.StringEncodedValue; import org.jf.dexlib.EncodedValue.TypeEncodedValue; import soot.G; import soot.SootClass; import soot.SootField; import soot.SootMethod; import soot.dexpler.DexType; import soot.dexpler.Util; import soot.options.Options; import soot.tagkit.AnnotationAnnotationElem; import soot.tagkit.AnnotationArrayElem; import soot.tagkit.AnnotationBooleanElem; import soot.tagkit.AnnotationClassElem; import soot.tagkit.AnnotationConstants; import soot.tagkit.AnnotationDoubleElem; import soot.tagkit.AnnotationElem; import soot.tagkit.AnnotationEnumElem; import soot.tagkit.AnnotationFloatElem; import soot.tagkit.AnnotationIntElem; import soot.tagkit.AnnotationLongElem; import soot.tagkit.AnnotationStringElem; import soot.tagkit.AnnotationTag; import soot.tagkit.EnclosingMethodTag; import soot.tagkit.InnerClassAttribute; import soot.tagkit.InnerClassTag; import soot.tagkit.SignatureTag; import soot.tagkit.Tag; import soot.tagkit.VisibilityAnnotationTag; import soot.tagkit.VisibilityParameterAnnotationTag; /** * Class to generate Dexlib Annotations from Jimple Annotations * @author alex * */ public class DexAnnotation { DexFile dexFile = null; SootClass currentClass = null; List<AnnotationItem> classAnnotationItems = new ArrayList<AnnotationItem>(); AnnotationSetItem classAnnotations = null; List<FieldAnnotation> fieldAnnotations = null; List<MethodAnnotation> methodAnnotations = null; List<ParameterAnnotation> parameterAnnotations = null; public DexAnnotation(DexFile dexFile, SootClass sc) { this.dexFile = dexFile; this.currentClass = sc; //classAnnotations = new AnnotationSetItem; fieldAnnotations = new ArrayList<FieldAnnotation>(); methodAnnotations = new ArrayList<MethodAnnotation>(); parameterAnnotations = new ArrayList<ParameterAnnotation>(); } /** * Add Annotation Directory to the Dexlib's representation of the target .dex file * @return */ public AnnotationDirectoryItem finish() { classAnnotations = AnnotationSetItem.internAnnotationSetItem(dexFile, classAnnotationItems); Debug.printDbg("add ", classAnnotations.getAnnotations().length , " class annotations, " , fieldAnnotations.size() ," field annotations " , methodAnnotations.size() , " method annotations " , parameterAnnotations.size() , " parameters annotations."); AnnotationDirectoryItem di = AnnotationDirectoryItem.internAnnotationDirectoryItem(dexFile, classAnnotations, fieldAnnotations, methodAnnotations, parameterAnnotations); return di; } /** * Handle Class Annotations * @param c SootClass * @param citem Dexlib class item */ // .annotation "Ldalvik/annotation/AnnotationDefault;" // .annotation "Ldalvik/annotation/EnclosingClass;" // .annotation "Ldalvik/annotation/EnclosingMethod;" // .annotation "Ldalvik/annotation/InnerClass;" // .annotation "Ldalvik/annotation/MemberClasses;" // .annotation "Ldalvik/annotation/Signature;" // .annotation "Ldalvik/annotation/Throws;" public void handleClass(SootClass c, ClassDataItem citem) { Debug.printDbg("1"); // handle inner class tags if (c.hasTag("InnerClassAttribute") && !Options.v().no_output_inner_classes_attribute()){ InnerClassTag innerClass = null; List<InnerClassTag> memberClasses = new ArrayList<InnerClassTag>(); InnerClassAttribute innerClassAttribute = (InnerClassAttribute) c.getTag("InnerClassAttribute"); Debug.printDbg("has tag: class attribute"); // separate inner class from member classes for (Tag t : innerClassAttribute.getSpecs()){ Debug.printDbg("t: ", t); InnerClassTag tag = (InnerClassTag) t; String innerC = tag.getInnerClass(); String innerCSootFormat = innerC.replaceAll("/", "\\."); Debug.printDbg("innercc: ", innerCSootFormat); if (innerCSootFormat.equals(c.toString())) { if (innerClass != null) G.v().out.println("warning: multiple inner class tags!"); innerClass = tag; } else { Debug.printDbg("1 add ", tag); memberClasses.add(tag); } } // inner class if (innerClass != null) { // enclosing class AnnotationItem enclosingItem = makeEnclosingClassAnnotation(innerClass); classAnnotationItems.add(enclosingItem); // inner class AnnotationItem innerItem = makeInnerClassAnnotation(innerClass); classAnnotationItems.add(innerItem); } // member classes if (memberClasses.size() > 0) { Debug.printDbg("here:"); AnnotationItem memberItem = makeMemberClasses(memberClasses); classAnnotationItems.add(memberItem); } } // handle enclosing method tags if (c.hasTag("EnclosingMethodTag")){ EnclosingMethodTag eMethTag = (EnclosingMethodTag)c.getTag("EnclosingMethodTag"); AnnotationItem enclosingMethodItem = makeEnclosingMethod(eMethTag); if (enclosingMethodItem != null) classAnnotationItems.add(enclosingMethodItem); } // handle deprecated tag if (c.hasTag("DeprecatedTag")){ AnnotationItem deprecatedItem = makeDeprecatedItem(); classAnnotationItems.add(deprecatedItem); } // handle visibility annotation tags for (Tag t : c.getTags()){ if (t.getName().equals("VisibilityAnnotationTag")){ Debug.printDbg("class visibility annotation tag: ", t); List<AnnotationItem> visibilityItems = makeVisibilityItem(t); for (AnnotationItem i : visibilityItems) classAnnotationItems.add(i); } } // Debug.printDbg("\n tag: ", t.getName()); // // List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>(); // List<StringIdItem> namesList = new ArrayList<StringIdItem>(); // // VisibilityAnnotationTag vat = (VisibilityAnnotationTag)t; // List<AnnotationTag> atList = vat.getAnnotations(); // for (AnnotationTag at: atList) { // Debug.printDbg("annotation tag name: ", at.getName(), " class: ", at.getClass()); // //String type = soot2DalvikType(at.getType()); // String type = at.getType(); // Debug.printDbg("tag type: ", type); // // for (AnnotationElem ae : at.getElems()) { // EncodedValue value = getAnnotationElement(ae); // encodedValueList.add(value); // namesList.add(StringIdItem.internStringIdItem(dexFile, ae.getName())); // Debug.printDbg("new class annotation: ", value ," ", ae.getName() ," ", at.getName() ," ", ae.getClass()); // } // // TypeIdItem annotationType = TypeIdItem.internTypeIdItem(dexFile, type); // StringIdItem[] names = namesList.toArray(new StringIdItem[namesList.size()]); // EncodedValue[] values = encodedValueList.toArray(new EncodedValue[encodedValueList.size()]); // AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue(annotationType, names, values); // AnnotationItem aItem = AnnotationItem.internAnnotationItem(dexFile, getVisibility(vat.getVisibility()), annotationValue); // classAnnotationItems.add(aItem); // } // // } } /** * Handle Field Annotations * @param sf SootField * @param fid DexLib Field */ private Set<String> alreadyDone = new HashSet<String>(); public void handleField(SootField sf, FieldIdItem fid) { if (!sf.getDeclaringClass().getName().equals(currentClass.getName())) return; if (alreadyDone.contains(sf.getSignature())) return; alreadyDone.add(sf.getSignature()); Debug.printDbg("handle annotations for field: '", sf ,"' current class: ", currentClass); List<AnnotationItem> aList = new ArrayList<AnnotationItem>(); // handle deprecated tag if (sf.hasTag("DeprecatedTag")){ AnnotationItem deprecatedItem = makeDeprecatedItem(); aList.add(deprecatedItem); } // handle signature tag if (sf.hasTag("SignatureTag")){ SignatureTag tag = (SignatureTag)sf.getTag("SignatureTag"); AnnotationItem deprecatedItem = makeSignatureItem(tag); aList.add(deprecatedItem); } // handle visibility annotation tags for (Tag t : sf.getTags()){ if (t.getName().equals("VisibilityAnnotationTag")){ Debug.printDbg("field visibility annotation tag: ", t); List<AnnotationItem> visibilityItems = makeVisibilityItem(t); for (AnnotationItem ai : visibilityItems) aList.add(ai); } } // // handle constant tag // int cst = 0; // for (Tag t : sf.getTags()) { // if (t instanceof ConstantValueTag) { // cst++; // if (cst > 1) // G.v().out.println("warning: more than one constant tag for field: "+ sf); // AnnotationItem ai = makeConstantItem(t); // aList.add(ai); // } // } AnnotationSetItem set = AnnotationSetItem.internAnnotationSetItem(dexFile, aList); FieldAnnotation fa = new FieldAnnotation(fid, set); fieldAnnotations.add(fa); } private Set<SootMethod> alreadyDoneMethods = new HashSet<SootMethod>(); /** * Handles Method and Parameter Annotations * @param sm SootMethod * @param mid Dexlib Method Item */ public void handleMethod(SootMethod sm, MethodIdItem mid) { if (!sm.getDeclaringClass().getName().equals(currentClass.getName())) return; if (!alreadyDoneMethods.add(sm)) return; Debug.printDbg("handle annotations for method: '", sm ,"' current class: ", currentClass); List<AnnotationItem> aList = new ArrayList<AnnotationItem>(); List<AnnotationSetItem> setList = new ArrayList<AnnotationSetItem>(); List<String> skipList = new ArrayList<String>(); if (sm.hasTag("DeprecatedTag")){ AnnotationItem deprecatedItem = makeDeprecatedItem(); aList.add(deprecatedItem); skipList.add("Ljava/lang/Deprecated;"); } if (sm.hasTag("SignatureTag")){ SignatureTag tag = (SignatureTag)sm.getTag("SignatureTag"); AnnotationItem signatureItem = makeSignatureItem(tag); aList.add(signatureItem); skipList.add("Ldalvik/annotation/Signature;"); } if (sm.hasTag("AnnotationDefaultTag")){ // AnnotationDefaultTag tag = (AnnotationDefaultTag)sm.getTag("AnnotationDefaultTag"); Debug.printDbg("TODO"); } for (Tag t : sm.getTags()) { // TODO: FIX if (t.getName().equals("VisibilityAnnotationTag")){ VisibilityAnnotationTag vat = (VisibilityAnnotationTag)t; aList.addAll(handleMethodTag(vat, mid, skipList)); } if (t.getName().equals("VisibilityParameterAnnotationTag")){ VisibilityParameterAnnotationTag vat = (VisibilityParameterAnnotationTag)t; setList.addAll(handleMethodParamTag(vat, mid)); } } // Sort the annotation list Collections.sort(aList, new Comparator<AnnotationItem>() { @Override public int compare(AnnotationItem o1, AnnotationItem o2) { int res = o1.getEncodedAnnotation().annotationType.getIndex() - o2.getEncodedAnnotation().annotationType.getIndex(); if (res == 0) throw new RuntimeException("Duplicate annotation type:" + o1); return res; } }); AnnotationSetItem set = AnnotationSetItem.internAnnotationSetItem(dexFile, aList); MethodAnnotation ma = new MethodAnnotation(mid, set); methodAnnotations.add(ma); AnnotationSetRefList asrList = AnnotationSetRefList.internAnnotationSetRefList(dexFile, setList); ParameterAnnotation pa = new ParameterAnnotation(mid, asrList); parameterAnnotations.add(pa); } /** * Handle Method Annotations * @param vat * @param mid * @return */ private List<AnnotationItem> handleMethodTag(VisibilityAnnotationTag vat, MethodIdItem mid, List<String> skipList) { List<AnnotationTag> atList = vat.getAnnotations(); List<AnnotationItem> aList = new ArrayList<AnnotationItem>(); for (AnnotationTag at: atList) { //String type = soot2DalvikType(at.getType()); String type = at.getType(); if (skipList.contains(type)) continue; List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>(); List<StringIdItem> namesList = new ArrayList<StringIdItem>(); for (AnnotationElem ae : at.getElems()) { EncodedValue value = getAnnotationElement(ae); encodedValueList.add(value); namesList.add(StringIdItem.internStringIdItem(dexFile, ae.getName())); Debug.printDbg("new method annotation: ", value ," ", ae.getName()); } TypeIdItem annotationType = TypeIdItem.internTypeIdItem(dexFile, type); StringIdItem[] names = namesList.toArray(new StringIdItem[namesList.size()]); EncodedValue[] values = encodedValueList.toArray(new EncodedValue[encodedValueList.size()]); AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue(annotationType, names, values); AnnotationItem a = AnnotationItem.internAnnotationItem(dexFile, getVisibility(vat.getVisibility()), annotationValue); aList.add(a); } return aList; } /** * Handle (Method) Parameter Annotations * @param vat1 * @param mid * @return */ private List<AnnotationSetItem> handleMethodParamTag(VisibilityParameterAnnotationTag vat1, MethodIdItem mid) { List<VisibilityAnnotationTag> vatList = vat1.getVisibilityAnnotations(); List<AnnotationSetItem> setList = new ArrayList<AnnotationSetItem>(); if (vatList != null) for (VisibilityAnnotationTag vat: vatList) { if (vat == null) continue; List<AnnotationItem> aList = new ArrayList<AnnotationItem>(); if (vat.getAnnotations() != null) for (AnnotationTag at: vat.getAnnotations()) { List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>(); List<StringIdItem> namesList = new ArrayList<StringIdItem>(); for (AnnotationElem ae : at.getElems()) { EncodedValue value = getAnnotationElement(ae); encodedValueList.add(value); namesList.add(StringIdItem.internStringIdItem(dexFile, ae.getName())); Debug.printDbg("new annotation: ", value ," ", ae.getName()); } //String type = soot2DalvikType(at.getType()); String type = at.getType(); TypeIdItem annotationType = TypeIdItem.internTypeIdItem(dexFile, type); StringIdItem[] names = namesList.toArray(new StringIdItem[namesList.size()]); EncodedValue[] values = encodedValueList.toArray(new EncodedValue[encodedValueList.size()]); AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue(annotationType, names, values); AnnotationItem a = AnnotationItem.internAnnotationItem(dexFile, getVisibility(vat.getVisibility()), annotationValue); aList.add(a); } AnnotationSetItem annotationSets = AnnotationSetItem.internAnnotationSetItem(dexFile, aList); setList.add(annotationSets); } return setList; } /** * Encodes Annotations Elements from Jimple to Dexlib * @param elem Jimple Element * @return Dexlib encoded element */ private EncodedValue getAnnotationElement(AnnotationElem elem){ EncodedValue v = null; Debug.printDbg("annotation kind: ", elem.getKind()); switch (elem.getKind()) { case 'Z': { if (elem instanceof AnnotationIntElem) { AnnotationIntElem e = (AnnotationIntElem)elem; if (e.getValue() == 0) { v = BooleanEncodedValue.FalseValue; } else if (e.getValue() == 1) { v = BooleanEncodedValue.TrueValue; } else { throw new RuntimeException("error: boolean value from int with value != 0 or 1."); } } else if (elem instanceof AnnotationBooleanElem) { AnnotationBooleanElem e = (AnnotationBooleanElem) elem; if (e.getValue()) v = BooleanEncodedValue.TrueValue; else v = BooleanEncodedValue.FalseValue; } else throw new RuntimeException("Annotation type incompatible with target type boolean"); break; } case 'S': { AnnotationIntElem e = (AnnotationIntElem)elem; ShortEncodedValue a = new ShortEncodedValue((short)e.getValue()); v = a; break; } case 'B': { AnnotationIntElem e = (AnnotationIntElem)elem; ByteEncodedValue a = new ByteEncodedValue((byte)e.getValue()); v = a; break; } case 'C': { AnnotationIntElem e = (AnnotationIntElem)elem; CharEncodedValue a = new CharEncodedValue((char)e.getValue()); v = a; break; } case 'I': { AnnotationIntElem e = (AnnotationIntElem)elem; IntEncodedValue a = new IntEncodedValue(e.getValue()); v = a; break; } case 'J': { AnnotationLongElem e = (AnnotationLongElem)elem; LongEncodedValue a = new LongEncodedValue(e.getValue()); v = a; break; } case 'F': { AnnotationFloatElem e = (AnnotationFloatElem)elem; FloatEncodedValue a = new FloatEncodedValue(e.getValue()); v = a; break; } case 'D': { AnnotationDoubleElem e = (AnnotationDoubleElem)elem; DoubleEncodedValue a = new DoubleEncodedValue(e.getValue()); v = a; break; } case 's': { AnnotationStringElem e = (AnnotationStringElem)elem; StringIdItem string = StringIdItem.internStringIdItem(dexFile, e.getValue()); StringEncodedValue a = new StringEncodedValue(string); v = a; break; } case 'e': { AnnotationEnumElem e = (AnnotationEnumElem)elem; String classT = soot2DalvikType(e.getTypeName()); String fieldT = soot2DalvikType(e.getTypeName()); String fieldNameString = e.getName(); TypeIdItem classType = TypeIdItem.internTypeIdItem(dexFile, classT); TypeIdItem fieldType = TypeIdItem.internTypeIdItem(dexFile, fieldT); StringIdItem fieldName = StringIdItem.internStringIdItem(dexFile, fieldNameString); FieldIdItem fId = FieldIdItem.internFieldIdItem(dexFile, classType, fieldType, fieldName); EnumEncodedValue a = new EnumEncodedValue(fId); v = a; break; } case 'c': { AnnotationClassElem e = (AnnotationClassElem)elem; String type = soot2DalvikType(e.getDesc()); StringIdItem strId = StringIdItem.internStringIdItem(dexFile, type); TypeIdItem typeId = TypeIdItem.internTypeIdItem(dexFile, strId); TypeEncodedValue a = new TypeEncodedValue(typeId); v = a; break; } case '[': { AnnotationArrayElem e = (AnnotationArrayElem)elem; List<EncodedValue> valueList = new ArrayList<EncodedValue>(); for (int i = 0; i < e.getNumValues(); i++){ EncodedValue val = getAnnotationElement(e.getValueAt(i)); valueList.add(val); } ArrayEncodedValue a = new ArrayEncodedValue(valueList.toArray( new EncodedValue[valueList.size()])); v = a; break; } case '@': { AnnotationAnnotationElem e = (AnnotationAnnotationElem)elem; List<StringIdItem> nameList = new ArrayList<StringIdItem>(); List<EncodedValue> valueList = new ArrayList<EncodedValue>(); for (AnnotationElem ae : e.getValue().getElems()){ EncodedValue val = getAnnotationElement(ae); valueList.add(val); nameList.add(StringIdItem.internStringIdItem(dexFile, ae.getName())); } //String type = soot2DalvikType(e.getValue().getType()); String type = e.getValue().getType(); TypeIdItem annotationType = TypeIdItem.internTypeIdItem(dexFile, type); StringIdItem[] names = nameList.toArray(new StringIdItem[nameList.size()]); EncodedValue[] values = valueList.toArray(new EncodedValue[valueList.size()]); AnnotationEncodedValue a = new AnnotationEncodedValue(annotationType, names, values); v = a; break; } case 'f': { // field (Dalvik specific?) AnnotationStringElem e = (AnnotationStringElem)elem; String fSig = e.getValue(); String[] sp = fSig.split(" "); String classString = soot2DalvikType(sp[0].split(":")[0]); String typeString = soot2DalvikType(sp[1]); String fieldName = sp[2]; StringIdItem ctypeDescriptor = StringIdItem.internStringIdItem(dexFile, classString); StringIdItem ftypeDescriptor = StringIdItem.internStringIdItem(dexFile, typeString); StringIdItem fieldNameItem = StringIdItem.internStringIdItem(dexFile, fieldName); Debug.printDbg("field item: ", classString ," ", typeString, " ", fieldName); TypeIdItem classType = TypeIdItem.internTypeIdItem(dexFile, ctypeDescriptor); TypeIdItem fieldType = TypeIdItem.internTypeIdItem(dexFile, ftypeDescriptor); FieldIdItem fId = FieldIdItem.internFieldIdItem(dexFile, classType, fieldType, fieldNameItem); FieldEncodedValue a = new FieldEncodedValue(fId); v = a; break; } case 'M': { // method (Dalvik specific?) AnnotationStringElem e = (AnnotationStringElem)elem; String mSig = e.getValue(); Debug.printDbg("msig: ", mSig); // String[] sp = mSig.split(" "); String classString = soot2DalvikType(sp[0].split(":")[0]); String returnType = soot2DalvikType(sp[1]); String[] sp2 = sp[2].split("\\("); String methodNameString = sp2[0]; String parameters = sp2[1].replaceAll("\\)", ""); Debug.printDbg("parameters: '", parameters ,"'"); List<String> paramTypeList = new ArrayList<String>(); if (parameters.length() > 0) for (String p: parameters.split(",")) { String type = soot2DalvikType(p); paramTypeList.add(type); } // StringIdItem ctypeDescriptor = StringIdItem.internStringIdItem(dexFile, classString); StringIdItem returnDescriptor = StringIdItem.internStringIdItem(dexFile, returnType); List<TypeIdItem> parametersItemList = new ArrayList<TypeIdItem>(); for (String p: paramTypeList) { StringIdItem t = StringIdItem.internStringIdItem(dexFile, p); parametersItemList.add(TypeIdItem.internTypeIdItem(dexFile, t)); } // TypeIdItem classType = TypeIdItem.internTypeIdItem(dexFile, ctypeDescriptor); TypeIdItem returnTypeItem = TypeIdItem.internTypeIdItem(dexFile, returnDescriptor); TypeListItem parametersItem = TypeListItem.internTypeListItem(dexFile, parametersItemList); ProtoIdItem methodPrototype = ProtoIdItem.internProtoIdItem(dexFile, returnTypeItem, parametersItem); StringIdItem methodName = StringIdItem.internStringIdItem(dexFile, methodNameString); MethodIdItem mId = MethodIdItem.internMethodIdItem(dexFile, classType, methodPrototype, methodName); MethodEncodedValue a = new MethodEncodedValue(mId); v = a; break; } case 'N': { // null (Dalvik specific?) NullEncodedValue a = NullEncodedValue.NullValue; v = a; break; } default : { throw new RuntimeException("Unknown Elem Attr Kind: "+elem.getKind()); } } return v; } private AnnotationItem makeEnclosingClassAnnotation(InnerClassTag tag) { String outerClass = tag.getOuterClass(); TypeIdItem string = TypeIdItem.internTypeIdItem(dexFile, "L" + outerClass + ";"); TypeEncodedValue a = new TypeEncodedValue(string); TypeIdItem annotationType = TypeIdItem.internTypeIdItem( dexFile, "Ldalvik/annotation/EnclosingClass;"); List<StringIdItem> namesList = new ArrayList<StringIdItem>(); List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>(); namesList.add(StringIdItem.internStringIdItem(dexFile, "value")); encodedValueList.add(a); StringIdItem[] names = namesList.toArray( new StringIdItem[namesList.size()]); EncodedValue[] values = encodedValueList.toArray( new EncodedValue[encodedValueList.size()]); AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue( annotationType, names, values); AnnotationItem aItem = AnnotationItem.internAnnotationItem( dexFile, AnnotationVisibility.SYSTEM, annotationValue); return aItem; } private AnnotationItem makeInnerClassAnnotation(InnerClassTag tag) { IntEncodedValue flags = new IntEncodedValue(tag.getAccessFlags()); TypeIdItem annotationType = TypeIdItem.internTypeIdItem( dexFile, "Ldalvik/annotation/InnerClass;"); List<StringIdItem> namesList = new ArrayList<StringIdItem>(); List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>(); namesList.add(StringIdItem.internStringIdItem(dexFile, "accessFlags")); encodedValueList.add(flags); if (tag.getShortName() != null) { StringIdItem nameId = StringIdItem.internStringIdItem(dexFile, tag.getShortName()); StringEncodedValue nameV = new StringEncodedValue(nameId); namesList.add(StringIdItem.internStringIdItem(dexFile, "name")); encodedValueList.add(nameV); } StringIdItem[] names = namesList.toArray( new StringIdItem[namesList.size()]); EncodedValue[] values = encodedValueList.toArray( new EncodedValue[encodedValueList.size()]); AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue( annotationType, names, values); AnnotationItem aItem = AnnotationItem.internAnnotationItem( dexFile, AnnotationVisibility.SYSTEM, annotationValue); return aItem; } private AnnotationItem makeMemberClasses(List<InnerClassTag> tags) { TypeIdItem annotationType = TypeIdItem.internTypeIdItem( dexFile, "Ldalvik/annotation/MemberClasses;"); List<StringIdItem> namesList = new ArrayList<StringIdItem>(); List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>(); namesList.add(StringIdItem.internStringIdItem(dexFile, "value")); List<EncodedValue> valueList = new ArrayList<EncodedValue>(); for (InnerClassTag t : tags) { TypeIdItem memberType = TypeIdItem.internTypeIdItem(dexFile, "L" + t.getInnerClass() + ";"); TypeEncodedValue memberEv = new TypeEncodedValue(memberType); valueList.add(memberEv); } ArrayEncodedValue a = new ArrayEncodedValue(valueList.toArray( new EncodedValue[valueList.size()])); encodedValueList.add(a); StringIdItem[] names = namesList.toArray( new StringIdItem[namesList.size()]); EncodedValue[] values = encodedValueList.toArray( new EncodedValue[encodedValueList.size()]); AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue( annotationType, names, values); AnnotationItem aItem = AnnotationItem.internAnnotationItem( dexFile, AnnotationVisibility.SYSTEM, annotationValue); return aItem; } private AnnotationItem makeEnclosingMethod(EnclosingMethodTag tag) { TypeIdItem annotationType = TypeIdItem.internTypeIdItem( dexFile, "Ldalvik/annotation/EnclosingMethod;"); String enclosingClass = DexType.toDalvikICAT(tag.getEnclosingClass()); TypeIdItem classType = TypeIdItem.internTypeIdItem(dexFile, enclosingClass); String enclosingMethod = tag.getEnclosingMethod(); String methodSig = tag.getEnclosingMethodSig(); // Sometimes we don't have an enclosing method if (methodSig == null || methodSig.isEmpty()) return null; String[] split1 = methodSig.split("\\)"); String parametersS = split1[0].replaceAll("\\(", ""); String returnTypeS = split1[1]; TypeIdItem returnType = TypeIdItem.internTypeIdItem(dexFile, returnTypeS); List<TypeIdItem> typeList = new ArrayList<TypeIdItem>(); Debug.printDbg("parameters:", parametersS); if (!parametersS.equals("")) { for (String p : Util.splitParameters(parametersS)) { if (p.equals("")) continue; Debug.printDbg("parametr: ", p); TypeIdItem i = TypeIdItem.internTypeIdItem(dexFile, p); typeList.add(i); } } TypeListItem parameters = TypeListItem.internTypeListItem(dexFile, typeList); ProtoIdItem methodPrototype = ProtoIdItem.internProtoIdItem(dexFile, returnType, parameters); StringIdItem methodName = StringIdItem.internStringIdItem(dexFile, enclosingMethod); MethodIdItem methodId = MethodIdItem.internMethodIdItem(dexFile, classType, methodPrototype, methodName); MethodEncodedValue a = new MethodEncodedValue(methodId); List<StringIdItem> namesList = new ArrayList<StringIdItem>(); List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>(); namesList.add(StringIdItem.internStringIdItem(dexFile, "value")); encodedValueList.add(a); StringIdItem[] names = namesList.toArray( new StringIdItem[namesList.size()]); EncodedValue[] values = encodedValueList.toArray( new EncodedValue[encodedValueList.size()]); AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue( annotationType, names, values); AnnotationItem aItem = AnnotationItem.internAnnotationItem( dexFile, AnnotationVisibility.SYSTEM, annotationValue); return aItem; } private AnnotationItem makeDeprecatedItem() { TypeIdItem annotationType = TypeIdItem.internTypeIdItem( dexFile, "Ljava/lang/Deprecated;"); List<StringIdItem> namesList = new ArrayList<StringIdItem>(); List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>();; StringIdItem[] names = namesList.toArray( new StringIdItem[namesList.size()]); EncodedValue[] values = encodedValueList.toArray( new EncodedValue[encodedValueList.size()]); AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue( annotationType, names, values); AnnotationItem aItem = AnnotationItem.internAnnotationItem( dexFile, AnnotationVisibility.SYSTEM, annotationValue); return aItem; } private AnnotationItem makeSignatureItem(SignatureTag t) { TypeIdItem annotationType = TypeIdItem.internTypeIdItem( dexFile, "Ldalvik/annotation/Signature;"); List<StringIdItem> namesList = new ArrayList<StringIdItem>(); List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>(); namesList.add(StringIdItem.internStringIdItem(dexFile, "value")); List<EncodedValue> valueList = new ArrayList<EncodedValue>(); for (String s : t.getSignature().split(" ")) { StringIdItem member = StringIdItem.internStringIdItem(dexFile, s); StringEncodedValue memberEv = new StringEncodedValue(member); //TypeEncodedValue memberEv = new TypeEncodedValue(memberType); valueList.add(memberEv); } ArrayEncodedValue a = new ArrayEncodedValue(valueList.toArray( new EncodedValue[valueList.size()])); encodedValueList.add(a); StringIdItem[] names = namesList.toArray( new StringIdItem[namesList.size()]); EncodedValue[] values = encodedValueList.toArray( new EncodedValue[encodedValueList.size()]); AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue( annotationType, names, values); AnnotationItem aItem = AnnotationItem.internAnnotationItem( dexFile, AnnotationVisibility.SYSTEM, annotationValue); return aItem; } private List<AnnotationItem> makeVisibilityItem(Tag t) { List<AnnotationItem> aList = new ArrayList<AnnotationItem>(); if (!(t instanceof VisibilityAnnotationTag)) return aList; VisibilityAnnotationTag vat = (VisibilityAnnotationTag)t; List<AnnotationTag> atList = vat.getAnnotations(); for (AnnotationTag at: atList) { List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>(); List<StringIdItem> namesList = new ArrayList<StringIdItem>(); for (AnnotationElem ae : at.getElems()) { EncodedValue value = getAnnotationElement(ae); encodedValueList.add(value); namesList.add(StringIdItem.internStringIdItem(dexFile, ae.getName())); Debug.printDbg("new annotation: ", value ," ", ae.getName() ," type: ", value.getClass()); } String type = at.getType(); Debug.printDbg(" annotation type: ", type); TypeIdItem annotationType = TypeIdItem.internTypeIdItem(dexFile, type); StringIdItem[] names = namesList.toArray(new StringIdItem[namesList.size()]); EncodedValue[] values = encodedValueList.toArray(new EncodedValue[encodedValueList.size()]); AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue(annotationType, names, values); AnnotationItem a = AnnotationItem.internAnnotationItem(dexFile, getVisibility(vat.getVisibility()), annotationValue); aList.add(a); } return aList; } // private AnnotationItem makeConstantItem(Tag t) { // if (!(t instanceof ConstantValueTag)) // throw new RuntimeException("error: t not ConstantValueTag."); // return null; // } /** * Converts type such as "a.b.c[][]" to "[[a/b/c". * * @param sootType Soot type to convert to Dexlib type. * @return String representation of the Dexlib type */ public static String soot2DalvikType(String sootType) { return sootType; // if (sootType.startsWith("L") || sootType.startsWith("[")) { // throw new RuntimeException("error: wrong type format: "+ sootType); // } // // int arraySize = 0; // while (sootType.endsWith("[]")) { // arraySize++; // sootType = sootType.replaceFirst("\\[\\]", ""); // } // String type = ""; // if (sootType.equals("int")) { // type = "I"; // } else if (sootType.equals("float")) { // type = "F"; // } else if (sootType.equals("long")) { // type = "J"; // } else if (sootType.equals("double")) { // type = "D"; // } else if (sootType.equals("char")) { // type = "C"; // } else if (sootType.equals("boolean")) { // type = "Z"; // } else if (sootType.equals("byte")) { // type = "B"; // } else if (sootType.equals("void")) { // type = "V"; // } else { // type = "L"+ sootType.replaceAll("\\.", "/") +";"; // } // // if (type.startsWith("LL")) { // throw new RuntimeException("error: wrong type format: "+ type); // } // // for (int i = 0; i< arraySize; i++) // type = "[" + type; // return type; } /** * Converts Jimple visibility to Dexlib visibility * @param visibility Jimple visibility * @return Dexlib visibility */ private static AnnotationVisibility getVisibility(int visibility) { if (visibility == AnnotationConstants.RUNTIME_VISIBLE) // 0 return AnnotationVisibility.RUNTIME; // 1 if (visibility == AnnotationConstants.RUNTIME_INVISIBLE) // 1 return AnnotationVisibility.BUILD; // 0 if (visibility == AnnotationConstants.SOURCE_VISIBLE) // 2 return AnnotationVisibility.SYSTEM; // 2 throw new RuntimeException("Unknown annotation visibility: '"+ visibility +"'"); } }
fix for #160 - check for duplicate annotation types must not fail if we have no ID for the type yet. In this case, we just compare the strings.
src/soot/toDex/DexAnnotation.java
fix for #160 - check for duplicate annotation types must not fail if we have no ID for the type yet. In this case, we just compare the strings.
<ide><path>rc/soot/toDex/DexAnnotation.java <ide> <ide> List<AnnotationItem> aList = new ArrayList<AnnotationItem>(); <ide> List<AnnotationSetItem> setList = new ArrayList<AnnotationSetItem>(); <del> List<String> skipList = new ArrayList<String>(); <add> Set<String> skipList = new HashSet<String>(); <ide> <ide> if (sm.hasTag("DeprecatedTag")){ <ide> AnnotationItem deprecatedItem = makeDeprecatedItem(); <ide> } <ide> <ide> for (Tag t : sm.getTags()) { <del> // TODO: FIX <ide> if (t.getName().equals("VisibilityAnnotationTag")){ <ide> VisibilityAnnotationTag vat = (VisibilityAnnotationTag)t; <ide> aList.addAll(handleMethodTag(vat, mid, skipList)); <ide> } <ide> if (t.getName().equals("VisibilityParameterAnnotationTag")){ <ide> VisibilityParameterAnnotationTag vat = (VisibilityParameterAnnotationTag)t; <del> setList.addAll(handleMethodParamTag(vat, mid)); <add> setList.addAll(handleMethodParamTag(vat, mid, Collections.<String>emptySet())); <ide> } <ide> } <ide> <ide> <ide> @Override <ide> public int compare(AnnotationItem o1, AnnotationItem o2) { <del> int res = o1.getEncodedAnnotation().annotationType.getIndex() <del> - o2.getEncodedAnnotation().annotationType.getIndex(); <del> if (res == 0) <add> int idx1 = o1.getEncodedAnnotation().annotationType.getIndex(); <add> int idx2 = o2.getEncodedAnnotation().annotationType.getIndex(); <add> int res = idx1 - idx2; <add> <add> // Check that our generated APK file will not be broken <add> if (res == 0 && !(idx1 == -1 && idx2 == -1)) <ide> throw new RuntimeException("Duplicate annotation type:" + o1); <add> if (o1.getEncodedAnnotation().annotationType.getTypeDescriptor().equals <add> (o2.getEncodedAnnotation().annotationType.getTypeDescriptor())) <add> throw new RuntimeException("Duplicate annotation type:" + o1); <add> <ide> return res; <ide> } <ide> <ide> * @return <ide> */ <ide> private List<AnnotationItem> handleMethodTag(VisibilityAnnotationTag vat, MethodIdItem mid, <del> List<String> skipList) { <add> Set<String> skipList) { <ide> List<AnnotationTag> atList = vat.getAnnotations(); <ide> <ide> List<AnnotationItem> aList = new ArrayList<AnnotationItem>(); <ide> namesList.add(StringIdItem.internStringIdItem(dexFile, ae.getName())); <ide> Debug.printDbg("new method annotation: ", value ," ", ae.getName()); <ide> } <del> <add> <ide> TypeIdItem annotationType = TypeIdItem.internTypeIdItem(dexFile, type); <ide> StringIdItem[] names = namesList.toArray(new StringIdItem[namesList.size()]); <ide> EncodedValue[] values = encodedValueList.toArray(new EncodedValue[encodedValueList.size()]); <ide> AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue(annotationType, names, values); <del> <add> <ide> AnnotationItem a = AnnotationItem.internAnnotationItem(dexFile, <ide> getVisibility(vat.getVisibility()), annotationValue); <ide> aList.add(a); <ide> * @param mid <ide> * @return <ide> */ <del> private List<AnnotationSetItem> handleMethodParamTag(VisibilityParameterAnnotationTag vat1, MethodIdItem mid) { <add> private List<AnnotationSetItem> handleMethodParamTag(VisibilityParameterAnnotationTag vat1, <add> MethodIdItem mid, Set<String> skipList) { <ide> List<VisibilityAnnotationTag> vatList = vat1.getVisibilityAnnotations(); <add> if (vatList == null) <add> return Collections.emptyList(); <ide> <ide> List<AnnotationSetItem> setList = new ArrayList<AnnotationSetItem>(); <del> if (vatList != null) <del> for (VisibilityAnnotationTag vat: vatList) { <del> if (vat == null) <del> continue; <add> for (VisibilityAnnotationTag vat: vatList) { <add> if (vat == null) <add> continue; <ide> <del> List<AnnotationItem> aList = new ArrayList<AnnotationItem>(); <del> if (vat.getAnnotations() != null) <del> for (AnnotationTag at: vat.getAnnotations()) { <del> List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>(); <del> List<StringIdItem> namesList = new ArrayList<StringIdItem>(); <del> for (AnnotationElem ae : at.getElems()) { <del> EncodedValue value = getAnnotationElement(ae); <del> encodedValueList.add(value); <del> namesList.add(StringIdItem.internStringIdItem(dexFile, ae.getName())); <del> Debug.printDbg("new annotation: ", value ," ", ae.getName()); <del> } <add> List<AnnotationItem> aList = new ArrayList<AnnotationItem>(); <add> if (vat.getAnnotations() != null) <add> for (AnnotationTag at: vat.getAnnotations()) { <add> List<EncodedValue> encodedValueList = new ArrayList<EncodedValue>(); <add> List<StringIdItem> namesList = new ArrayList<StringIdItem>(); <add> for (AnnotationElem ae : at.getElems()) { <add> EncodedValue value = getAnnotationElement(ae); <add> encodedValueList.add(value); <add> namesList.add(StringIdItem.internStringIdItem(dexFile, ae.getName())); <add> Debug.printDbg("new annotation: ", value ," ", ae.getName()); <add> } <ide> <del> //String type = soot2DalvikType(at.getType()); <del> String type = at.getType(); <del> TypeIdItem annotationType = TypeIdItem.internTypeIdItem(dexFile, type); <del> StringIdItem[] names = namesList.toArray(new StringIdItem[namesList.size()]); <del> EncodedValue[] values = encodedValueList.toArray(new EncodedValue[encodedValueList.size()]); <del> AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue(annotationType, names, values); <del> <del> AnnotationItem a = AnnotationItem.internAnnotationItem(dexFile, getVisibility(vat.getVisibility()), annotationValue); <del> aList.add(a); <del> <del> } <add> //String type = soot2DalvikType(at.getType()); <add> String type = at.getType(); <add> if (skipList.contains(type)) <add> continue; <add> <add> TypeIdItem annotationType = TypeIdItem.internTypeIdItem(dexFile, type); <add> StringIdItem[] names = namesList.toArray(new StringIdItem[namesList.size()]); <add> EncodedValue[] values = encodedValueList.toArray(new EncodedValue[encodedValueList.size()]); <add> AnnotationEncodedSubValue annotationValue = new AnnotationEncodedSubValue(annotationType, names, values); <add> <add> AnnotationItem a = AnnotationItem.internAnnotationItem(dexFile, getVisibility(vat.getVisibility()), annotationValue); <add> aList.add(a); <add> } <ide> <ide> AnnotationSetItem annotationSets = AnnotationSetItem.internAnnotationSetItem(dexFile, aList); <ide> setList.add(annotationSets); <del> <del> } <del> <del> return setList; <add> } <add> return setList; <ide> } <ide> <ide> /**
Java
cc0-1.0
476a484ccd853d69bd2934ebc741f6095d22b363
0
Chuddington/COMP329AssignmentOne
/* * COMP329 Assignment One * File Purpose: To start the program and link with other files */ //import statements here import java.io.*; import lejos.nxt.*; import lejos.nxt.comm.*; import lejos.nxt.Button; import lejos.nxt.Motor; import lejos.nxt.SensorPort; import lejos.nxt.UltrasonicSensor; import lejos.nxt.TouchSensor; import lejos.robotics.navigation.DifferentialPilot; import lejos.robotics.localization.OdometryPoseProvider; import lejos.nxt.Button; import lejos.nxt.Motor; public class AssOneMain { //global variables here - templates for now public static int main(String[] args) { //import classes here public MapSystem mapObj = new MapSystem(); public BtStuff btObj = new BtStuff() ; public Movement movObj = new Movement() ; //for each Column //movRow() method //movCol() method return 0; } public static void movRow() { //sonar scan in front of the robot //if object detected: // call movAround() method //else // move forward a cell } public static void movCol() { //rotate 90 degrees //move forward a cell //rotate 90 degrees //scan / move 2 cells forward //scan at the side to see if object is passed //move back to correct column if empty // keep moving forward if object is still there } public static void movAround() { //check for empty adjacent space //rotate to face it //move forward a cell //rotate to face the correct way again //move forward } } //EndOfFile
Java/AssOneMain.java
/* * COMP329 Assignment One * File Purpose: To start the program and link with other files */ //import statements here import java.io.*; import lejos.nxt.*; import lejos.nxt.comm.*; import lejos.nxt.Button; import lejos.nxt.Motor; import lejos.nxt.SensorPort; import lejos.nxt.UltrasonicSensor; import lejos.nxt.TouchSensor; import lejos.robotics.navigation.DifferentialPilot; import lejos.robotics.localization.OdometryPoseProvider; import lejos.nxt.Button; import lejos.nxt.Motor; public class AssOneMain { //global variables here - templates for now public static int main(String[] args) { //import classes here public MapSystem mapObj = new MapSystem(); public BtStuff btObj = new BtStuff() ; public Movement movObj = new Movement() ; //for each Column //moveRow() method //movCol return 0; } public static void movRow() { //sonar scan in front of the robot //if empty move forward; if not, call movAround() method } public static void movAround() { } } //EndOfFile
Added comments to show the suggested structure within the Main Class
Java/AssOneMain.java
Added comments to show the suggested structure within the Main Class
<ide><path>ava/AssOneMain.java <ide> public Movement movObj = new Movement() ; <ide> <ide> //for each Column <del> //moveRow() method <del> //movCol <add> //movRow() method <add> //movCol() method <ide> <ide> return 0; <ide> } <ide> public static void movRow() { <ide> //sonar scan in front of the robot <ide> <del> //if empty move forward; if not, call movAround() method <add> //if object detected: <add> // call movAround() method <add> //else <add> // move forward a cell <add> } <add> <add> public static void movCol() { <add> //rotate 90 degrees <add> //move forward a cell <add> //rotate 90 degrees <add> //scan / move 2 cells forward <add> //scan at the side to see if object is passed <add> //move back to correct column if empty <add> // keep moving forward if object is still there <add> <ide> } <ide> <ide> public static void movAround() { <del> <add> //check for empty adjacent space <add> //rotate to face it <add> //move forward a cell <add> //rotate to face the correct way again <add> //move forward <ide> <ide> } <ide>
Java
apache-2.0
error: pathspec 'src/main/java/com/hsjawanda/gaeobjectify/data/WebSafeKeyGen.java' did not match any file(s) known to git
5267754c815e5d87cdf3ff4254683db7a754f60f
1
hsjawanda/gae-objectify-utils
/** * */ package com.hsjawanda.gaeobjectify.data; import com.hsjawanda.gaeobjectify.collections.KeyGenerator; /** * @author Harshdeep S Jawanda ([email protected]) * * @param <V> */ public class WebSafeKeyGen<V> implements KeyGenerator<String, V> { /* * (non-Javadoc) * * @see com.hsjawanda.gaeobjectify.collections.KeyGenerator#keyFor(java.lang.Object) */ @Override public String keyFor(V value) { return GaeDataUtil.getWebKeyFromPojo(value); } }
src/main/java/com/hsjawanda/gaeobjectify/data/WebSafeKeyGen.java
KeyGenerator for getting the web-safe String representation (webKey) of an entity.
src/main/java/com/hsjawanda/gaeobjectify/data/WebSafeKeyGen.java
KeyGenerator for getting the web-safe String representation (webKey) of an entity.
<ide><path>rc/main/java/com/hsjawanda/gaeobjectify/data/WebSafeKeyGen.java <add>/** <add> * <add> */ <add>package com.hsjawanda.gaeobjectify.data; <add> <add>import com.hsjawanda.gaeobjectify.collections.KeyGenerator; <add> <add> <add>/** <add> * @author Harshdeep S Jawanda ([email protected]) <add> * <add> * @param <V> <add> */ <add>public class WebSafeKeyGen<V> implements KeyGenerator<String, V> { <add> <add> /* <add> * (non-Javadoc) <add> * <add> * @see com.hsjawanda.gaeobjectify.collections.KeyGenerator#keyFor(java.lang.Object) <add> */ <add> @Override <add> public String keyFor(V value) { <add> return GaeDataUtil.getWebKeyFromPojo(value); <add> } <add> <add>}
Java
epl-1.0
ec37f031f49aaf551b72d3dd3bcc36ab1bf75796
0
ControlSystemStudio/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio
/*************************************************************************\ * Copyright (c) 2010 UChicago Argonne, LLC * This file is distributed subject to a Software License Agreement found * in the file LICENSE that is included with this distribution. /*************************************************************************/ package org.csstudio.opibuilder.adl2boy.translator; import org.csstudio.opibuilder.model.AbstractContainerModel; import org.csstudio.opibuilder.runmode.RunModeService.DisplayMode; import org.csstudio.opibuilder.util.MacrosInput; import org.csstudio.opibuilder.widgetActions.ActionsInput; import org.csstudio.opibuilder.widgetActions.OpenDisplayAction; import org.csstudio.opibuilder.widgets.model.MenuButtonModel; import org.csstudio.utility.adlparser.fileParser.ADLWidget; import org.csstudio.utility.adlparser.fileParser.widgetParts.RelatedDisplayItem; import org.csstudio.utility.adlparser.fileParser.widgets.RelatedDisplay; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.swt.graphics.RGB; /** * Convert MEDMs related display to BOYs MenuButton * * @author John Hammonds, Argonne National Laboratory * */ public class RelatedDisplay2Model extends AbstractADL2Model { // MenuButtonModel menuModel = new MenuButtonModel(); public RelatedDisplay2Model(ADLWidget adlWidget, RGB[] colorMap, AbstractContainerModel parentModel) { super(adlWidget, colorMap, parentModel); } public RelatedDisplay2Model(RGB[] colorMap) { super(colorMap); } @Override public void makeModel(ADLWidget adlWidget, AbstractContainerModel parentModel){ widgetModel = new MenuButtonModel(); parentModel.addChild(widgetModel, true); } /** * @param adlWidget */ @Override public void processWidget(ADLWidget adlWidget) { RelatedDisplay rdWidget = new RelatedDisplay(adlWidget); if (rdWidget != null) { setADLObjectProps(rdWidget, widgetModel); setADLDynamicAttributeProps(rdWidget, widgetModel); setWidgetColors(rdWidget); RelatedDisplayItem[] rdDisplays = rdWidget.getRelatedDisplayItems(); if (rdDisplays.length > 0) { ActionsInput ai = widgetModel.getActionsInput(); for (int ii = 0; ii < rdDisplays.length; ii++) { if (!(rdDisplays[ii].getFileName().replaceAll("\"", "") .equals(""))) { OpenDisplayAction odAction = createOpenDisplayAction(rdDisplays[ii]); ai.addAction(odAction); } } } } String label = rdWidget.getLabel(); if (label != null) { if (label.startsWith("-")) { // leading "-" was used to flag not // using the icon. Just don't use // the icon and throw this away label = label.substring(1); } } widgetModel.setPropertyValue(MenuButtonModel.PROP_LABEL, label); } /** * @param rdDisplays * @param ii * @return */ public OpenDisplayAction createOpenDisplayAction( RelatedDisplayItem rdDisplay) { OpenDisplayAction odAction = new OpenDisplayAction(); // Try to add the filename to the PROP_PATH IPath fPath = new Path(rdDisplay.getFileName().replaceAll("\"", "") .replace(".adl", ".opi")); System.out.println("Related display file: " + rdDisplay.getFileName().replace(".adl", ".opi")); odAction.setPropertyValue(OpenDisplayAction.PROP_PATH, fPath); // Try to add macros addMacrosToOpenDisplayAction(rdDisplay, odAction); if (rdDisplay.getLabel() != null) { odAction.setPropertyValue(OpenDisplayAction.PROP_DESCRIPTION, rdDisplay.getLabel().replaceAll("\"", "")); } if ((rdDisplay.getPolicy() != null)) { // policy is present if (rdDisplay.getPolicy().replaceAll("\"", "").equals("replace display")) { // replace the display odAction.setPropertyValue(OpenDisplayAction.PROP_MODE, DisplayMode.REPLACE); } else { // don't replace the display odAction.setPropertyValue(OpenDisplayAction.PROP_MODE, DisplayMode.NEW_TAB); } } else { // policy not present go to default, i.e. don't replace, open new tab odAction.setPropertyValue(OpenDisplayAction.PROP_MODE, DisplayMode.NEW_TAB); } return odAction; } /** * @param rdDisplays * @param ii * @param odAction */ public void addMacrosToOpenDisplayAction(RelatedDisplayItem rdDisplay, OpenDisplayAction odAction) { if (rdDisplay.getArgs() != null && !rdDisplay.getArgs().isEmpty()) { String args = rdDisplay.getArgs().replaceAll("\"", ""); MacrosInput macIn = makeMacros(args); odAction.setPropertyValue(OpenDisplayAction.PROP_MACROS, macIn); } } public void cleanup() { widgetModel = null; } }
applications/opibuilder/opibuilder-plugins/org.csstudio.opibuilder.adl2boy/src/org/csstudio/opibuilder/adl2boy/translator/RelatedDisplay2Model.java
/*************************************************************************\ * Copyright (c) 2010 UChicago Argonne, LLC * This file is distributed subject to a Software License Agreement found * in the file LICENSE that is included with this distribution. /*************************************************************************/ package org.csstudio.opibuilder.adl2boy.translator; import org.csstudio.opibuilder.model.AbstractContainerModel; import org.csstudio.opibuilder.runmode.RunModeService.DisplayMode; import org.csstudio.opibuilder.util.MacrosInput; import org.csstudio.opibuilder.widgetActions.ActionsInput; import org.csstudio.opibuilder.widgetActions.OpenDisplayAction; import org.csstudio.opibuilder.widgets.model.MenuButtonModel; import org.csstudio.utility.adlparser.fileParser.ADLWidget; import org.csstudio.utility.adlparser.fileParser.widgetParts.RelatedDisplayItem; import org.csstudio.utility.adlparser.fileParser.widgets.RelatedDisplay; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.swt.graphics.RGB; /** * Convert MEDMs related display to BOYs MenuButton * * @author John Hammonds, Argonne National Laboratory * */ public class RelatedDisplay2Model extends AbstractADL2Model { // MenuButtonModel menuModel = new MenuButtonModel(); public RelatedDisplay2Model(ADLWidget adlWidget, RGB[] colorMap, AbstractContainerModel parentModel) { super(adlWidget, colorMap, parentModel); } public RelatedDisplay2Model(RGB[] colorMap) { super(colorMap); } public void makeModel(ADLWidget adlWidget, AbstractContainerModel parentModel){ widgetModel = new MenuButtonModel(); parentModel.addChild(widgetModel, true); } /** * @param adlWidget */ public void processWidget(ADLWidget adlWidget) { RelatedDisplay rdWidget = new RelatedDisplay(adlWidget); if (rdWidget != null) { setADLObjectProps(rdWidget, widgetModel); setADLDynamicAttributeProps(rdWidget, widgetModel); setWidgetColors(rdWidget); RelatedDisplayItem[] rdDisplays = rdWidget.getRelatedDisplayItems(); if (rdDisplays.length > 0) { ActionsInput ai = widgetModel.getActionsInput(); for (int ii = 0; ii < rdDisplays.length; ii++) { if (!(rdDisplays[ii].getFileName().replaceAll("\"", "") .equals(""))) { OpenDisplayAction odAction = createOpenDisplayAction(rdDisplays[ii]); ai.addAction(odAction); } } } } String label = rdWidget.getLabel(); if (label != null) { if (label.startsWith("-")) { // leading "-" was used to flag not // using the icon. Just don't use // the icon and throw this away label = label.substring(1); } } widgetModel.setPropertyValue(MenuButtonModel.PROP_LABEL, label); } /** * @param rdDisplays * @param ii * @return */ public OpenDisplayAction createOpenDisplayAction( RelatedDisplayItem rdDisplay) { OpenDisplayAction odAction = new OpenDisplayAction(); // Try to add macros addMacrosToOpenDisplayAction(rdDisplay, odAction); if (rdDisplay.getLabel() != null) { odAction.setPropertyValue(OpenDisplayAction.PROP_DESCRIPTION, rdDisplay.getLabel().replaceAll("\"", "")); } if ((rdDisplay.getPolicy() != null)) { // policy is present if (rdDisplay.getPolicy().replaceAll("\"", "").equals("replace display")) { // replace // the // display odAction.setPropertyValue(OpenDisplayAction.PROP_MODE, DisplayMode.REPLACE); } else { // don't replace the display odAction.setPropertyValue(OpenDisplayAction.PROP_MODE, DisplayMode.NEW_TAB); } } else { // policy not present go to default odAction.setPropertyValue(OpenDisplayAction.PROP_MODE, DisplayMode.NEW_TAB); // don't // replace // the // display } return odAction; } // Try to add macros addMacrosToOpenDisplayAction(rdDisplay, odAction); if (rdDisplay.getLabel() != null) { odAction.setPropertyValue(OpenDisplayAction.PROP_DESCRIPTION, rdDisplay.getLabel().replaceAll("\"", "")); } if ((rdDisplay.getPolicy() != null)) { // policy is present if (rdDisplay.getPolicy().replaceAll("\"", "").equals("replace display")) { // replace // the // display odAction.setPropertyValue(OpenDisplayAction.PROP_REPLACE, 1); } else { // don't replace the display odAction.setPropertyValue(OpenDisplayAction.PROP_REPLACE, 0); } } else { // policy not present go to default odAction.setPropertyValue(OpenDisplayAction.PROP_REPLACE, 0); // don't // replace // the // display } return odAction; } /** * @param rdDisplays * @param ii * @param odAction */ public void addMacrosToOpenDisplayAction(RelatedDisplayItem rdDisplay, OpenDisplayAction odAction) { if (rdDisplay.getArgs() != null && !rdDisplay.getArgs().isEmpty()) { String args = rdDisplay.getArgs().replaceAll("\"", ""); MacrosInput macIn = makeMacros(args); odAction.setPropertyValue(OpenDisplayAction.PROP_MACROS, macIn); } } public void cleanup() { widgetModel = null; } }
o.c.opibuilder.adl2boy: Fix compile error after failed merge
applications/opibuilder/opibuilder-plugins/org.csstudio.opibuilder.adl2boy/src/org/csstudio/opibuilder/adl2boy/translator/RelatedDisplay2Model.java
o.c.opibuilder.adl2boy: Fix compile error after failed merge
<ide><path>pplications/opibuilder/opibuilder-plugins/org.csstudio.opibuilder.adl2boy/src/org/csstudio/opibuilder/adl2boy/translator/RelatedDisplay2Model.java <ide> super(colorMap); <ide> } <ide> <add> @Override <ide> public void makeModel(ADLWidget adlWidget, AbstractContainerModel parentModel){ <ide> widgetModel = new MenuButtonModel(); <ide> parentModel.addChild(widgetModel, true); <ide> /** <ide> * @param adlWidget <ide> */ <add> @Override <ide> public void processWidget(ADLWidget adlWidget) { <ide> RelatedDisplay rdWidget = new RelatedDisplay(adlWidget); <ide> if (rdWidget != null) { <ide> RelatedDisplayItem rdDisplay) { <ide> OpenDisplayAction odAction = new OpenDisplayAction(); <ide> <del> // Try to add macros <del> addMacrosToOpenDisplayAction(rdDisplay, odAction); <del> if (rdDisplay.getLabel() != null) { <del> odAction.setPropertyValue(OpenDisplayAction.PROP_DESCRIPTION, <del> rdDisplay.getLabel().replaceAll("\"", "")); <del> } <del> if ((rdDisplay.getPolicy() != null)) { // policy is present <del> if (rdDisplay.getPolicy().replaceAll("\"", "").equals("replace display")) { // replace <del> // the <del> // display <del> odAction.setPropertyValue(OpenDisplayAction.PROP_MODE, DisplayMode.REPLACE); <del> } else { // don't replace the display <del> odAction.setPropertyValue(OpenDisplayAction.PROP_MODE, DisplayMode.NEW_TAB); <del> } <del> } else { // policy not present go to default <del> odAction.setPropertyValue(OpenDisplayAction.PROP_MODE, DisplayMode.NEW_TAB); // don't <del> // replace <del> // the <del> // display <del> } <del> return odAction; <del> } <add> // Try to add the filename to the PROP_PATH <add> IPath fPath = new Path(rdDisplay.getFileName().replaceAll("\"", "") <add> .replace(".adl", ".opi")); <add> System.out.println("Related display file: " <add> + rdDisplay.getFileName().replace(".adl", ".opi")); <add> odAction.setPropertyValue(OpenDisplayAction.PROP_PATH, fPath); <ide> <ide> // Try to add macros <ide> addMacrosToOpenDisplayAction(rdDisplay, odAction); <ide> rdDisplay.getLabel().replaceAll("\"", "")); <ide> } <ide> if ((rdDisplay.getPolicy() != null)) { // policy is present <del> if (rdDisplay.getPolicy().replaceAll("\"", "").equals("replace display")) { // replace <del> // the <del> // display <del> odAction.setPropertyValue(OpenDisplayAction.PROP_REPLACE, 1); <add> if (rdDisplay.getPolicy().replaceAll("\"", "").equals("replace display")) { <add> // replace the display <add> odAction.setPropertyValue(OpenDisplayAction.PROP_MODE, DisplayMode.REPLACE); <ide> } else { // don't replace the display <del> odAction.setPropertyValue(OpenDisplayAction.PROP_REPLACE, 0); <add> odAction.setPropertyValue(OpenDisplayAction.PROP_MODE, DisplayMode.NEW_TAB); <ide> } <del> } else { // policy not present go to default <del> odAction.setPropertyValue(OpenDisplayAction.PROP_REPLACE, 0); // don't <del> // replace <del> // the <del> // display <add> } else { // policy not present go to default, i.e. don't replace, open new tab <add> odAction.setPropertyValue(OpenDisplayAction.PROP_MODE, DisplayMode.NEW_TAB); <ide> } <ide> return odAction; <ide> }
JavaScript
mit
ff3977da77edee6473d21039781a5d38a84d7279
0
facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper
/** * Copyright 2018-present Facebook. * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * @format */ import {FlipperBasePlugin} from '../plugin.js'; import type BaseDevice from '../devices/BaseDevice.js'; import type Client from '../Client.js'; import type {UninitializedClient} from '../UninitializedClient.js'; import type {PluginNotification} from '../reducers/notifications'; import { Component, Sidebar, FlexBox, colors, brandColors, Text, Glyph, styled, GK, FlipperPlugin, FlipperDevicePlugin, LoadingIndicator, } from 'flipper'; import React from 'react'; import {devicePlugins, clientPlugins} from '../plugins/index.js'; import NotificationsHub from '../NotificationsHub.js'; import {selectPlugin} from '../reducers/connections.js'; import {connect} from 'react-redux'; const ListItem = styled('div')(({active}) => ({ paddingLeft: 10, display: 'flex', alignItems: 'center', marginBottom: 2, flexShrink: 0, backgroundColor: active ? colors.macOSTitleBarIconSelected : 'none', color: active ? colors.white : colors.macOSSidebarSectionItem, lineHeight: '25px', padding: '0 10px', '&[disabled]': { color: 'rgba(0, 0, 0, 0.5)', }, })); const SidebarHeader = styled(FlexBox)({ display: 'block', alignItems: 'center', padding: 3, color: colors.macOSSidebarSectionTitle, fontSize: 11, fontWeight: 500, marginLeft: 7, textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap', flexShrink: 0, }); const PluginShape = styled(FlexBox)(({backgroundColor}) => ({ marginRight: 5, backgroundColor, borderRadius: 3, flexShrink: 0, width: 18, height: 18, justifyContent: 'center', alignItems: 'center', })); const PluginName = styled(Text)(props => ({ minWidth: 0, textOverflow: 'ellipsis', whiteSpace: 'nowrap', overflow: 'hidden', display: 'flex', flexDirection: 'row', justifyContent: 'space-between', flexGrow: 1, '::after': { fontSize: 12, display: props.count ? 'inline-block' : 'none', padding: '0 8px', lineHeight: '17px', height: 17, alignSelf: 'center', content: `"${props.count}"`, borderRadius: '999em', color: props.isActive ? colors.macOSTitleBarIconSelected : colors.white, backgroundColor: props.isActive ? colors.white : colors.macOSTitleBarIconSelected, fontWeight: 500, }, })); function PluginIcon({ isActive, backgroundColor, name, color, }: { isActive: boolean, backgroundColor?: string, name: string, color: string, }) { return ( <PluginShape backgroundColor={backgroundColor}> <Glyph size={12} name={name} color={isActive ? colors.white : color} /> </PluginShape> ); } class PluginSidebarListItem extends Component<{ onClick: () => void, isActive: boolean, plugin: Class<FlipperBasePlugin<>>, app?: ?string, }> { render() { const {isActive, plugin} = this.props; const app = this.props.app || 'Facebook'; let iconColor = brandColors[app]; if (!iconColor) { const pluginColors = [ colors.seaFoam, colors.teal, colors.lime, colors.lemon, colors.orange, colors.tomato, colors.cherry, colors.pink, colors.grape, ]; iconColor = pluginColors[parseInt(app, 36) % pluginColors.length]; } return ( <ListItem active={isActive} onClick={this.props.onClick}> <PluginIcon isActive={isActive} name={plugin.icon} backgroundColor={iconColor} color={colors.white} /> <PluginName>{plugin.title}</PluginName> </ListItem> ); } } const Spinner = styled(LoadingIndicator)({ marginTop: '10px', marginBottom: '10px', marginLeft: 'auto', marginRight: 'auto', }); type MainSidebarProps = {| selectedPlugin: ?string, selectedApp: ?string, selectedDevice: ?BaseDevice, windowIsFocused: boolean, selectPlugin: (payload: { selectedPlugin: ?string, selectedApp: ?string, }) => void, clients: Array<Client>, uninitializedClients: Array<{ client: UninitializedClient, deviceId?: string, }>, activeNotifications: Array<PluginNotification>, blacklistedPlugins: Array<string>, |}; class MainSidebar extends Component<MainSidebarProps> { render() { const { selectedDevice, selectedPlugin, selectedApp, selectPlugin, windowIsFocused, activeNotifications, } = this.props; let {clients, uninitializedClients} = this.props; clients = clients .filter( (client: Client) => selectedDevice && selectedDevice.supportsOS(client.query.os), ) .sort((a, b) => (a.query.app || '').localeCompare(b.query.app)); let blacklistedPlugins = new Set(this.props.blacklistedPlugins); const notifications = activeNotifications.filter( (n: PluginNotification) => !blacklistedPlugins.has(n.pluginId), ); return ( <Sidebar position="left" width={200} backgroundColor={ process.platform === 'darwin' && windowIsFocused ? 'transparent' : '' }> {!GK.get('flipper_disable_notifications') && ( <ListItem active={selectedPlugin === 'notifications'} onClick={() => selectPlugin({ selectedPlugin: 'notifications', selectedApp: null, }) }> <PluginIcon color={colors.light50} name={ notifications.length > 0 ? NotificationsHub.icon : 'bell-null' } isActive={selectedPlugin === NotificationsHub.id} /> <PluginName count={notifications.length} isActive={selectedPlugin === NotificationsHub.id}> {NotificationsHub.title} </PluginName> </ListItem> )} {selectedDevice && ( <SidebarHeader>{selectedDevice.title}</SidebarHeader> )} {selectedDevice && devicePlugins .filter(plugin => plugin.supportsDevice(selectedDevice)) .map((plugin: Class<FlipperDevicePlugin<>>) => ( <PluginSidebarListItem key={plugin.id} isActive={plugin.id === selectedPlugin} onClick={() => selectPlugin({ selectedPlugin: plugin.id, selectedApp: null, }) } plugin={plugin} /> ))} {clients .filter( (client: Client) => (selectedDevice && client.query.device_id === selectedDevice.serial) || // Old android sdk versions don't know their device_id // Display their plugins under all selected devices until they die out client.query.device_id === 'unknown', ) .map((client: Client) => ( <React.Fragment key={client.id}> <SidebarHeader>{client.query.app}</SidebarHeader> {clientPlugins .filter( (p: Class<FlipperPlugin<>>) => client.plugins.indexOf(p.id) > -1, ) .map((plugin: Class<FlipperPlugin<>>) => ( <PluginSidebarListItem key={plugin.id} isActive={ plugin.id === selectedPlugin && selectedApp === client.id } onClick={() => selectPlugin({ selectedPlugin: plugin.id, selectedApp: client.id, }) } plugin={plugin} app={client.query.app} /> ))} </React.Fragment> ))} {uninitializedClients.map(entry => ( <React.Fragment key={JSON.stringify(entry.client)}> <SidebarHeader>{entry.client.appName}</SidebarHeader> <Spinner size={16} /> </React.Fragment> ))} </Sidebar> ); } } /* $FlowFixMe(>=0.86.0) This * comment suppresses an error found when Flow v0.86 was * deployed. To see the error, delete this comment and * run Flow. */ export default connect( ({ application: {windowIsFocused}, connections: { selectedDevice, selectedPlugin, selectedApp, clients, uninitializedClients, }, notifications: {activeNotifications, blacklistedPlugins}, }) => ({ blacklistedPlugins, activeNotifications, windowIsFocused, selectedDevice, selectedPlugin, selectedApp, clients, uninitializedClients, }), { selectPlugin, }, )(MainSidebar);
src/chrome/MainSidebar.js
/** * Copyright 2018-present Facebook. * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * @format */ import {FlipperBasePlugin} from '../plugin.js'; import type BaseDevice from '../devices/BaseDevice.js'; import type Client from '../Client.js'; import type {PluginNotification} from '../reducers/notifications'; import { Component, Sidebar, FlexBox, colors, brandColors, Text, Glyph, styled, GK, FlipperPlugin, FlipperDevicePlugin, } from 'flipper'; import React from 'react'; import {devicePlugins, clientPlugins} from '../plugins/index.js'; import NotificationsHub from '../NotificationsHub.js'; import {selectPlugin} from '../reducers/connections.js'; import {connect} from 'react-redux'; const ListItem = styled('div')(({active}) => ({ paddingLeft: 10, display: 'flex', alignItems: 'center', marginBottom: 2, flexShrink: 0, backgroundColor: active ? colors.macOSTitleBarIconSelected : 'none', color: active ? colors.white : colors.macOSSidebarSectionItem, lineHeight: '25px', padding: '0 10px', '&[disabled]': { color: 'rgba(0, 0, 0, 0.5)', }, })); const SidebarHeader = styled(FlexBox)({ display: 'block', alignItems: 'center', padding: 3, color: colors.macOSSidebarSectionTitle, fontSize: 11, fontWeight: 500, marginLeft: 7, textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap', flexShrink: 0, }); const PluginShape = styled(FlexBox)(({backgroundColor}) => ({ marginRight: 5, backgroundColor, borderRadius: 3, flexShrink: 0, width: 18, height: 18, justifyContent: 'center', alignItems: 'center', })); const PluginName = styled(Text)(props => ({ minWidth: 0, textOverflow: 'ellipsis', whiteSpace: 'nowrap', overflow: 'hidden', display: 'flex', flexDirection: 'row', justifyContent: 'space-between', flexGrow: 1, '::after': { fontSize: 12, display: props.count ? 'inline-block' : 'none', padding: '0 8px', lineHeight: '17px', height: 17, alignSelf: 'center', content: `"${props.count}"`, borderRadius: '999em', color: props.isActive ? colors.macOSTitleBarIconSelected : colors.white, backgroundColor: props.isActive ? colors.white : colors.macOSTitleBarIconSelected, fontWeight: 500, }, })); function PluginIcon({ isActive, backgroundColor, name, color, }: { isActive: boolean, backgroundColor?: string, name: string, color: string, }) { return ( <PluginShape backgroundColor={backgroundColor}> <Glyph size={12} name={name} color={isActive ? colors.white : color} /> </PluginShape> ); } class PluginSidebarListItem extends Component<{ onClick: () => void, isActive: boolean, plugin: Class<FlipperBasePlugin<>>, app?: ?string, }> { render() { const {isActive, plugin} = this.props; const app = this.props.app || 'Facebook'; let iconColor = brandColors[app]; if (!iconColor) { const pluginColors = [ colors.seaFoam, colors.teal, colors.lime, colors.lemon, colors.orange, colors.tomato, colors.cherry, colors.pink, colors.grape, ]; iconColor = pluginColors[parseInt(app, 36) % pluginColors.length]; } return ( <ListItem active={isActive} onClick={this.props.onClick}> <PluginIcon isActive={isActive} name={plugin.icon} backgroundColor={iconColor} color={colors.white} /> <PluginName>{plugin.title}</PluginName> </ListItem> ); } } type MainSidebarProps = {| selectedPlugin: ?string, selectedApp: ?string, selectedDevice: ?BaseDevice, windowIsFocused: boolean, selectPlugin: (payload: { selectedPlugin: ?string, selectedApp: ?string, }) => void, clients: Array<Client>, activeNotifications: Array<PluginNotification>, blacklistedPlugins: Array<string>, |}; class MainSidebar extends Component<MainSidebarProps> { render() { const { selectedDevice, selectedPlugin, selectedApp, selectPlugin, windowIsFocused, activeNotifications, } = this.props; let {clients} = this.props; clients = clients .filter( (client: Client) => selectedDevice && selectedDevice.supportsOS(client.query.os), ) .sort((a, b) => (a.query.app || '').localeCompare(b.query.app)); let blacklistedPlugins = new Set(this.props.blacklistedPlugins); const notifications = activeNotifications.filter( (n: PluginNotification) => !blacklistedPlugins.has(n.pluginId), ); return ( <Sidebar position="left" width={200} backgroundColor={ process.platform === 'darwin' && windowIsFocused ? 'transparent' : '' }> {!GK.get('flipper_disable_notifications') && ( <ListItem active={selectedPlugin === 'notifications'} onClick={() => selectPlugin({ selectedPlugin: 'notifications', selectedApp: null, }) }> <PluginIcon color={colors.light50} name={ notifications.length > 0 ? NotificationsHub.icon : 'bell-null' } isActive={selectedPlugin === NotificationsHub.id} /> <PluginName count={notifications.length} isActive={selectedPlugin === NotificationsHub.id}> {NotificationsHub.title} </PluginName> </ListItem> )} {selectedDevice && ( <SidebarHeader>{selectedDevice.title}</SidebarHeader> )} {selectedDevice && devicePlugins .filter(plugin => plugin.supportsDevice(selectedDevice)) .map((plugin: Class<FlipperDevicePlugin<>>) => ( <PluginSidebarListItem key={plugin.id} isActive={plugin.id === selectedPlugin} onClick={() => selectPlugin({ selectedPlugin: plugin.id, selectedApp: null, }) } plugin={plugin} /> ))} {clients .filter( (client: Client) => (selectedDevice && client.query.device_id === selectedDevice.serial) || // Old android sdk versions don't know their device_id // Display their plugins under all selected devices until they die out client.query.device_id === 'unknown', ) .map((client: Client) => ( <React.Fragment key={client.id}> <SidebarHeader>{client.query.app}</SidebarHeader> {clientPlugins .filter( (p: Class<FlipperPlugin<>>) => client.plugins.indexOf(p.id) > -1, ) .map((plugin: Class<FlipperPlugin<>>) => ( <PluginSidebarListItem key={plugin.id} isActive={ plugin.id === selectedPlugin && selectedApp === client.id } onClick={() => selectPlugin({ selectedPlugin: plugin.id, selectedApp: client.id, }) } plugin={plugin} app={client.query.app} /> ))} </React.Fragment> ))} </Sidebar> ); } } /* $FlowFixMe(>=0.86.0) This * comment suppresses an error found when Flow v0.86 was * deployed. To see the error, delete this comment and * run Flow. */ export default connect( ({ application: {windowIsFocused}, connections: {selectedDevice, selectedPlugin, selectedApp, clients}, notifications: {activeNotifications, blacklistedPlugins}, }) => ({ blacklistedPlugins, activeNotifications, windowIsFocused, selectedDevice, selectedPlugin, selectedApp, clients, }), { selectPlugin, }, )(MainSidebar);
Show connecting spinner Summary: First step in visualising the connection setup process. Just a spinner while cert exchange is happening, so it doesn't look like nothing is happening. Reviewed By: passy Differential Revision: D13062514 fbshipit-source-id: a0692821025f42f4fe4af86faf059d4719008f25
src/chrome/MainSidebar.js
Show connecting spinner
<ide><path>rc/chrome/MainSidebar.js <ide> import {FlipperBasePlugin} from '../plugin.js'; <ide> import type BaseDevice from '../devices/BaseDevice.js'; <ide> import type Client from '../Client.js'; <add>import type {UninitializedClient} from '../UninitializedClient.js'; <ide> import type {PluginNotification} from '../reducers/notifications'; <ide> <ide> import { <ide> GK, <ide> FlipperPlugin, <ide> FlipperDevicePlugin, <add> LoadingIndicator, <ide> } from 'flipper'; <ide> import React from 'react'; <ide> import {devicePlugins, clientPlugins} from '../plugins/index.js'; <ide> } <ide> } <ide> <add>const Spinner = styled(LoadingIndicator)({ <add> marginTop: '10px', <add> marginBottom: '10px', <add> marginLeft: 'auto', <add> marginRight: 'auto', <add>}); <add> <ide> type MainSidebarProps = {| <ide> selectedPlugin: ?string, <ide> selectedApp: ?string, <ide> selectedApp: ?string, <ide> }) => void, <ide> clients: Array<Client>, <add> uninitializedClients: Array<{ <add> client: UninitializedClient, <add> deviceId?: string, <add> }>, <ide> activeNotifications: Array<PluginNotification>, <ide> blacklistedPlugins: Array<string>, <ide> |}; <ide> windowIsFocused, <ide> activeNotifications, <ide> } = this.props; <del> let {clients} = this.props; <add> let {clients, uninitializedClients} = this.props; <ide> <ide> clients = clients <ide> .filter( <ide> ))} <ide> </React.Fragment> <ide> ))} <add> {uninitializedClients.map(entry => ( <add> <React.Fragment key={JSON.stringify(entry.client)}> <add> <SidebarHeader>{entry.client.appName}</SidebarHeader> <add> <Spinner size={16} /> <add> </React.Fragment> <add> ))} <ide> </Sidebar> <ide> ); <ide> } <ide> export default connect( <ide> ({ <ide> application: {windowIsFocused}, <del> connections: {selectedDevice, selectedPlugin, selectedApp, clients}, <add> connections: { <add> selectedDevice, <add> selectedPlugin, <add> selectedApp, <add> clients, <add> uninitializedClients, <add> }, <ide> notifications: {activeNotifications, blacklistedPlugins}, <ide> }) => ({ <ide> blacklistedPlugins, <ide> selectedPlugin, <ide> selectedApp, <ide> clients, <add> uninitializedClients, <ide> }), <ide> { <ide> selectPlugin,
Java
mit
1806931c7df42d49974ad7ece4ec681ea22e46ff
0
gturri/aXMLRPC,gturri/aXMLRPC,timroes/aXMLRPC
package de.timeroes.axmlrpc; import java.net.URL; import org.junit.Test; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static org.junit.Assert.*; import org.junit.Rule; import com.github.tomakehurst.wiremock.junit.WireMockRule; import de.timroes.axmlrpc.XMLRPCClient; public class TestResponseParser { private final int port = 8080; private final String endPoint = "/dummyEndPoint"; @Rule public WireMockRule wireMockRule = new WireMockRule(port); @Test public void canParseString() throws Exception { setMockWithXmlRpcContent("<value><string>toto</string></value>"); assertEquals("toto", makeDummyCall()); } @Test public void canParseAsStringWhenTypeIsntExplicitelyProvided() throws Exception { setMockWithXmlRpcContent("<value>toto</value>"); assertEquals("toto", makeDummyCall(XMLRPCClient.FLAGS_DEFAULT_TYPE_STRING)); } @Test public void canParseInt() throws Exception { setMockWithXmlRpcContent("<value><i4>32</i4></value>"); assertEquals(32, makeDummyCall()); setMockWithXmlRpcContent("<value><int>33</int></value>"); assertEquals(33, makeDummyCall()); } @Test public void canParseBoolean() throws Exception { setMockWithXmlRpcContent("<value><boolean>1</boolean></value>"); assertEquals(true, makeDummyCall()); setMockWithXmlRpcContent("<value><boolean>0</boolean></value>"); assertEquals(false, makeDummyCall()); } private void setMockWithXmlRpcContent(String content){ stubFor(post(urlEqualTo(endPoint)) .willReturn(aResponse() .withStatus(200) .withBody("<methodResponse><params><param>" + content + "</param></params></methodResponse>") )); } private Object makeDummyCall() throws Exception { return makeDummyCall(XMLRPCClient.FLAGS_NONE); } private Object makeDummyCall(int flags) throws Exception { return new XMLRPCClient(new URL("http://localhost:" + port + endPoint), flags).call("dummy_method"); } }
src/test/java/de/timeroes/axmlrpc/TestResponseParser.java
package de.timeroes.axmlrpc; import java.net.URL; import org.junit.Test; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static org.junit.Assert.*; import org.junit.Rule; import com.github.tomakehurst.wiremock.junit.WireMockRule; import de.timroes.axmlrpc.XMLRPCClient; public class TestResponseParser { private final int port = 8080; private final String endPoint = "/dummyEndPoint"; @Rule public WireMockRule wireMockRule = new WireMockRule(port); @Test public void canParseString() throws Exception { setMockWithXmlRpcContent("<value><string>toto</string></value>"); assertEquals("toto", makeDummyCall()); } @Test public void canParseInt() throws Exception { setMockWithXmlRpcContent("<value><i4>32</i4></value>"); assertEquals(32, makeDummyCall()); setMockWithXmlRpcContent("<value><int>33</int></value>"); assertEquals(33, makeDummyCall()); } @Test public void canParseBoolean() throws Exception { setMockWithXmlRpcContent("<value><boolean>1</boolean></value>"); assertEquals(true, makeDummyCall()); setMockWithXmlRpcContent("<value><boolean>0</boolean></value>"); assertEquals(false, makeDummyCall()); } private void setMockWithXmlRpcContent(String content){ stubFor(post(urlEqualTo(endPoint)) .willReturn(aResponse() .withStatus(200) .withBody("<methodResponse><params><param>" + content + "</param></params></methodResponse>") )); } private Object makeDummyCall() throws Exception { return new XMLRPCClient(new URL("http://localhost:" + port + endPoint)).call("dummy_method"); } }
Add test for case where type String is implicit
src/test/java/de/timeroes/axmlrpc/TestResponseParser.java
Add test for case where type String is implicit
<ide><path>rc/test/java/de/timeroes/axmlrpc/TestResponseParser.java <ide> } <ide> <ide> @Test <add> public void canParseAsStringWhenTypeIsntExplicitelyProvided() throws Exception { <add> setMockWithXmlRpcContent("<value>toto</value>"); <add> assertEquals("toto", makeDummyCall(XMLRPCClient.FLAGS_DEFAULT_TYPE_STRING)); <add> } <add> <add> @Test <ide> public void canParseInt() throws Exception { <ide> setMockWithXmlRpcContent("<value><i4>32</i4></value>"); <ide> assertEquals(32, makeDummyCall()); <ide> } <ide> <ide> private Object makeDummyCall() throws Exception { <del> return new XMLRPCClient(new URL("http://localhost:" + port + endPoint)).call("dummy_method"); <add> return makeDummyCall(XMLRPCClient.FLAGS_NONE); <add> } <add> <add> private Object makeDummyCall(int flags) throws Exception { <add> return new XMLRPCClient(new URL("http://localhost:" + port + endPoint), flags).call("dummy_method"); <ide> } <ide> }
Java
agpl-3.0
2646c8e200681cb7ded020b2b830fe0ba1b2f7c2
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
98aaa9b6-2e60-11e5-9284-b827eb9e62be
hello.java
98a50100-2e60-11e5-9284-b827eb9e62be
98aaa9b6-2e60-11e5-9284-b827eb9e62be
hello.java
98aaa9b6-2e60-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>98a50100-2e60-11e5-9284-b827eb9e62be <add>98aaa9b6-2e60-11e5-9284-b827eb9e62be
Java
mit
4dfe066227b76a39cface567c624a427a7857bfa
0
lihengming/java-codes
package thread; import java.util.concurrent.TimeUnit; /** * Created by 李恒名 on 2017/8/29. * * 死锁测试,线程1获得A锁(monitor)之后尝试获得B锁,线程2获得B锁后尝试获得A锁,线程1和线程2即产生死锁。 */ public class DeadlockTest { public static void main(String[] args) { Object lockA = new Object(); Object lockB = new Object(); new Thread(() -> { //线程1获得A锁 synchronized (lockA){ System.out.println("Thread 1 get lock A ."); //增加死锁发生几率 try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {} //尝试获得B锁 System.out.println("Thread 1 try get lock B, waiting..."); synchronized (lockB){ //永远无法获得B锁,所以不会打印出来 System.out.println("Thread 1 get lock B ."); } } }, "Thread 1").start(); new Thread(() -> { //线程2获得B锁 synchronized (lockB){ System.out.println("Thread 2 get lock B ."); //增加死锁发生几率 try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {} //尝试获得A锁 System.out.println("Thread 2 try get lock A, waiting..."); synchronized (lockA){ //永远无法获得A锁,所以不会打印出来 System.out.println("Thread 2 get lock A ."); } } }, "Thread 2").start(); } }
concurrent/src/main/java/thread/DeadlockTest.java
package thread; import java.util.concurrent.TimeUnit; /** * Created by 李恒名 on 2017/8/29. * * 死锁测试,线程1获得A锁之后尝试获得B锁,线程2获得B锁后尝试获得A锁,线程1和线程2即产生死锁。 */ public class DeadlockTest { public static void main(String[] args) { Object lockA = new Object(); Object lockB = new Object(); new Thread(() -> { //线程1获得A锁 synchronized (lockA){ System.out.println("Thread 1 get lock A ."); //增加死锁发生几率 try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {} //尝试获得B锁 System.out.println("Thread 1 try get lock B, waiting..."); synchronized (lockB){ //永远无法获得B锁,所以不会打印出来 System.out.println("Thread 1 get lock B ."); } } }, "Thread 1").start(); new Thread(() -> { //线程2获得B锁 synchronized (lockB){ System.out.println("Thread 2 get lock B ."); //增加死锁发生几率 try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {} //尝试获得A锁 System.out.println("Thread 2 try get lock A, waiting..."); synchronized (lockA){ //永远无法获得A锁,所以不会打印出来 System.out.println("Thread 2 get lock A ."); } } }, "Thread 2").start(); } }
add > deadlock test
concurrent/src/main/java/thread/DeadlockTest.java
add > deadlock test
<ide><path>oncurrent/src/main/java/thread/DeadlockTest.java <ide> /** <ide> * Created by 李恒名 on 2017/8/29. <ide> * <del> * 死锁测试,线程1获得A锁之后尝试获得B锁,线程2获得B锁后尝试获得A锁,线程1和线程2即产生死锁。 <add> * 死锁测试,线程1获得A锁(monitor)之后尝试获得B锁,线程2获得B锁后尝试获得A锁,线程1和线程2即产生死锁。 <ide> */ <ide> public class DeadlockTest { <ide> public static void main(String[] args) {
JavaScript
agpl-3.0
abd7463f8baffe7250d5745d96d9fc63ba7bcaa1
0
threadvis/ThreadVis,threadvis/ThreadVis,threadvis/ThreadVis
/* ***************************************************************************** * This file is part of ThreadVis. * http://threadvis.mozdev.org/ * * ThreadVis started as part of Alexander C. Hubmann-Haidvogel's Master's Thesis * titled "ThreadVis for Thunderbird: A Thread Visualisation Extension for the * Mozilla Thunderbird Email Client" at Graz University of Technology, Austria. * An electronic version of the thesis is available online at * http://www.iicm.tugraz.at/ahubmann.pdf * * Copyright (C) 2005, 2006, 2007 Alexander C. Hubmann * Copyright (C) 2007, 2008, 2009, 2010 Alexander C. Hubmann-Haidvogel * * ThreadVis is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * ThreadVis is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with ThreadVis. If not, see <http://www.gnu.org/licenses/>. * * Version: $Id$ * ***************************************************************************** * Main JavaScript file. ******************************************************************************/ if (! window.ThreadVisNS) { window.ThreadVisNS = {}; } var THREADVIS = null; // add visualisation at startup addEventListener("load", function() { ThreadVisNS.createThreadVis(); }, false); /** **************************************************************************** * Create one and only one threadvis object * * @return * void ******************************************************************************/ ThreadVisNS.createThreadVis = function() { var threadvisParent = ThreadVisNS.checkForThreadVis(window); if (THREADVIS == null) { THREADVIS = new ThreadVisNS.ThreadVis(threadvisParent); THREADVIS.init(); } } /** **************************************************************************** * Check all openers for threadvis * * @param win * The window object to check * @return * A found threadvis object ******************************************************************************/ ThreadVisNS.checkForThreadVis = function(win) { if (! win) { return null; } if (win.THREADVIS) { return win.THREADVIS; } if (win.parent && win != win.parent) { return ThreadVisNS.checkForThreadVis(win.parent); } if (win.opener) { return ThreadVisNS.checkForThreadVis(win.opener); } return null; } /** **************************************************************************** * Constructor * * @param threadvisparent * Link to parent object (if it exists) * @return * A new ThreadVis object ******************************************************************************/ ThreadVisNS.ThreadVis = function(threadvisParent) { this.XUL_NAMESPACE = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; // increment this to trigger about dialog this.ABOUT = 1; this.clear = false; this.strings = document.getElementById("ThreadVisStrings"); // store server to react to server switch this.server = null; // if parent object exists, reuse some of the internal objects this.threadvisParent = threadvisParent; // remember all local accounts, for sent-mail comparison var accountManager = Components.classes["@mozilla.org/messenger/account-manager;1"] .getService(Components.interfaces.nsIMsgAccountManager); var identities = accountManager.allIdentities.QueryInterface( Components.interfaces.nsICollection).Enumerate(); var done = false; this.sentMailIdentities = new Object(); while (! done) { try { var identity = identities.currentItem().QueryInterface( Components.interfaces.nsIMsgIdentity); } catch (e) { done = true; } if (identity) { this.sentMailIdentities[identity.email] = true; } try { identities.next(); } catch (e) { done = true; } } } /** **************************************************************************** * Callback function from extension. Called after mouse click in extension * Select message in mail view. * * @param message * The message to display * @param isMessageWindow * True if standalone window * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.callback = function(message, isMessageWindow) { if (! this.checkEnabled()) { return; } // re-search message in case its folder has changed var folder = MailUtils.getFolderForURI(message.getFolder(), true); var msg = this.cache.searchMessageByMsgId(message.getId(), folder.rootFolder); if (! isMessageWindow) { gFolderTreeView.selectFolder(msg.folder); } gFolderDisplay.clearSelection(); gFolderDisplay.show(msg.folder); gFolderDisplay.selectMessage(msg); } /** **************************************************************************** * Check if extension and all needed other parts (e.g. gloda) are enabled * * @return * True if the extension is enabled, false if not. ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.checkEnabled = function() { var threadvisEnabled = this.preferences.getPreference(this.preferences.PREF_ENABLED); var glodaEnabled = this.preferences.getPreference(this.preferences.PREF_GLODA_ENABLED); return threadvisEnabled && glodaEnabled; } /** **************************************************************************** * Check if current account is enabled in extension * * @param folder * The folder to check * @return * True if the folder/account is enabled, false if not. ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.checkEnabledAccountOrFolder = function(folder) { if (! folder) { folder = this.getMainWindow().gFolderDisplay.displayedFolder; } if (! folder) { return false; } var server = folder.server; var account = (Components.classes["@mozilla.org/messenger/account-manager;1"] .getService(Components.interfaces.nsIMsgAccountManager)) .FindAccountForServer(server); if (this.preferences.getPreference(this.preferences.PREF_DISABLED_ACCOUNTS) != "" && this.preferences.getPreference(this.preferences.PREF_DISABLED_ACCOUNTS) .indexOf(" " + account.key + " ") > -1) { return false; } else { if (this.preferences.getPreference(this.preferences.PREF_DISABLED_FOLDERS) != "" && this.preferences.getPreference(this.preferences.PREF_DISABLED_FOLDERS) .indexOf(" " + folder.URI + " ") > -1) { return false; } else { return true; } } } /** **************************************************************************** * Clear visualisation * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.clearVisualisation = function() { if (! this.checkEnabled()) { return; } if (this.clear) { return; } this.visualisation.createStack(); this.clear = true; // also clear popup if (this.popupWindow && ! this.popupWindow.closed) { this.popupWindow.THREADVIS.clearVisualisation(); } // also clear legend if (this.legendWindow && ! this.legendWindow.closed) { this.legendWindow.clearLegend(); } // also clear legend in opener if (opener && opener.THREADVIS && opener.THREADVIS.legendWindow && ! opener.THREADVIS.legendWindow.closed) { opener.THREADVIS.legendWindow.clearLegend(); } } /** **************************************************************************** * Create threadvis XUL box * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.createBox = function() { var elem = document.getElementById("ThreadVis"); elem.hidden = false; } /** **************************************************************************** * Delete threadvis XUL box * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.deleteBox = function() { var elem = document.getElementById("ThreadVis"); elem.hidden = true; } /** **************************************************************************** * Display legend popup * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.displayLegend = function() { if (window.opener && window.opener.THREADVIS) { window.opener.THREADVIS.displayLegend(); } if (this.legendWindow != null && ! this.legendWindow.closed) { this.legendWindow.displayLegend(); } } /** **************************************************************************** * Display legend popup * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.displayLegendWindow = function() { if (this.visualisation.disabled) { return; } if (window.opener && window.opener.THREADVIS) { window.opener.THREADVIS.displayLegendWindow(); return; } if (this.legendWindow != null && ! this.legendWindow.closed) { this.legendWindow.close(); return; } var flags = "chrome=yes,resizable=no,alwaysRaised=yes,dependent=yes,dialog=yes"; this.legendWindow = window.openDialog("chrome://threadvis/content/Legend.xul", "ThreadVisLegend", flags); } /** **************************************************************************** * Display about dialog when first starting ThreadVis * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.displayAbout = function() { var showedAbout = this.preferences .getPreference(this.preferences.PREF_ABOUT); if (showedAbout < this.ABOUT) { window.openDialog("chrome://threadvis/content/About.xul", "ThreadVisAbout", "chrome=yes,resizable=true;alwaysRaised=false,dependent=yes"); } } /** **************************************************************************** * Display a popup window for the visualisation * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.displayVisualisationWindow = function() { if (this.visualisation.disabled) { return; } if (this.popupWindow != null && ! this.popupWindow.closed) { this.popupWindow.focus(); return; } var flags = "chrome=yes,resizable=yes,alwaysRaised=yes,dependent=yes"; this.popupWindow = window.openDialog("chrome://threadvis/content/ThreadVisPopup.xul", "ThreadVisPopup", flags); this.deleteBox(); clearInterval(this.visualisation.checkResizeInterval); this.visualisedMsgId = null; } /** **************************************************************************** * Get legend object * * @return * The legend object, null if it doesn't exist ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.getLegend = function() { if (this.popupWindow && this.popupWindow.THREADVIS) { return this.popupWindow.THREADVIS.visualisation.legend; } else { return this.visualisation.legend; } } /** **************************************************************************** * Return main window object * * @return * The main window ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.getMainWindow = function() { var w = window; while (w != null) { if (typeof(w.GetThreadTree) == "function") { return w; } w = w.opener; } return null; } /** **************************************************************************** * Get popup visualisation * * @return * The popup window, null if no popup exists ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.getPopupVisualisation = function() { if (this.popupWindow != null && ! this.popupWindow.closed) { return this.popupWindow; } if (this.threadvisParent) { return this.threadvisParent.getPopupVisualisation(); } return null; } /** **************************************************************************** * Check if a popup visualisation exists * * @return * True if a popup exists, false if not ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.hasPopupVisualisation = function() { if (this.popupWindow != null && ! this.popupWindow.closed) { return true; } if (this.threadvisParent) { return this.threadvisParent.hasPopupVisualisation(); } return false; } /** **************************************************************************** * Init object * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.init = function() { if (this.threadvisParent) { this.threader = this.threadvisParent.getThreader(); this.server = this.threadvisParent.server; this.preferences = this.threadvisParent.preferences; this.cache = this.threadvisParent.cache; } else { var ref = this; this.preferences = new ThreadVisNS.PreferenceObserver(); this.preferences.registerCallback(this.preferences.PREF_DISABLED_ACCOUNTS, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_DISABLED_FOLDERS, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_ENABLED, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_TIMELINE, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_TIMESCALING, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_DOTSIZE, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_ARC_MINHEIGHT, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_ARC_RADIUS, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_ARC_DIFFERENCE, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_ARC_WIDTH, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_SPACING, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_MESSAGE_CIRCLES, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_COLOUR, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_COLOURS_BACKGROUND, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_COLOURS_BORDER, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_COLOURS_RECEIVED, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_COLOURS_SENT, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_HIGHLIGHT, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_OPACITY, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_ZOOM, function(value) {ref.preferenceChanged();}); this.cache = new ThreadVisNS.Cache(this); // display about dialog and email reminder only once on each startup setTimeout(function() { THREADVIS.displayAbout(); }, 5000); } if (! this.checkEnabled()) { this.deleteBox(); return; } // visualisation object if (! this.visualisation) { this.visualisation = new ThreadVisNS.Visualisation(); } // create box object this.createBox(); this.clearVisualisation(); // check to see if parent threadvis object exists if (this.threadvisParent) { // visualise selected message // delay drawing until size of box is known this.delayDrawing(); return; } else { if (! this.threader) { this.threader= new ThreadVisNS.Threader(); } } /* ************************************************************************ * code below only gets executed if no parent threadvis object was found * ***********************************************************************/ // remember msgid of visualised message this.visualisedMsgId = ""; // remember selected message this.selectedMsgUri = ""; // remember container of selected message this.selectedContainer = null; // register for message selection var ref = this; var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); observerService.addObserver({ observe: function(subject, topic, data) { ref.selectedMsgUri = data; ref.setSelectedMessage(); } }, "MsgMsgDisplayed", false); } /** **************************************************************************** * Delay drawing of visualisation until size of box is known * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.delayDrawing = function() { var boxSize = this.visualisation.getBoxSize(); if (boxSize.width > 0) { this.visualise(this.threadvisParent.selectedContainer); } else { var ref = this; setTimeout(function() { ref.delayDrawing(); }, 100); } } /** **************************************************************************** * Check if the current window is a message window * * @return * True if the current window is a message window, false if not ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.isMessageWindow = function() { if (this.threadvisParent && document.getElementById("expandedHeaderView") != null) { return true; } else { return false; } } /** **************************************************************************** * Check if this window is a popup * * @return * True if this window is a popup, false if not ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.isPopupVisualisation = function() { return document.documentElement.id == "ThreadVisPopup"; } /** **************************************************************************** * Called when popup window gets closed * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.onVisualisationWindowClose = function() { this.visualisedMsgId = null; this.threadvisParent.visualisedMsgId = null; this.threadvisParent.setSelectedMessage(); } /** **************************************************************************** * Open the options dialog for this extension * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.openThreadVisOptionsDialog = function() { this.getMainWindow().openOptionsDialog('paneThreadVis', null); } /** **************************************************************************** * Preference changed * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.preferenceChanged = function() { this.visualisation.changed = true; if (this.popupWindow && this.popupWindow.THREADVIS) this.popupWindow.THREADVIS.visualisation.changed = true; this.setSelectedMessage(true); } /** **************************************************************************** * Called after user resized visualisation using splitter * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.setMinimalWidth = function() { var width = document.getElementById("ThreadVis").boxObject.width; this.preferences.setPreference(this.preferences.PREF_VIS_MINIMAL_WIDTH, width, this.preferences.PREF_INT); } /** **************************************************************************** * Called when a message is selected * Call visualisation with messageid to visualise * * @param force * True to force display of message * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.setSelectedMessage = function(force) { if (! this.checkEnabled()) { this.visualisation.disabled = true; this.visualisation.displayDisabled(); this.visualisedMsgId = null; this.setStatus(null, {enabled: false}); return; } if (! this.checkEnabledAccountOrFolder()) { this.visualisation.disabled = true; this.visualisation.displayDisabled(); this.visualisedMsgId = null; this.setStatus(null, {folderEnabled: false}); return; } this.setStatus(null, {enabled: true, folderEnabled: true}); this.visualisation.disabled = false; // get currently loaded message var msg = messenger.messageServiceFromURI(this.selectedMsgUri) .messageURIToMsgHdr(this.selectedMsgUri); var loadedMsgFolder = msg.folder; this.rootFolder = loadedMsgFolder.rootFolder; this.server = loadedMsgFolder.server; this.account = (Components.classes["@mozilla.org/messenger/account-manager;1"] .getService(Components.interfaces.nsIMsgAccountManager)) .FindAccountForServer(this.server); // delay display to give UI time to layout var ref = this; setTimeout(function(){ref.visualiseMessage(msg, force);}, 100); } /** **************************************************************************** * Visualise a container * * @param container * The container to visualise * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.visualise = function(container) { if (! this.checkEnabled() || ! this.checkEnabledAccountOrFolder()) { return; } var msgCount = container.getTopContainer().getCountRecursive(); if (this.hasPopupVisualisation() && ! this.isPopupVisualisation()) { this.getPopupVisualisation().THREADVIS.visualise(container); return; } // if user wants to hide visualisation if it only consists of a single // message, do so, but not in popup visualisation if (msgCount == 1 && this.preferences.getPreference(this.preferences.PREF_VIS_HIDE_ON_SINGLE) && ! this.isPopupVisualisation()) { this.visualisation.disabled = true; this.visualisation.displayDisabled(true); this.visualisedMsgId = null; this.selectedContainer = null; return; } this.clear = false; this.createBox(); this.visualisation.disabled = false; this.visualisation.visualise(container); this.selectedContainer = container; } /** **************************************************************************** * Visualise a message. Find the container. Call visualise() * * @param message * The message to visualise * @param force * True to force the display of the visualisation * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.visualiseMessage = function(message, force) { if (this.visualisedMsgId == message.messageId && ! force) { return; } if (! this.checkEnabled() || ! this.checkEnabledAccountOrFolder()) { return; } // try to find in threader var container = this.getThreader().findContainer(message.messageId); // if not in threader, try to get from cache if (container == null || container.isDummy()) { var ref = this; this.cache.getCache(message, function() { ref.visualiseMessage(message, force); }); return; } // not in threader, not in cache, start caching if (container == null || container.isDummy()) { alert("NOT IN CACHE"); return; } this.visualisedMsgId = message.messageId; // clear threader //this.threader.reset(); if (container != null && ! container.isDummy()) { // visualise any popup windows that might exist if (this.popupWindow && this.popupWindow.THREADVIS) { this.popupWindow.THREADVIS.visualise(container); } else { this.visualise(container); } } else { // - message id not found, or // - container with id was dummy // this means we somehow missed to thread this message // TODO: check this error if (this.popupWindow && this.popupWindow.THREADVIS) { this.popupWindow.THREADVIS.clearVisualisation(); } else { this.clearVisualisation(); } } container = null; } /** **************************************************************************** * Zoom function to call from user click * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.zoomIn = function() { this.visualisation.zoomIn(); } /** **************************************************************************** * Zoom function to call from user click * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.zoomOut = function() { this.visualisation.zoomOut(); } /** **************************************************************************** * Get the threader object * * @return * The shared threader ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.getThreader = function() { return this.threader; } /** **************************************************************************** * Set the status text in the statusbar * * @param text * The text to display * @param tooltip * Tooltip data to display * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.setStatus = function(text, tooltip) { if (text != null) { var elem = document.getElementById("ThreadVisStatusText"); if (text != "") { elem.value = text; } else { elem.value = elem.getAttribute("defaultvalue"); } } if (typeof(tooltip) != "undefined") { if (typeof(tooltip.enabled) != "undefined") { if (tooltip.enabled) { document.getElementById("ThreadVisStatusTooltipDisabled").hidden = true; } else { document.getElementById("ThreadVisStatusTooltipDisabled").hidden = false; document.getElementById("ThreadVisStatusMenuEnableFolder").setAttribute("disabled", true); document.getElementById("ThreadVisStatusMenuDisableFolder").setAttribute("disabled", true); } } if (typeof(tooltip.folderEnabled) != "undefined") { if (tooltip.folderEnabled) { document.getElementById("ThreadVisStatusTooltipFolderDisabled").hidden = true; document.getElementById("ThreadVisStatusTooltipFolderEnabled").hidden = false; document.getElementById("ThreadVisStatusMenuEnableFolder").setAttribute("disabled", true); document.getElementById("ThreadVisStatusMenuDisableFolder").setAttribute("disabled", false); } else { document.getElementById("ThreadVisStatusTooltipFolderDisabled").hidden = false; document.getElementById("ThreadVisStatusTooltipFolderEnabled").hidden = true; document.getElementById("ThreadVisStatusMenuEnableFolder").setAttribute("disabled", false); document.getElementById("ThreadVisStatusMenuDisableFolder").setAttribute("disabled", true); } } } } /** **************************************************************************** * Disable for current folder * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.disableCurrentFolder = function() { // get currently displayed folder var folder = this.getMainWindow().GetLoadedMsgFolder(); if (folder) { var folderSetting = this.preferences.getPreference( this.preferences.PREF_DISABLED_FOLDERS); folderSetting = folderSetting + " " + folder.URI; this.preferences.setPreference( this.preferences.PREF_DISABLED_FOLDERS, folderSetting, this.preferences.PREF_STRING); } } /** **************************************************************************** * Enable for current folder * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.enableCurrentFolder = function() { // get currently displayed folder var folder = this.getMainWindow().GetLoadedMsgFolder(); if (folder) { var folderSetting = this.preferences.getPreference( this.preferences.PREF_DISABLED_FOLDERS); var index = folderSetting.indexOf(" " + folder.URI + " "); folderSetting = folderSetting.substring(0, index) + folderSetting.substring(index + folder.URI.length); this.preferences.setPreference( this.preferences.PREF_DISABLED_FOLDERS, folderSetting, this.preferences.PREF_STRING); } }
src/chrome/content/ThreadVis.js
/* ***************************************************************************** * This file is part of ThreadVis. * http://threadvis.mozdev.org/ * * ThreadVis started as part of Alexander C. Hubmann-Haidvogel's Master's Thesis * titled "ThreadVis for Thunderbird: A Thread Visualisation Extension for the * Mozilla Thunderbird Email Client" at Graz University of Technology, Austria. * An electronic version of the thesis is available online at * http://www.iicm.tugraz.at/ahubmann.pdf * * Copyright (C) 2005, 2006, 2007 Alexander C. Hubmann * Copyright (C) 2007, 2008, 2009, 2010 Alexander C. Hubmann-Haidvogel * * ThreadVis is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * ThreadVis is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with ThreadVis. If not, see <http://www.gnu.org/licenses/>. * * Version: $Id$ * ***************************************************************************** * Main JavaScript file. ******************************************************************************/ if (! window.ThreadVisNS) { window.ThreadVisNS = {}; } var THREADVIS = null; // add visualisation at startup addEventListener("load", function() { ThreadVisNS.createThreadVis(); }, false); /** **************************************************************************** * Create one and only one threadvis object * * @return * void ******************************************************************************/ ThreadVisNS.createThreadVis = function() { var threadvisParent = ThreadVisNS.checkForThreadVis(window); if (THREADVIS == null) { THREADVIS = new ThreadVisNS.ThreadVis(threadvisParent); THREADVIS.init(); } } /** **************************************************************************** * Check all openers for threadvis * * @param win * The window object to check * @return * A found threadvis object ******************************************************************************/ ThreadVisNS.checkForThreadVis = function(win) { if (! win) { return null; } if (win.THREADVIS) { return win.THREADVIS; } if (win.parent && win != win.parent) { return ThreadVisNS.checkForThreadVis(win.parent); } if (win.opener) { return ThreadVisNS.checkForThreadVis(win.opener); } return null; } /** **************************************************************************** * Constructor * * @param threadvisparent * Link to parent object (if it exists) * @return * A new ThreadVis object ******************************************************************************/ ThreadVisNS.ThreadVis = function(threadvisParent) { this.XUL_NAMESPACE = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; // increment this to trigger about dialog this.ABOUT = 1; this.clear = false; this.strings = document.getElementById("ThreadVisStrings"); // store server to react to server switch this.server = null; // if parent object exists, reuse some of the internal objects this.threadvisParent = threadvisParent; // remember all local accounts, for sent-mail comparison var accountManager = Components.classes["@mozilla.org/messenger/account-manager;1"] .getService(Components.interfaces.nsIMsgAccountManager); var identities = accountManager.allIdentities.QueryInterface( Components.interfaces.nsICollection).Enumerate(); var done = false; this.sentMailIdentities = new Object(); while (! done) { try { var identity = identities.currentItem().QueryInterface( Components.interfaces.nsIMsgIdentity); } catch (e) { done = true; } if (identity) { this.sentMailIdentities[identity.email] = true; } try { identities.next(); } catch (e) { done = true; } } } /** **************************************************************************** * Callback function from extension. Called after mouse click in extension * Select message in mail view. * * @param message * The message to display * @param isMessageWindow * True if standalone window * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.callback = function(message, isMessageWindow) { if (! this.checkEnabled()) { return; } // re-search message in case its folder has changed var folder = MailUtils.getFolderForURI(message.getFolder(), true); var msg = this.cache.searchMessageByMsgId(message.getId(), folder.rootFolder); if (! isMessageWindow) { gFolderTreeView.selectFolder(msg.folder); } gFolderDisplay.clearSelection(); gFolderDisplay.show(msg.folder); gFolderDisplay.selectMessage(msg); } /** **************************************************************************** * Check if extension and all needed other parts (e.g. gloda) are enabled * * @return * True if the extension is enabled, false if not. ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.checkEnabled = function() { var threadvisEnabled = this.preferences.getPreference(this.preferences.PREF_ENABLED); var glodaEnabled = this.preferences.getPreference(this.preferences.PREF_GLODA_ENABLED); return threadvisEnabled && glodaEnabled; } /** **************************************************************************** * Check if current account is enabled in extension * * @param folder * The folder to check * @return * True if the folder/account is enabled, false if not. ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.checkEnabledAccountOrFolder = function(folder) { if (! folder) { folder = this.getMainWindow().gFolderDisplay.displayedFolder; } if (! folder) { return false; } var server = folder.server; var account = (Components.classes["@mozilla.org/messenger/account-manager;1"] .getService(Components.interfaces.nsIMsgAccountManager)) .FindAccountForServer(server); if (this.preferences.getPreference(this.preferences.PREF_DISABLED_ACCOUNTS) != "" && this.preferences.getPreference(this.preferences.PREF_DISABLED_ACCOUNTS) .indexOf(" " + account.key + " ") > -1) { return false; } else { if (this.preferences.getPreference(this.preferences.PREF_DISABLED_FOLDERS) != "" && this.preferences.getPreference(this.preferences.PREF_DISABLED_FOLDERS) .indexOf(" " + folder.URI + " ") > -1) { return false; } else { return true; } } } /** **************************************************************************** * Clear visualisation * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.clearVisualisation = function() { if (! this.checkEnabled()) { return; } if (this.clear) { return; } this.visualisation.createStack(); this.clear = true; // also clear popup if (this.popupWindow && ! this.popupWindow.closed) { this.popupWindow.THREADVIS.clearVisualisation(); } // also clear legend if (this.legendWindow && ! this.legendWindow.closed) { this.legendWindow.clearLegend(); } // also clear legend in opener if (opener && opener.THREADVIS && opener.THREADVIS.legendWindow && ! opener.THREADVIS.legendWindow.closed) { opener.THREADVIS.legendWindow.clearLegend(); } } /** **************************************************************************** * Create threadvis XUL box * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.createBox = function() { var elem = document.getElementById("ThreadVis"); elem.hidden = false; } /** **************************************************************************** * Delete threadvis XUL box * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.deleteBox = function() { var elem = document.getElementById("ThreadVis"); elem.hidden = true; } /** **************************************************************************** * Display legend popup * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.displayLegend = function() { if (window.opener && window.opener.THREADVIS) { window.opener.THREADVIS.displayLegend(); } if (this.legendWindow != null && ! this.legendWindow.closed) { this.legendWindow.displayLegend(); } } /** **************************************************************************** * Display legend popup * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.displayLegendWindow = function() { if (this.visualisation.disabled) { return; } if (window.opener && window.opener.THREADVIS) { window.opener.THREADVIS.displayLegendWindow(); return; } if (this.legendWindow != null && ! this.legendWindow.closed) { this.legendWindow.close(); return; } var flags = "chrome=yes,resizable=no,alwaysRaised=yes,dependent=yes,dialog=yes"; this.legendWindow = window.openDialog("chrome://threadvis/content/Legend.xul", "ThreadVisLegend", flags); } /** **************************************************************************** * Display about dialog when first starting ThreadVis * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.displayAbout = function() { var showedAbout = this.preferences .getPreference(this.preferences.PREF_ABOUT); if (showedAbout < this.ABOUT) { window.openDialog("chrome://threadvis/content/About.xul", "ThreadVisAbout", "chrome=yes,resizable=true;alwaysRaised=false,dependent=yes"); } } /** **************************************************************************** * Display a popup window for the visualisation * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.displayVisualisationWindow = function() { if (this.visualisation.disabled) { return; } if (this.popupWindow != null && ! this.popupWindow.closed) { this.popupWindow.focus(); return; } var flags = "chrome=yes,resizable=yes,alwaysRaised=yes,dependent=yes"; this.popupWindow = window.openDialog("chrome://threadvis/content/ThreadVisPopup.xul", "ThreadVisPopup", flags); this.deleteBox(); clearInterval(this.visualisation.checkResizeInterval); this.visualisedMsgId = null; } /** **************************************************************************** * Get legend object * * @return * The legend object, null if it doesn't exist ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.getLegend = function() { if (this.popupWindow && this.popupWindow.THREADVIS) { return this.popupWindow.THREADVIS.visualisation.legend; } else { return this.visualisation.legend; } } /** **************************************************************************** * Return main window object * * @return * The main window ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.getMainWindow = function() { var w = window; while (w != null) { if (typeof(w.GetThreadTree) == "function") { return w; } w = w.opener; } return null; } /** **************************************************************************** * Get popup visualisation * * @return * The popup window, null if no popup exists ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.getPopupVisualisation = function() { if (this.popupWindow != null && ! this.popupWindow.closed) { return this.popupWindow; } if (this.threadvisParent) { return this.threadvisParent.getPopupVisualisation(); } return null; } /** **************************************************************************** * Check if a popup visualisation exists * * @return * True if a popup exists, false if not ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.hasPopupVisualisation = function() { if (this.popupWindow != null && ! this.popupWindow.closed) { return true; } if (this.threadvisParent) { return this.threadvisParent.hasPopupVisualisation(); } return false; } /** **************************************************************************** * Init object * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.init = function() { if (this.threadvisParent) { this.threader = this.threadvisParent.getThreader(); this.server = this.threadvisParent.server; this.preferences = this.threadvisParent.preferences; this.cache = this.threadvisParent.cache; } else { var ref = this; this.preferences = new ThreadVisNS.PreferenceObserver(); this.preferences.registerCallback(this.preferences.PREF_DISABLED_ACCOUNTS, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_DISABLED_FOLDERS, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_ENABLED, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_TIMELINE, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_TIMESCALING, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_DOTSIZE, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_ARC_MINHEIGHT, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_ARC_RADIUS, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_ARC_DIFFERENCE, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_ARC_WIDTH, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_SPACING, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_MESSAGE_CIRCLES, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_COLOUR, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_COLOURS_BACKGROUND, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_COLOURS_BORDER, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_COLOURS_RECEIVED, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_COLOURS_SENT, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_HIGHLIGHT, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_OPACITY, function(value) {ref.preferenceChanged();}); this.preferences.registerCallback(this.preferences.PREF_VIS_ZOOM, function(value) {ref.preferenceChanged();}); this.cache = new ThreadVisNS.Cache(this); } if (! this.checkEnabled()) { this.deleteBox(); return; } // visualisation object if (! this.visualisation) { this.visualisation = new ThreadVisNS.Visualisation(); } // create box object this.createBox(); this.clearVisualisation(); // check to see if parent threadvis object exists if (this.threadvisParent) { // visualise selected message // delay drawing until size of box is known this.delayDrawing(); return; } else { if (! this.threader) { this.threader= new ThreadVisNS.Threader(); } } /* ************************************************************************ * code below only gets executed if no parent threadvis object was found * ***********************************************************************/ // display about dialog and email reminder only once on each startup setTimeout(function() { THREADVIS.displayAbout(); }, 5000); // remember msgid of visualised message this.visualisedMsgId = ""; // remember selected message this.selectedMsgUri = ""; // remember container of selected message this.selectedContainer = null; // register for message selection var ref = this; var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); observerService.addObserver({ observe: function(subject, topic, data) { ref.selectedMsgUri = data; ref.setSelectedMessage(); } }, "MsgMsgDisplayed", false); } /** **************************************************************************** * Delay drawing of visualisation until size of box is known * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.delayDrawing = function() { var boxSize = this.visualisation.getBoxSize(); if (boxSize.width > 0) { this.visualise(this.threadvisParent.selectedContainer); } else { var ref = this; setTimeout(function() { ref.delayDrawing(); }, 100); } } /** **************************************************************************** * Check if the current window is a message window * * @return * True if the current window is a message window, false if not ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.isMessageWindow = function() { if (this.threadvisParent && document.getElementById("expandedHeaderView") != null) { return true; } else { return false; } } /** **************************************************************************** * Check if this window is a popup * * @return * True if this window is a popup, false if not ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.isPopupVisualisation = function() { return document.documentElement.id == "ThreadVisPopup"; } /** **************************************************************************** * Called when popup window gets closed * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.onVisualisationWindowClose = function() { this.visualisedMsgId = null; this.threadvisParent.visualisedMsgId = null; this.threadvisParent.setSelectedMessage(); } /** **************************************************************************** * Open the options dialog for this extension * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.openThreadVisOptionsDialog = function() { this.getMainWindow().openOptionsDialog('paneThreadVis', null); } /** **************************************************************************** * Preference changed * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.preferenceChanged = function() { this.visualisation.changed = true; if (this.popupWindow && this.popupWindow.THREADVIS) this.popupWindow.THREADVIS.visualisation.changed = true; this.setSelectedMessage(true); } /** **************************************************************************** * Called after user resized visualisation using splitter * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.setMinimalWidth = function() { var width = document.getElementById("ThreadVis").boxObject.width; this.preferences.setPreference(this.preferences.PREF_VIS_MINIMAL_WIDTH, width, this.preferences.PREF_INT); } /** **************************************************************************** * Called when a message is selected * Call visualisation with messageid to visualise * * @param force * True to force display of message * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.setSelectedMessage = function(force) { if (! this.checkEnabled()) { this.visualisation.disabled = true; this.visualisation.displayDisabled(); this.visualisedMsgId = null; this.setStatus(null, {enabled: false}); return; } if (! this.checkEnabledAccountOrFolder()) { this.visualisation.disabled = true; this.visualisation.displayDisabled(); this.visualisedMsgId = null; this.setStatus(null, {folderEnabled: false}); return; } this.setStatus(null, {enabled: true, folderEnabled: true}); this.visualisation.disabled = false; // get currently loaded message var msg = messenger.messageServiceFromURI(this.selectedMsgUri) .messageURIToMsgHdr(this.selectedMsgUri); var loadedMsgFolder = msg.folder; this.rootFolder = loadedMsgFolder.rootFolder; this.server = loadedMsgFolder.server; this.account = (Components.classes["@mozilla.org/messenger/account-manager;1"] .getService(Components.interfaces.nsIMsgAccountManager)) .FindAccountForServer(this.server); // delay display to give UI time to layout var ref = this; setTimeout(function(){ref.visualiseMessage(msg, force);}, 100); } /** **************************************************************************** * Visualise a container * * @param container * The container to visualise * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.visualise = function(container) { if (! this.checkEnabled() || ! this.checkEnabledAccountOrFolder()) { return; } var msgCount = container.getTopContainer().getCountRecursive(); if (this.hasPopupVisualisation() && ! this.isPopupVisualisation()) { this.getPopupVisualisation().THREADVIS.visualise(container); return; } // if user wants to hide visualisation if it only consists of a single // message, do so, but not in popup visualisation if (msgCount == 1 && this.preferences.getPreference(this.preferences.PREF_VIS_HIDE_ON_SINGLE) && ! this.isPopupVisualisation()) { this.visualisation.disabled = true; this.visualisation.displayDisabled(true); this.visualisedMsgId = null; this.selectedContainer = null; return; } this.clear = false; this.createBox(); this.visualisation.disabled = false; this.visualisation.visualise(container); this.selectedContainer = container; } /** **************************************************************************** * Visualise a message. Find the container. Call visualise() * * @param message * The message to visualise * @param force * True to force the display of the visualisation * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.visualiseMessage = function(message, force) { if (this.visualisedMsgId == message.messageId && ! force) { return; } if (! this.checkEnabled() || ! this.checkEnabledAccountOrFolder()) { return; } // try to find in threader var container = this.getThreader().findContainer(message.messageId); // if not in threader, try to get from cache if (container == null || container.isDummy()) { var ref = this; this.cache.getCache(message, function() { ref.visualiseMessage(message, force); }); return; } // not in threader, not in cache, start caching if (container == null || container.isDummy()) { alert("NOT IN CACHE"); return; } this.visualisedMsgId = message.messageId; // clear threader //this.threader.reset(); if (container != null && ! container.isDummy()) { // visualise any popup windows that might exist if (this.popupWindow && this.popupWindow.THREADVIS) { this.popupWindow.THREADVIS.visualise(container); } else { this.visualise(container); } } else { // - message id not found, or // - container with id was dummy // this means we somehow missed to thread this message // TODO: check this error if (this.popupWindow && this.popupWindow.THREADVIS) { this.popupWindow.THREADVIS.clearVisualisation(); } else { this.clearVisualisation(); } } container = null; } /** **************************************************************************** * Zoom function to call from user click * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.zoomIn = function() { this.visualisation.zoomIn(); } /** **************************************************************************** * Zoom function to call from user click * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.zoomOut = function() { this.visualisation.zoomOut(); } /** **************************************************************************** * Get the threader object * * @return * The shared threader ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.getThreader = function() { return this.threader; } /** **************************************************************************** * Set the status text in the statusbar * * @param text * The text to display * @param tooltip * Tooltip data to display * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.setStatus = function(text, tooltip) { if (text != null) { var elem = document.getElementById("ThreadVisStatusText"); if (text != "") { elem.value = text; } else { elem.value = elem.getAttribute("defaultvalue"); } } if (typeof(tooltip) != "undefined") { if (typeof(tooltip.enabled) != "undefined") { if (tooltip.enabled) { document.getElementById("ThreadVisStatusTooltipDisabled").hidden = true; } else { document.getElementById("ThreadVisStatusTooltipDisabled").hidden = false; document.getElementById("ThreadVisStatusMenuEnableFolder").setAttribute("disabled", true); document.getElementById("ThreadVisStatusMenuDisableFolder").setAttribute("disabled", true); } } if (typeof(tooltip.folderEnabled) != "undefined") { if (tooltip.folderEnabled) { document.getElementById("ThreadVisStatusTooltipFolderDisabled").hidden = true; document.getElementById("ThreadVisStatusTooltipFolderEnabled").hidden = false; document.getElementById("ThreadVisStatusMenuEnableFolder").setAttribute("disabled", true); document.getElementById("ThreadVisStatusMenuDisableFolder").setAttribute("disabled", false); } else { document.getElementById("ThreadVisStatusTooltipFolderDisabled").hidden = false; document.getElementById("ThreadVisStatusTooltipFolderEnabled").hidden = true; document.getElementById("ThreadVisStatusMenuEnableFolder").setAttribute("disabled", false); document.getElementById("ThreadVisStatusMenuDisableFolder").setAttribute("disabled", true); } } } } /** **************************************************************************** * Disable for current folder * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.disableCurrentFolder = function() { // get currently displayed folder var folder = this.getMainWindow().GetLoadedMsgFolder(); if (folder) { var folderSetting = this.preferences.getPreference( this.preferences.PREF_DISABLED_FOLDERS); folderSetting = folderSetting + " " + folder.URI; this.preferences.setPreference( this.preferences.PREF_DISABLED_FOLDERS, folderSetting, this.preferences.PREF_STRING); } } /** **************************************************************************** * Enable for current folder * * @return * void ******************************************************************************/ ThreadVisNS.ThreadVis.prototype.enableCurrentFolder = function() { // get currently displayed folder var folder = this.getMainWindow().GetLoadedMsgFolder(); if (folder) { var folderSetting = this.preferences.getPreference( this.preferences.PREF_DISABLED_FOLDERS); var index = folderSetting.indexOf(" " + folder.URI + " "); folderSetting = folderSetting.substring(0, index) + folderSetting.substring(index + folder.URI.length); this.preferences.setPreference( this.preferences.PREF_DISABLED_FOLDERS, folderSetting, this.preferences.PREF_STRING); } }
also display about wizard when disabled
src/chrome/content/ThreadVis.js
also display about wizard when disabled
<ide><path>rc/chrome/content/ThreadVis.js <ide> this.server = this.threadvisParent.server; <ide> this.preferences = this.threadvisParent.preferences; <ide> this.cache = this.threadvisParent.cache; <del> } <del> else { <add> } else { <ide> var ref = this; <ide> this.preferences = new ThreadVisNS.PreferenceObserver(); <ide> this.preferences.registerCallback(this.preferences.PREF_DISABLED_ACCOUNTS, <ide> function(value) {ref.preferenceChanged();}); <ide> <ide> this.cache = new ThreadVisNS.Cache(this); <add> <add> // display about dialog and email reminder only once on each startup <add> setTimeout(function() { THREADVIS.displayAbout(); }, 5000); <ide> } <ide> <ide> if (! this.checkEnabled()) { <ide> /* ************************************************************************ <ide> * code below only gets executed if no parent threadvis object was found <ide> * ***********************************************************************/ <del> <del> // display about dialog and email reminder only once on each startup <del> setTimeout(function() { THREADVIS.displayAbout(); }, 5000); <ide> <ide> // remember msgid of visualised message <ide> this.visualisedMsgId = "";
Java
apache-2.0
3ee038b5c1009dc4d0533f51b67aaa97df582887
0
sopel39/presto,youngwookim/presto,mvp/presto,prestodb/presto,nezihyigitbasi/presto,losipiuk/presto,mvp/presto,nezihyigitbasi/presto,treasure-data/presto,facebook/presto,stewartpark/presto,ptkool/presto,hgschmie/presto,nezihyigitbasi/presto,youngwookim/presto,ebyhr/presto,electrum/presto,raghavsethi/presto,stewartpark/presto,smartnews/presto,ptkool/presto,hgschmie/presto,zzhao0/presto,haozhun/presto,prestodb/presto,zzhao0/presto,treasure-data/presto,dain/presto,martint/presto,mvp/presto,youngwookim/presto,EvilMcJerkface/presto,martint/presto,shixuan-fan/presto,sopel39/presto,smartnews/presto,facebook/presto,treasure-data/presto,wyukawa/presto,haozhun/presto,EvilMcJerkface/presto,arhimondr/presto,Praveen2112/presto,sopel39/presto,raghavsethi/presto,11xor6/presto,twitter-forks/presto,treasure-data/presto,ebyhr/presto,haozhun/presto,sopel39/presto,miniway/presto,facebook/presto,EvilMcJerkface/presto,prestodb/presto,prestodb/presto,ptkool/presto,wyukawa/presto,hgschmie/presto,11xor6/presto,erichwang/presto,martint/presto,wyukawa/presto,shixuan-fan/presto,prestodb/presto,miniway/presto,martint/presto,hgschmie/presto,Yaliang/presto,twitter-forks/presto,ebyhr/presto,arhimondr/presto,raghavsethi/presto,zzhao0/presto,dain/presto,electrum/presto,youngwookim/presto,twitter-forks/presto,arhimondr/presto,arhimondr/presto,Praveen2112/presto,11xor6/presto,prestodb/presto,ptkool/presto,erichwang/presto,zzhao0/presto,haozhun/presto,shixuan-fan/presto,stewartpark/presto,smartnews/presto,treasure-data/presto,smartnews/presto,Praveen2112/presto,Praveen2112/presto,miniway/presto,mvp/presto,Yaliang/presto,11xor6/presto,losipiuk/presto,martint/presto,erichwang/presto,losipiuk/presto,losipiuk/presto,ptkool/presto,EvilMcJerkface/presto,erichwang/presto,mvp/presto,electrum/presto,arhimondr/presto,dain/presto,sopel39/presto,raghavsethi/presto,Praveen2112/presto,ebyhr/presto,Yaliang/presto,shixuan-fan/presto,miniway/presto,electrum/presto,haozhun/presto,miniway/presto,EvilMcJerkface/presto,raghavsethi/presto,Yaliang/presto,stewartpark/presto,zzhao0/presto,dain/presto,treasure-data/presto,youngwookim/presto,losipiuk/presto,11xor6/presto,nezihyigitbasi/presto,facebook/presto,dain/presto,stewartpark/presto,shixuan-fan/presto,ebyhr/presto,twitter-forks/presto,twitter-forks/presto,Yaliang/presto,wyukawa/presto,wyukawa/presto,electrum/presto,smartnews/presto,hgschmie/presto,erichwang/presto,facebook/presto,nezihyigitbasi/presto
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.hive; import com.facebook.presto.GroupByHashPageIndexerFactory; import com.facebook.presto.hive.HdfsEnvironment.HdfsContext; import com.facebook.presto.hive.LocationService.WriteInfo; import com.facebook.presto.hive.authentication.NoHdfsAuthentication; import com.facebook.presto.hive.metastore.CachingHiveMetastore; import com.facebook.presto.hive.metastore.Column; import com.facebook.presto.hive.metastore.ExtendedHiveMetastore; import com.facebook.presto.hive.metastore.HiveColumnStatistics; import com.facebook.presto.hive.metastore.HivePrivilegeInfo; import com.facebook.presto.hive.metastore.HivePrivilegeInfo.HivePrivilege; import com.facebook.presto.hive.metastore.Partition; import com.facebook.presto.hive.metastore.PrincipalPrivileges; import com.facebook.presto.hive.metastore.SemiTransactionalHiveMetastore; import com.facebook.presto.hive.metastore.SortingColumn; import com.facebook.presto.hive.metastore.StorageFormat; import com.facebook.presto.hive.metastore.Table; import com.facebook.presto.hive.metastore.thrift.BridgingHiveMetastore; import com.facebook.presto.hive.metastore.thrift.HiveCluster; import com.facebook.presto.hive.metastore.thrift.TestingHiveCluster; import com.facebook.presto.hive.metastore.thrift.ThriftHiveMetastore; import com.facebook.presto.hive.orc.OrcPageSource; import com.facebook.presto.hive.parquet.ParquetHiveRecordCursor; import com.facebook.presto.hive.parquet.ParquetPageSource; import com.facebook.presto.hive.rcfile.RcFilePageSource; import com.facebook.presto.metadata.MetadataManager; import com.facebook.presto.spi.ColumnHandle; import com.facebook.presto.spi.ColumnMetadata; import com.facebook.presto.spi.ConnectorInsertTableHandle; import com.facebook.presto.spi.ConnectorOutputTableHandle; import com.facebook.presto.spi.ConnectorPageSink; import com.facebook.presto.spi.ConnectorPageSource; import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.ConnectorSplit; import com.facebook.presto.spi.ConnectorSplitSource; import com.facebook.presto.spi.ConnectorTableHandle; import com.facebook.presto.spi.ConnectorTableLayout; import com.facebook.presto.spi.ConnectorTableLayoutHandle; import com.facebook.presto.spi.ConnectorTableLayoutResult; import com.facebook.presto.spi.ConnectorTableMetadata; import com.facebook.presto.spi.ConnectorViewDefinition; import com.facebook.presto.spi.Constraint; import com.facebook.presto.spi.DiscretePredicates; import com.facebook.presto.spi.Page; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.RecordCursor; import com.facebook.presto.spi.RecordPageSource; import com.facebook.presto.spi.SchemaTableName; import com.facebook.presto.spi.SchemaTablePrefix; import com.facebook.presto.spi.TableNotFoundException; import com.facebook.presto.spi.ViewNotFoundException; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.connector.ConnectorMetadata; import com.facebook.presto.spi.connector.ConnectorPageSinkProvider; import com.facebook.presto.spi.connector.ConnectorPageSourceProvider; import com.facebook.presto.spi.connector.ConnectorSplitManager; import com.facebook.presto.spi.connector.ConnectorTransactionHandle; import com.facebook.presto.spi.predicate.Domain; import com.facebook.presto.spi.predicate.NullableValue; import com.facebook.presto.spi.predicate.Range; import com.facebook.presto.spi.predicate.TupleDomain; import com.facebook.presto.spi.predicate.ValueSet; import com.facebook.presto.spi.statistics.ColumnStatistics; import com.facebook.presto.spi.statistics.RangeColumnStatistics; import com.facebook.presto.spi.statistics.TableStatistics; import com.facebook.presto.spi.type.ArrayType; import com.facebook.presto.spi.type.MapType; import com.facebook.presto.spi.type.NamedTypeSignature; import com.facebook.presto.spi.type.RowFieldName; import com.facebook.presto.spi.type.RowType; import com.facebook.presto.spi.type.SqlDate; import com.facebook.presto.spi.type.SqlTimestamp; import com.facebook.presto.spi.type.SqlVarbinary; import com.facebook.presto.spi.type.StandardTypes; import com.facebook.presto.spi.type.Type; import com.facebook.presto.sql.analyzer.FeaturesConfig; import com.facebook.presto.sql.gen.JoinCompiler; import com.facebook.presto.testing.MaterializedResult; import com.facebook.presto.testing.MaterializedRow; import com.facebook.presto.testing.TestingConnectorSession; import com.facebook.presto.testing.TestingNodeManager; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.net.HostAndPort; import io.airlift.json.JsonCodec; import io.airlift.log.Logger; import io.airlift.slice.Slice; import io.airlift.stats.CounterStat; import io.airlift.units.DataSize; import io.airlift.units.Duration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.metastore.TableType; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.IOException; import java.math.BigDecimal; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.Set; import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.IntStream; import java.util.stream.LongStream; import static com.facebook.presto.hive.AbstractTestHiveClient.TransactionDeleteInsertTestTag.COMMIT; import static com.facebook.presto.hive.AbstractTestHiveClient.TransactionDeleteInsertTestTag.ROLLBACK_AFTER_APPEND_PAGE; import static com.facebook.presto.hive.AbstractTestHiveClient.TransactionDeleteInsertTestTag.ROLLBACK_AFTER_BEGIN_INSERT; import static com.facebook.presto.hive.AbstractTestHiveClient.TransactionDeleteInsertTestTag.ROLLBACK_AFTER_DELETE; import static com.facebook.presto.hive.AbstractTestHiveClient.TransactionDeleteInsertTestTag.ROLLBACK_AFTER_FINISH_INSERT; import static com.facebook.presto.hive.AbstractTestHiveClient.TransactionDeleteInsertTestTag.ROLLBACK_AFTER_SINK_FINISH; import static com.facebook.presto.hive.AbstractTestHiveClient.TransactionDeleteInsertTestTag.ROLLBACK_RIGHT_AWAY; import static com.facebook.presto.hive.HiveBasicStatistics.createEmptyStatistics; import static com.facebook.presto.hive.HiveBasicStatistics.createZeroStatistics; import static com.facebook.presto.hive.HiveColumnHandle.BUCKET_COLUMN_NAME; import static com.facebook.presto.hive.HiveColumnHandle.ColumnType.PARTITION_KEY; import static com.facebook.presto.hive.HiveColumnHandle.ColumnType.REGULAR; import static com.facebook.presto.hive.HiveColumnHandle.bucketColumnHandle; import static com.facebook.presto.hive.HiveErrorCode.HIVE_INVALID_PARTITION_VALUE; import static com.facebook.presto.hive.HiveErrorCode.HIVE_PARTITION_SCHEMA_MISMATCH; import static com.facebook.presto.hive.HiveMetadata.PRESTO_QUERY_ID_NAME; import static com.facebook.presto.hive.HiveMetadata.PRESTO_VERSION_NAME; import static com.facebook.presto.hive.HiveMetadata.convertToPredicate; import static com.facebook.presto.hive.HiveStorageFormat.AVRO; import static com.facebook.presto.hive.HiveStorageFormat.DWRF; import static com.facebook.presto.hive.HiveStorageFormat.JSON; import static com.facebook.presto.hive.HiveStorageFormat.ORC; import static com.facebook.presto.hive.HiveStorageFormat.PARQUET; import static com.facebook.presto.hive.HiveStorageFormat.RCBINARY; import static com.facebook.presto.hive.HiveStorageFormat.RCTEXT; import static com.facebook.presto.hive.HiveStorageFormat.SEQUENCEFILE; import static com.facebook.presto.hive.HiveStorageFormat.TEXTFILE; import static com.facebook.presto.hive.HiveTableProperties.BUCKETED_BY_PROPERTY; import static com.facebook.presto.hive.HiveTableProperties.BUCKET_COUNT_PROPERTY; import static com.facebook.presto.hive.HiveTableProperties.PARTITIONED_BY_PROPERTY; import static com.facebook.presto.hive.HiveTableProperties.SORTED_BY_PROPERTY; import static com.facebook.presto.hive.HiveTableProperties.STORAGE_FORMAT_PROPERTY; import static com.facebook.presto.hive.HiveTestUtils.PAGE_SORTER; import static com.facebook.presto.hive.HiveTestUtils.SESSION; import static com.facebook.presto.hive.HiveTestUtils.TYPE_MANAGER; import static com.facebook.presto.hive.HiveTestUtils.arrayType; import static com.facebook.presto.hive.HiveTestUtils.getDefaultHiveDataStreamFactories; import static com.facebook.presto.hive.HiveTestUtils.getDefaultHiveFileWriterFactories; import static com.facebook.presto.hive.HiveTestUtils.getDefaultHiveRecordCursorProvider; import static com.facebook.presto.hive.HiveTestUtils.getTypes; import static com.facebook.presto.hive.HiveTestUtils.mapType; import static com.facebook.presto.hive.HiveTestUtils.rowType; import static com.facebook.presto.hive.HiveType.HIVE_INT; import static com.facebook.presto.hive.HiveType.HIVE_LONG; import static com.facebook.presto.hive.HiveType.HIVE_STRING; import static com.facebook.presto.hive.HiveType.toHiveType; import static com.facebook.presto.hive.HiveUtil.columnExtraInfo; import static com.facebook.presto.hive.HiveWriteUtils.createDirectory; import static com.facebook.presto.hive.LocationHandle.WriteMode.STAGE_AND_MOVE_TO_TARGET_DIRECTORY; import static com.facebook.presto.hive.metastore.HiveColumnStatistics.createBinaryColumnStatistics; import static com.facebook.presto.hive.metastore.HiveColumnStatistics.createBooleanColumnStatistics; import static com.facebook.presto.hive.metastore.HiveColumnStatistics.createDateColumnStatistics; import static com.facebook.presto.hive.metastore.HiveColumnStatistics.createDecimalColumnStatistics; import static com.facebook.presto.hive.metastore.HiveColumnStatistics.createDoubleColumnStatistics; import static com.facebook.presto.hive.metastore.HiveColumnStatistics.createIntegerColumnStatistics; import static com.facebook.presto.hive.metastore.HiveColumnStatistics.createStringColumnStatistics; import static com.facebook.presto.hive.metastore.StorageFormat.fromHiveStorageFormat; import static com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED; import static com.facebook.presto.spi.StandardErrorCode.TRANSACTION_CONFLICT; import static com.facebook.presto.spi.connector.ConnectorSplitManager.SplitSchedulingStrategy.UNGROUPED_SCHEDULING; import static com.facebook.presto.spi.connector.NotPartitionedPartitionHandle.NOT_PARTITIONED; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.type.CharType.createCharType; import static com.facebook.presto.spi.type.Chars.isCharType; import static com.facebook.presto.spi.type.DateType.DATE; import static com.facebook.presto.spi.type.DecimalType.createDecimalType; import static com.facebook.presto.spi.type.DoubleType.DOUBLE; import static com.facebook.presto.spi.type.HyperLogLogType.HYPER_LOG_LOG; import static com.facebook.presto.spi.type.IntegerType.INTEGER; import static com.facebook.presto.spi.type.RealType.REAL; import static com.facebook.presto.spi.type.SmallintType.SMALLINT; import static com.facebook.presto.spi.type.TimeZoneKey.UTC_KEY; import static com.facebook.presto.spi.type.TimestampType.TIMESTAMP; import static com.facebook.presto.spi.type.TinyintType.TINYINT; import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature; import static com.facebook.presto.spi.type.VarbinaryType.VARBINARY; import static com.facebook.presto.spi.type.VarcharType.VARCHAR; import static com.facebook.presto.spi.type.VarcharType.createUnboundedVarcharType; import static com.facebook.presto.spi.type.VarcharType.createVarcharType; import static com.facebook.presto.spi.type.Varchars.isVarcharType; import static com.facebook.presto.testing.DateTimeTestingUtils.sqlTimestampOf; import static com.facebook.presto.testing.MaterializedResult.materializeSourceDataStream; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Verify.verify; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.concat; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Maps.uniqueIndex; import static com.google.common.collect.MoreCollectors.onlyElement; import static com.google.common.collect.Sets.difference; import static com.google.common.hash.Hashing.sha256; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import static io.airlift.concurrent.MoreFutures.getFutureValue; import static io.airlift.concurrent.Threads.daemonThreadsNamed; import static io.airlift.slice.Slices.utf8Slice; import static io.airlift.testing.Assertions.assertEqualsIgnoreOrder; import static io.airlift.testing.Assertions.assertGreaterThan; import static io.airlift.testing.Assertions.assertGreaterThanOrEqual; import static io.airlift.testing.Assertions.assertInstanceOf; import static io.airlift.testing.Assertions.assertLessThanOrEqual; import static io.airlift.units.DataSize.Unit.MEGABYTE; import static java.lang.Float.floatToRawIntBits; import static java.lang.Math.toIntExact; import static java.lang.String.format; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Locale.ENGLISH; import static java.util.Objects.requireNonNull; import static java.util.concurrent.Executors.newCachedThreadPool; import static java.util.concurrent.Executors.newFixedThreadPool; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.stream.Collectors.toList; import static org.apache.hadoop.hive.common.FileUtils.makePartName; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import static org.joda.time.DateTimeZone.UTC; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; public abstract class AbstractTestHiveClient { protected static final String TEMPORARY_TABLE_PREFIX = "tmp_presto_test_"; protected static final String INVALID_DATABASE = "totally_invalid_database_name"; protected static final String INVALID_TABLE = "totally_invalid_table_name"; protected static final String INVALID_COLUMN = "totally_invalid_column_name"; protected static final String TEST_SERVER_VERSION = "test_version"; private static final Type ARRAY_TYPE = arrayType(createUnboundedVarcharType()); private static final Type MAP_TYPE = mapType(createUnboundedVarcharType(), BIGINT); private static final Type ROW_TYPE = rowType(ImmutableList.of( new NamedTypeSignature(Optional.of(new RowFieldName("f_string", false)), createUnboundedVarcharType().getTypeSignature()), new NamedTypeSignature(Optional.of(new RowFieldName("f_bigint", false)), BIGINT.getTypeSignature()), new NamedTypeSignature(Optional.of(new RowFieldName("f_boolean", false)), BOOLEAN.getTypeSignature()))); private static final List<ColumnMetadata> CREATE_TABLE_COLUMNS = ImmutableList.<ColumnMetadata>builder() .add(new ColumnMetadata("id", BIGINT)) .add(new ColumnMetadata("t_string", createUnboundedVarcharType())) .add(new ColumnMetadata("t_tinyint", TINYINT)) .add(new ColumnMetadata("t_smallint", SMALLINT)) .add(new ColumnMetadata("t_integer", INTEGER)) .add(new ColumnMetadata("t_bigint", BIGINT)) .add(new ColumnMetadata("t_float", REAL)) .add(new ColumnMetadata("t_double", DOUBLE)) .add(new ColumnMetadata("t_boolean", BOOLEAN)) .add(new ColumnMetadata("t_array", ARRAY_TYPE)) .add(new ColumnMetadata("t_map", MAP_TYPE)) .add(new ColumnMetadata("t_row", ROW_TYPE)) .build(); private static final MaterializedResult CREATE_TABLE_DATA = MaterializedResult.resultBuilder(SESSION, BIGINT, createUnboundedVarcharType(), TINYINT, SMALLINT, INTEGER, BIGINT, REAL, DOUBLE, BOOLEAN, ARRAY_TYPE, MAP_TYPE, ROW_TYPE) .row(1L, "hello", (byte) 45, (short) 345, 234, 123L, -754.1985f, 43.5, true, ImmutableList.of("apple", "banana"), ImmutableMap.of("one", 1L, "two", 2L), ImmutableList.of("true", 1L, true)) .row(2L, null, null, null, null, null, null, null, null, null, null, null) .row(3L, "bye", (byte) 46, (short) 346, 345, 456L, 754.2008f, 98.1, false, ImmutableList.of("ape", "bear"), ImmutableMap.of("three", 3L, "four", 4L), ImmutableList.of("false", 0L, false)) .build(); private static final List<ColumnMetadata> CREATE_TABLE_COLUMNS_PARTITIONED = ImmutableList.<ColumnMetadata>builder() .addAll(CREATE_TABLE_COLUMNS) .add(new ColumnMetadata("ds", createUnboundedVarcharType())) .build(); private static final MaterializedResult CREATE_TABLE_PARTITIONED_DATA = new MaterializedResult( CREATE_TABLE_DATA.getMaterializedRows().stream() .map(row -> new MaterializedRow(row.getPrecision(), newArrayList(concat(row.getFields(), ImmutableList.of("2015-07-0" + row.getField(0)))))) .collect(toList()), ImmutableList.<Type>builder() .addAll(CREATE_TABLE_DATA.getTypes()) .add(createUnboundedVarcharType()) .build()); private static final String CREATE_TABLE_PARTITIONED_DATA_2ND_PARTITION_VALUE = "2015-07-04"; private static final MaterializedResult CREATE_TABLE_PARTITIONED_DATA_2ND = MaterializedResult.resultBuilder(SESSION, BIGINT, createUnboundedVarcharType(), TINYINT, SMALLINT, INTEGER, BIGINT, REAL, DOUBLE, BOOLEAN, ARRAY_TYPE, MAP_TYPE, ROW_TYPE, createUnboundedVarcharType()) .row(4L, "hello", (byte) 45, (short) 345, 234, 123L, 754.1985f, 43.5, true, ImmutableList.of("apple", "banana"), ImmutableMap.of("one", 1L, "two", 2L), ImmutableList.of("true", 1L, true), CREATE_TABLE_PARTITIONED_DATA_2ND_PARTITION_VALUE) .row(5L, null, null, null, null, null, null, null, null, null, null, null, CREATE_TABLE_PARTITIONED_DATA_2ND_PARTITION_VALUE) .row(6L, "bye", (byte) 46, (short) 346, 345, 456L, -754.2008f, 98.1, false, ImmutableList.of("ape", "bear"), ImmutableMap.of("three", 3L, "four", 4L), ImmutableList.of("false", 0L, false), CREATE_TABLE_PARTITIONED_DATA_2ND_PARTITION_VALUE) .build(); private static final List<ColumnMetadata> MISMATCH_SCHEMA_PRIMITIVE_COLUMN_BEFORE = ImmutableList.<ColumnMetadata>builder() .add(new ColumnMetadata("tinyint_to_smallint", TINYINT)) .add(new ColumnMetadata("tinyint_to_integer", TINYINT)) .add(new ColumnMetadata("tinyint_to_bigint", TINYINT)) .add(new ColumnMetadata("smallint_to_integer", SMALLINT)) .add(new ColumnMetadata("smallint_to_bigint", SMALLINT)) .add(new ColumnMetadata("integer_to_bigint", INTEGER)) .add(new ColumnMetadata("integer_to_varchar", INTEGER)) .add(new ColumnMetadata("varchar_to_integer", createUnboundedVarcharType())) .add(new ColumnMetadata("float_to_double", REAL)) .add(new ColumnMetadata("varchar_to_drop_in_row", createUnboundedVarcharType())) .build(); private static final List<ColumnMetadata> MISMATCH_SCHEMA_TABLE_BEFORE = ImmutableList.<ColumnMetadata>builder() .addAll(MISMATCH_SCHEMA_PRIMITIVE_COLUMN_BEFORE) .add(new ColumnMetadata("struct_to_struct", toRowType(MISMATCH_SCHEMA_PRIMITIVE_COLUMN_BEFORE))) .add(new ColumnMetadata("list_to_list", arrayType(toRowType(MISMATCH_SCHEMA_PRIMITIVE_COLUMN_BEFORE)))) .add(new ColumnMetadata("map_to_map", mapType(MISMATCH_SCHEMA_PRIMITIVE_COLUMN_BEFORE.get(1).getType(), toRowType(MISMATCH_SCHEMA_PRIMITIVE_COLUMN_BEFORE)))) .add(new ColumnMetadata("ds", createUnboundedVarcharType())) .build(); private static RowType toRowType(List<ColumnMetadata> columns) { return rowType(columns.stream() .map(col -> new NamedTypeSignature(Optional.of(new RowFieldName(format("f_%s", col.getName()), false)), col.getType().getTypeSignature())) .collect(toList())); } private static final MaterializedResult MISMATCH_SCHEMA_PRIMITIVE_FIELDS_DATA_BEFORE = MaterializedResult.resultBuilder(SESSION, TINYINT, TINYINT, TINYINT, SMALLINT, SMALLINT, INTEGER, INTEGER, createUnboundedVarcharType(), REAL, createUnboundedVarcharType()) .row((byte) -11, (byte) 12, (byte) -13, (short) 14, (short) 15, -16, 17, "2147483647", 18.0f, "2016-08-01") .row((byte) 21, (byte) -22, (byte) 23, (short) -24, (short) 25, 26, -27, "asdf", -28.0f, "2016-08-02") .row((byte) -31, (byte) -32, (byte) 33, (short) 34, (short) -35, 36, 37, "-923", 39.5f, "2016-08-03") .row(null, (byte) 42, (byte) 43, (short) 44, (short) -45, 46, 47, "2147483648", 49.5f, "2016-08-03") .build(); private static final MaterializedResult MISMATCH_SCHEMA_TABLE_DATA_BEFORE = MaterializedResult.resultBuilder(SESSION, MISMATCH_SCHEMA_TABLE_BEFORE.stream().map(ColumnMetadata::getType).collect(toList())) .rows(MISMATCH_SCHEMA_PRIMITIVE_FIELDS_DATA_BEFORE.getMaterializedRows() .stream() .map(materializedRow -> { List<Object> result = materializedRow.getFields(); List<Object> rowResult = materializedRow.getFields(); result.add(rowResult); result.add(Arrays.asList(rowResult, null, rowResult)); result.add(ImmutableMap.of(rowResult.get(1), rowResult)); result.add(rowResult.get(9)); return new MaterializedRow(materializedRow.getPrecision(), result); }).collect(toList())) .build(); private static final List<ColumnMetadata> MISMATCH_SCHEMA_PRIMITIVE_COLUMN_AFTER = ImmutableList.<ColumnMetadata>builder() .add(new ColumnMetadata("tinyint_to_smallint", SMALLINT)) .add(new ColumnMetadata("tinyint_to_integer", INTEGER)) .add(new ColumnMetadata("tinyint_to_bigint", BIGINT)) .add(new ColumnMetadata("smallint_to_integer", INTEGER)) .add(new ColumnMetadata("smallint_to_bigint", BIGINT)) .add(new ColumnMetadata("integer_to_bigint", BIGINT)) .add(new ColumnMetadata("integer_to_varchar", createUnboundedVarcharType())) .add(new ColumnMetadata("varchar_to_integer", INTEGER)) .add(new ColumnMetadata("float_to_double", DOUBLE)) .add(new ColumnMetadata("varchar_to_drop_in_row", createUnboundedVarcharType())) .build(); private static final Type MISMATCH_SCHEMA_ROW_TYPE_APPEND = toRowType(ImmutableList.<ColumnMetadata>builder() .addAll(MISMATCH_SCHEMA_PRIMITIVE_COLUMN_AFTER) .add(new ColumnMetadata(format("%s_append", MISMATCH_SCHEMA_PRIMITIVE_COLUMN_AFTER.get(0).getName()), MISMATCH_SCHEMA_PRIMITIVE_COLUMN_AFTER.get(0).getType())) .build()); private static final Type MISMATCH_SCHEMA_ROW_TYPE_DROP = toRowType(MISMATCH_SCHEMA_PRIMITIVE_COLUMN_AFTER.subList(0, MISMATCH_SCHEMA_PRIMITIVE_COLUMN_AFTER.size() - 1)); private static final List<ColumnMetadata> MISMATCH_SCHEMA_TABLE_AFTER = ImmutableList.<ColumnMetadata>builder() .addAll(MISMATCH_SCHEMA_PRIMITIVE_COLUMN_AFTER) .add(new ColumnMetadata("struct_to_struct", MISMATCH_SCHEMA_ROW_TYPE_APPEND)) .add(new ColumnMetadata("list_to_list", arrayType(MISMATCH_SCHEMA_ROW_TYPE_APPEND))) .add(new ColumnMetadata("map_to_map", mapType(MISMATCH_SCHEMA_PRIMITIVE_COLUMN_AFTER.get(1).getType(), MISMATCH_SCHEMA_ROW_TYPE_DROP))) .add(new ColumnMetadata("ds", createUnboundedVarcharType())) .build(); private static final MaterializedResult MISMATCH_SCHEMA_PRIMITIVE_FIELDS_DATA_AFTER = MaterializedResult.resultBuilder(SESSION, SMALLINT, INTEGER, BIGINT, INTEGER, BIGINT, BIGINT, createUnboundedVarcharType(), INTEGER, DOUBLE, createUnboundedVarcharType()) .row((short) -11, 12, -13L, 14, 15L, -16L, "17", 2147483647, 18.0, "2016-08-01") .row((short) 21, -22, 23L, -24, 25L, 26L, "-27", null, -28.0, "2016-08-02") .row((short) -31, -32, 33L, 34, -35L, 36L, "37", -923, 39.5, "2016-08-03") .row(null, 42, 43L, 44, -45L, 46L, "47", null, 49.5, "2016-08-03") .build(); private static final MaterializedResult MISMATCH_SCHEMA_TABLE_DATA_AFTER = MaterializedResult.resultBuilder(SESSION, MISMATCH_SCHEMA_TABLE_AFTER.stream().map(ColumnMetadata::getType).collect(toList())) .rows(MISMATCH_SCHEMA_PRIMITIVE_FIELDS_DATA_AFTER.getMaterializedRows() .stream() .map(materializedRow -> { List<Object> result = materializedRow.getFields(); List<Object> appendFieldRowResult = materializedRow.getFields(); appendFieldRowResult.add(null); List<Object> dropFieldRowResult = materializedRow.getFields().subList(0, materializedRow.getFields().size() - 1); result.add(appendFieldRowResult); result.add(Arrays.asList(appendFieldRowResult, null, appendFieldRowResult)); result.add(ImmutableMap.of(result.get(1), dropFieldRowResult)); result.add(result.get(9)); return new MaterializedRow(materializedRow.getPrecision(), result); }).collect(toList())) .build(); protected Set<HiveStorageFormat> createTableFormats = difference(ImmutableSet.copyOf(HiveStorageFormat.values()), ImmutableSet.of(AVRO)); private static final JoinCompiler JOIN_COMPILER = new JoinCompiler(MetadataManager.createTestMetadataManager(), new FeaturesConfig()); private static final List<ColumnMetadata> STATISTICS_TABLE_COLUMNS = ImmutableList.<ColumnMetadata>builder() .add(new ColumnMetadata("t_boolean", BOOLEAN)) .add(new ColumnMetadata("t_bigint", BIGINT)) .add(new ColumnMetadata("t_integer", INTEGER)) .add(new ColumnMetadata("t_smallint", SMALLINT)) .add(new ColumnMetadata("t_tinyint", TINYINT)) .add(new ColumnMetadata("t_double", DOUBLE)) .add(new ColumnMetadata("t_float", REAL)) .add(new ColumnMetadata("t_string", createUnboundedVarcharType())) .add(new ColumnMetadata("t_varchar", createVarcharType(100))) .add(new ColumnMetadata("t_char", createCharType(5))) .add(new ColumnMetadata("t_varbinary", VARBINARY)) .add(new ColumnMetadata("t_date", DATE)) .add(new ColumnMetadata("t_timestamp", TIMESTAMP)) .add(new ColumnMetadata("t_short_decimal", createDecimalType(5, 2))) .add(new ColumnMetadata("t_long_decimal", createDecimalType(20, 3))) .build(); private static final List<ColumnMetadata> STATISTICS_PARTITIONED_TABLE_COLUMNS = ImmutableList.<ColumnMetadata>builder() .addAll(STATISTICS_TABLE_COLUMNS) .add(new ColumnMetadata("ds", VARCHAR)) .build(); protected static final PartitionStatistics EMPTY_TABLE_STATISTICS = new PartitionStatistics(createZeroStatistics(), ImmutableMap.of()); protected static final PartitionStatistics BASIC_STATISTICS_1 = new PartitionStatistics(new HiveBasicStatistics(0, 2, 3, 0), ImmutableMap.of()); protected static final PartitionStatistics BASIC_STATISTICS_2 = new PartitionStatistics(new HiveBasicStatistics(0, 3, 2, 0), ImmutableMap.of()); private static final PartitionStatistics STATISTICS_1 = new PartitionStatistics( BASIC_STATISTICS_1.getBasicStatistics(), ImmutableMap.<String, HiveColumnStatistics>builder() .put("t_boolean", createBooleanColumnStatistics(OptionalLong.of(5), OptionalLong.of(6), OptionalLong.of(3))) .put("t_bigint", createIntegerColumnStatistics(OptionalLong.of(1234L), OptionalLong.of(5678L), OptionalLong.of(2), OptionalLong.of(5))) .put("t_integer", createIntegerColumnStatistics(OptionalLong.of(123L), OptionalLong.of(567L), OptionalLong.of(3), OptionalLong.of(4))) .put("t_smallint", createIntegerColumnStatistics(OptionalLong.of(12L), OptionalLong.of(56L), OptionalLong.of(2), OptionalLong.of(6))) .put("t_tinyint", createIntegerColumnStatistics(OptionalLong.of(1L), OptionalLong.of(2L), OptionalLong.of(1), OptionalLong.of(3))) .put("t_double", createDoubleColumnStatistics(OptionalDouble.of(1234.25), OptionalDouble.of(5678.58), OptionalLong.of(7), OptionalLong.of(8))) .put("t_float", createDoubleColumnStatistics(OptionalDouble.of(123.25), OptionalDouble.of(567.58), OptionalLong.of(9), OptionalLong.of(10))) .put("t_string", createStringColumnStatistics(OptionalLong.of(10), OptionalDouble.of(5.0), OptionalLong.of(3), OptionalLong.of(7))) .put("t_varchar", createStringColumnStatistics(OptionalLong.of(100), OptionalDouble.of(23.3), OptionalLong.of(5), OptionalLong.of(3))) .put("t_char", createStringColumnStatistics(OptionalLong.of(5), OptionalDouble.of(5.0), OptionalLong.of(1), OptionalLong.of(4))) .put("t_varbinary", createBinaryColumnStatistics(OptionalLong.of(4), OptionalDouble.of(3.0), OptionalLong.of(1))) .put("t_date", createDateColumnStatistics(Optional.of(java.time.LocalDate.ofEpochDay(1)), Optional.of(java.time.LocalDate.ofEpochDay(2)), OptionalLong.of(7), OptionalLong.of(6))) .put("t_timestamp", createIntegerColumnStatistics(OptionalLong.of(1234567L), OptionalLong.of(71234567L), OptionalLong.of(7), OptionalLong.of(5))) .put("t_short_decimal", createDecimalColumnStatistics(Optional.of(new BigDecimal(10)), Optional.of(new BigDecimal(12)), OptionalLong.of(3), OptionalLong.of(5))) .put("t_long_decimal", createDecimalColumnStatistics(Optional.of(new BigDecimal("12345678901234567.123")), Optional.of(new BigDecimal("81234567890123456.123")), OptionalLong.of(2), OptionalLong.of(1))) .build()); private static final PartitionStatistics STATISTICS_1_1 = new PartitionStatistics( new HiveBasicStatistics(OptionalLong.of(0), OptionalLong.of(2), OptionalLong.empty(), OptionalLong.of(0)), STATISTICS_1.getColumnStatistics().entrySet() .stream() .filter(entry -> entry.getKey().hashCode() % 2 == 0) .collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue))); private static final PartitionStatistics STATISTICS_1_2 = new PartitionStatistics( new HiveBasicStatistics(OptionalLong.of(0), OptionalLong.empty(), OptionalLong.of(3), OptionalLong.of(0)), STATISTICS_1.getColumnStatistics().entrySet() .stream() .filter(entry -> entry.getKey().hashCode() % 2 == 1) .collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue))); private static final PartitionStatistics STATISTICS_2 = new PartitionStatistics( BASIC_STATISTICS_2.getBasicStatistics(), ImmutableMap.<String, HiveColumnStatistics>builder() .put("t_boolean", createBooleanColumnStatistics(OptionalLong.of(4), OptionalLong.of(3), OptionalLong.of(2))) .put("t_bigint", createIntegerColumnStatistics(OptionalLong.of(2345L), OptionalLong.of(6789L), OptionalLong.of(4), OptionalLong.of(7))) .put("t_integer", createIntegerColumnStatistics(OptionalLong.of(234L), OptionalLong.of(678L), OptionalLong.of(5), OptionalLong.of(6))) .put("t_smallint", createIntegerColumnStatistics(OptionalLong.of(23L), OptionalLong.of(65L), OptionalLong.of(7), OptionalLong.of(5))) .put("t_tinyint", createIntegerColumnStatistics(OptionalLong.of(12), OptionalLong.of(3L), OptionalLong.of(2), OptionalLong.of(3))) .put("t_double", createDoubleColumnStatistics(OptionalDouble.of(2345.25), OptionalDouble.of(6785.58), OptionalLong.of(6), OptionalLong.of(3))) .put("t_float", createDoubleColumnStatistics(OptionalDouble.of(235.25), OptionalDouble.of(676.58), OptionalLong.of(7), OptionalLong.of(11))) .put("t_string", createStringColumnStatistics(OptionalLong.of(11), OptionalDouble.of(6.0), OptionalLong.of(2), OptionalLong.of(6))) .put("t_varchar", createStringColumnStatistics(OptionalLong.of(99), OptionalDouble.of(22.3), OptionalLong.of(7), OptionalLong.of(1))) .put("t_char", createStringColumnStatistics(OptionalLong.of(6), OptionalDouble.of(6.0), OptionalLong.of(0), OptionalLong.of(3))) .put("t_varbinary", createBinaryColumnStatistics(OptionalLong.of(2), OptionalDouble.of(1.0), OptionalLong.of(2))) .put("t_date", createDateColumnStatistics(Optional.of(java.time.LocalDate.ofEpochDay(2)), Optional.of(java.time.LocalDate.ofEpochDay(3)), OptionalLong.of(8), OptionalLong.of(7))) .put("t_timestamp", createIntegerColumnStatistics(OptionalLong.of(2345671L), OptionalLong.of(12345677L), OptionalLong.of(9), OptionalLong.of(1))) .put("t_short_decimal", createDecimalColumnStatistics(Optional.of(new BigDecimal(11)), Optional.of(new BigDecimal(14)), OptionalLong.of(5), OptionalLong.of(7))) .put("t_long_decimal", createDecimalColumnStatistics(Optional.of(new BigDecimal("71234567890123456.123")), Optional.of(new BigDecimal("78123456789012345.123")), OptionalLong.of(2), OptionalLong.of(1))) .build()); private static final PartitionStatistics STATISTICS_EMPTY_OPTIONAL_FIELDS = new PartitionStatistics( new HiveBasicStatistics(OptionalLong.of(0), OptionalLong.empty(), OptionalLong.empty(), OptionalLong.of(0)), ImmutableMap.<String, HiveColumnStatistics>builder() .put("t_boolean", createBooleanColumnStatistics(OptionalLong.of(4), OptionalLong.of(3), OptionalLong.of(2))) .put("t_bigint", createIntegerColumnStatistics(OptionalLong.empty(), OptionalLong.empty(), OptionalLong.of(4), OptionalLong.of(7))) .put("t_integer", createIntegerColumnStatistics(OptionalLong.empty(), OptionalLong.empty(), OptionalLong.of(5), OptionalLong.of(6))) .put("t_smallint", createIntegerColumnStatistics(OptionalLong.empty(), OptionalLong.empty(), OptionalLong.of(7), OptionalLong.of(5))) .put("t_tinyint", createIntegerColumnStatistics(OptionalLong.empty(), OptionalLong.empty(), OptionalLong.of(2), OptionalLong.of(3))) .put("t_double", createDoubleColumnStatistics(OptionalDouble.empty(), OptionalDouble.empty(), OptionalLong.of(6), OptionalLong.of(3))) .put("t_float", createDoubleColumnStatistics(OptionalDouble.empty(), OptionalDouble.empty(), OptionalLong.of(7), OptionalLong.of(11))) .put("t_string", createStringColumnStatistics(OptionalLong.of(0), OptionalDouble.of(0), OptionalLong.of(2), OptionalLong.of(6))) .put("t_varchar", createStringColumnStatistics(OptionalLong.of(0), OptionalDouble.of(0), OptionalLong.of(7), OptionalLong.of(1))) .put("t_char", createStringColumnStatistics(OptionalLong.of(0), OptionalDouble.of(0), OptionalLong.of(0), OptionalLong.of(3))) .put("t_varbinary", createBinaryColumnStatistics(OptionalLong.of(0), OptionalDouble.of(0), OptionalLong.of(2))) // https://issues.apache.org/jira/browse/HIVE-20098 // .put("t_date", createDateColumnStatistics(Optional.empty(), Optional.empty(), OptionalLong.of(8), OptionalLong.of(7))) .put("t_timestamp", createIntegerColumnStatistics(OptionalLong.empty(), OptionalLong.empty(), OptionalLong.of(9), OptionalLong.of(1))) .put("t_short_decimal", createDecimalColumnStatistics(Optional.empty(), Optional.empty(), OptionalLong.of(5), OptionalLong.of(7))) .put("t_long_decimal", createDecimalColumnStatistics(Optional.empty(), Optional.empty(), OptionalLong.of(2), OptionalLong.of(1))) .build()); protected String clientId; protected String database; protected SchemaTableName tablePartitionFormat; protected SchemaTableName tableUnpartitioned; protected SchemaTableName tableOffline; protected SchemaTableName tableOfflinePartition; protected SchemaTableName tableNotReadable; protected SchemaTableName view; protected SchemaTableName invalidTable; protected SchemaTableName tableBucketedStringInt; protected SchemaTableName tableBucketedBigintBoolean; protected SchemaTableName tableBucketedDoubleFloat; protected SchemaTableName tablePartitionSchemaChange; protected SchemaTableName tablePartitionSchemaChangeNonCanonical; protected SchemaTableName tableBucketEvolution; protected String invalidClientId; protected ConnectorTableHandle invalidTableHandle; protected ColumnHandle dsColumn; protected ColumnHandle fileFormatColumn; protected ColumnHandle dummyColumn; protected ColumnHandle intColumn; protected ColumnHandle invalidColumnHandle; protected int partitionCount; protected TupleDomain<ColumnHandle> tupleDomain; protected ConnectorTableLayout tableLayout; protected ConnectorTableLayout unpartitionedTableLayout; protected ConnectorTableLayoutHandle invalidTableLayoutHandle; protected DateTimeZone timeZone; protected HdfsEnvironment hdfsEnvironment; protected LocationService locationService; protected HiveMetadataFactory metadataFactory; protected HiveTransactionManager transactionManager; protected ExtendedHiveMetastore metastoreClient; protected ConnectorSplitManager splitManager; protected ConnectorPageSourceProvider pageSourceProvider; protected ConnectorPageSinkProvider pageSinkProvider; protected ExecutorService executor; @BeforeClass public void setupClass() { executor = newCachedThreadPool(daemonThreadsNamed("hive-%s")); } @AfterClass(alwaysRun = true) public void tearDown() { if (executor != null) { executor.shutdownNow(); executor = null; } } protected void setupHive(String connectorId, String databaseName, String timeZoneId) { clientId = connectorId; database = databaseName; tablePartitionFormat = new SchemaTableName(database, "presto_test_partition_format"); tableUnpartitioned = new SchemaTableName(database, "presto_test_unpartitioned"); tableOffline = new SchemaTableName(database, "presto_test_offline"); tableOfflinePartition = new SchemaTableName(database, "presto_test_offline_partition"); tableNotReadable = new SchemaTableName(database, "presto_test_not_readable"); view = new SchemaTableName(database, "presto_test_view"); invalidTable = new SchemaTableName(database, INVALID_TABLE); tableBucketedStringInt = new SchemaTableName(database, "presto_test_bucketed_by_string_int"); tableBucketedBigintBoolean = new SchemaTableName(database, "presto_test_bucketed_by_bigint_boolean"); tableBucketedDoubleFloat = new SchemaTableName(database, "presto_test_bucketed_by_double_float"); tablePartitionSchemaChange = new SchemaTableName(database, "presto_test_partition_schema_change"); tablePartitionSchemaChangeNonCanonical = new SchemaTableName(database, "presto_test_partition_schema_change_non_canonical"); tableBucketEvolution = new SchemaTableName(database, "presto_test_bucket_evolution"); invalidClientId = "hive"; invalidTableHandle = new HiveTableHandle(database, INVALID_TABLE); invalidTableLayoutHandle = new HiveTableLayoutHandle( invalidTable, ImmutableList.of(), ImmutableList.of(new HivePartition(invalidTable, "unknown", ImmutableMap.of())), TupleDomain.all(), TupleDomain.all(), Optional.empty(), Optional.empty()); dsColumn = new HiveColumnHandle("ds", HIVE_STRING, parseTypeSignature(StandardTypes.VARCHAR), -1, PARTITION_KEY, Optional.empty()); fileFormatColumn = new HiveColumnHandle("file_format", HIVE_STRING, parseTypeSignature(StandardTypes.VARCHAR), -1, PARTITION_KEY, Optional.empty()); dummyColumn = new HiveColumnHandle("dummy", HIVE_INT, parseTypeSignature(StandardTypes.INTEGER), -1, PARTITION_KEY, Optional.empty()); intColumn = new HiveColumnHandle("t_int", HIVE_INT, parseTypeSignature(StandardTypes.INTEGER), -1, PARTITION_KEY, Optional.empty()); invalidColumnHandle = new HiveColumnHandle(INVALID_COLUMN, HIVE_STRING, parseTypeSignature(StandardTypes.VARCHAR), 0, REGULAR, Optional.empty()); List<ColumnHandle> partitionColumns = ImmutableList.of(dsColumn, fileFormatColumn, dummyColumn); List<HivePartition> partitions = ImmutableList.<HivePartition>builder() .add(new HivePartition(tablePartitionFormat, "ds=2012-12-29/file_format=textfile/dummy=1", ImmutableMap.<ColumnHandle, NullableValue>builder() .put(dsColumn, NullableValue.of(createUnboundedVarcharType(), utf8Slice("2012-12-29"))) .put(fileFormatColumn, NullableValue.of(createUnboundedVarcharType(), utf8Slice("textfile"))) .put(dummyColumn, NullableValue.of(INTEGER, 1L)) .build())) .add(new HivePartition(tablePartitionFormat, "ds=2012-12-29/file_format=sequencefile/dummy=2", ImmutableMap.<ColumnHandle, NullableValue>builder() .put(dsColumn, NullableValue.of(createUnboundedVarcharType(), utf8Slice("2012-12-29"))) .put(fileFormatColumn, NullableValue.of(createUnboundedVarcharType(), utf8Slice("sequencefile"))) .put(dummyColumn, NullableValue.of(INTEGER, 2L)) .build())) .add(new HivePartition(tablePartitionFormat, "ds=2012-12-29/file_format=rctext/dummy=3", ImmutableMap.<ColumnHandle, NullableValue>builder() .put(dsColumn, NullableValue.of(createUnboundedVarcharType(), utf8Slice("2012-12-29"))) .put(fileFormatColumn, NullableValue.of(createUnboundedVarcharType(), utf8Slice("rctext"))) .put(dummyColumn, NullableValue.of(INTEGER, 3L)) .build())) .add(new HivePartition(tablePartitionFormat, "ds=2012-12-29/file_format=rcbinary/dummy=4", ImmutableMap.<ColumnHandle, NullableValue>builder() .put(dsColumn, NullableValue.of(createUnboundedVarcharType(), utf8Slice("2012-12-29"))) .put(fileFormatColumn, NullableValue.of(createUnboundedVarcharType(), utf8Slice("rcbinary"))) .put(dummyColumn, NullableValue.of(INTEGER, 4L)) .build())) .build(); partitionCount = partitions.size(); tupleDomain = TupleDomain.fromFixedValues(ImmutableMap.of(dsColumn, NullableValue.of(createUnboundedVarcharType(), utf8Slice("2012-12-29")))); tableLayout = new ConnectorTableLayout( new HiveTableLayoutHandle(tablePartitionFormat, partitionColumns, partitions, tupleDomain, tupleDomain, Optional.empty(), Optional.empty()), Optional.empty(), TupleDomain.withColumnDomains(ImmutableMap.of( dsColumn, Domain.create(ValueSet.ofRanges(Range.equal(createUnboundedVarcharType(), utf8Slice("2012-12-29"))), false), fileFormatColumn, Domain.create(ValueSet.ofRanges(Range.equal(createUnboundedVarcharType(), utf8Slice("textfile")), Range.equal(createUnboundedVarcharType(), utf8Slice("sequencefile")), Range.equal(createUnboundedVarcharType(), utf8Slice("rctext")), Range.equal(createUnboundedVarcharType(), utf8Slice("rcbinary"))), false), dummyColumn, Domain.create(ValueSet.ofRanges(Range.equal(INTEGER, 1L), Range.equal(INTEGER, 2L), Range.equal(INTEGER, 3L), Range.equal(INTEGER, 4L)), false))), Optional.empty(), Optional.empty(), Optional.of(new DiscretePredicates(partitionColumns, ImmutableList.of( TupleDomain.withColumnDomains(ImmutableMap.of( dsColumn, Domain.create(ValueSet.ofRanges(Range.equal(createUnboundedVarcharType(), utf8Slice("2012-12-29"))), false), fileFormatColumn, Domain.create(ValueSet.ofRanges(Range.equal(createUnboundedVarcharType(), utf8Slice("textfile"))), false), dummyColumn, Domain.create(ValueSet.ofRanges(Range.equal(INTEGER, 1L)), false))), TupleDomain.withColumnDomains(ImmutableMap.of( dsColumn, Domain.create(ValueSet.ofRanges(Range.equal(createUnboundedVarcharType(), utf8Slice("2012-12-29"))), false), fileFormatColumn, Domain.create(ValueSet.ofRanges(Range.equal(createUnboundedVarcharType(), utf8Slice("sequencefile"))), false), dummyColumn, Domain.create(ValueSet.ofRanges(Range.equal(INTEGER, 2L)), false))), TupleDomain.withColumnDomains(ImmutableMap.of( dsColumn, Domain.create(ValueSet.ofRanges(Range.equal(createUnboundedVarcharType(), utf8Slice("2012-12-29"))), false), fileFormatColumn, Domain.create(ValueSet.ofRanges(Range.equal(createUnboundedVarcharType(), utf8Slice("rctext"))), false), dummyColumn, Domain.create(ValueSet.ofRanges(Range.equal(INTEGER, 3L)), false))), TupleDomain.withColumnDomains(ImmutableMap.of( dsColumn, Domain.create(ValueSet.ofRanges(Range.equal(createUnboundedVarcharType(), utf8Slice("2012-12-29"))), false), fileFormatColumn, Domain.create(ValueSet.ofRanges(Range.equal(createUnboundedVarcharType(), utf8Slice("rcbinary"))), false), dummyColumn, Domain.create(ValueSet.ofRanges(Range.equal(INTEGER, 4L)), false)))))), ImmutableList.of()); List<HivePartition> unpartitionedPartitions = ImmutableList.of(new HivePartition(tableUnpartitioned)); unpartitionedTableLayout = new ConnectorTableLayout(new HiveTableLayoutHandle(tableUnpartitioned, ImmutableList.of(), unpartitionedPartitions, TupleDomain.all(), TupleDomain.all(), Optional.empty(), Optional.empty())); timeZone = DateTimeZone.forTimeZone(TimeZone.getTimeZone(timeZoneId)); } protected final void setup(String host, int port, String databaseName, String timeZone) { HiveClientConfig hiveClientConfig = getHiveClientConfig(); hiveClientConfig.setTimeZone(timeZone); String proxy = System.getProperty("hive.metastore.thrift.client.socks-proxy"); if (proxy != null) { hiveClientConfig.setMetastoreSocksProxy(HostAndPort.fromString(proxy)); } HiveCluster hiveCluster = new TestingHiveCluster(hiveClientConfig, host, port); ExtendedHiveMetastore metastore = new CachingHiveMetastore( new BridgingHiveMetastore(new ThriftHiveMetastore(hiveCluster)), executor, Duration.valueOf("1m"), Duration.valueOf("15s"), 10000); setup(databaseName, hiveClientConfig, metastore); } protected final void setup(String databaseName, HiveClientConfig hiveClientConfig, ExtendedHiveMetastore hiveMetastore) { HiveConnectorId connectorId = new HiveConnectorId("hive-test"); setupHive(connectorId.toString(), databaseName, hiveClientConfig.getTimeZone()); metastoreClient = hiveMetastore; HdfsConfiguration hdfsConfiguration = new HiveHdfsConfiguration(new HdfsConfigurationUpdater(hiveClientConfig)); hdfsEnvironment = new HdfsEnvironment(hdfsConfiguration, hiveClientConfig, new NoHdfsAuthentication()); locationService = new HiveLocationService(hdfsEnvironment); JsonCodec<PartitionUpdate> partitionUpdateCodec = JsonCodec.jsonCodec(PartitionUpdate.class); metadataFactory = new HiveMetadataFactory( metastoreClient, hdfsEnvironment, new HivePartitionManager(TYPE_MANAGER, hiveClientConfig), timeZone, 10, true, false, false, true, 1000, getHiveClientConfig().getMaxPartitionsPerScan(), TYPE_MANAGER, locationService, new TableParameterCodec(), partitionUpdateCodec, newFixedThreadPool(2), new HiveTypeTranslator(), TEST_SERVER_VERSION); transactionManager = new HiveTransactionManager(); splitManager = new HiveSplitManager( transactionHandle -> ((HiveMetadata) transactionManager.get(transactionHandle)).getMetastore(), new NamenodeStats(), hdfsEnvironment, new HadoopDirectoryLister(), directExecutor(), new HiveCoercionPolicy(TYPE_MANAGER), new CounterStat(), 100, hiveClientConfig.getMaxOutstandingSplitsSize(), hiveClientConfig.getMinPartitionBatchSize(), hiveClientConfig.getMaxPartitionBatchSize(), hiveClientConfig.getMaxInitialSplits(), hiveClientConfig.getSplitLoaderConcurrency(), false); pageSinkProvider = new HivePageSinkProvider( getDefaultHiveFileWriterFactories(hiveClientConfig), hdfsEnvironment, PAGE_SORTER, metastoreClient, new GroupByHashPageIndexerFactory(JOIN_COMPILER), TYPE_MANAGER, getHiveClientConfig(), locationService, partitionUpdateCodec, new TestingNodeManager("fake-environment"), new HiveEventClient(), new HiveSessionProperties(hiveClientConfig, new OrcFileWriterConfig()), new HiveWriterStats()); pageSourceProvider = new HivePageSourceProvider(hiveClientConfig, hdfsEnvironment, getDefaultHiveRecordCursorProvider(hiveClientConfig), getDefaultHiveDataStreamFactories(hiveClientConfig), TYPE_MANAGER); } /** * Allow subclass to change default configuration. */ protected HiveClientConfig getHiveClientConfig() { return new HiveClientConfig(); } protected ConnectorSession newSession() { return new TestingConnectorSession(new HiveSessionProperties(getHiveClientConfig(), new OrcFileWriterConfig()).getSessionProperties()); } protected Transaction newTransaction() { return new HiveTransaction(transactionManager, metadataFactory.create()); } interface Transaction extends AutoCloseable { ConnectorMetadata getMetadata(); SemiTransactionalHiveMetastore getMetastore(String schema); ConnectorTransactionHandle getTransactionHandle(); void commit(); void rollback(); @Override void close(); } static class HiveTransaction implements Transaction { private final HiveTransactionManager transactionManager; private final ConnectorTransactionHandle transactionHandle; private boolean closed; public HiveTransaction(HiveTransactionManager transactionManager, HiveMetadata hiveMetadata) { this.transactionManager = requireNonNull(transactionManager, "transactionManager is null"); this.transactionHandle = new HiveTransactionHandle(); transactionManager.put(transactionHandle, hiveMetadata); getMetastore().testOnlyThrowOnCleanupFailures(); } @Override public ConnectorMetadata getMetadata() { return transactionManager.get(transactionHandle); } @Override public SemiTransactionalHiveMetastore getMetastore(String schema) { return getMetastore(); } private SemiTransactionalHiveMetastore getMetastore() { return ((HiveMetadata) transactionManager.get(transactionHandle)).getMetastore(); } @Override public ConnectorTransactionHandle getTransactionHandle() { return transactionHandle; } @Override public void commit() { checkState(!closed); closed = true; HiveMetadata metadata = (HiveMetadata) transactionManager.remove(transactionHandle); checkArgument(metadata != null, "no such transaction: %s", transactionHandle); metadata.commit(); } @Override public void rollback() { checkState(!closed); closed = true; HiveMetadata metadata = (HiveMetadata) transactionManager.remove(transactionHandle); checkArgument(metadata != null, "no such transaction: %s", transactionHandle); metadata.rollback(); } @Override public void close() { if (!closed) { try { getMetastore().testOnlyCheckIsReadOnly(); // transactions in this test with writes in it must explicitly commit or rollback } finally { rollback(); } } } } @Test public void testGetDatabaseNames() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); List<String> databases = metadata.listSchemaNames(newSession()); assertTrue(databases.contains(database)); } } @Test public void testGetTableNames() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); List<SchemaTableName> tables = metadata.listTables(newSession(), database); assertTrue(tables.contains(tablePartitionFormat)); assertTrue(tables.contains(tableUnpartitioned)); } } @Test public void testGetAllTableNames() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); List<SchemaTableName> tables = metadata.listTables(newSession(), Optional.empty()); assertTrue(tables.contains(tablePartitionFormat)); assertTrue(tables.contains(tableUnpartitioned)); } } @Test public void testGetAllTableColumns() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); Map<SchemaTableName, List<ColumnMetadata>> allColumns = metadata.listTableColumns(newSession(), new SchemaTablePrefix()); assertTrue(allColumns.containsKey(tablePartitionFormat)); assertTrue(allColumns.containsKey(tableUnpartitioned)); } } @Test public void testGetAllTableColumnsInSchema() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); Map<SchemaTableName, List<ColumnMetadata>> allColumns = metadata.listTableColumns(newSession(), new SchemaTablePrefix(database)); assertTrue(allColumns.containsKey(tablePartitionFormat)); assertTrue(allColumns.containsKey(tableUnpartitioned)); } } @Test public void testListUnknownSchema() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); assertNull(metadata.getTableHandle(session, new SchemaTableName(INVALID_DATABASE, INVALID_TABLE))); assertEquals(metadata.listTables(session, INVALID_DATABASE), ImmutableList.of()); assertEquals(metadata.listTableColumns(session, new SchemaTablePrefix(INVALID_DATABASE, INVALID_TABLE)), ImmutableMap.of()); assertEquals(metadata.listViews(session, INVALID_DATABASE), ImmutableList.of()); assertEquals(metadata.getViews(session, new SchemaTablePrefix(INVALID_DATABASE, INVALID_TABLE)), ImmutableMap.of()); } } @Test public void testGetPartitions() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tablePartitionFormat); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(newSession(), tableHandle, Constraint.alwaysTrue(), Optional.empty()); assertExpectedTableLayout(getOnlyElement(tableLayoutResults).getTableLayout(), tableLayout); } } @Test public void testGetPartitionsWithBindings() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tablePartitionFormat); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(newSession(), tableHandle, new Constraint<>(TupleDomain.withColumnDomains(ImmutableMap.of(intColumn, Domain.singleValue(BIGINT, 5L)))), Optional.empty()); assertExpectedTableLayout(getOnlyElement(tableLayoutResults).getTableLayout(), tableLayout); } } @Test(expectedExceptions = TableNotFoundException.class) public void testGetPartitionsException() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); metadata.getTableLayouts(newSession(), invalidTableHandle, Constraint.alwaysTrue(), Optional.empty()); } } @Test public void testGetPartitionNames() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tablePartitionFormat); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(newSession(), tableHandle, Constraint.alwaysTrue(), Optional.empty()); assertExpectedTableLayout(getOnlyElement(tableLayoutResults).getTableLayout(), tableLayout); } } @Test public void testMismatchSchemaTable() throws Exception { for (HiveStorageFormat storageFormat : createTableFormats) { // TODO: fix coercion for JSON if (storageFormat == JSON) { continue; } SchemaTableName temporaryMismatchSchemaTable = temporaryTable("mismatch_schema"); try { doTestMismatchSchemaTable( temporaryMismatchSchemaTable, storageFormat, MISMATCH_SCHEMA_TABLE_BEFORE, MISMATCH_SCHEMA_TABLE_DATA_BEFORE, MISMATCH_SCHEMA_TABLE_AFTER, MISMATCH_SCHEMA_TABLE_DATA_AFTER); } finally { dropTable(temporaryMismatchSchemaTable); } } } protected void doTestMismatchSchemaTable( SchemaTableName schemaTableName, HiveStorageFormat storageFormat, List<ColumnMetadata> tableBefore, MaterializedResult dataBefore, List<ColumnMetadata> tableAfter, MaterializedResult dataAfter) throws Exception { String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); doCreateEmptyTable(schemaTableName, storageFormat, tableBefore); // insert the data try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, schemaTableName); ConnectorInsertTableHandle insertTableHandle = metadata.beginInsert(session, tableHandle); ConnectorPageSink sink = pageSinkProvider.createPageSink(transaction.getTransactionHandle(), session, insertTableHandle); sink.appendPage(dataBefore.toPage()); Collection<Slice> fragments = getFutureValue(sink.finish()); metadata.finishInsert(session, insertTableHandle, fragments); transaction.commit(); } // load the table and verify the data try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, schemaTableName); List<ColumnHandle> columnHandles = metadata.getColumnHandles(session, tableHandle).values().stream() .filter(columnHandle -> !((HiveColumnHandle) columnHandle).isHidden()) .collect(toList()); MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.empty()); assertEqualsIgnoreOrder(result.getMaterializedRows(), dataBefore.getMaterializedRows()); transaction.commit(); } // alter the table schema try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); PrincipalPrivileges principalPrivileges = testingPrincipalPrivilege(session.getUser()); Table oldTable = transaction.getMetastore(schemaName).getTable(schemaName, tableName).get(); HiveTypeTranslator hiveTypeTranslator = new HiveTypeTranslator(); List<Column> dataColumns = tableAfter.stream() .filter(columnMetadata -> !columnMetadata.getName().equals("ds")) .map(columnMetadata -> new Column(columnMetadata.getName(), toHiveType(hiveTypeTranslator, columnMetadata.getType()), Optional.empty())) .collect(toList()); Table.Builder newTable = Table.builder(oldTable) .setDataColumns(dataColumns); transaction.getMetastore(schemaName).replaceView(schemaName, tableName, newTable.build(), principalPrivileges); transaction.commit(); } // load the altered table and verify the data try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, schemaTableName); List<ColumnHandle> columnHandles = metadata.getColumnHandles(session, tableHandle).values().stream() .filter(columnHandle -> !((HiveColumnHandle) columnHandle).isHidden()) .collect(toList()); MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.empty()); assertEqualsIgnoreOrder(result.getMaterializedRows(), dataAfter.getMaterializedRows()); transaction.commit(); } // insertions to the partitions with type mismatches should fail try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, schemaTableName); ConnectorInsertTableHandle insertTableHandle = metadata.beginInsert(session, tableHandle); ConnectorPageSink sink = pageSinkProvider.createPageSink(transaction.getTransactionHandle(), session, insertTableHandle); sink.appendPage(dataAfter.toPage()); Collection<Slice> fragments = getFutureValue(sink.finish()); metadata.finishInsert(session, insertTableHandle, fragments); transaction.commit(); fail("expected exception"); } catch (PrestoException e) { // expected assertEquals(e.getErrorCode(), HIVE_PARTITION_SCHEMA_MISMATCH.toErrorCode()); } } protected void assertExpectedTableLayout(ConnectorTableLayout actualTableLayout, ConnectorTableLayout expectedTableLayout) { assertExpectedTableLayoutHandle(actualTableLayout.getHandle(), expectedTableLayout.getHandle()); assertEquals(actualTableLayout.getPredicate(), expectedTableLayout.getPredicate()); assertEquals(actualTableLayout.getDiscretePredicates().isPresent(), expectedTableLayout.getDiscretePredicates().isPresent()); actualTableLayout.getDiscretePredicates().ifPresent(actual -> { DiscretePredicates expected = expectedTableLayout.getDiscretePredicates().get(); assertEquals(actual.getColumns(), expected.getColumns()); assertEqualsIgnoreOrder(actual.getPredicates(), expected.getPredicates()); }); assertEquals(actualTableLayout.getStreamPartitioningColumns(), expectedTableLayout.getStreamPartitioningColumns()); assertEquals(actualTableLayout.getLocalProperties(), expectedTableLayout.getLocalProperties()); } protected void assertExpectedTableLayoutHandle(ConnectorTableLayoutHandle actualTableLayoutHandle, ConnectorTableLayoutHandle expectedTableLayoutHandle) { assertInstanceOf(actualTableLayoutHandle, HiveTableLayoutHandle.class); assertInstanceOf(expectedTableLayoutHandle, HiveTableLayoutHandle.class); HiveTableLayoutHandle actual = (HiveTableLayoutHandle) actualTableLayoutHandle; HiveTableLayoutHandle expected = (HiveTableLayoutHandle) expectedTableLayoutHandle; assertExpectedPartitions(actual.getPartitions().get(), expected.getPartitions().get()); } protected void assertExpectedPartitions(List<HivePartition> actualPartitions, Iterable<HivePartition> expectedPartitions) { Map<String, ?> actualById = uniqueIndex(actualPartitions, HivePartition::getPartitionId); for (Object expected : expectedPartitions) { assertInstanceOf(expected, HivePartition.class); HivePartition expectedPartition = (HivePartition) expected; Object actual = actualById.get(expectedPartition.getPartitionId()); assertEquals(actual, expected); assertInstanceOf(actual, HivePartition.class); HivePartition actualPartition = (HivePartition) actual; assertNotNull(actualPartition, "partition " + expectedPartition.getPartitionId()); assertEquals(actualPartition.getPartitionId(), expectedPartition.getPartitionId()); assertEquals(actualPartition.getKeys(), expectedPartition.getKeys()); assertEquals(actualPartition.getTableName(), expectedPartition.getTableName()); } } @Test public void testGetPartitionNamesUnpartitioned() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableUnpartitioned); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(newSession(), tableHandle, Constraint.alwaysTrue(), Optional.empty()); assertEquals(getAllPartitions(getOnlyElement(tableLayoutResults).getTableLayout().getHandle()).size(), 1); assertExpectedTableLayout(getOnlyElement(tableLayoutResults).getTableLayout(), unpartitionedTableLayout); } } @Test(expectedExceptions = TableNotFoundException.class) public void testGetPartitionNamesException() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); metadata.getTableLayouts(newSession(), invalidTableHandle, Constraint.alwaysTrue(), Optional.empty()); } } @SuppressWarnings({"ValueOfIncrementOrDecrementUsed", "UnusedAssignment"}) @Test public void testGetTableSchemaPartitionFormat() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(newSession(), getTableHandle(metadata, tablePartitionFormat)); Map<String, ColumnMetadata> map = uniqueIndex(tableMetadata.getColumns(), ColumnMetadata::getName); assertPrimitiveField(map, "t_string", createUnboundedVarcharType(), false); assertPrimitiveField(map, "t_tinyint", TINYINT, false); assertPrimitiveField(map, "t_smallint", SMALLINT, false); assertPrimitiveField(map, "t_int", INTEGER, false); assertPrimitiveField(map, "t_bigint", BIGINT, false); assertPrimitiveField(map, "t_float", REAL, false); assertPrimitiveField(map, "t_double", DOUBLE, false); assertPrimitiveField(map, "t_boolean", BOOLEAN, false); assertPrimitiveField(map, "ds", createUnboundedVarcharType(), true); assertPrimitiveField(map, "file_format", createUnboundedVarcharType(), true); assertPrimitiveField(map, "dummy", INTEGER, true); } } @Test public void testGetTableSchemaUnpartitioned() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableUnpartitioned); ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(newSession(), tableHandle); Map<String, ColumnMetadata> map = uniqueIndex(tableMetadata.getColumns(), ColumnMetadata::getName); assertPrimitiveField(map, "t_string", createUnboundedVarcharType(), false); assertPrimitiveField(map, "t_tinyint", TINYINT, false); } } @Test public void testGetTableSchemaOffline() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); Map<SchemaTableName, List<ColumnMetadata>> columns = metadata.listTableColumns(newSession(), tableOffline.toSchemaTablePrefix()); assertEquals(columns.size(), 1); Map<String, ColumnMetadata> map = uniqueIndex(getOnlyElement(columns.values()), ColumnMetadata::getName); assertPrimitiveField(map, "t_string", createUnboundedVarcharType(), false); } } @Test public void testGetTableSchemaOfflinePartition() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableOfflinePartition); ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(newSession(), tableHandle); Map<String, ColumnMetadata> map = uniqueIndex(tableMetadata.getColumns(), ColumnMetadata::getName); assertPrimitiveField(map, "t_string", createUnboundedVarcharType(), false); } } @Test public void testGetTableSchemaNotReadablePartition() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableNotReadable); ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(newSession(), tableHandle); Map<String, ColumnMetadata> map = uniqueIndex(tableMetadata.getColumns(), ColumnMetadata::getName); assertPrimitiveField(map, "t_string", createUnboundedVarcharType(), false); } } @Test public void testGetTableSchemaException() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); assertNull(metadata.getTableHandle(newSession(), invalidTable)); } } @Test public void testGetTableStatsBucketedStringInt() { assertTableStatsComputed( tableBucketedStringInt, ImmutableSet.of( "t_bigint", "t_boolean", "t_double", "t_float", "t_int", "t_smallint", "t_string", "t_tinyint", "ds")); } @Test public void testGetTableStatsUnpartitioned() { assertTableStatsComputed( tableUnpartitioned, ImmutableSet.of("t_string", "t_tinyint")); } private void assertTableStatsComputed( SchemaTableName tableName, Set<String> expectedColumnStatsColumns) { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); TableStatistics tableStatistics = metadata.getTableStatistics(session, tableHandle, Constraint.alwaysTrue()); assertFalse(tableStatistics.getRowCount().isValueUnknown(), "row count is unknown"); Map<String, ColumnStatistics> columnsStatistics = tableStatistics .getColumnStatistics() .entrySet() .stream() .collect( toImmutableMap( entry -> ((HiveColumnHandle) entry.getKey()).getName(), Map.Entry::getValue)); assertEquals(columnsStatistics.keySet(), expectedColumnStatsColumns, "columns with statistics"); columnsStatistics.forEach((columnName, columnStatistics) -> { assertFalse( columnStatistics.getNullsFraction().isValueUnknown(), "unknown nulls fraction for " + columnName); RangeColumnStatistics rangeColumnStatistics = columnStatistics.getOnlyRangeColumnStatistics(); assertFalse( rangeColumnStatistics.getDistinctValuesCount().isValueUnknown(), "unknown range distinct values count for " + columnName); assertFalse( rangeColumnStatistics.getFraction().isValueUnknown(), "unknown range non-null fraction for " + columnName); }); } } @Test public void testGetPartitionSplitsBatch() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tablePartitionFormat); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(session, tableHandle, Constraint.alwaysTrue(), Optional.empty()); ConnectorSplitSource splitSource = splitManager.getSplits(transaction.getTransactionHandle(), session, getOnlyElement(tableLayoutResults).getTableLayout().getHandle(), UNGROUPED_SCHEDULING); assertEquals(getSplitCount(splitSource), partitionCount); } } @Test public void testGetPartitionSplitsBatchUnpartitioned() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableUnpartitioned); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(session, tableHandle, Constraint.alwaysTrue(), Optional.empty()); ConnectorSplitSource splitSource = splitManager.getSplits(transaction.getTransactionHandle(), session, getOnlyElement(tableLayoutResults).getTableLayout().getHandle(), UNGROUPED_SCHEDULING); assertEquals(getSplitCount(splitSource), 1); } } @Test(expectedExceptions = TableNotFoundException.class) public void testGetPartitionSplitsBatchInvalidTable() { try (Transaction transaction = newTransaction()) { splitManager.getSplits(transaction.getTransactionHandle(), newSession(), invalidTableLayoutHandle, UNGROUPED_SCHEDULING); } } @Test public void testGetPartitionTableOffline() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); try { getTableHandle(metadata, tableOffline); fail("expected TableOfflineException"); } catch (TableOfflineException e) { assertEquals(e.getTableName(), tableOffline); } } } @Test public void testGetPartitionSplitsTableOfflinePartition() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableOfflinePartition); assertNotNull(tableHandle); ColumnHandle dsColumn = metadata.getColumnHandles(session, tableHandle).get("ds"); assertNotNull(dsColumn); Domain domain = Domain.singleValue(createUnboundedVarcharType(), utf8Slice("2012-12-30")); TupleDomain<ColumnHandle> tupleDomain = TupleDomain.withColumnDomains(ImmutableMap.of(dsColumn, domain)); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(session, tableHandle, new Constraint<>(tupleDomain), Optional.empty()); try { getSplitCount(splitManager.getSplits(transaction.getTransactionHandle(), session, getOnlyElement(tableLayoutResults).getTableLayout().getHandle(), UNGROUPED_SCHEDULING)); fail("Expected PartitionOfflineException"); } catch (PartitionOfflineException e) { assertEquals(e.getTableName(), tableOfflinePartition); assertEquals(e.getPartition(), "ds=2012-12-30"); } } } @Test public void testGetPartitionSplitsTableNotReadablePartition() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableNotReadable); assertNotNull(tableHandle); ColumnHandle dsColumn = metadata.getColumnHandles(session, tableHandle).get("ds"); assertNotNull(dsColumn); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(session, tableHandle, Constraint.alwaysTrue(), Optional.empty()); try { getSplitCount(splitManager.getSplits(transaction.getTransactionHandle(), session, getOnlyElement(tableLayoutResults).getTableLayout().getHandle(), UNGROUPED_SCHEDULING)); fail("Expected HiveNotReadableException"); } catch (HiveNotReadableException e) { assertThat(e).hasMessageMatching("Table '.*\\.presto_test_not_readable' is not readable: reason for not readable"); assertEquals(e.getTableName(), tableNotReadable); assertEquals(e.getPartition(), Optional.empty()); } } } @Test public void testBucketedTableStringInt() throws Exception { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableBucketedStringInt); List<ColumnHandle> columnHandles = ImmutableList.copyOf(metadata.getColumnHandles(session, tableHandle).values()); Map<String, Integer> columnIndex = indexColumns(columnHandles); assertTableIsBucketed(tableHandle); String testString = "test"; Integer testInt = 13; Short testSmallint = 12; // Reverse the order of bindings as compared to bucketing order ImmutableMap<ColumnHandle, NullableValue> bindings = ImmutableMap.<ColumnHandle, NullableValue>builder() .put(columnHandles.get(columnIndex.get("t_int")), NullableValue.of(INTEGER, (long) testInt)) .put(columnHandles.get(columnIndex.get("t_string")), NullableValue.of(createUnboundedVarcharType(), utf8Slice(testString))) .put(columnHandles.get(columnIndex.get("t_smallint")), NullableValue.of(SMALLINT, (long) testSmallint)) .build(); MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.fromFixedValues(bindings), OptionalInt.of(1), Optional.empty()); boolean rowFound = false; for (MaterializedRow row : result) { if (testString.equals(row.getField(columnIndex.get("t_string"))) && testInt.equals(row.getField(columnIndex.get("t_int"))) && testSmallint.equals(row.getField(columnIndex.get("t_smallint")))) { rowFound = true; } } assertTrue(rowFound); } } @SuppressWarnings("ConstantConditions") @Test public void testBucketedTableBigintBoolean() throws Exception { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableBucketedBigintBoolean); List<ColumnHandle> columnHandles = ImmutableList.copyOf(metadata.getColumnHandles(session, tableHandle).values()); Map<String, Integer> columnIndex = indexColumns(columnHandles); assertTableIsBucketed(tableHandle); String testString = "test"; Long testBigint = 89L; Boolean testBoolean = true; ImmutableMap<ColumnHandle, NullableValue> bindings = ImmutableMap.<ColumnHandle, NullableValue>builder() .put(columnHandles.get(columnIndex.get("t_string")), NullableValue.of(createUnboundedVarcharType(), utf8Slice(testString))) .put(columnHandles.get(columnIndex.get("t_bigint")), NullableValue.of(BIGINT, testBigint)) .put(columnHandles.get(columnIndex.get("t_boolean")), NullableValue.of(BOOLEAN, testBoolean)) .build(); MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.fromFixedValues(bindings), OptionalInt.of(1), Optional.empty()); boolean rowFound = false; for (MaterializedRow row : result) { if (testString.equals(row.getField(columnIndex.get("t_string"))) && testBigint.equals(row.getField(columnIndex.get("t_bigint"))) && testBoolean.equals(row.getField(columnIndex.get("t_boolean")))) { rowFound = true; break; } } assertTrue(rowFound); } } @Test public void testBucketedTableDoubleFloat() throws Exception { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableBucketedDoubleFloat); List<ColumnHandle> columnHandles = ImmutableList.copyOf(metadata.getColumnHandles(session, tableHandle).values()); Map<String, Integer> columnIndex = indexColumns(columnHandles); assertTableIsBucketed(tableHandle); ImmutableMap<ColumnHandle, NullableValue> bindings = ImmutableMap.<ColumnHandle, NullableValue>builder() .put(columnHandles.get(columnIndex.get("t_float")), NullableValue.of(REAL, (long) floatToRawIntBits(87.1f))) .put(columnHandles.get(columnIndex.get("t_double")), NullableValue.of(DOUBLE, 88.2)) .build(); // floats and doubles are not supported, so we should see all splits MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.fromFixedValues(bindings), OptionalInt.of(32), Optional.empty()); assertEquals(result.getRowCount(), 100); } } @Test public void testBucketedTableEvolution() throws Exception { for (HiveStorageFormat storageFormat : createTableFormats) { SchemaTableName temporaryBucketEvolutionTable = temporaryTable("bucket_evolution"); try { doTestBucketedTableEvolution(storageFormat, temporaryBucketEvolutionTable); } finally { dropTable(temporaryBucketEvolutionTable); } } } private void doTestBucketedTableEvolution(HiveStorageFormat storageFormat, SchemaTableName tableName) throws Exception { int rowCount = 100; // // Produce a table with 8 buckets. // The table has 3 partitions of 3 different bucket count (4, 8, 16). createEmptyTable( tableName, storageFormat, ImmutableList.of( new Column("id", HIVE_LONG, Optional.empty()), new Column("name", HIVE_STRING, Optional.empty())), ImmutableList.of(new Column("pk", HIVE_STRING, Optional.empty())), Optional.of(new HiveBucketProperty(ImmutableList.of("id"), 4, ImmutableList.of()))); // write a 4-bucket partition MaterializedResult.Builder bucket4Builder = MaterializedResult.resultBuilder(SESSION, BIGINT, VARCHAR, VARCHAR); IntStream.range(0, rowCount).forEach(i -> bucket4Builder.row((long) i, String.valueOf(i), "four")); insertData(tableName, bucket4Builder.build()); // write a 16-bucket partition alterBucketProperty(tableName, Optional.of(new HiveBucketProperty(ImmutableList.of("id"), 16, ImmutableList.of()))); MaterializedResult.Builder bucket16Builder = MaterializedResult.resultBuilder(SESSION, BIGINT, VARCHAR, VARCHAR); IntStream.range(0, rowCount).forEach(i -> bucket16Builder.row((long) i, String.valueOf(i), "sixteen")); insertData(tableName, bucket16Builder.build()); // write an 8-bucket partition alterBucketProperty(tableName, Optional.of(new HiveBucketProperty(ImmutableList.of("id"), 8, ImmutableList.of()))); MaterializedResult.Builder bucket8Builder = MaterializedResult.resultBuilder(SESSION, BIGINT, VARCHAR, VARCHAR); IntStream.range(0, rowCount).forEach(i -> bucket8Builder.row((long) i, String.valueOf(i), "eight")); insertData(tableName, bucket8Builder.build()); try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); // read entire table List<ColumnHandle> columnHandles = ImmutableList.<ColumnHandle>builder() .addAll(metadata.getColumnHandles(session, tableHandle).values()) .build(); MaterializedResult result = readTable( transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.empty()); assertBucketTableEvolutionResult(result, columnHandles, ImmutableSet.of(0, 1, 2, 3, 4, 5, 6, 7), rowCount); // read single bucket (table/logical bucket) result = readTable( transaction, tableHandle, columnHandles, session, TupleDomain.fromFixedValues(ImmutableMap.of(bucketColumnHandle(), NullableValue.of(INTEGER, 6L))), OptionalInt.empty(), Optional.empty()); assertBucketTableEvolutionResult(result, columnHandles, ImmutableSet.of(6), rowCount); // read single bucket, without selecting the bucketing column (i.e. id column) columnHandles = ImmutableList.<ColumnHandle>builder() .addAll(metadata.getColumnHandles(session, tableHandle).values().stream() .filter(columnHandle -> !"id".equals(((HiveColumnHandle) columnHandle).getName())) .collect(toImmutableList())) .build(); result = readTable( transaction, tableHandle, columnHandles, session, TupleDomain.fromFixedValues(ImmutableMap.of(bucketColumnHandle(), NullableValue.of(INTEGER, 6L))), OptionalInt.empty(), Optional.empty()); assertBucketTableEvolutionResult(result, columnHandles, ImmutableSet.of(6), rowCount); } } private static void assertBucketTableEvolutionResult(MaterializedResult result, List<ColumnHandle> columnHandles, Set<Integer> bucketIds, int rowCount) { // Assert that only elements in the specified bucket shows up, and each element shows up 3 times. int bucketCount = 8; Set<Long> expectedIds = LongStream.range(0, rowCount) .filter(x -> bucketIds.contains(toIntExact(x % bucketCount))) .boxed() .collect(toImmutableSet()); // assert that content from all three buckets are the same Map<String, Integer> columnIndex = indexColumns(columnHandles); OptionalInt idColumnIndex = columnIndex.containsKey("id") ? OptionalInt.of(columnIndex.get("id")) : OptionalInt.empty(); int nameColumnIndex = columnIndex.get("name"); int bucketColumnIndex = columnIndex.get(BUCKET_COLUMN_NAME); Map<Long, Integer> idCount = new HashMap<>(); for (MaterializedRow row : result.getMaterializedRows()) { String name = (String) row.getField(nameColumnIndex); int bucket = (int) row.getField(bucketColumnIndex); idCount.compute(Long.parseLong(name), (key, oldValue) -> oldValue == null ? 1 : oldValue + 1); assertEquals(bucket, Integer.parseInt(name) % bucketCount); if (idColumnIndex.isPresent()) { long id = (long) row.getField(idColumnIndex.getAsInt()); assertEquals(Integer.parseInt(name), id); } } assertEquals( (int) idCount.values().stream() .distinct() .collect(onlyElement()), 3); assertEquals(idCount.keySet(), expectedIds); } private void assertTableIsBucketed(ConnectorTableHandle tableHandle) { // the bucketed test tables should have exactly 32 splits List<ConnectorSplit> splits = getAllSplits(tableHandle, TupleDomain.all()); assertEquals(splits.size(), 32); // verify all paths are unique Set<String> paths = new HashSet<>(); for (ConnectorSplit split : splits) { assertTrue(paths.add(((HiveSplit) split).getPath())); } } @Test public void testGetRecords() throws Exception { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tablePartitionFormat); ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(session, tableHandle); List<ColumnHandle> columnHandles = ImmutableList.copyOf(metadata.getColumnHandles(session, tableHandle).values()); Map<String, Integer> columnIndex = indexColumns(columnHandles); List<ConnectorSplit> splits = getAllSplits(tableHandle, TupleDomain.all()); assertEquals(splits.size(), partitionCount); for (ConnectorSplit split : splits) { HiveSplit hiveSplit = (HiveSplit) split; List<HivePartitionKey> partitionKeys = hiveSplit.getPartitionKeys(); String ds = partitionKeys.get(0).getValue(); String fileFormat = partitionKeys.get(1).getValue(); HiveStorageFormat fileType = HiveStorageFormat.valueOf(fileFormat.toUpperCase()); int dummyPartition = Integer.parseInt(partitionKeys.get(2).getValue()); long rowNumber = 0; long completedBytes = 0; try (ConnectorPageSource pageSource = pageSourceProvider.createPageSource(transaction.getTransactionHandle(), session, hiveSplit, columnHandles)) { MaterializedResult result = materializeSourceDataStream(session, pageSource, getTypes(columnHandles)); assertPageSourceType(pageSource, fileType); for (MaterializedRow row : result) { try { assertValueTypes(row, tableMetadata.getColumns()); } catch (RuntimeException e) { throw new RuntimeException("row " + rowNumber, e); } rowNumber++; Object value; value = row.getField(columnIndex.get("t_string")); if (rowNumber % 19 == 0) { assertNull(value); } else if (rowNumber % 19 == 1) { assertEquals(value, ""); } else { assertEquals(value, "test"); } assertEquals(row.getField(columnIndex.get("t_tinyint")), (byte) (1 + rowNumber)); assertEquals(row.getField(columnIndex.get("t_smallint")), (short) (2 + rowNumber)); assertEquals(row.getField(columnIndex.get("t_int")), 3 + (int) rowNumber); if (rowNumber % 13 == 0) { assertNull(row.getField(columnIndex.get("t_bigint"))); } else { assertEquals(row.getField(columnIndex.get("t_bigint")), 4 + rowNumber); } assertEquals((Float) row.getField(columnIndex.get("t_float")), 5.1f + rowNumber, 0.001); assertEquals(row.getField(columnIndex.get("t_double")), 6.2 + rowNumber); if (rowNumber % 3 == 2) { assertNull(row.getField(columnIndex.get("t_boolean"))); } else { assertEquals(row.getField(columnIndex.get("t_boolean")), rowNumber % 3 != 0); } assertEquals(row.getField(columnIndex.get("ds")), ds); assertEquals(row.getField(columnIndex.get("file_format")), fileFormat); assertEquals(row.getField(columnIndex.get("dummy")), dummyPartition); long newCompletedBytes = pageSource.getCompletedBytes(); assertTrue(newCompletedBytes >= completedBytes); assertTrue(newCompletedBytes <= hiveSplit.getLength()); completedBytes = newCompletedBytes; } assertTrue(completedBytes <= hiveSplit.getLength()); assertEquals(rowNumber, 100); } } } } @Test public void testGetPartialRecords() throws Exception { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tablePartitionFormat); List<ColumnHandle> columnHandles = ImmutableList.copyOf(metadata.getColumnHandles(session, tableHandle).values()); Map<String, Integer> columnIndex = indexColumns(columnHandles); List<ConnectorSplit> splits = getAllSplits(tableHandle, TupleDomain.all()); assertEquals(splits.size(), partitionCount); for (ConnectorSplit split : splits) { HiveSplit hiveSplit = (HiveSplit) split; List<HivePartitionKey> partitionKeys = hiveSplit.getPartitionKeys(); String ds = partitionKeys.get(0).getValue(); String fileFormat = partitionKeys.get(1).getValue(); HiveStorageFormat fileType = HiveStorageFormat.valueOf(fileFormat.toUpperCase()); int dummyPartition = Integer.parseInt(partitionKeys.get(2).getValue()); long rowNumber = 0; try (ConnectorPageSource pageSource = pageSourceProvider.createPageSource(transaction.getTransactionHandle(), session, hiveSplit, columnHandles)) { assertPageSourceType(pageSource, fileType); MaterializedResult result = materializeSourceDataStream(session, pageSource, getTypes(columnHandles)); for (MaterializedRow row : result) { rowNumber++; assertEquals(row.getField(columnIndex.get("t_double")), 6.2 + rowNumber); assertEquals(row.getField(columnIndex.get("ds")), ds); assertEquals(row.getField(columnIndex.get("file_format")), fileFormat); assertEquals(row.getField(columnIndex.get("dummy")), dummyPartition); } } assertEquals(rowNumber, 100); } } } @Test public void testGetRecordsUnpartitioned() throws Exception { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableUnpartitioned); List<ColumnHandle> columnHandles = ImmutableList.copyOf(metadata.getColumnHandles(session, tableHandle).values()); Map<String, Integer> columnIndex = indexColumns(columnHandles); List<ConnectorSplit> splits = getAllSplits(tableHandle, TupleDomain.all()); assertEquals(splits.size(), 1); for (ConnectorSplit split : splits) { HiveSplit hiveSplit = (HiveSplit) split; assertEquals(hiveSplit.getPartitionKeys(), ImmutableList.of()); long rowNumber = 0; try (ConnectorPageSource pageSource = pageSourceProvider.createPageSource(transaction.getTransactionHandle(), session, split, columnHandles)) { assertPageSourceType(pageSource, TEXTFILE); MaterializedResult result = materializeSourceDataStream(session, pageSource, getTypes(columnHandles)); for (MaterializedRow row : result) { rowNumber++; if (rowNumber % 19 == 0) { assertNull(row.getField(columnIndex.get("t_string"))); } else if (rowNumber % 19 == 1) { assertEquals(row.getField(columnIndex.get("t_string")), ""); } else { assertEquals(row.getField(columnIndex.get("t_string")), "unpartitioned"); } assertEquals(row.getField(columnIndex.get("t_tinyint")), (byte) (1 + rowNumber)); } } assertEquals(rowNumber, 100); } } } @Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = ".*" + INVALID_COLUMN + ".*") public void testGetRecordsInvalidColumn() throws Exception { try (Transaction transaction = newTransaction()) { ConnectorMetadata connectorMetadata = transaction.getMetadata(); ConnectorTableHandle table = getTableHandle(connectorMetadata, tableUnpartitioned); readTable(transaction, table, ImmutableList.of(invalidColumnHandle), newSession(), TupleDomain.all(), OptionalInt.empty(), Optional.empty()); } } @Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = ".*The column 't_data' in table '.*\\.presto_test_partition_schema_change' is declared as type 'double', but partition 'ds=2012-12-29' declared column 't_data' as type 'string'.") public void testPartitionSchemaMismatch() throws Exception { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle table = getTableHandle(metadata, tablePartitionSchemaChange); readTable(transaction, table, ImmutableList.of(dsColumn), newSession(), TupleDomain.all(), OptionalInt.empty(), Optional.empty()); } } // TODO coercion of non-canonical values should be supported @Test(enabled = false) public void testPartitionSchemaNonCanonical() throws Exception { try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle table = getTableHandle(metadata, tablePartitionSchemaChangeNonCanonical); ColumnHandle column = metadata.getColumnHandles(session, table).get("t_boolean"); assertNotNull(column); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(session, table, new Constraint<>(TupleDomain.fromFixedValues(ImmutableMap.of(column, NullableValue.of(BOOLEAN, false)))), Optional.empty()); ConnectorTableLayoutHandle layoutHandle = getOnlyElement(tableLayoutResults).getTableLayout().getHandle(); assertEquals(getAllPartitions(layoutHandle).size(), 1); assertEquals(getPartitionId(getAllPartitions(layoutHandle).get(0)), "t_boolean=0"); ConnectorSplitSource splitSource = splitManager.getSplits(transaction.getTransactionHandle(), session, layoutHandle, UNGROUPED_SCHEDULING); ConnectorSplit split = getOnlyElement(getAllSplits(splitSource)); ImmutableList<ColumnHandle> columnHandles = ImmutableList.of(column); try (ConnectorPageSource ignored = pageSourceProvider.createPageSource(transaction.getTransactionHandle(), session, split, columnHandles)) { fail("expected exception"); } catch (PrestoException e) { assertEquals(e.getErrorCode(), HIVE_INVALID_PARTITION_VALUE.toErrorCode()); } } } @Test public void testTypesTextFile() throws Exception { assertGetRecords("presto_test_types_textfile", TEXTFILE); } @Test public void testTypesSequenceFile() throws Exception { assertGetRecords("presto_test_types_sequencefile", SEQUENCEFILE); } @Test public void testTypesRcText() throws Exception { assertGetRecords("presto_test_types_rctext", RCTEXT); } @Test public void testTypesRcBinary() throws Exception { assertGetRecords("presto_test_types_rcbinary", RCBINARY); } @Test public void testTypesOrc() throws Exception { assertGetRecordsOptional("presto_test_types_orc", ORC); } @Test public void testTypesParquet() throws Exception { assertGetRecordsOptional("presto_test_types_parquet", PARQUET); } @Test public void testEmptyTextFile() throws Exception { assertEmptyFile(TEXTFILE); } @Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = "Error opening Hive split .*SequenceFile.*EOFException") public void testEmptySequenceFile() throws Exception { assertEmptyFile(SEQUENCEFILE); } @Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = "RCFile is empty: .*") public void testEmptyRcTextFile() throws Exception { assertEmptyFile(RCTEXT); } @Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = "RCFile is empty: .*") public void testEmptyRcBinaryFile() throws Exception { assertEmptyFile(RCBINARY); } @Test public void testEmptyOrcFile() throws Exception { assertEmptyFile(ORC); } @Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = "ORC file is empty: .*") public void testEmptyDwrfFile() throws Exception { assertEmptyFile(DWRF); } private void assertEmptyFile(HiveStorageFormat format) throws Exception { SchemaTableName tableName = temporaryTable("empty_file"); try { List<Column> columns = ImmutableList.of(new Column("test", HIVE_STRING, Optional.empty())); createEmptyTable(tableName, format, columns, ImmutableList.of()); try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); Table table = transaction.getMetastore(tableName.getSchemaName()) .getTable(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(AssertionError::new); // verify directory is empty HdfsContext context = new HdfsContext(session, tableName.getSchemaName(), tableName.getTableName()); Path location = new Path(table.getStorage().getLocation()); assertTrue(listDirectory(context, location).isEmpty()); // read table with empty directory readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.of(0), Optional.of(ORC)); // create empty file FileSystem fileSystem = hdfsEnvironment.getFileSystem(context, location); assertTrue(fileSystem.createNewFile(new Path(location, "empty-file"))); assertEquals(listDirectory(context, location), ImmutableList.of("empty-file")); // read table with empty file MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.of(1), Optional.empty()); assertEquals(result.getRowCount(), 0); } } finally { dropTable(tableName); } } @Test public void testHiveViewsAreNotSupported() { try (Transaction transaction = newTransaction()) { try { ConnectorMetadata metadata = transaction.getMetadata(); getTableHandle(metadata, view); fail("Expected HiveViewNotSupportedException"); } catch (HiveViewNotSupportedException e) { assertEquals(e.getTableName(), view); } } } @Test public void testHiveViewsHaveNoColumns() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); assertEquals(metadata.listTableColumns(newSession(), new SchemaTablePrefix(view.getSchemaName(), view.getTableName())), ImmutableMap.of()); } } @Test public void testRenameTable() { SchemaTableName temporaryRenameTableOld = temporaryTable("rename_old"); SchemaTableName temporaryRenameTableNew = temporaryTable("rename_new"); try { createDummyTable(temporaryRenameTableOld); try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); metadata.renameTable(session, getTableHandle(metadata, temporaryRenameTableOld), temporaryRenameTableNew); transaction.commit(); } try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); assertNull(metadata.getTableHandle(session, temporaryRenameTableOld)); assertNotNull(metadata.getTableHandle(session, temporaryRenameTableNew)); } } finally { dropTable(temporaryRenameTableOld); dropTable(temporaryRenameTableNew); } } @Test public void testTableCreation() throws Exception { for (HiveStorageFormat storageFormat : createTableFormats) { SchemaTableName temporaryCreateTable = temporaryTable("create"); try { doCreateTable(temporaryCreateTable, storageFormat); } finally { dropTable(temporaryCreateTable); } } } @Test public void testTableCreationRollback() throws Exception { SchemaTableName temporaryCreateRollbackTable = temporaryTable("create_rollback"); try { Path stagingPathRoot; try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); // begin creating the table ConnectorTableMetadata tableMetadata = new ConnectorTableMetadata(temporaryCreateRollbackTable, CREATE_TABLE_COLUMNS, createTableProperties(RCBINARY)); ConnectorOutputTableHandle outputHandle = metadata.beginCreateTable(session, tableMetadata, Optional.empty()); // write the data ConnectorPageSink sink = pageSinkProvider.createPageSink(transaction.getTransactionHandle(), session, outputHandle); sink.appendPage(CREATE_TABLE_DATA.toPage()); getFutureValue(sink.finish()); // verify we have data files stagingPathRoot = getStagingPathRoot(outputHandle); HdfsContext context = new HdfsContext(session, temporaryCreateRollbackTable.getSchemaName(), temporaryCreateRollbackTable.getTableName()); assertFalse(listAllDataFiles(context, stagingPathRoot).isEmpty()); // rollback the table transaction.rollback(); } // verify all files have been deleted HdfsContext context = new HdfsContext(newSession(), temporaryCreateRollbackTable.getSchemaName(), temporaryCreateRollbackTable.getTableName()); assertTrue(listAllDataFiles(context, stagingPathRoot).isEmpty()); // verify table is not in the metastore try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); assertNull(metadata.getTableHandle(session, temporaryCreateRollbackTable)); } } finally { dropTable(temporaryCreateRollbackTable); } } @Test public void testTableCreationIgnoreExisting() { List<Column> columns = ImmutableList.of(new Column("dummy", HiveType.valueOf("uniontype<smallint,tinyint>"), Optional.empty())); SchemaTableName schemaTableName = temporaryTable("create"); ConnectorSession session = newSession(); String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); PrincipalPrivileges privileges = testingPrincipalPrivilege(session.getUser()); Path targetPath; try { try (Transaction transaction = newTransaction()) { LocationService locationService = getLocationService(schemaName); LocationHandle locationHandle = locationService.forNewTable(transaction.getMetastore(schemaName), session, schemaName, tableName); targetPath = locationService.getQueryWriteInfo(locationHandle).getTargetPath(); Table table = createSimpleTable(schemaTableName, columns, session, targetPath, "q1"); transaction.getMetastore(schemaName) .createTable(session, table, privileges, Optional.empty(), false, EMPTY_TABLE_STATISTICS); Optional<Table> tableHandle = transaction.getMetastore(schemaName).getTable(schemaName, tableName); assertTrue(tableHandle.isPresent()); transaction.commit(); } // try creating it again from another transaction with ignoreExisting=false try (Transaction transaction = newTransaction()) { Table table = createSimpleTable(schemaTableName, columns, session, targetPath.suffix("_2"), "q2"); transaction.getMetastore(schemaName) .createTable(session, table, privileges, Optional.empty(), false, EMPTY_TABLE_STATISTICS); transaction.commit(); fail("Expected exception"); } catch (PrestoException e) { assertInstanceOf(e, TableAlreadyExistsException.class); } // try creating it again from another transaction with ignoreExisting=true try (Transaction transaction = newTransaction()) { Table table = createSimpleTable(schemaTableName, columns, session, targetPath.suffix("_3"), "q3"); transaction.getMetastore(schemaName) .createTable(session, table, privileges, Optional.empty(), true, EMPTY_TABLE_STATISTICS); transaction.commit(); } // at this point the table should exist, now try creating the table again with a different table definition columns = ImmutableList.of(new Column("new_column", HiveType.valueOf("string"), Optional.empty())); try (Transaction transaction = newTransaction()) { Table table = createSimpleTable(schemaTableName, columns, session, targetPath.suffix("_4"), "q4"); transaction.getMetastore(schemaName) .createTable(session, table, privileges, Optional.empty(), true, EMPTY_TABLE_STATISTICS); transaction.commit(); fail("Expected exception"); } catch (PrestoException e) { assertEquals(e.getErrorCode(), TRANSACTION_CONFLICT.toErrorCode()); assertEquals(e.getMessage(), format("Table already exists with a different schema: '%s'", schemaTableName.getTableName())); } } finally { dropTable(schemaTableName); } } private static Table createSimpleTable(SchemaTableName schemaTableName, List<Column> columns, ConnectorSession session, Path targetPath, String queryId) { String tableOwner = session.getUser(); String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); return Table.builder() .setDatabaseName(schemaName) .setTableName(tableName) .setOwner(tableOwner) .setTableType(TableType.MANAGED_TABLE.name()) .setParameters(ImmutableMap.of( PRESTO_VERSION_NAME, TEST_SERVER_VERSION, PRESTO_QUERY_ID_NAME, queryId)) .setDataColumns(columns) .withStorage(storage -> storage .setLocation(targetPath.toString()) .setStorageFormat(fromHiveStorageFormat(ORC)) .setSerdeParameters(ImmutableMap.of())) .build(); } @Test public void testBucketSortedTables() throws Exception { SchemaTableName table = temporaryTable("create_sorted"); try { doTestBucketSortedTables(table); } finally { dropTable(table); } } private void doTestBucketSortedTables(SchemaTableName table) throws IOException { int bucketCount = 3; try (Transaction transaction = newTransaction()) { HiveClientConfig hiveConfig = getHiveClientConfig() .setSortedWritingEnabled(true) .setWriterSortBufferSize(new DataSize(1, MEGABYTE)); ConnectorSession session = new TestingConnectorSession(new HiveSessionProperties(hiveConfig, new OrcFileWriterConfig()).getSessionProperties()); ConnectorMetadata metadata = transaction.getMetadata(); // begin creating the table ConnectorTableMetadata tableMetadata = new ConnectorTableMetadata( table, ImmutableList.<ColumnMetadata>builder() .add(new ColumnMetadata("id", VARCHAR)) .add(new ColumnMetadata("value_asc", VARCHAR)) .add(new ColumnMetadata("value_desc", BIGINT)) .add(new ColumnMetadata("ds", VARCHAR)) .build(), ImmutableMap.<String, Object>builder() .put(STORAGE_FORMAT_PROPERTY, RCBINARY) .put(PARTITIONED_BY_PROPERTY, ImmutableList.of("ds")) .put(BUCKETED_BY_PROPERTY, ImmutableList.of("id")) .put(BUCKET_COUNT_PROPERTY, bucketCount) .put(SORTED_BY_PROPERTY, ImmutableList.builder() .add(new SortingColumn("value_asc", SortingColumn.Order.ASCENDING)) .add(new SortingColumn("value_desc", SortingColumn.Order.DESCENDING)) .build()) .build()); ConnectorOutputTableHandle outputHandle = metadata.beginCreateTable(session, tableMetadata, Optional.empty()); // write the data ConnectorPageSink sink = pageSinkProvider.createPageSink(transaction.getTransactionHandle(), session, outputHandle); List<Type> types = tableMetadata.getColumns().stream() .map(ColumnMetadata::getType) .collect(toList()); ThreadLocalRandom random = ThreadLocalRandom.current(); for (int i = 0; i < 200; i++) { MaterializedResult.Builder builder = MaterializedResult.resultBuilder(session, types); for (int j = 0; j < 1000; j++) { builder.row( sha256().hashLong(random.nextLong()).toString(), "test" + random.nextInt(100), random.nextLong(100_000), "2018-04-01"); } sink.appendPage(builder.build().toPage()); } // verify we have several temporary files per bucket Path stagingPathRoot = getStagingPathRoot(outputHandle); HdfsContext context = new HdfsContext(session, table.getSchemaName(), table.getTableName()); assertThat(listAllDataFiles(context, stagingPathRoot)) .filteredOn(file -> file.contains(".tmp-sort.")) .size().isGreaterThanOrEqualTo(bucketCount * 3); // finish the write Collection<Slice> fragments = getFutureValue(sink.finish()); // verify there are no temporary files for (String file : listAllDataFiles(context, stagingPathRoot)) { assertThat(file).doesNotStartWith(".tmp-sort."); } // finish creating table metadata.finishCreateTable(session, outputHandle, fragments); transaction.commit(); } // verify that bucket files are sorted try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, table); List<ColumnHandle> columnHandles = ImmutableList.copyOf(metadata.getColumnHandles(session, tableHandle).values()); List<ConnectorSplit> splits = getAllSplits(tableHandle, TupleDomain.all()); assertThat(splits).hasSize(bucketCount); for (ConnectorSplit split : splits) { try (ConnectorPageSource pageSource = pageSourceProvider.createPageSource(transaction.getTransactionHandle(), session, split, columnHandles)) { String lastValueAsc = null; long lastValueDesc = -1; while (!pageSource.isFinished()) { Page page = pageSource.getNextPage(); if (page == null) { continue; } for (int i = 0; i < page.getPositionCount(); i++) { Block blockAsc = page.getBlock(1); Block blockDesc = page.getBlock(2); assertFalse(blockAsc.isNull(i)); assertFalse(blockDesc.isNull(i)); String valueAsc = VARCHAR.getSlice(blockAsc, i).toStringUtf8(); if (lastValueAsc != null) { assertGreaterThanOrEqual(valueAsc, lastValueAsc); if (valueAsc.equals(lastValueAsc)) { long valueDesc = BIGINT.getLong(blockDesc, i); if (lastValueDesc != -1) { assertLessThanOrEqual(valueDesc, lastValueDesc); } lastValueDesc = valueDesc; } else { lastValueDesc = -1; } } lastValueAsc = valueAsc; } } } } } } @Test public void testInsert() throws Exception { for (HiveStorageFormat storageFormat : createTableFormats) { SchemaTableName temporaryInsertTable = temporaryTable("insert"); try { doInsert(storageFormat, temporaryInsertTable); } finally { dropTable(temporaryInsertTable); } } } @Test public void testInsertIntoNewPartition() throws Exception { for (HiveStorageFormat storageFormat : createTableFormats) { SchemaTableName temporaryInsertIntoNewPartitionTable = temporaryTable("insert_new_partitioned"); try { doInsertIntoNewPartition(storageFormat, temporaryInsertIntoNewPartitionTable); } finally { dropTable(temporaryInsertIntoNewPartitionTable); } } } @Test public void testInsertIntoExistingPartition() throws Exception { for (HiveStorageFormat storageFormat : createTableFormats) { SchemaTableName temporaryInsertIntoExistingPartitionTable = temporaryTable("insert_existing_partitioned"); try { doInsertIntoExistingPartition(storageFormat, temporaryInsertIntoExistingPartitionTable); } finally { dropTable(temporaryInsertIntoExistingPartitionTable); } } } @Test public void testInsertIntoExistingPartitionEmptyStatistics() throws Exception { for (HiveStorageFormat storageFormat : createTableFormats) { SchemaTableName temporaryInsertIntoExistingPartitionTable = temporaryTable("insert_existing_partitioned_empty_statistics"); try { doInsertIntoExistingPartitionEmptyStatistics(storageFormat, temporaryInsertIntoExistingPartitionTable); } finally { dropTable(temporaryInsertIntoExistingPartitionTable); } } } @Test public void testInsertUnsupportedWriteType() throws Exception { SchemaTableName temporaryInsertUnsupportedWriteType = temporaryTable("insert_unsupported_type"); try { doInsertUnsupportedWriteType(ORC, temporaryInsertUnsupportedWriteType); } finally { dropTable(temporaryInsertUnsupportedWriteType); } } @Test public void testMetadataDelete() throws Exception { for (HiveStorageFormat storageFormat : createTableFormats) { SchemaTableName temporaryMetadataDeleteTable = temporaryTable("metadata_delete"); try { doTestMetadataDelete(storageFormat, temporaryMetadataDeleteTable); } finally { dropTable(temporaryMetadataDeleteTable); } } } @Test public void testEmptyTableCreation() throws Exception { for (HiveStorageFormat storageFormat : createTableFormats) { SchemaTableName temporaryCreateEmptyTable = temporaryTable("create_empty"); try { doCreateEmptyTable(temporaryCreateEmptyTable, storageFormat, CREATE_TABLE_COLUMNS); } finally { dropTable(temporaryCreateEmptyTable); } } } @Test public void testViewCreation() { SchemaTableName temporaryCreateView = temporaryTable("create_view"); try { verifyViewCreation(temporaryCreateView); } finally { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); metadata.dropView(newSession(), temporaryCreateView); transaction.commit(); } catch (RuntimeException e) { // this usually occurs because the view was not created } } } @Test public void testCreateTableUnsupportedType() { for (HiveStorageFormat storageFormat : createTableFormats) { try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); List<ColumnMetadata> columns = ImmutableList.of(new ColumnMetadata("dummy", HYPER_LOG_LOG)); ConnectorTableMetadata tableMetadata = new ConnectorTableMetadata(invalidTable, columns, createTableProperties(storageFormat)); metadata.beginCreateTable(session, tableMetadata, Optional.empty()); fail("create table with unsupported type should fail for storage format " + storageFormat); } catch (PrestoException e) { assertEquals(e.getErrorCode(), NOT_SUPPORTED.toErrorCode()); } } } @Test public void testUpdateTableParameters() throws Exception { SchemaTableName tableName = temporaryTable("compare_and_set_table_parameters"); try { doCreateEmptyTable(tableName, ORC, CREATE_TABLE_COLUMNS); ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); metastoreClient.updateTableParameters(tableName.getSchemaName(), tableName.getTableName(), parameters -> { Map<String, String> updated = new HashMap<>(parameters); updated.put("test_key", "test_value"); return updated; }); Table table = metastoreClient.getTable(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(() -> new TableNotFoundException(tableName)); assertThat(table.getParameters()).contains(entry("test_key", "test_value")); } finally { dropTable(tableName); } } @Test public void testUpdatePartitionParameters() throws Exception { SchemaTableName tableName = temporaryTable("compare_and_set_partition_parameters"); try { doCreateEmptyTable(tableName, ORC, CREATE_TABLE_COLUMNS_PARTITIONED); insertData(tableName, CREATE_TABLE_PARTITIONED_DATA); ImmutableList<String> partitionValues = ImmutableList.of("2015-07-01"); ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); metastoreClient.updatePartitionParameters(tableName.getSchemaName(), tableName.getTableName(), partitionValues, parameters -> { Map<String, String> updated = new HashMap<>(parameters); updated.put("test_key", "test_value"); return updated; }); Partition partition = metastoreClient.getPartition(tableName.getSchemaName(), tableName.getTableName(), partitionValues) .orElseThrow(() -> new PartitionNotFoundException(tableName, partitionValues)); assertThat(partition.getParameters()).contains(entry("test_key", "test_value")); } finally { dropTable(tableName); } } @Test public void testUpdateBasicTableStatistics() throws Exception { SchemaTableName tableName = temporaryTable("update_basic_table_statistics"); try { doCreateEmptyTable(tableName, ORC, STATISTICS_TABLE_COLUMNS); testUpdateTableStatistics(tableName, EMPTY_TABLE_STATISTICS, BASIC_STATISTICS_1, BASIC_STATISTICS_2); } finally { dropTable(tableName); } } @Test public void testUpdateTableColumnStatistics() throws Exception { SchemaTableName tableName = temporaryTable("update_table_column_statistics"); ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); if (!metastoreClient.supportsColumnStatistics()) { throw new SkipException("column level statistics are not supported"); } try { doCreateEmptyTable(tableName, ORC, STATISTICS_TABLE_COLUMNS); testUpdateTableStatistics(tableName, EMPTY_TABLE_STATISTICS, STATISTICS_1_1, STATISTICS_1_2, STATISTICS_2); } finally { dropTable(tableName); } } @Test public void testUpdateTableColumnStatisticsEmptyOptionalFields() throws Exception { SchemaTableName tableName = temporaryTable("update_table_column_statistics_empty_optional_fields"); ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); if (!metastoreClient.supportsColumnStatistics()) { throw new SkipException("column level statistics are not supported"); } try { doCreateEmptyTable(tableName, ORC, STATISTICS_TABLE_COLUMNS); testUpdateTableStatistics(tableName, EMPTY_TABLE_STATISTICS, STATISTICS_EMPTY_OPTIONAL_FIELDS); } finally { dropTable(tableName); } } protected void testUpdateTableStatistics(SchemaTableName tableName, PartitionStatistics initialStatistics, PartitionStatistics... statistics) { ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); assertThat(metastoreClient.getTableStatistics(tableName.getSchemaName(), tableName.getTableName())) .isEqualTo(initialStatistics); AtomicReference<PartitionStatistics> expectedStatistics = new AtomicReference<>(initialStatistics); for (PartitionStatistics partitionStatistics : statistics) { metastoreClient.updateTableStatistics(tableName.getSchemaName(), tableName.getTableName(), actualStatistics -> { assertThat(actualStatistics).isEqualTo(expectedStatistics.get()); return partitionStatistics; }); assertThat(metastoreClient.getTableStatistics(tableName.getSchemaName(), tableName.getTableName())) .isEqualTo(partitionStatistics); expectedStatistics.set(partitionStatistics); } assertThat(metastoreClient.getTableStatistics(tableName.getSchemaName(), tableName.getTableName())) .isEqualTo(expectedStatistics.get()); metastoreClient.updateTableStatistics(tableName.getSchemaName(), tableName.getTableName(), actualStatistics -> { assertThat(actualStatistics).isEqualTo(expectedStatistics.get()); return initialStatistics; }); assertThat(metastoreClient.getTableStatistics(tableName.getSchemaName(), tableName.getTableName())) .isEqualTo(initialStatistics); } @Test public void testUpdateBasicPartitionStatistics() throws Exception { SchemaTableName tableName = temporaryTable("update_basic_partition_statistics"); try { createDummyPartitionedTable(tableName, STATISTICS_PARTITIONED_TABLE_COLUMNS); testUpdatePartitionStatistics( tableName, EMPTY_TABLE_STATISTICS, ImmutableList.of(BASIC_STATISTICS_1, BASIC_STATISTICS_2), ImmutableList.of(BASIC_STATISTICS_2, BASIC_STATISTICS_1)); } finally { dropTable(tableName); } } @Test public void testUpdatePartitionColumnStatistics() throws Exception { SchemaTableName tableName = temporaryTable("update_partition_column_statistics"); ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); if (!metastoreClient.supportsColumnStatistics()) { throw new SkipException("column level statistics are not supported"); } try { createDummyPartitionedTable(tableName, STATISTICS_PARTITIONED_TABLE_COLUMNS); testUpdatePartitionStatistics( tableName, EMPTY_TABLE_STATISTICS, ImmutableList.of(STATISTICS_1_1, STATISTICS_1_2, STATISTICS_2), ImmutableList.of(STATISTICS_1_2, STATISTICS_1_1, STATISTICS_2)); } finally { dropTable(tableName); } } @Test public void testUpdatePartitionColumnStatisticsEmptyOptionalFields() throws Exception { SchemaTableName tableName = temporaryTable("update_partition_column_statistics"); ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); if (!metastoreClient.supportsColumnStatistics()) { throw new SkipException("column level statistics are not supported"); } try { createDummyPartitionedTable(tableName, STATISTICS_PARTITIONED_TABLE_COLUMNS); testUpdatePartitionStatistics( tableName, EMPTY_TABLE_STATISTICS, ImmutableList.of(STATISTICS_EMPTY_OPTIONAL_FIELDS), ImmutableList.of(STATISTICS_EMPTY_OPTIONAL_FIELDS)); } finally { dropTable(tableName); } } private void createDummyTable(SchemaTableName tableName) { try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); List<ColumnMetadata> columns = ImmutableList.of(new ColumnMetadata("dummy", createUnboundedVarcharType())); ConnectorTableMetadata tableMetadata = new ConnectorTableMetadata(tableName, columns, createTableProperties(TEXTFILE)); ConnectorOutputTableHandle handle = metadata.beginCreateTable(session, tableMetadata, Optional.empty()); metadata.finishCreateTable(session, handle, ImmutableList.of()); transaction.commit(); } } protected void createDummyPartitionedTable(SchemaTableName tableName, List<ColumnMetadata> columns) throws Exception { doCreateEmptyTable(tableName, ORC, columns); ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); Table table = metastoreClient.getTable(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(() -> new TableNotFoundException(tableName)); List<String> firstPartitionValues = ImmutableList.of("2016-01-01"); List<String> secondPartitionValues = ImmutableList.of("2016-01-02"); String firstPartitionName = makePartName(ImmutableList.of("ds"), firstPartitionValues); String secondPartitionName = makePartName(ImmutableList.of("ds"), secondPartitionValues); List<Partition> partitions = ImmutableList.of(firstPartitionValues, secondPartitionValues) .stream() .map(values -> Partition.builder() .setDatabaseName(tableName.getSchemaName()) .setTableName(tableName.getTableName()) .setColumns(table.getDataColumns()) .setValues(values) .withStorage(storage -> storage .setStorageFormat(fromHiveStorageFormat(HiveStorageFormat.ORC)) .setLocation(table.getStorage().getLocation() + "/" + makePartName(ImmutableList.of("ds"), values))) .build()) .collect(toImmutableList()); metastoreClient.addPartitions(tableName.getSchemaName(), tableName.getTableName(), partitions); metastoreClient.updatePartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), firstPartitionName, currentStatistics -> EMPTY_TABLE_STATISTICS); metastoreClient.updatePartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), secondPartitionName, currentStatistics -> EMPTY_TABLE_STATISTICS); } protected void testUpdatePartitionStatistics( SchemaTableName tableName, PartitionStatistics initialStatistics, List<PartitionStatistics> firstPartitionStatistics, List<PartitionStatistics> secondPartitionStatistics) { verify(firstPartitionStatistics.size() == secondPartitionStatistics.size()); String firstPartitionName = "ds=2016-01-01"; String secondPartitionName = "ds=2016-01-02"; ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); assertThat(metastoreClient.getPartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), ImmutableSet.of(firstPartitionName, secondPartitionName))) .isEqualTo(ImmutableMap.of(firstPartitionName, initialStatistics, secondPartitionName, initialStatistics)); AtomicReference<PartitionStatistics> expectedStatisticsPartition1 = new AtomicReference<>(initialStatistics); AtomicReference<PartitionStatistics> expectedStatisticsPartition2 = new AtomicReference<>(initialStatistics); for (int i = 0; i < firstPartitionStatistics.size(); i++) { PartitionStatistics statisticsPartition1 = firstPartitionStatistics.get(i); PartitionStatistics statisticsPartition2 = secondPartitionStatistics.get(i); metastoreClient.updatePartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), firstPartitionName, actualStatistics -> { assertThat(actualStatistics).isEqualTo(expectedStatisticsPartition1.get()); return statisticsPartition1; }); metastoreClient.updatePartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), secondPartitionName, actualStatistics -> { assertThat(actualStatistics).isEqualTo(expectedStatisticsPartition2.get()); return statisticsPartition2; }); assertThat(metastoreClient.getPartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), ImmutableSet.of(firstPartitionName, secondPartitionName))) .isEqualTo(ImmutableMap.of(firstPartitionName, statisticsPartition1, secondPartitionName, statisticsPartition2)); expectedStatisticsPartition1.set(statisticsPartition1); expectedStatisticsPartition2.set(statisticsPartition2); } assertThat(metastoreClient.getPartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), ImmutableSet.of(firstPartitionName, secondPartitionName))) .isEqualTo(ImmutableMap.of(firstPartitionName, expectedStatisticsPartition1.get(), secondPartitionName, expectedStatisticsPartition2.get())); metastoreClient.updatePartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), firstPartitionName, currentStatistics -> { assertThat(currentStatistics).isEqualTo(expectedStatisticsPartition1.get()); return initialStatistics; }); metastoreClient.updatePartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), secondPartitionName, currentStatistics -> { assertThat(currentStatistics).isEqualTo(expectedStatisticsPartition2.get()); return initialStatistics; }); assertThat(metastoreClient.getPartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), ImmutableSet.of(firstPartitionName, secondPartitionName))) .isEqualTo(ImmutableMap.of(firstPartitionName, initialStatistics, secondPartitionName, initialStatistics)); } /** * This test creates 2 identical partitions and verifies that the statistics projected based on * a single partition sample are equal to the statistics computed in a fair way */ @Test public void testPartitionStatisticsSampling() throws Exception { testPartitionStatisticsSampling(STATISTICS_PARTITIONED_TABLE_COLUMNS, STATISTICS_1); } protected void testPartitionStatisticsSampling(List<ColumnMetadata> columns, PartitionStatistics statistics) throws Exception { SchemaTableName tableName = temporaryTable("test_partition_statistics_sampling"); try { createDummyPartitionedTable(tableName, columns); ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); metastoreClient.updatePartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), "ds=2016-01-01", actualStatistics -> statistics); metastoreClient.updatePartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), "ds=2016-01-02", actualStatistics -> statistics); try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = metadata.getTableHandle(session, tableName); TableStatistics unsampledStatistics = metadata.getTableStatistics(sampleSize(2), tableHandle, Constraint.alwaysTrue()); TableStatistics sampledStatistics = metadata.getTableStatistics(sampleSize(1), tableHandle, Constraint.alwaysTrue()); assertEquals(sampledStatistics, unsampledStatistics); } } finally { dropTable(tableName); } } private ConnectorSession sampleSize(int sampleSize) { HiveSessionProperties properties = new HiveSessionProperties( getHiveClientConfig().setPartitionStatisticsSampleSize(sampleSize), new OrcFileWriterConfig()); return new TestingConnectorSession(properties.getSessionProperties()); } private void verifyViewCreation(SchemaTableName temporaryCreateView) { // replace works for new view doCreateView(temporaryCreateView, true); // replace works for existing view doCreateView(temporaryCreateView, true); // create fails for existing view try { doCreateView(temporaryCreateView, false); fail("create existing should fail"); } catch (ViewAlreadyExistsException e) { assertEquals(e.getViewName(), temporaryCreateView); } try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); // drop works when view exists metadata.dropView(newSession(), temporaryCreateView); transaction.commit(); } try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); assertEquals(metadata.getViews(newSession(), temporaryCreateView.toSchemaTablePrefix()).size(), 0); assertFalse(metadata.listViews(newSession(), temporaryCreateView.getSchemaName()).contains(temporaryCreateView)); } // drop fails when view does not exist try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); metadata.dropView(newSession(), temporaryCreateView); fail("drop non-existing should fail"); } catch (ViewNotFoundException e) { assertEquals(e.getViewName(), temporaryCreateView); } // create works for new view doCreateView(temporaryCreateView, false); } private void doCreateView(SchemaTableName viewName, boolean replace) { String viewData = "test data"; try (Transaction transaction = newTransaction()) { transaction.getMetadata().createView(newSession(), viewName, viewData, replace); transaction.commit(); } try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); Map<SchemaTableName, ConnectorViewDefinition> views = metadata.getViews(newSession(), viewName.toSchemaTablePrefix()); assertEquals(views.size(), 1); assertEquals(views.get(viewName).getViewData(), viewData); assertTrue(metadata.listViews(newSession(), viewName.getSchemaName()).contains(viewName)); } } protected void doCreateTable(SchemaTableName tableName, HiveStorageFormat storageFormat) throws Exception { String queryId; try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); queryId = session.getQueryId(); // begin creating the table ConnectorTableMetadata tableMetadata = new ConnectorTableMetadata(tableName, CREATE_TABLE_COLUMNS, createTableProperties(storageFormat)); ConnectorOutputTableHandle outputHandle = metadata.beginCreateTable(session, tableMetadata, Optional.empty()); // write the data ConnectorPageSink sink = pageSinkProvider.createPageSink(transaction.getTransactionHandle(), session, outputHandle); sink.appendPage(CREATE_TABLE_DATA.toPage()); Collection<Slice> fragments = getFutureValue(sink.finish()); // verify all new files start with the unique prefix HdfsContext context = new HdfsContext(session, tableName.getSchemaName(), tableName.getTableName()); for (String filePath : listAllDataFiles(context, getStagingPathRoot(outputHandle))) { assertTrue(new Path(filePath).getName().startsWith(getFilePrefix(outputHandle))); } // commit the table metadata.finishCreateTable(session, outputHandle, fragments); transaction.commit(); } try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); // load the new table ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); // verify the metadata ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(session, getTableHandle(metadata, tableName)); assertEquals(filterNonHiddenColumnMetadata(tableMetadata.getColumns()), CREATE_TABLE_COLUMNS); // verify the data MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.of(storageFormat)); assertEqualsIgnoreOrder(result.getMaterializedRows(), CREATE_TABLE_DATA.getMaterializedRows()); // verify the node version and query ID in table Table table = getMetastoreClient(tableName.getSchemaName()).getTable(tableName.getSchemaName(), tableName.getTableName()).get(); assertEquals(table.getParameters().get(PRESTO_VERSION_NAME), TEST_SERVER_VERSION); assertEquals(table.getParameters().get(PRESTO_QUERY_ID_NAME), queryId); // verify basic statistics HiveBasicStatistics statistics = getBasicStatisticsForTable(transaction, tableName); assertEquals(statistics.getRowCount().getAsLong(), CREATE_TABLE_DATA.getRowCount()); assertEquals(statistics.getFileCount().getAsLong(), 1L); assertGreaterThan(statistics.getInMemoryDataSizeInBytes().getAsLong(), 0L); assertGreaterThan(statistics.getOnDiskDataSizeInBytes().getAsLong(), 0L); } } protected void doCreateEmptyTable(SchemaTableName tableName, HiveStorageFormat storageFormat, List<ColumnMetadata> createTableColumns) throws Exception { List<String> partitionedBy = createTableColumns.stream() .filter(column -> column.getName().equals("ds")) .map(ColumnMetadata::getName) .collect(toList()); String queryId; try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); queryId = session.getQueryId(); ConnectorTableMetadata tableMetadata = new ConnectorTableMetadata(tableName, createTableColumns, createTableProperties(storageFormat, partitionedBy)); metadata.createTable(session, tableMetadata, false); transaction.commit(); } try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); // load the new table ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); // verify the metadata ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(session, getTableHandle(metadata, tableName)); List<ColumnMetadata> expectedColumns = createTableColumns.stream() .map(column -> new ColumnMetadata( column.getName(), column.getType(), column.getComment(), columnExtraInfo(partitionedBy.contains(column.getName())), false)) .collect(toList()); assertEquals(filterNonHiddenColumnMetadata(tableMetadata.getColumns()), expectedColumns); // verify table format Table table = transaction.getMetastore(tableName.getSchemaName()).getTable(tableName.getSchemaName(), tableName.getTableName()).get(); assertEquals(table.getStorage().getStorageFormat().getInputFormat(), storageFormat.getInputFormat()); // verify the node version and query ID assertEquals(table.getParameters().get(PRESTO_VERSION_NAME), TEST_SERVER_VERSION); assertEquals(table.getParameters().get(PRESTO_QUERY_ID_NAME), queryId); // verify the table is empty List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.of(storageFormat)); assertEquals(result.getRowCount(), 0); // verify basic statistics if (partitionedBy.isEmpty()) { HiveBasicStatistics statistics = getBasicStatisticsForTable(transaction, tableName); assertEquals(statistics.getRowCount().getAsLong(), 0L); assertEquals(statistics.getFileCount().getAsLong(), 0L); assertEquals(statistics.getInMemoryDataSizeInBytes().getAsLong(), 0L); assertEquals(statistics.getOnDiskDataSizeInBytes().getAsLong(), 0L); } } } private void doInsert(HiveStorageFormat storageFormat, SchemaTableName tableName) throws Exception { // creating the table doCreateEmptyTable(tableName, storageFormat, CREATE_TABLE_COLUMNS); MaterializedResult.Builder resultBuilder = MaterializedResult.resultBuilder(SESSION, CREATE_TABLE_DATA.getTypes()); for (int i = 0; i < 3; i++) { insertData(tableName, CREATE_TABLE_DATA); try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); // load the new table ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); // verify the metadata ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(session, getTableHandle(metadata, tableName)); assertEquals(filterNonHiddenColumnMetadata(tableMetadata.getColumns()), CREATE_TABLE_COLUMNS); // verify the data resultBuilder.rows(CREATE_TABLE_DATA.getMaterializedRows()); MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.empty()); assertEqualsIgnoreOrder(result.getMaterializedRows(), resultBuilder.build().getMaterializedRows()); // statistics HiveBasicStatistics tableStatistics = getBasicStatisticsForTable(transaction, tableName); assertEquals(tableStatistics.getRowCount().getAsLong(), CREATE_TABLE_DATA.getRowCount() * (i + 1)); assertEquals(tableStatistics.getFileCount().getAsLong(), i + 1L); assertGreaterThan(tableStatistics.getInMemoryDataSizeInBytes().getAsLong(), 0L); assertGreaterThan(tableStatistics.getOnDiskDataSizeInBytes().getAsLong(), 0L); } } // test rollback Set<String> existingFiles; try (Transaction transaction = newTransaction()) { existingFiles = listAllDataFiles(transaction, tableName.getSchemaName(), tableName.getTableName()); assertFalse(existingFiles.isEmpty()); } Path stagingPathRoot; try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); // "stage" insert data ConnectorInsertTableHandle insertTableHandle = metadata.beginInsert(session, tableHandle); ConnectorPageSink sink = pageSinkProvider.createPageSink(transaction.getTransactionHandle(), session, insertTableHandle); sink.appendPage(CREATE_TABLE_DATA.toPage()); sink.appendPage(CREATE_TABLE_DATA.toPage()); Collection<Slice> fragments = getFutureValue(sink.finish()); metadata.finishInsert(session, insertTableHandle, fragments); // statistics, visible from within transaction HiveBasicStatistics tableStatistics = getBasicStatisticsForTable(transaction, tableName); assertEquals(tableStatistics.getRowCount().getAsLong(), CREATE_TABLE_DATA.getRowCount() * 5L); try (Transaction otherTransaction = newTransaction()) { // statistics, not visible from outside transaction HiveBasicStatistics otherTableStatistics = getBasicStatisticsForTable(otherTransaction, tableName); assertEquals(otherTableStatistics.getRowCount().getAsLong(), CREATE_TABLE_DATA.getRowCount() * 3L); } // verify we did not modify the table directory assertEquals(listAllDataFiles(transaction, tableName.getSchemaName(), tableName.getTableName()), existingFiles); // verify all temp files start with the unique prefix stagingPathRoot = getStagingPathRoot(insertTableHandle); HdfsContext context = new HdfsContext(session, tableName.getSchemaName(), tableName.getTableName()); Set<String> tempFiles = listAllDataFiles(context, stagingPathRoot); assertTrue(!tempFiles.isEmpty()); for (String filePath : tempFiles) { assertTrue(new Path(filePath).getName().startsWith(getFilePrefix(insertTableHandle))); } // rollback insert transaction.rollback(); } // verify temp directory is empty HdfsContext context = new HdfsContext(newSession(), tableName.getSchemaName(), tableName.getTableName()); assertTrue(listAllDataFiles(context, stagingPathRoot).isEmpty()); // verify the data is unchanged try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.empty()); assertEqualsIgnoreOrder(result.getMaterializedRows(), resultBuilder.build().getMaterializedRows()); // verify we did not modify the table directory assertEquals(listAllDataFiles(transaction, tableName.getSchemaName(), tableName.getTableName()), existingFiles); } // verify statistics unchanged try (Transaction transaction = newTransaction()) { HiveBasicStatistics statistics = getBasicStatisticsForTable(transaction, tableName); assertEquals(statistics.getRowCount().getAsLong(), CREATE_TABLE_DATA.getRowCount() * 3L); assertEquals(statistics.getFileCount().getAsLong(), 3L); } } // These are protected so extensions to the hive connector can replace the handle classes protected String getFilePrefix(ConnectorOutputTableHandle outputTableHandle) { return ((HiveWritableTableHandle) outputTableHandle).getFilePrefix(); } protected String getFilePrefix(ConnectorInsertTableHandle insertTableHandle) { return ((HiveWritableTableHandle) insertTableHandle).getFilePrefix(); } protected Path getStagingPathRoot(ConnectorInsertTableHandle insertTableHandle) { HiveInsertTableHandle handle = (HiveInsertTableHandle) insertTableHandle; WriteInfo writeInfo = getLocationService(handle.getSchemaName()).getQueryWriteInfo(handle.getLocationHandle()); if (writeInfo.getWriteMode() != STAGE_AND_MOVE_TO_TARGET_DIRECTORY) { throw new AssertionError("writeMode is not STAGE_AND_MOVE_TO_TARGET_DIRECTORY"); } return writeInfo.getWritePath(); } protected Path getStagingPathRoot(ConnectorOutputTableHandle outputTableHandle) { HiveOutputTableHandle handle = (HiveOutputTableHandle) outputTableHandle; return getLocationService(handle.getSchemaName()) .getQueryWriteInfo(handle.getLocationHandle()) .getWritePath(); } protected Path getTargetPathRoot(ConnectorInsertTableHandle insertTableHandle) { HiveInsertTableHandle hiveInsertTableHandle = (HiveInsertTableHandle) insertTableHandle; return getLocationService(hiveInsertTableHandle.getSchemaName()) .getQueryWriteInfo(hiveInsertTableHandle.getLocationHandle()) .getTargetPath(); } protected Set<String> listAllDataFiles(Transaction transaction, String schemaName, String tableName) throws IOException { HdfsContext context = new HdfsContext(newSession(), schemaName, tableName); Set<String> existingFiles = new HashSet<>(); for (String location : listAllDataPaths(transaction.getMetastore(schemaName), schemaName, tableName)) { existingFiles.addAll(listAllDataFiles(context, new Path(location))); } return existingFiles; } public static List<String> listAllDataPaths(SemiTransactionalHiveMetastore metastore, String schemaName, String tableName) { ImmutableList.Builder<String> locations = ImmutableList.builder(); Table table = metastore.getTable(schemaName, tableName).get(); if (table.getStorage().getLocation() != null) { // For partitioned table, there should be nothing directly under this directory. // But including this location in the set makes the directory content assert more // extensive, which is desirable. locations.add(table.getStorage().getLocation()); } Optional<List<String>> partitionNames = metastore.getPartitionNames(schemaName, tableName); if (partitionNames.isPresent()) { metastore.getPartitionsByNames(schemaName, tableName, partitionNames.get()).values().stream() .map(Optional::get) .map(partition -> partition.getStorage().getLocation()) .filter(location -> !location.startsWith(table.getStorage().getLocation())) .forEach(locations::add); } return locations.build(); } protected Set<String> listAllDataFiles(HdfsContext context, Path path) throws IOException { Set<String> result = new HashSet<>(); FileSystem fileSystem = hdfsEnvironment.getFileSystem(context, path); if (fileSystem.exists(path)) { for (FileStatus fileStatus : fileSystem.listStatus(path)) { if (fileStatus.getPath().getName().startsWith(".presto")) { // skip hidden files } else if (fileStatus.isFile()) { result.add(fileStatus.getPath().toString()); } else if (fileStatus.isDirectory()) { result.addAll(listAllDataFiles(context, fileStatus.getPath())); } } } return result; } private void doInsertIntoNewPartition(HiveStorageFormat storageFormat, SchemaTableName tableName) throws Exception { // creating the table doCreateEmptyTable(tableName, storageFormat, CREATE_TABLE_COLUMNS_PARTITIONED); // insert the data String queryId = insertData(tableName, CREATE_TABLE_PARTITIONED_DATA); Set<String> existingFiles; try (Transaction transaction = newTransaction()) { // verify partitions were created List<String> partitionNames = transaction.getMetastore(tableName.getSchemaName()).getPartitionNames(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(() -> new AssertionError("Table does not exist: " + tableName)); assertEqualsIgnoreOrder(partitionNames, CREATE_TABLE_PARTITIONED_DATA.getMaterializedRows().stream() .map(row -> "ds=" + row.getField(CREATE_TABLE_PARTITIONED_DATA.getTypes().size() - 1)) .collect(toList())); // verify the node versions in partitions Map<String, Optional<Partition>> partitions = getMetastoreClient(tableName.getSchemaName()).getPartitionsByNames(tableName.getSchemaName(), tableName.getTableName(), partitionNames); assertEquals(partitions.size(), partitionNames.size()); for (String partitionName : partitionNames) { Partition partition = partitions.get(partitionName).get(); assertEquals(partition.getParameters().get(PRESTO_VERSION_NAME), TEST_SERVER_VERSION); assertEquals(partition.getParameters().get(PRESTO_QUERY_ID_NAME), queryId); } // load the new table ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); // verify the data MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.of(storageFormat)); assertEqualsIgnoreOrder(result.getMaterializedRows(), CREATE_TABLE_PARTITIONED_DATA.getMaterializedRows()); // test rollback existingFiles = listAllDataFiles(transaction, tableName.getSchemaName(), tableName.getTableName()); assertFalse(existingFiles.isEmpty()); // test statistics for (String partitionName : partitionNames) { HiveBasicStatistics partitionStatistics = getBasicStatisticsForPartition(transaction, tableName, partitionName); assertEquals(partitionStatistics.getRowCount().getAsLong(), 1L); assertEquals(partitionStatistics.getFileCount().getAsLong(), 1L); assertGreaterThan(partitionStatistics.getInMemoryDataSizeInBytes().getAsLong(), 0L); assertGreaterThan(partitionStatistics.getOnDiskDataSizeInBytes().getAsLong(), 0L); } } Path stagingPathRoot; try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); // "stage" insert data ConnectorInsertTableHandle insertTableHandle = metadata.beginInsert(session, tableHandle); stagingPathRoot = getStagingPathRoot(insertTableHandle); ConnectorPageSink sink = pageSinkProvider.createPageSink(transaction.getTransactionHandle(), session, insertTableHandle); sink.appendPage(CREATE_TABLE_PARTITIONED_DATA_2ND.toPage()); Collection<Slice> fragments = getFutureValue(sink.finish()); metadata.finishInsert(session, insertTableHandle, fragments); // verify all temp files start with the unique prefix HdfsContext context = new HdfsContext(session, tableName.getSchemaName(), tableName.getTableName()); Set<String> tempFiles = listAllDataFiles(context, getStagingPathRoot(insertTableHandle)); assertTrue(!tempFiles.isEmpty()); for (String filePath : tempFiles) { assertTrue(new Path(filePath).getName().startsWith(getFilePrefix(insertTableHandle))); } // rollback insert transaction.rollback(); } // verify the data is unchanged try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); MaterializedResult result = readTable(transaction, tableHandle, columnHandles, newSession(), TupleDomain.all(), OptionalInt.empty(), Optional.empty()); assertEqualsIgnoreOrder(result.getMaterializedRows(), CREATE_TABLE_PARTITIONED_DATA.getMaterializedRows()); // verify we did not modify the table directory assertEquals(listAllDataFiles(transaction, tableName.getSchemaName(), tableName.getTableName()), existingFiles); // verify temp directory is empty HdfsContext context = new HdfsContext(session, tableName.getSchemaName(), tableName.getTableName()); assertTrue(listAllDataFiles(context, stagingPathRoot).isEmpty()); } } private void doInsertUnsupportedWriteType(HiveStorageFormat storageFormat, SchemaTableName tableName) throws Exception { List<Column> columns = ImmutableList.of(new Column("dummy", HiveType.valueOf("uniontype<smallint,tinyint>"), Optional.empty())); List<Column> partitionColumns = ImmutableList.of(new Column("name", HIVE_STRING, Optional.empty())); createEmptyTable(tableName, storageFormat, columns, partitionColumns); try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); metadata.beginInsert(session, tableHandle); fail("expected failure"); } catch (PrestoException e) { assertThat(e).hasMessageMatching("Inserting into Hive table .* with column type uniontype<smallint,tinyint> not supported"); } } private void doInsertIntoExistingPartition(HiveStorageFormat storageFormat, SchemaTableName tableName) throws Exception { // creating the table doCreateEmptyTable(tableName, storageFormat, CREATE_TABLE_COLUMNS_PARTITIONED); MaterializedResult.Builder resultBuilder = MaterializedResult.resultBuilder(SESSION, CREATE_TABLE_PARTITIONED_DATA.getTypes()); for (int i = 0; i < 3; i++) { // insert the data insertData(tableName, CREATE_TABLE_PARTITIONED_DATA); try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); // verify partitions were created List<String> partitionNames = transaction.getMetastore(tableName.getSchemaName()).getPartitionNames(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(() -> new AssertionError("Table does not exist: " + tableName)); assertEqualsIgnoreOrder(partitionNames, CREATE_TABLE_PARTITIONED_DATA.getMaterializedRows().stream() .map(row -> "ds=" + row.getField(CREATE_TABLE_PARTITIONED_DATA.getTypes().size() - 1)) .collect(toList())); // load the new table List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); // verify the data resultBuilder.rows(CREATE_TABLE_PARTITIONED_DATA.getMaterializedRows()); MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.of(storageFormat)); assertEqualsIgnoreOrder(result.getMaterializedRows(), resultBuilder.build().getMaterializedRows()); // test statistics for (String partitionName : partitionNames) { HiveBasicStatistics statistics = getBasicStatisticsForPartition(transaction, tableName, partitionName); assertEquals(statistics.getRowCount().getAsLong(), i + 1L); assertEquals(statistics.getFileCount().getAsLong(), i + 1L); assertGreaterThan(statistics.getInMemoryDataSizeInBytes().getAsLong(), 0L); assertGreaterThan(statistics.getOnDiskDataSizeInBytes().getAsLong(), 0L); } } } // test rollback Set<String> existingFiles; Path stagingPathRoot; try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); existingFiles = listAllDataFiles(transaction, tableName.getSchemaName(), tableName.getTableName()); assertFalse(existingFiles.isEmpty()); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); // "stage" insert data ConnectorInsertTableHandle insertTableHandle = metadata.beginInsert(session, tableHandle); stagingPathRoot = getStagingPathRoot(insertTableHandle); ConnectorPageSink sink = pageSinkProvider.createPageSink(transaction.getTransactionHandle(), session, insertTableHandle); sink.appendPage(CREATE_TABLE_PARTITIONED_DATA.toPage()); sink.appendPage(CREATE_TABLE_PARTITIONED_DATA.toPage()); Collection<Slice> fragments = getFutureValue(sink.finish()); metadata.finishInsert(session, insertTableHandle, fragments); // verify all temp files start with the unique prefix HdfsContext context = new HdfsContext(session, tableName.getSchemaName(), tableName.getTableName()); Set<String> tempFiles = listAllDataFiles(context, getStagingPathRoot(insertTableHandle)); assertTrue(!tempFiles.isEmpty()); for (String filePath : tempFiles) { assertTrue(new Path(filePath).getName().startsWith(getFilePrefix(insertTableHandle))); } // verify statistics are visible from within of the current transaction List<String> partitionNames = transaction.getMetastore(tableName.getSchemaName()).getPartitionNames(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(() -> new AssertionError("Table does not exist: " + tableName)); for (String partitionName : partitionNames) { HiveBasicStatistics partitionStatistics = getBasicStatisticsForPartition(transaction, tableName, partitionName); assertEquals(partitionStatistics.getRowCount().getAsLong(), 5L); } // rollback insert transaction.rollback(); } try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); // verify the data is unchanged MaterializedResult result = readTable(transaction, tableHandle, columnHandles, newSession(), TupleDomain.all(), OptionalInt.empty(), Optional.empty()); assertEqualsIgnoreOrder(result.getMaterializedRows(), resultBuilder.build().getMaterializedRows()); // verify we did not modify the table directory assertEquals(listAllDataFiles(transaction, tableName.getSchemaName(), tableName.getTableName()), existingFiles); // verify temp directory is empty HdfsContext context = new HdfsContext(session, tableName.getSchemaName(), tableName.getTableName()); assertTrue(listAllDataFiles(context, stagingPathRoot).isEmpty()); // verify statistics have been rolled back List<String> partitionNames = transaction.getMetastore(tableName.getSchemaName()).getPartitionNames(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(() -> new AssertionError("Table does not exist: " + tableName)); for (String partitionName : partitionNames) { HiveBasicStatistics partitionStatistics = getBasicStatisticsForPartition(transaction, tableName, partitionName); assertEquals(partitionStatistics.getRowCount().getAsLong(), 3L); } } } private void doInsertIntoExistingPartitionEmptyStatistics(HiveStorageFormat storageFormat, SchemaTableName tableName) throws Exception { doCreateEmptyTable(tableName, storageFormat, CREATE_TABLE_COLUMNS_PARTITIONED); insertData(tableName, CREATE_TABLE_PARTITIONED_DATA); eraseStatistics(tableName); insertData(tableName, CREATE_TABLE_PARTITIONED_DATA); try (Transaction transaction = newTransaction()) { List<String> partitionNames = transaction.getMetastore(tableName.getSchemaName()).getPartitionNames(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(() -> new AssertionError("Table does not exist: " + tableName)); for (String partitionName : partitionNames) { HiveBasicStatistics statistics = getBasicStatisticsForPartition(transaction, tableName, partitionName); assertThat(statistics.getRowCount()).isNotPresent(); assertThat(statistics.getInMemoryDataSizeInBytes()).isNotPresent(); // fileCount and rawSize statistics are computed on the fly by the metastore, thus cannot be erased } } } private static HiveBasicStatistics getBasicStatisticsForTable(Transaction transaction, SchemaTableName table) { return transaction .getMetastore(table.getSchemaName()) .getTableStatistics(table.getSchemaName(), table.getTableName()) .getBasicStatistics(); } private static HiveBasicStatistics getBasicStatisticsForPartition(Transaction transaction, SchemaTableName table, String partitionName) { return transaction .getMetastore(table.getSchemaName()) .getPartitionStatistics(table.getSchemaName(), table.getTableName(), ImmutableSet.of(partitionName)) .get(partitionName) .getBasicStatistics(); } private void eraseStatistics(SchemaTableName schemaTableName) { ExtendedHiveMetastore metastoreClient = getMetastoreClient(schemaTableName.getSchemaName()); metastoreClient.updateTableStatistics(schemaTableName.getSchemaName(), schemaTableName.getTableName(), statistics -> new PartitionStatistics(createEmptyStatistics(), ImmutableMap.of())); Table table = metastoreClient.getTable(schemaTableName.getSchemaName(), schemaTableName.getTableName()) .orElseThrow(() -> new TableNotFoundException(schemaTableName)); List<String> partitionColumns = table.getPartitionColumns().stream() .map(Column::getName) .collect(toImmutableList()); if (!table.getPartitionColumns().isEmpty()) { List<String> partitionNames = metastoreClient.getPartitionNames(schemaTableName.getSchemaName(), schemaTableName.getTableName()) .orElse(ImmutableList.of()); List<Partition> partitions = metastoreClient .getPartitionsByNames(schemaTableName.getSchemaName(), schemaTableName.getTableName(), partitionNames) .entrySet() .stream() .map(Map.Entry::getValue) .filter(Optional::isPresent) .map(Optional::get) .collect(toImmutableList()); for (Partition partition : partitions) { metastoreClient.updatePartitionStatistics( schemaTableName.getSchemaName(), schemaTableName.getTableName(), makePartName(partitionColumns, partition.getValues()), statistics -> new PartitionStatistics(createEmptyStatistics(), ImmutableMap.of())); } } } /** * @return query id */ private String insertData(SchemaTableName tableName, MaterializedResult data) throws Exception { Path writePath; Path targetPath; String queryId; try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); ConnectorInsertTableHandle insertTableHandle = metadata.beginInsert(session, tableHandle); queryId = session.getQueryId(); writePath = getStagingPathRoot(insertTableHandle); targetPath = getTargetPathRoot(insertTableHandle); ConnectorPageSink sink = pageSinkProvider.createPageSink(transaction.getTransactionHandle(), session, insertTableHandle); // write data sink.appendPage(data.toPage()); Collection<Slice> fragments = getFutureValue(sink.finish()); // commit the insert metadata.finishInsert(session, insertTableHandle, fragments); transaction.commit(); } // check that temporary files are removed if (!writePath.equals(targetPath)) { HdfsContext context = new HdfsContext(newSession(), tableName.getSchemaName(), tableName.getTableName()); FileSystem fileSystem = hdfsEnvironment.getFileSystem(context, writePath); assertFalse(fileSystem.exists(writePath)); } return queryId; } private void doTestMetadataDelete(HiveStorageFormat storageFormat, SchemaTableName tableName) throws Exception { // creating the table doCreateEmptyTable(tableName, storageFormat, CREATE_TABLE_COLUMNS_PARTITIONED); insertData(tableName, CREATE_TABLE_PARTITIONED_DATA); MaterializedResult.Builder expectedResultBuilder = MaterializedResult.resultBuilder(SESSION, CREATE_TABLE_PARTITIONED_DATA.getTypes()); expectedResultBuilder.rows(CREATE_TABLE_PARTITIONED_DATA.getMaterializedRows()); try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); // verify partitions were created List<String> partitionNames = transaction.getMetastore(tableName.getSchemaName()).getPartitionNames(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(() -> new AssertionError("Table does not exist: " + tableName)); assertEqualsIgnoreOrder(partitionNames, CREATE_TABLE_PARTITIONED_DATA.getMaterializedRows().stream() .map(row -> "ds=" + row.getField(CREATE_TABLE_PARTITIONED_DATA.getTypes().size() - 1)) .collect(toList())); // verify table directory is not empty Set<String> filesAfterInsert = listAllDataFiles(transaction, tableName.getSchemaName(), tableName.getTableName()); assertFalse(filesAfterInsert.isEmpty()); // verify the data ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.of(storageFormat)); assertEqualsIgnoreOrder(result.getMaterializedRows(), expectedResultBuilder.build().getMaterializedRows()); } try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); // get ds column handle ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); HiveColumnHandle dsColumnHandle = (HiveColumnHandle) metadata.getColumnHandles(session, tableHandle).get("ds"); // delete ds=2015-07-03 session = newSession(); TupleDomain<ColumnHandle> tupleDomain = TupleDomain.fromFixedValues(ImmutableMap.of(dsColumnHandle, NullableValue.of(createUnboundedVarcharType(), utf8Slice("2015-07-03")))); Constraint<ColumnHandle> constraint = new Constraint<>(tupleDomain, convertToPredicate(tupleDomain)); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(session, tableHandle, constraint, Optional.empty()); ConnectorTableLayoutHandle tableLayoutHandle = getOnlyElement(tableLayoutResults).getTableLayout().getHandle(); metadata.metadataDelete(session, tableHandle, tableLayoutHandle); transaction.commit(); } try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); HiveColumnHandle dsColumnHandle = (HiveColumnHandle) metadata.getColumnHandles(session, tableHandle).get("ds"); int dsColumnOrdinalPosition = columnHandles.indexOf(dsColumnHandle); // verify the data session = newSession(); ImmutableList<MaterializedRow> expectedRows = expectedResultBuilder.build().getMaterializedRows().stream() .filter(row -> !"2015-07-03".equals(row.getField(dsColumnOrdinalPosition))) .collect(toImmutableList()); MaterializedResult actualAfterDelete = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.of(storageFormat)); assertEqualsIgnoreOrder(actualAfterDelete.getMaterializedRows(), expectedRows); } try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); HiveColumnHandle dsColumnHandle = (HiveColumnHandle) metadata.getColumnHandles(session, tableHandle).get("ds"); // delete ds=2015-07-01 and 2015-07-02 session = newSession(); TupleDomain<ColumnHandle> tupleDomain2 = TupleDomain.withColumnDomains( ImmutableMap.of(dsColumnHandle, Domain.create(ValueSet.ofRanges(Range.range(createUnboundedVarcharType(), utf8Slice("2015-07-01"), true, utf8Slice("2015-07-02"), true)), false))); Constraint<ColumnHandle> constraint2 = new Constraint<>(tupleDomain2, convertToPredicate(tupleDomain2)); List<ConnectorTableLayoutResult> tableLayoutResults2 = metadata.getTableLayouts(session, tableHandle, constraint2, Optional.empty()); ConnectorTableLayoutHandle tableLayoutHandle2 = getOnlyElement(tableLayoutResults2).getTableLayout().getHandle(); metadata.metadataDelete(session, tableHandle, tableLayoutHandle2); transaction.commit(); } try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = ImmutableList.copyOf(metadata.getColumnHandles(session, tableHandle).values()); // verify the data session = newSession(); MaterializedResult actualAfterDelete2 = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.of(storageFormat)); assertEqualsIgnoreOrder(actualAfterDelete2.getMaterializedRows(), ImmutableList.of()); // verify table directory is empty Set<String> filesAfterDelete = listAllDataFiles(transaction, tableName.getSchemaName(), tableName.getTableName()); assertTrue(filesAfterDelete.isEmpty()); } } protected void assertGetRecordsOptional(String tableName, HiveStorageFormat hiveStorageFormat) throws Exception { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); if (metadata.getTableHandle(newSession(), new SchemaTableName(database, tableName)) != null) { assertGetRecords(tableName, hiveStorageFormat); } } } protected void assertGetRecords(String tableName, HiveStorageFormat hiveStorageFormat) throws Exception { try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, new SchemaTableName(database, tableName)); ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(session, tableHandle); HiveSplit hiveSplit = getHiveSplit(tableHandle); List<ColumnHandle> columnHandles = ImmutableList.copyOf(metadata.getColumnHandles(session, tableHandle).values()); ConnectorPageSource pageSource = pageSourceProvider.createPageSource(transaction.getTransactionHandle(), session, hiveSplit, columnHandles); assertGetRecords(hiveStorageFormat, tableMetadata, hiveSplit, pageSource, columnHandles); } } protected HiveSplit getHiveSplit(ConnectorTableHandle tableHandle) { List<ConnectorSplit> splits = getAllSplits(tableHandle, TupleDomain.all()); assertEquals(splits.size(), 1); return (HiveSplit) getOnlyElement(splits); } protected void assertGetRecords( HiveStorageFormat hiveStorageFormat, ConnectorTableMetadata tableMetadata, HiveSplit hiveSplit, ConnectorPageSource pageSource, List<? extends ColumnHandle> columnHandles) throws IOException { try { MaterializedResult result = materializeSourceDataStream(newSession(), pageSource, getTypes(columnHandles)); assertPageSourceType(pageSource, hiveStorageFormat); ImmutableMap<String, Integer> columnIndex = indexColumns(tableMetadata); long rowNumber = 0; long completedBytes = 0; for (MaterializedRow row : result) { try { assertValueTypes(row, tableMetadata.getColumns()); } catch (RuntimeException e) { throw new RuntimeException("row " + rowNumber, e); } rowNumber++; Integer index; Object value; // STRING index = columnIndex.get("t_string"); value = row.getField(index); if (rowNumber % 19 == 0) { assertNull(value); } else if (rowNumber % 19 == 1) { assertEquals(value, ""); } else { assertEquals(value, "test"); } // NUMBERS assertEquals(row.getField(columnIndex.get("t_tinyint")), (byte) (1 + rowNumber)); assertEquals(row.getField(columnIndex.get("t_smallint")), (short) (2 + rowNumber)); assertEquals(row.getField(columnIndex.get("t_int")), (int) (3 + rowNumber)); index = columnIndex.get("t_bigint"); if ((rowNumber % 13) == 0) { assertNull(row.getField(index)); } else { assertEquals(row.getField(index), 4 + rowNumber); } assertEquals((Float) row.getField(columnIndex.get("t_float")), 5.1f + rowNumber, 0.001); assertEquals(row.getField(columnIndex.get("t_double")), 6.2 + rowNumber); // BOOLEAN index = columnIndex.get("t_boolean"); if ((rowNumber % 3) == 2) { assertNull(row.getField(index)); } else { assertEquals(row.getField(index), (rowNumber % 3) != 0); } // TIMESTAMP index = columnIndex.get("t_timestamp"); if (index != null) { if ((rowNumber % 17) == 0) { assertNull(row.getField(index)); } else { SqlTimestamp expected = sqlTimestampOf(2011, 5, 6, 7, 8, 9, 123, timeZone, UTC_KEY, SESSION); assertEquals(row.getField(index), expected); } } // BINARY index = columnIndex.get("t_binary"); if (index != null) { if ((rowNumber % 23) == 0) { assertNull(row.getField(index)); } else { assertEquals(row.getField(index), new SqlVarbinary("test binary".getBytes(UTF_8))); } } // DATE index = columnIndex.get("t_date"); if (index != null) { if ((rowNumber % 37) == 0) { assertNull(row.getField(index)); } else { SqlDate expected = new SqlDate(toIntExact(MILLISECONDS.toDays(new DateTime(2013, 8, 9, 0, 0, 0, UTC).getMillis()))); assertEquals(row.getField(index), expected); } } // VARCHAR(50) index = columnIndex.get("t_varchar"); if (index != null) { value = row.getField(index); if (rowNumber % 39 == 0) { assertNull(value); } else if (rowNumber % 39 == 1) { // https://issues.apache.org/jira/browse/HIVE-13289 // RCBINARY reads empty VARCHAR as null if (hiveStorageFormat == RCBINARY) { assertNull(value); } else { assertEquals(value, ""); } } else { assertEquals(value, "test varchar"); } } //CHAR(25) index = columnIndex.get("t_char"); if (index != null) { value = row.getField(index); if ((rowNumber % 41) == 0) { assertNull(value); } else { assertEquals(value, (rowNumber % 41) == 1 ? " " : "test char "); } } // MAP<STRING, STRING> index = columnIndex.get("t_map"); if (index != null) { if ((rowNumber % 27) == 0) { assertNull(row.getField(index)); } else { assertEquals(row.getField(index), ImmutableMap.of("test key", "test value")); } } // ARRAY<STRING> index = columnIndex.get("t_array_string"); if (index != null) { if ((rowNumber % 29) == 0) { assertNull(row.getField(index)); } else { assertEquals(row.getField(index), ImmutableList.of("abc", "xyz", "data")); } } // ARRAY<STRUCT<s_string: STRING, s_double:DOUBLE>> index = columnIndex.get("t_array_struct"); if (index != null) { if ((rowNumber % 31) == 0) { assertNull(row.getField(index)); } else { List<Object> expected1 = ImmutableList.of("test abc", 0.1); List<Object> expected2 = ImmutableList.of("test xyz", 0.2); assertEquals(row.getField(index), ImmutableList.of(expected1, expected2)); } } // STRUCT<s_string: STRING, s_double:DOUBLE> index = columnIndex.get("t_struct"); if (index != null) { if ((rowNumber % 31) == 0) { assertNull(row.getField(index)); } else { assertTrue(row.getField(index) instanceof List); List values = (List) row.getField(index); assertEquals(values.size(), 2); assertEquals(values.get(0), "test abc"); assertEquals(values.get(1), 0.1); } } // MAP<INT, ARRAY<STRUCT<s_string: STRING, s_double:DOUBLE>>> index = columnIndex.get("t_complex"); if (index != null) { if ((rowNumber % 33) == 0) { assertNull(row.getField(index)); } else { List<Object> expected1 = ImmutableList.of("test abc", 0.1); List<Object> expected2 = ImmutableList.of("test xyz", 0.2); assertEquals(row.getField(index), ImmutableMap.of(1, ImmutableList.of(expected1, expected2))); } } // NEW COLUMN assertNull(row.getField(columnIndex.get("new_column"))); long newCompletedBytes = pageSource.getCompletedBytes(); assertTrue(newCompletedBytes >= completedBytes); assertTrue(newCompletedBytes <= hiveSplit.getLength()); completedBytes = newCompletedBytes; } assertTrue(completedBytes <= hiveSplit.getLength()); assertEquals(rowNumber, 100); } finally { pageSource.close(); } } protected void dropTable(SchemaTableName table) { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle handle = metadata.getTableHandle(session, table); if (handle == null) { return; } metadata.dropTable(session, handle); try { // todo I have no idea why this is needed... maybe there is a propagation delay in the metastore? metadata.dropTable(session, handle); fail("expected NotFoundException"); } catch (TableNotFoundException expected) { } transaction.commit(); } catch (Exception e) { Logger.get(getClass()).warn(e, "failed to drop table"); } } protected ConnectorTableHandle getTableHandle(ConnectorMetadata metadata, SchemaTableName tableName) { ConnectorTableHandle handle = metadata.getTableHandle(newSession(), tableName); checkArgument(handle != null, "table not found: %s", tableName); return handle; } private MaterializedResult readTable( Transaction transaction, ConnectorTableHandle tableHandle, List<ColumnHandle> columnHandles, ConnectorSession session, TupleDomain<ColumnHandle> tupleDomain, OptionalInt expectedSplitCount, Optional<HiveStorageFormat> expectedStorageFormat) throws Exception { List<ConnectorTableLayoutResult> tableLayoutResults = transaction.getMetadata().getTableLayouts( session, tableHandle, new Constraint<>(tupleDomain), Optional.empty()); ConnectorTableLayoutHandle layoutHandle = getOnlyElement(tableLayoutResults).getTableLayout().getHandle(); List<ConnectorSplit> splits = getAllSplits(splitManager.getSplits(transaction.getTransactionHandle(), session, layoutHandle, UNGROUPED_SCHEDULING)); if (expectedSplitCount.isPresent()) { assertEquals(splits.size(), expectedSplitCount.getAsInt()); } ImmutableList.Builder<MaterializedRow> allRows = ImmutableList.builder(); for (ConnectorSplit split : splits) { try (ConnectorPageSource pageSource = pageSourceProvider.createPageSource(transaction.getTransactionHandle(), session, split, columnHandles)) { expectedStorageFormat.ifPresent(format -> assertPageSourceType(pageSource, format)); MaterializedResult result = materializeSourceDataStream(session, pageSource, getTypes(columnHandles)); allRows.addAll(result.getMaterializedRows()); } } return new MaterializedResult(allRows.build(), getTypes(columnHandles)); } public ExtendedHiveMetastore getMetastoreClient(String namespace) { return metastoreClient; } public LocationService getLocationService(String namespace) { return locationService; } protected static int getSplitCount(ConnectorSplitSource splitSource) { int splitCount = 0; while (!splitSource.isFinished()) { splitCount += getFutureValue(splitSource.getNextBatch(NOT_PARTITIONED, 1000)).getSplits().size(); } return splitCount; } private List<ConnectorSplit> getAllSplits(ConnectorTableHandle tableHandle, TupleDomain<ColumnHandle> tupleDomain) { try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(session, tableHandle, new Constraint<>(tupleDomain), Optional.empty()); ConnectorTableLayoutHandle layoutHandle = getOnlyElement(tableLayoutResults).getTableLayout().getHandle(); return getAllSplits(splitManager.getSplits(transaction.getTransactionHandle(), session, layoutHandle, UNGROUPED_SCHEDULING)); } } protected static List<ConnectorSplit> getAllSplits(ConnectorSplitSource splitSource) { ImmutableList.Builder<ConnectorSplit> splits = ImmutableList.builder(); while (!splitSource.isFinished()) { splits.addAll(getFutureValue(splitSource.getNextBatch(NOT_PARTITIONED, 1000)).getSplits()); } return splits.build(); } protected List<?> getAllPartitions(ConnectorTableLayoutHandle layoutHandle) { return ((HiveTableLayoutHandle) layoutHandle).getPartitions() .orElseThrow(() -> new AssertionError("layout has no partitions")); } protected String getPartitionId(Object partition) { return ((HivePartition) partition).getPartitionId(); } protected static void assertPageSourceType(ConnectorPageSource pageSource, HiveStorageFormat hiveStorageFormat) { if (pageSource instanceof RecordPageSource) { RecordCursor hiveRecordCursor = ((RecordPageSource) pageSource).getCursor(); hiveRecordCursor = ((HiveRecordCursor) hiveRecordCursor).getRegularColumnRecordCursor(); if (hiveRecordCursor instanceof HiveCoercionRecordCursor) { hiveRecordCursor = ((HiveCoercionRecordCursor) hiveRecordCursor).getRegularColumnRecordCursor(); } assertInstanceOf(hiveRecordCursor, recordCursorType(hiveStorageFormat), hiveStorageFormat.name()); } else { assertInstanceOf(((HivePageSource) pageSource).getPageSource(), pageSourceType(hiveStorageFormat), hiveStorageFormat.name()); } } private static Class<? extends RecordCursor> recordCursorType(HiveStorageFormat hiveStorageFormat) { switch (hiveStorageFormat) { case PARQUET: return ParquetHiveRecordCursor.class; } return GenericHiveRecordCursor.class; } private static Class<? extends ConnectorPageSource> pageSourceType(HiveStorageFormat hiveStorageFormat) { switch (hiveStorageFormat) { case RCTEXT: case RCBINARY: return RcFilePageSource.class; case ORC: case DWRF: return OrcPageSource.class; case PARQUET: return ParquetPageSource.class; default: throw new AssertionError("File type does not use a PageSource: " + hiveStorageFormat); } } private static void assertValueTypes(MaterializedRow row, List<ColumnMetadata> schema) { for (int columnIndex = 0; columnIndex < schema.size(); columnIndex++) { ColumnMetadata column = schema.get(columnIndex); Object value = row.getField(columnIndex); if (value != null) { if (BOOLEAN.equals(column.getType())) { assertInstanceOf(value, Boolean.class); } else if (TINYINT.equals(column.getType())) { assertInstanceOf(value, Byte.class); } else if (SMALLINT.equals(column.getType())) { assertInstanceOf(value, Short.class); } else if (INTEGER.equals(column.getType())) { assertInstanceOf(value, Integer.class); } else if (BIGINT.equals(column.getType())) { assertInstanceOf(value, Long.class); } else if (DOUBLE.equals(column.getType())) { assertInstanceOf(value, Double.class); } else if (REAL.equals(column.getType())) { assertInstanceOf(value, Float.class); } else if (isVarcharType(column.getType())) { assertInstanceOf(value, String.class); } else if (isCharType(column.getType())) { assertInstanceOf(value, String.class); } else if (VARBINARY.equals(column.getType())) { assertInstanceOf(value, SqlVarbinary.class); } else if (TIMESTAMP.equals(column.getType())) { assertInstanceOf(value, SqlTimestamp.class); } else if (DATE.equals(column.getType())) { assertInstanceOf(value, SqlDate.class); } else if (column.getType() instanceof ArrayType || column.getType() instanceof RowType) { assertInstanceOf(value, List.class); } else if (column.getType() instanceof MapType) { assertInstanceOf(value, Map.class); } else { fail("Unknown primitive type " + columnIndex); } } } } private static void assertPrimitiveField(Map<String, ColumnMetadata> map, String name, Type type, boolean partitionKey) { assertTrue(map.containsKey(name)); ColumnMetadata column = map.get(name); assertEquals(column.getType(), type, name); assertEquals(column.getExtraInfo(), columnExtraInfo(partitionKey)); } protected static ImmutableMap<String, Integer> indexColumns(List<ColumnHandle> columnHandles) { ImmutableMap.Builder<String, Integer> index = ImmutableMap.builder(); int i = 0; for (ColumnHandle columnHandle : columnHandles) { HiveColumnHandle hiveColumnHandle = (HiveColumnHandle) columnHandle; index.put(hiveColumnHandle.getName(), i); i++; } return index.build(); } protected static ImmutableMap<String, Integer> indexColumns(ConnectorTableMetadata tableMetadata) { ImmutableMap.Builder<String, Integer> index = ImmutableMap.builder(); int i = 0; for (ColumnMetadata columnMetadata : tableMetadata.getColumns()) { index.put(columnMetadata.getName(), i); i++; } return index.build(); } protected SchemaTableName temporaryTable(String tableName) { return temporaryTable(database, tableName); } protected static SchemaTableName temporaryTable(String database, String tableName) { String randomName = UUID.randomUUID().toString().toLowerCase(ENGLISH).replace("-", ""); return new SchemaTableName(database, TEMPORARY_TABLE_PREFIX + tableName + "_" + randomName); } protected static Map<String, Object> createTableProperties(HiveStorageFormat storageFormat) { return createTableProperties(storageFormat, ImmutableList.of()); } private static Map<String, Object> createTableProperties(HiveStorageFormat storageFormat, Iterable<String> parititonedBy) { return ImmutableMap.<String, Object>builder() .put(STORAGE_FORMAT_PROPERTY, storageFormat) .put(PARTITIONED_BY_PROPERTY, ImmutableList.copyOf(parititonedBy)) .put(BUCKETED_BY_PROPERTY, ImmutableList.of()) .put(BUCKET_COUNT_PROPERTY, 0) .put(SORTED_BY_PROPERTY, ImmutableList.of()) .build(); } protected static List<ColumnHandle> filterNonHiddenColumnHandles(Collection<ColumnHandle> columnHandles) { return columnHandles.stream() .filter(columnHandle -> !((HiveColumnHandle) columnHandle).isHidden()) .collect(toList()); } protected static List<ColumnMetadata> filterNonHiddenColumnMetadata(Collection<ColumnMetadata> columnMetadatas) { return columnMetadatas.stream() .filter(columnMetadata -> !columnMetadata.isHidden()) .collect(toList()); } private void createEmptyTable(SchemaTableName schemaTableName, HiveStorageFormat hiveStorageFormat, List<Column> columns, List<Column> partitionColumns) throws Exception { createEmptyTable(schemaTableName, hiveStorageFormat, columns, partitionColumns, Optional.empty()); } private void createEmptyTable(SchemaTableName schemaTableName, HiveStorageFormat hiveStorageFormat, List<Column> columns, List<Column> partitionColumns, Optional<HiveBucketProperty> bucketProperty) throws Exception { Path targetPath; try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); String tableOwner = session.getUser(); String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); LocationService locationService = getLocationService(schemaName); LocationHandle locationHandle = locationService.forNewTable(transaction.getMetastore(schemaName), session, schemaName, tableName); targetPath = locationService.getQueryWriteInfo(locationHandle).getTargetPath(); Table.Builder tableBuilder = Table.builder() .setDatabaseName(schemaName) .setTableName(tableName) .setOwner(tableOwner) .setTableType(TableType.MANAGED_TABLE.name()) .setParameters(ImmutableMap.of( PRESTO_VERSION_NAME, TEST_SERVER_VERSION, PRESTO_QUERY_ID_NAME, session.getQueryId())) .setDataColumns(columns) .setPartitionColumns(partitionColumns); tableBuilder.getStorageBuilder() .setLocation(targetPath.toString()) .setStorageFormat(StorageFormat.create(hiveStorageFormat.getSerDe(), hiveStorageFormat.getInputFormat(), hiveStorageFormat.getOutputFormat())) .setBucketProperty(bucketProperty) .setSerdeParameters(ImmutableMap.of()); PrincipalPrivileges principalPrivileges = testingPrincipalPrivilege(tableOwner); transaction.getMetastore(schemaName).createTable(session, tableBuilder.build(), principalPrivileges, Optional.empty(), true, EMPTY_TABLE_STATISTICS); transaction.commit(); } HdfsContext context = new HdfsContext(newSession(), schemaTableName.getSchemaName(), schemaTableName.getTableName()); List<String> targetDirectoryList = listDirectory(context, targetPath); assertEquals(targetDirectoryList, ImmutableList.of()); } private void alterBucketProperty(SchemaTableName schemaTableName, Optional<HiveBucketProperty> bucketProperty) { try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); String tableOwner = session.getUser(); String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); Optional<Table> table = transaction.getMetastore(schemaName).getTable(schemaName, tableName); Table.Builder tableBuilder = Table.builder(table.get()); tableBuilder.getStorageBuilder().setBucketProperty(bucketProperty); PrincipalPrivileges principalPrivileges = testingPrincipalPrivilege(tableOwner); // hack: replaceView can be used as replaceTable despite its name transaction.getMetastore(schemaName).replaceView(schemaName, tableName, tableBuilder.build(), principalPrivileges); transaction.commit(); } } private PrincipalPrivileges testingPrincipalPrivilege(String tableOwner) { return new PrincipalPrivileges( ImmutableMultimap.<String, HivePrivilegeInfo>builder() .put(tableOwner, new HivePrivilegeInfo(HivePrivilege.SELECT, true)) .put(tableOwner, new HivePrivilegeInfo(HivePrivilege.INSERT, true)) .put(tableOwner, new HivePrivilegeInfo(HivePrivilege.UPDATE, true)) .put(tableOwner, new HivePrivilegeInfo(HivePrivilege.DELETE, true)) .build(), ImmutableMultimap.of()); } private List<String> listDirectory(HdfsContext context, Path path) throws IOException { FileSystem fileSystem = hdfsEnvironment.getFileSystem(context, path); return Arrays.stream(fileSystem.listStatus(path)) .map(FileStatus::getPath) .map(Path::getName) .filter(name -> !name.startsWith(".presto")) .collect(toList()); } @Test public void testTransactionDeleteInsert() throws Exception { doTestTransactionDeleteInsert( RCBINARY, true, ImmutableList.<TransactionDeleteInsertTestCase>builder() .add(new TransactionDeleteInsertTestCase(false, false, ROLLBACK_RIGHT_AWAY, Optional.empty())) .add(new TransactionDeleteInsertTestCase(false, false, ROLLBACK_AFTER_DELETE, Optional.empty())) .add(new TransactionDeleteInsertTestCase(false, false, ROLLBACK_AFTER_BEGIN_INSERT, Optional.empty())) .add(new TransactionDeleteInsertTestCase(false, false, ROLLBACK_AFTER_APPEND_PAGE, Optional.empty())) .add(new TransactionDeleteInsertTestCase(false, false, ROLLBACK_AFTER_SINK_FINISH, Optional.empty())) .add(new TransactionDeleteInsertTestCase(false, false, ROLLBACK_AFTER_FINISH_INSERT, Optional.empty())) .add(new TransactionDeleteInsertTestCase(false, false, COMMIT, Optional.of(new AddPartitionFailure()))) .add(new TransactionDeleteInsertTestCase(false, false, COMMIT, Optional.of(new DirectoryRenameFailure()))) .add(new TransactionDeleteInsertTestCase(false, false, COMMIT, Optional.of(new FileRenameFailure()))) .add(new TransactionDeleteInsertTestCase(true, false, COMMIT, Optional.of(new DropPartitionFailure()))) .add(new TransactionDeleteInsertTestCase(true, true, COMMIT, Optional.empty())) .build()); } protected void doTestTransactionDeleteInsert(HiveStorageFormat storageFormat, boolean allowInsertExisting, List<TransactionDeleteInsertTestCase> testCases) throws Exception { // There are 4 types of operations on a partition: add, drop, alter (drop then add), insert existing. // There are 12 partitions in this test, 3 for each type. // 3 is chosen to verify that cleanups, commit aborts, rollbacks are always as complete as possible regardless of failure. MaterializedResult beforeData = MaterializedResult.resultBuilder(SESSION, BIGINT, createUnboundedVarcharType(), createUnboundedVarcharType()) .row(110L, "a", "alter1") .row(120L, "a", "insert1") .row(140L, "a", "drop1") .row(210L, "b", "drop2") .row(310L, "c", "alter2") .row(320L, "c", "alter3") .row(510L, "e", "drop3") .row(610L, "f", "insert2") .row(620L, "f", "insert3") .build(); Domain domainToDrop = Domain.create(ValueSet.of( createUnboundedVarcharType(), utf8Slice("alter1"), utf8Slice("alter2"), utf8Slice("alter3"), utf8Slice("drop1"), utf8Slice("drop2"), utf8Slice("drop3")), false); List<MaterializedRow> extraRowsForInsertExisting = ImmutableList.of(); if (allowInsertExisting) { extraRowsForInsertExisting = MaterializedResult.resultBuilder(SESSION, BIGINT, createUnboundedVarcharType(), createUnboundedVarcharType()) .row(121L, "a", "insert1") .row(611L, "f", "insert2") .row(621L, "f", "insert3") .build() .getMaterializedRows(); } MaterializedResult insertData = MaterializedResult.resultBuilder(SESSION, BIGINT, createUnboundedVarcharType(), createUnboundedVarcharType()) .row(111L, "a", "alter1") .row(131L, "a", "add1") .row(221L, "b", "add2") .row(311L, "c", "alter2") .row(321L, "c", "alter3") .row(411L, "d", "add3") .rows(extraRowsForInsertExisting) .build(); MaterializedResult afterData = MaterializedResult.resultBuilder(SESSION, BIGINT, createUnboundedVarcharType(), createUnboundedVarcharType()) .row(120L, "a", "insert1") .row(610L, "f", "insert2") .row(620L, "f", "insert3") .rows(insertData.getMaterializedRows()) .build(); for (TransactionDeleteInsertTestCase testCase : testCases) { SchemaTableName temporaryDeleteInsert = temporaryTable("delete_insert"); try { createEmptyTable( temporaryDeleteInsert, storageFormat, ImmutableList.of(new Column("col1", HIVE_LONG, Optional.empty())), ImmutableList.of(new Column("pk1", HIVE_STRING, Optional.empty()), new Column("pk2", HIVE_STRING, Optional.empty()))); insertData(temporaryDeleteInsert, beforeData); try { doTestTransactionDeleteInsert( storageFormat, temporaryDeleteInsert, domainToDrop, insertData, testCase.isExpectCommitedData() ? afterData : beforeData, testCase.getTag(), testCase.isExpectQuerySucceed(), testCase.getConflictTrigger()); } catch (AssertionError e) { throw new AssertionError(format("Test case: %s", testCase.toString()), e); } } finally { dropTable(temporaryDeleteInsert); } } } private void doTestTransactionDeleteInsert( HiveStorageFormat storageFormat, SchemaTableName tableName, Domain domainToDrop, MaterializedResult insertData, MaterializedResult expectedData, TransactionDeleteInsertTestTag tag, boolean expectQuerySucceed, Optional<ConflictTrigger> conflictTrigger) throws Exception { Path writePath = null; Path targetPath = null; try (Transaction transaction = newTransaction()) { try { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); ConnectorSession session; rollbackIfEquals(tag, ROLLBACK_RIGHT_AWAY); // Query 1: delete session = newSession(); HiveColumnHandle dsColumnHandle = (HiveColumnHandle) metadata.getColumnHandles(session, tableHandle).get("pk2"); TupleDomain<ColumnHandle> tupleDomain = TupleDomain.withColumnDomains(ImmutableMap.of( dsColumnHandle, domainToDrop)); Constraint<ColumnHandle> constraint = new Constraint<>(tupleDomain, convertToPredicate(tupleDomain)); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(session, tableHandle, constraint, Optional.empty()); ConnectorTableLayoutHandle tableLayoutHandle = getOnlyElement(tableLayoutResults).getTableLayout().getHandle(); metadata.metadataDelete(session, tableHandle, tableLayoutHandle); rollbackIfEquals(tag, ROLLBACK_AFTER_DELETE); // Query 2: insert session = newSession(); ConnectorInsertTableHandle insertTableHandle = metadata.beginInsert(session, tableHandle); rollbackIfEquals(tag, ROLLBACK_AFTER_BEGIN_INSERT); writePath = getStagingPathRoot(insertTableHandle); targetPath = getTargetPathRoot(insertTableHandle); ConnectorPageSink sink = pageSinkProvider.createPageSink(transaction.getTransactionHandle(), session, insertTableHandle); sink.appendPage(insertData.toPage()); rollbackIfEquals(tag, ROLLBACK_AFTER_APPEND_PAGE); Collection<Slice> fragments = getFutureValue(sink.finish()); rollbackIfEquals(tag, ROLLBACK_AFTER_SINK_FINISH); metadata.finishInsert(session, insertTableHandle, fragments); rollbackIfEquals(tag, ROLLBACK_AFTER_FINISH_INSERT); assertEquals(tag, COMMIT); if (conflictTrigger.isPresent()) { JsonCodec<PartitionUpdate> partitionUpdateCodec = JsonCodec.jsonCodec(PartitionUpdate.class); List<PartitionUpdate> partitionUpdates = fragments.stream() .map(Slice::getBytes) .map(partitionUpdateCodec::fromJson) .collect(toList()); conflictTrigger.get().triggerConflict(session, tableName, insertTableHandle, partitionUpdates); } transaction.commit(); if (conflictTrigger.isPresent()) { assertTrue(expectQuerySucceed); conflictTrigger.get().verifyAndCleanup(tableName); } } catch (TestingRollbackException e) { transaction.rollback(); } catch (PrestoException e) { assertFalse(expectQuerySucceed); if (conflictTrigger.isPresent()) { conflictTrigger.get().verifyAndCleanup(tableName); } } } // check that temporary files are removed if (writePath != null && !writePath.equals(targetPath)) { HdfsContext context = new HdfsContext(newSession(), tableName.getSchemaName(), tableName.getTableName()); FileSystem fileSystem = hdfsEnvironment.getFileSystem(context, writePath); assertFalse(fileSystem.exists(writePath)); } try (Transaction transaction = newTransaction()) { // verify partitions List<String> partitionNames = transaction.getMetastore(tableName.getSchemaName()) .getPartitionNames(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(() -> new AssertionError("Table does not exist: " + tableName)); assertEqualsIgnoreOrder( partitionNames, expectedData.getMaterializedRows().stream() .map(row -> format("pk1=%s/pk2=%s", row.getField(1), row.getField(2))) .distinct() .collect(toList())); // load the new table ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); // verify the data MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.of(storageFormat)); assertEqualsIgnoreOrder(result.getMaterializedRows(), expectedData.getMaterializedRows()); } } private static void rollbackIfEquals(TransactionDeleteInsertTestTag tag, TransactionDeleteInsertTestTag expectedTag) { if (expectedTag == tag) { throw new TestingRollbackException(); } } private static class TestingRollbackException extends RuntimeException { } protected static class TransactionDeleteInsertTestCase { private final boolean expectCommitedData; private final boolean expectQuerySucceed; private final TransactionDeleteInsertTestTag tag; private final Optional<ConflictTrigger> conflictTrigger; public TransactionDeleteInsertTestCase(boolean expectCommitedData, boolean expectQuerySucceed, TransactionDeleteInsertTestTag tag, Optional<ConflictTrigger> conflictTrigger) { this.expectCommitedData = expectCommitedData; this.expectQuerySucceed = expectQuerySucceed; this.tag = tag; this.conflictTrigger = conflictTrigger; } public boolean isExpectCommitedData() { return expectCommitedData; } public boolean isExpectQuerySucceed() { return expectQuerySucceed; } public TransactionDeleteInsertTestTag getTag() { return tag; } public Optional<ConflictTrigger> getConflictTrigger() { return conflictTrigger; } @Override public String toString() { return toStringHelper(this) .add("tag", tag) .add("conflictTrigger", conflictTrigger.map(conflictTrigger -> conflictTrigger.getClass().getName())) .add("expectCommitedData", expectCommitedData) .add("expectQuerySucceed", expectQuerySucceed) .toString(); } } protected enum TransactionDeleteInsertTestTag { ROLLBACK_RIGHT_AWAY, ROLLBACK_AFTER_DELETE, ROLLBACK_AFTER_BEGIN_INSERT, ROLLBACK_AFTER_APPEND_PAGE, ROLLBACK_AFTER_SINK_FINISH, ROLLBACK_AFTER_FINISH_INSERT, COMMIT, } protected interface ConflictTrigger { void triggerConflict(ConnectorSession session, SchemaTableName tableName, ConnectorInsertTableHandle insertTableHandle, List<PartitionUpdate> partitionUpdates) throws IOException; void verifyAndCleanup(SchemaTableName tableName) throws IOException; } protected class AddPartitionFailure implements ConflictTrigger { private final ImmutableList<String> copyPartitionFrom = ImmutableList.of("a", "insert1"); private final ImmutableList<String> partitionValueToConflict = ImmutableList.of("b", "add2"); private Partition conflictPartition; @Override public void triggerConflict(ConnectorSession session, SchemaTableName tableName, ConnectorInsertTableHandle insertTableHandle, List<PartitionUpdate> partitionUpdates) { // This method bypasses transaction interface because this method is inherently hacky and doesn't work well with the transaction abstraction. // Additionally, this method is not part of a test. Its purpose is to set up an environment for another test. ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); Optional<Partition> partition = metastoreClient.getPartition(tableName.getSchemaName(), tableName.getTableName(), copyPartitionFrom); conflictPartition = Partition.builder(partition.get()) .setValues(partitionValueToConflict) .build(); metastoreClient.addPartitions(tableName.getSchemaName(), tableName.getTableName(), ImmutableList.of(conflictPartition)); } @Override public void verifyAndCleanup(SchemaTableName tableName) { // This method bypasses transaction interface because this method is inherently hacky and doesn't work well with the transaction abstraction. // Additionally, this method is not part of a test. Its purpose is to set up an environment for another test. ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); Optional<Partition> actualPartition = metastoreClient.getPartition(tableName.getSchemaName(), tableName.getTableName(), partitionValueToConflict); // Make sure the partition inserted to trigger conflict was not overwritten // Checking storage location is sufficient because implement never uses .../pk1=a/pk2=a2 as the directory for partition [b, b2]. assertEquals(actualPartition.get().getStorage().getLocation(), conflictPartition.getStorage().getLocation()); metastoreClient.dropPartition(tableName.getSchemaName(), tableName.getTableName(), conflictPartition.getValues(), false); } } protected class DropPartitionFailure implements ConflictTrigger { private final ImmutableList<String> partitionValueToConflict = ImmutableList.of("b", "drop2"); @Override public void triggerConflict(ConnectorSession session, SchemaTableName tableName, ConnectorInsertTableHandle insertTableHandle, List<PartitionUpdate> partitionUpdates) { // This method bypasses transaction interface because this method is inherently hacky and doesn't work well with the transaction abstraction. // Additionally, this method is not part of a test. Its purpose is to set up an environment for another test. ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); metastoreClient.dropPartition(tableName.getSchemaName(), tableName.getTableName(), partitionValueToConflict, false); } @Override public void verifyAndCleanup(SchemaTableName tableName) { // Do not add back the deleted partition because the implementation is expected to move forward instead of backward when delete fails } } protected class DirectoryRenameFailure implements ConflictTrigger { private HdfsContext context; private Path path; @Override public void triggerConflict(ConnectorSession session, SchemaTableName tableName, ConnectorInsertTableHandle insertTableHandle, List<PartitionUpdate> partitionUpdates) { Path writePath = getStagingPathRoot(insertTableHandle); Path targetPath = getTargetPathRoot(insertTableHandle); if (writePath.equals(targetPath)) { // This conflict does not apply. Trigger a rollback right away so that this test case passes. throw new TestingRollbackException(); } path = new Path(targetPath + "/pk1=b/pk2=add2"); context = new HdfsContext(session, tableName.getSchemaName(), tableName.getTableName()); createDirectory(context, hdfsEnvironment, path); } @Override public void verifyAndCleanup(SchemaTableName tableName) throws IOException { assertEquals(listDirectory(context, path), ImmutableList.of()); hdfsEnvironment.getFileSystem(context, path).delete(path, false); } } protected class FileRenameFailure implements ConflictTrigger { private HdfsContext context; private Path path; @Override public void triggerConflict(ConnectorSession session, SchemaTableName tableName, ConnectorInsertTableHandle insertTableHandle, List<PartitionUpdate> partitionUpdates) throws IOException { for (PartitionUpdate partitionUpdate : partitionUpdates) { if ("pk2=insert2".equals(partitionUpdate.getTargetPath().getName())) { path = new Path(partitionUpdate.getTargetPath(), partitionUpdate.getFileNames().get(0)); break; } } assertNotNull(path); context = new HdfsContext(session, tableName.getSchemaName(), tableName.getTableName()); FileSystem fileSystem = hdfsEnvironment.getFileSystem(context, path); fileSystem.createNewFile(path); } @Override public void verifyAndCleanup(SchemaTableName tableName) throws IOException { // The file we added to trigger a conflict was cleaned up because it matches the query prefix. // Consider this the same as a network failure that caused the successful creation of file not reported to the caller. assertFalse(hdfsEnvironment.getFileSystem(context, path).exists(path)); } } }
presto-hive/src/test/java/com/facebook/presto/hive/AbstractTestHiveClient.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.hive; import com.facebook.presto.GroupByHashPageIndexerFactory; import com.facebook.presto.hive.HdfsEnvironment.HdfsContext; import com.facebook.presto.hive.LocationService.WriteInfo; import com.facebook.presto.hive.authentication.NoHdfsAuthentication; import com.facebook.presto.hive.metastore.CachingHiveMetastore; import com.facebook.presto.hive.metastore.Column; import com.facebook.presto.hive.metastore.ExtendedHiveMetastore; import com.facebook.presto.hive.metastore.HiveColumnStatistics; import com.facebook.presto.hive.metastore.HivePrivilegeInfo; import com.facebook.presto.hive.metastore.HivePrivilegeInfo.HivePrivilege; import com.facebook.presto.hive.metastore.Partition; import com.facebook.presto.hive.metastore.PrincipalPrivileges; import com.facebook.presto.hive.metastore.SemiTransactionalHiveMetastore; import com.facebook.presto.hive.metastore.SortingColumn; import com.facebook.presto.hive.metastore.StorageFormat; import com.facebook.presto.hive.metastore.Table; import com.facebook.presto.hive.metastore.thrift.BridgingHiveMetastore; import com.facebook.presto.hive.metastore.thrift.HiveCluster; import com.facebook.presto.hive.metastore.thrift.TestingHiveCluster; import com.facebook.presto.hive.metastore.thrift.ThriftHiveMetastore; import com.facebook.presto.hive.orc.OrcPageSource; import com.facebook.presto.hive.parquet.ParquetHiveRecordCursor; import com.facebook.presto.hive.parquet.ParquetPageSource; import com.facebook.presto.hive.rcfile.RcFilePageSource; import com.facebook.presto.metadata.MetadataManager; import com.facebook.presto.spi.ColumnHandle; import com.facebook.presto.spi.ColumnMetadata; import com.facebook.presto.spi.ConnectorInsertTableHandle; import com.facebook.presto.spi.ConnectorOutputTableHandle; import com.facebook.presto.spi.ConnectorPageSink; import com.facebook.presto.spi.ConnectorPageSource; import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.ConnectorSplit; import com.facebook.presto.spi.ConnectorSplitSource; import com.facebook.presto.spi.ConnectorTableHandle; import com.facebook.presto.spi.ConnectorTableLayout; import com.facebook.presto.spi.ConnectorTableLayoutHandle; import com.facebook.presto.spi.ConnectorTableLayoutResult; import com.facebook.presto.spi.ConnectorTableMetadata; import com.facebook.presto.spi.ConnectorViewDefinition; import com.facebook.presto.spi.Constraint; import com.facebook.presto.spi.DiscretePredicates; import com.facebook.presto.spi.Page; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.RecordCursor; import com.facebook.presto.spi.RecordPageSource; import com.facebook.presto.spi.SchemaTableName; import com.facebook.presto.spi.SchemaTablePrefix; import com.facebook.presto.spi.TableNotFoundException; import com.facebook.presto.spi.ViewNotFoundException; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.connector.ConnectorMetadata; import com.facebook.presto.spi.connector.ConnectorPageSinkProvider; import com.facebook.presto.spi.connector.ConnectorPageSourceProvider; import com.facebook.presto.spi.connector.ConnectorSplitManager; import com.facebook.presto.spi.connector.ConnectorTransactionHandle; import com.facebook.presto.spi.predicate.Domain; import com.facebook.presto.spi.predicate.NullableValue; import com.facebook.presto.spi.predicate.Range; import com.facebook.presto.spi.predicate.TupleDomain; import com.facebook.presto.spi.predicate.ValueSet; import com.facebook.presto.spi.statistics.ColumnStatistics; import com.facebook.presto.spi.statistics.RangeColumnStatistics; import com.facebook.presto.spi.statistics.TableStatistics; import com.facebook.presto.spi.type.ArrayType; import com.facebook.presto.spi.type.MapType; import com.facebook.presto.spi.type.NamedTypeSignature; import com.facebook.presto.spi.type.RowFieldName; import com.facebook.presto.spi.type.RowType; import com.facebook.presto.spi.type.SqlDate; import com.facebook.presto.spi.type.SqlTimestamp; import com.facebook.presto.spi.type.SqlVarbinary; import com.facebook.presto.spi.type.StandardTypes; import com.facebook.presto.spi.type.Type; import com.facebook.presto.sql.analyzer.FeaturesConfig; import com.facebook.presto.sql.gen.JoinCompiler; import com.facebook.presto.testing.MaterializedResult; import com.facebook.presto.testing.MaterializedRow; import com.facebook.presto.testing.TestingConnectorSession; import com.facebook.presto.testing.TestingNodeManager; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.net.HostAndPort; import io.airlift.json.JsonCodec; import io.airlift.log.Logger; import io.airlift.slice.Slice; import io.airlift.stats.CounterStat; import io.airlift.units.DataSize; import io.airlift.units.Duration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.metastore.TableType; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.IOException; import java.math.BigDecimal; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.Set; import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.IntStream; import java.util.stream.LongStream; import static com.facebook.presto.hive.AbstractTestHiveClient.TransactionDeleteInsertTestTag.COMMIT; import static com.facebook.presto.hive.AbstractTestHiveClient.TransactionDeleteInsertTestTag.ROLLBACK_AFTER_APPEND_PAGE; import static com.facebook.presto.hive.AbstractTestHiveClient.TransactionDeleteInsertTestTag.ROLLBACK_AFTER_BEGIN_INSERT; import static com.facebook.presto.hive.AbstractTestHiveClient.TransactionDeleteInsertTestTag.ROLLBACK_AFTER_DELETE; import static com.facebook.presto.hive.AbstractTestHiveClient.TransactionDeleteInsertTestTag.ROLLBACK_AFTER_FINISH_INSERT; import static com.facebook.presto.hive.AbstractTestHiveClient.TransactionDeleteInsertTestTag.ROLLBACK_AFTER_SINK_FINISH; import static com.facebook.presto.hive.AbstractTestHiveClient.TransactionDeleteInsertTestTag.ROLLBACK_RIGHT_AWAY; import static com.facebook.presto.hive.HiveBasicStatistics.createEmptyStatistics; import static com.facebook.presto.hive.HiveBasicStatistics.createZeroStatistics; import static com.facebook.presto.hive.HiveColumnHandle.BUCKET_COLUMN_NAME; import static com.facebook.presto.hive.HiveColumnHandle.ColumnType.PARTITION_KEY; import static com.facebook.presto.hive.HiveColumnHandle.ColumnType.REGULAR; import static com.facebook.presto.hive.HiveColumnHandle.bucketColumnHandle; import static com.facebook.presto.hive.HiveErrorCode.HIVE_INVALID_PARTITION_VALUE; import static com.facebook.presto.hive.HiveErrorCode.HIVE_PARTITION_SCHEMA_MISMATCH; import static com.facebook.presto.hive.HiveMetadata.PRESTO_QUERY_ID_NAME; import static com.facebook.presto.hive.HiveMetadata.PRESTO_VERSION_NAME; import static com.facebook.presto.hive.HiveMetadata.convertToPredicate; import static com.facebook.presto.hive.HiveStorageFormat.AVRO; import static com.facebook.presto.hive.HiveStorageFormat.DWRF; import static com.facebook.presto.hive.HiveStorageFormat.JSON; import static com.facebook.presto.hive.HiveStorageFormat.ORC; import static com.facebook.presto.hive.HiveStorageFormat.PARQUET; import static com.facebook.presto.hive.HiveStorageFormat.RCBINARY; import static com.facebook.presto.hive.HiveStorageFormat.RCTEXT; import static com.facebook.presto.hive.HiveStorageFormat.SEQUENCEFILE; import static com.facebook.presto.hive.HiveStorageFormat.TEXTFILE; import static com.facebook.presto.hive.HiveTableProperties.BUCKETED_BY_PROPERTY; import static com.facebook.presto.hive.HiveTableProperties.BUCKET_COUNT_PROPERTY; import static com.facebook.presto.hive.HiveTableProperties.PARTITIONED_BY_PROPERTY; import static com.facebook.presto.hive.HiveTableProperties.SORTED_BY_PROPERTY; import static com.facebook.presto.hive.HiveTableProperties.STORAGE_FORMAT_PROPERTY; import static com.facebook.presto.hive.HiveTestUtils.PAGE_SORTER; import static com.facebook.presto.hive.HiveTestUtils.SESSION; import static com.facebook.presto.hive.HiveTestUtils.TYPE_MANAGER; import static com.facebook.presto.hive.HiveTestUtils.arrayType; import static com.facebook.presto.hive.HiveTestUtils.getDefaultHiveDataStreamFactories; import static com.facebook.presto.hive.HiveTestUtils.getDefaultHiveFileWriterFactories; import static com.facebook.presto.hive.HiveTestUtils.getDefaultHiveRecordCursorProvider; import static com.facebook.presto.hive.HiveTestUtils.getTypes; import static com.facebook.presto.hive.HiveTestUtils.mapType; import static com.facebook.presto.hive.HiveTestUtils.rowType; import static com.facebook.presto.hive.HiveType.HIVE_INT; import static com.facebook.presto.hive.HiveType.HIVE_LONG; import static com.facebook.presto.hive.HiveType.HIVE_STRING; import static com.facebook.presto.hive.HiveType.toHiveType; import static com.facebook.presto.hive.HiveUtil.columnExtraInfo; import static com.facebook.presto.hive.HiveWriteUtils.createDirectory; import static com.facebook.presto.hive.LocationHandle.WriteMode.STAGE_AND_MOVE_TO_TARGET_DIRECTORY; import static com.facebook.presto.hive.metastore.HiveColumnStatistics.createBinaryColumnStatistics; import static com.facebook.presto.hive.metastore.HiveColumnStatistics.createBooleanColumnStatistics; import static com.facebook.presto.hive.metastore.HiveColumnStatistics.createDateColumnStatistics; import static com.facebook.presto.hive.metastore.HiveColumnStatistics.createDecimalColumnStatistics; import static com.facebook.presto.hive.metastore.HiveColumnStatistics.createDoubleColumnStatistics; import static com.facebook.presto.hive.metastore.HiveColumnStatistics.createIntegerColumnStatistics; import static com.facebook.presto.hive.metastore.HiveColumnStatistics.createStringColumnStatistics; import static com.facebook.presto.hive.metastore.StorageFormat.fromHiveStorageFormat; import static com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED; import static com.facebook.presto.spi.StandardErrorCode.TRANSACTION_CONFLICT; import static com.facebook.presto.spi.connector.ConnectorSplitManager.SplitSchedulingStrategy.UNGROUPED_SCHEDULING; import static com.facebook.presto.spi.connector.NotPartitionedPartitionHandle.NOT_PARTITIONED; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.type.CharType.createCharType; import static com.facebook.presto.spi.type.Chars.isCharType; import static com.facebook.presto.spi.type.DateType.DATE; import static com.facebook.presto.spi.type.DecimalType.createDecimalType; import static com.facebook.presto.spi.type.DoubleType.DOUBLE; import static com.facebook.presto.spi.type.HyperLogLogType.HYPER_LOG_LOG; import static com.facebook.presto.spi.type.IntegerType.INTEGER; import static com.facebook.presto.spi.type.RealType.REAL; import static com.facebook.presto.spi.type.SmallintType.SMALLINT; import static com.facebook.presto.spi.type.TimeZoneKey.UTC_KEY; import static com.facebook.presto.spi.type.TimestampType.TIMESTAMP; import static com.facebook.presto.spi.type.TinyintType.TINYINT; import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature; import static com.facebook.presto.spi.type.VarbinaryType.VARBINARY; import static com.facebook.presto.spi.type.VarcharType.VARCHAR; import static com.facebook.presto.spi.type.VarcharType.createUnboundedVarcharType; import static com.facebook.presto.spi.type.VarcharType.createVarcharType; import static com.facebook.presto.spi.type.Varchars.isVarcharType; import static com.facebook.presto.testing.DateTimeTestingUtils.sqlTimestampOf; import static com.facebook.presto.testing.MaterializedResult.materializeSourceDataStream; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Verify.verify; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.concat; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Maps.uniqueIndex; import static com.google.common.collect.MoreCollectors.onlyElement; import static com.google.common.collect.Sets.difference; import static com.google.common.hash.Hashing.sha256; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import static io.airlift.concurrent.MoreFutures.getFutureValue; import static io.airlift.concurrent.Threads.daemonThreadsNamed; import static io.airlift.slice.Slices.utf8Slice; import static io.airlift.testing.Assertions.assertEqualsIgnoreOrder; import static io.airlift.testing.Assertions.assertGreaterThan; import static io.airlift.testing.Assertions.assertGreaterThanOrEqual; import static io.airlift.testing.Assertions.assertInstanceOf; import static io.airlift.testing.Assertions.assertLessThanOrEqual; import static io.airlift.units.DataSize.Unit.MEGABYTE; import static java.lang.Float.floatToRawIntBits; import static java.lang.Math.toIntExact; import static java.lang.String.format; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Locale.ENGLISH; import static java.util.Objects.requireNonNull; import static java.util.concurrent.Executors.newCachedThreadPool; import static java.util.concurrent.Executors.newFixedThreadPool; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.stream.Collectors.toList; import static org.apache.hadoop.hive.common.FileUtils.makePartName; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import static org.joda.time.DateTimeZone.UTC; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; public abstract class AbstractTestHiveClient { protected static final String TEMPORARY_TABLE_PREFIX = "tmp_presto_test_"; protected static final String INVALID_DATABASE = "totally_invalid_database_name"; protected static final String INVALID_TABLE = "totally_invalid_table_name"; protected static final String INVALID_COLUMN = "totally_invalid_column_name"; protected static final String TEST_SERVER_VERSION = "test_version"; private static final Type ARRAY_TYPE = arrayType(createUnboundedVarcharType()); private static final Type MAP_TYPE = mapType(createUnboundedVarcharType(), BIGINT); private static final Type ROW_TYPE = rowType(ImmutableList.of( new NamedTypeSignature(Optional.of(new RowFieldName("f_string", false)), createUnboundedVarcharType().getTypeSignature()), new NamedTypeSignature(Optional.of(new RowFieldName("f_bigint", false)), BIGINT.getTypeSignature()), new NamedTypeSignature(Optional.of(new RowFieldName("f_boolean", false)), BOOLEAN.getTypeSignature()))); private static final List<ColumnMetadata> CREATE_TABLE_COLUMNS = ImmutableList.<ColumnMetadata>builder() .add(new ColumnMetadata("id", BIGINT)) .add(new ColumnMetadata("t_string", createUnboundedVarcharType())) .add(new ColumnMetadata("t_tinyint", TINYINT)) .add(new ColumnMetadata("t_smallint", SMALLINT)) .add(new ColumnMetadata("t_integer", INTEGER)) .add(new ColumnMetadata("t_bigint", BIGINT)) .add(new ColumnMetadata("t_float", REAL)) .add(new ColumnMetadata("t_double", DOUBLE)) .add(new ColumnMetadata("t_boolean", BOOLEAN)) .add(new ColumnMetadata("t_array", ARRAY_TYPE)) .add(new ColumnMetadata("t_map", MAP_TYPE)) .add(new ColumnMetadata("t_row", ROW_TYPE)) .build(); private static final MaterializedResult CREATE_TABLE_DATA = MaterializedResult.resultBuilder(SESSION, BIGINT, createUnboundedVarcharType(), TINYINT, SMALLINT, INTEGER, BIGINT, REAL, DOUBLE, BOOLEAN, ARRAY_TYPE, MAP_TYPE, ROW_TYPE) .row(1L, "hello", (byte) 45, (short) 345, 234, 123L, -754.1985f, 43.5, true, ImmutableList.of("apple", "banana"), ImmutableMap.of("one", 1L, "two", 2L), ImmutableList.of("true", 1L, true)) .row(2L, null, null, null, null, null, null, null, null, null, null, null) .row(3L, "bye", (byte) 46, (short) 346, 345, 456L, 754.2008f, 98.1, false, ImmutableList.of("ape", "bear"), ImmutableMap.of("three", 3L, "four", 4L), ImmutableList.of("false", 0L, false)) .build(); private static final List<ColumnMetadata> CREATE_TABLE_COLUMNS_PARTITIONED = ImmutableList.<ColumnMetadata>builder() .addAll(CREATE_TABLE_COLUMNS) .add(new ColumnMetadata("ds", createUnboundedVarcharType())) .build(); private static final MaterializedResult CREATE_TABLE_PARTITIONED_DATA = new MaterializedResult( CREATE_TABLE_DATA.getMaterializedRows().stream() .map(row -> new MaterializedRow(row.getPrecision(), newArrayList(concat(row.getFields(), ImmutableList.of("2015-07-0" + row.getField(0)))))) .collect(toList()), ImmutableList.<Type>builder() .addAll(CREATE_TABLE_DATA.getTypes()) .add(createUnboundedVarcharType()) .build()); private static final String CREATE_TABLE_PARTITIONED_DATA_2ND_PARTITION_VALUE = "2015-07-04"; private static final MaterializedResult CREATE_TABLE_PARTITIONED_DATA_2ND = MaterializedResult.resultBuilder(SESSION, BIGINT, createUnboundedVarcharType(), TINYINT, SMALLINT, INTEGER, BIGINT, REAL, DOUBLE, BOOLEAN, ARRAY_TYPE, MAP_TYPE, ROW_TYPE, createUnboundedVarcharType()) .row(4L, "hello", (byte) 45, (short) 345, 234, 123L, 754.1985f, 43.5, true, ImmutableList.of("apple", "banana"), ImmutableMap.of("one", 1L, "two", 2L), ImmutableList.of("true", 1L, true), CREATE_TABLE_PARTITIONED_DATA_2ND_PARTITION_VALUE) .row(5L, null, null, null, null, null, null, null, null, null, null, null, CREATE_TABLE_PARTITIONED_DATA_2ND_PARTITION_VALUE) .row(6L, "bye", (byte) 46, (short) 346, 345, 456L, -754.2008f, 98.1, false, ImmutableList.of("ape", "bear"), ImmutableMap.of("three", 3L, "four", 4L), ImmutableList.of("false", 0L, false), CREATE_TABLE_PARTITIONED_DATA_2ND_PARTITION_VALUE) .build(); private static final List<ColumnMetadata> MISMATCH_SCHEMA_PRIMITIVE_COLUMN_BEFORE = ImmutableList.<ColumnMetadata>builder() .add(new ColumnMetadata("tinyint_to_smallint", TINYINT)) .add(new ColumnMetadata("tinyint_to_integer", TINYINT)) .add(new ColumnMetadata("tinyint_to_bigint", TINYINT)) .add(new ColumnMetadata("smallint_to_integer", SMALLINT)) .add(new ColumnMetadata("smallint_to_bigint", SMALLINT)) .add(new ColumnMetadata("integer_to_bigint", INTEGER)) .add(new ColumnMetadata("integer_to_varchar", INTEGER)) .add(new ColumnMetadata("varchar_to_integer", createUnboundedVarcharType())) .add(new ColumnMetadata("float_to_double", REAL)) .add(new ColumnMetadata("varchar_to_drop_in_row", createUnboundedVarcharType())) .build(); private static final List<ColumnMetadata> MISMATCH_SCHEMA_TABLE_BEFORE = ImmutableList.<ColumnMetadata>builder() .addAll(MISMATCH_SCHEMA_PRIMITIVE_COLUMN_BEFORE) .add(new ColumnMetadata("struct_to_struct", toRowType(MISMATCH_SCHEMA_PRIMITIVE_COLUMN_BEFORE))) .add(new ColumnMetadata("list_to_list", arrayType(toRowType(MISMATCH_SCHEMA_PRIMITIVE_COLUMN_BEFORE)))) .add(new ColumnMetadata("map_to_map", mapType(MISMATCH_SCHEMA_PRIMITIVE_COLUMN_BEFORE.get(1).getType(), toRowType(MISMATCH_SCHEMA_PRIMITIVE_COLUMN_BEFORE)))) .add(new ColumnMetadata("ds", createUnboundedVarcharType())) .build(); private static RowType toRowType(List<ColumnMetadata> columns) { return rowType(columns.stream() .map(col -> new NamedTypeSignature(Optional.of(new RowFieldName(format("f_%s", col.getName()), false)), col.getType().getTypeSignature())) .collect(toList())); } private static final MaterializedResult MISMATCH_SCHEMA_PRIMITIVE_FIELDS_DATA_BEFORE = MaterializedResult.resultBuilder(SESSION, TINYINT, TINYINT, TINYINT, SMALLINT, SMALLINT, INTEGER, INTEGER, createUnboundedVarcharType(), REAL, createUnboundedVarcharType()) .row((byte) -11, (byte) 12, (byte) -13, (short) 14, (short) 15, -16, 17, "2147483647", 18.0f, "2016-08-01") .row((byte) 21, (byte) -22, (byte) 23, (short) -24, (short) 25, 26, -27, "asdf", -28.0f, "2016-08-02") .row((byte) -31, (byte) -32, (byte) 33, (short) 34, (short) -35, 36, 37, "-923", 39.5f, "2016-08-03") .row(null, (byte) 42, (byte) 43, (short) 44, (short) -45, 46, 47, "2147483648", 49.5f, "2016-08-03") .build(); private static final MaterializedResult MISMATCH_SCHEMA_TABLE_DATA_BEFORE = MaterializedResult.resultBuilder(SESSION, MISMATCH_SCHEMA_TABLE_BEFORE.stream().map(ColumnMetadata::getType).collect(toList())) .rows(MISMATCH_SCHEMA_PRIMITIVE_FIELDS_DATA_BEFORE.getMaterializedRows() .stream() .map(materializedRow -> { List<Object> result = materializedRow.getFields(); List<Object> rowResult = materializedRow.getFields(); result.add(rowResult); result.add(Arrays.asList(rowResult, null, rowResult)); result.add(ImmutableMap.of(rowResult.get(1), rowResult)); result.add(rowResult.get(9)); return new MaterializedRow(materializedRow.getPrecision(), result); }).collect(toList())) .build(); private static final List<ColumnMetadata> MISMATCH_SCHEMA_PRIMITIVE_COLUMN_AFTER = ImmutableList.<ColumnMetadata>builder() .add(new ColumnMetadata("tinyint_to_smallint", SMALLINT)) .add(new ColumnMetadata("tinyint_to_integer", INTEGER)) .add(new ColumnMetadata("tinyint_to_bigint", BIGINT)) .add(new ColumnMetadata("smallint_to_integer", INTEGER)) .add(new ColumnMetadata("smallint_to_bigint", BIGINT)) .add(new ColumnMetadata("integer_to_bigint", BIGINT)) .add(new ColumnMetadata("integer_to_varchar", createUnboundedVarcharType())) .add(new ColumnMetadata("varchar_to_integer", INTEGER)) .add(new ColumnMetadata("float_to_double", DOUBLE)) .add(new ColumnMetadata("varchar_to_drop_in_row", createUnboundedVarcharType())) .build(); private static final Type MISMATCH_SCHEMA_ROW_TYPE_APPEND = toRowType(ImmutableList.<ColumnMetadata>builder() .addAll(MISMATCH_SCHEMA_PRIMITIVE_COLUMN_AFTER) .add(new ColumnMetadata(format("%s_append", MISMATCH_SCHEMA_PRIMITIVE_COLUMN_AFTER.get(0).getName()), MISMATCH_SCHEMA_PRIMITIVE_COLUMN_AFTER.get(0).getType())) .build()); private static final Type MISMATCH_SCHEMA_ROW_TYPE_DROP = toRowType(MISMATCH_SCHEMA_PRIMITIVE_COLUMN_AFTER.subList(0, MISMATCH_SCHEMA_PRIMITIVE_COLUMN_AFTER.size() - 1)); private static final List<ColumnMetadata> MISMATCH_SCHEMA_TABLE_AFTER = ImmutableList.<ColumnMetadata>builder() .addAll(MISMATCH_SCHEMA_PRIMITIVE_COLUMN_AFTER) .add(new ColumnMetadata("struct_to_struct", MISMATCH_SCHEMA_ROW_TYPE_APPEND)) .add(new ColumnMetadata("list_to_list", arrayType(MISMATCH_SCHEMA_ROW_TYPE_APPEND))) .add(new ColumnMetadata("map_to_map", mapType(MISMATCH_SCHEMA_PRIMITIVE_COLUMN_AFTER.get(1).getType(), MISMATCH_SCHEMA_ROW_TYPE_DROP))) .add(new ColumnMetadata("ds", createUnboundedVarcharType())) .build(); private static final MaterializedResult MISMATCH_SCHEMA_PRIMITIVE_FIELDS_DATA_AFTER = MaterializedResult.resultBuilder(SESSION, SMALLINT, INTEGER, BIGINT, INTEGER, BIGINT, BIGINT, createUnboundedVarcharType(), INTEGER, DOUBLE, createUnboundedVarcharType()) .row((short) -11, 12, -13L, 14, 15L, -16L, "17", 2147483647, 18.0, "2016-08-01") .row((short) 21, -22, 23L, -24, 25L, 26L, "-27", null, -28.0, "2016-08-02") .row((short) -31, -32, 33L, 34, -35L, 36L, "37", -923, 39.5, "2016-08-03") .row(null, 42, 43L, 44, -45L, 46L, "47", null, 49.5, "2016-08-03") .build(); private static final MaterializedResult MISMATCH_SCHEMA_TABLE_DATA_AFTER = MaterializedResult.resultBuilder(SESSION, MISMATCH_SCHEMA_TABLE_AFTER.stream().map(ColumnMetadata::getType).collect(toList())) .rows(MISMATCH_SCHEMA_PRIMITIVE_FIELDS_DATA_AFTER.getMaterializedRows() .stream() .map(materializedRow -> { List<Object> result = materializedRow.getFields(); List<Object> appendFieldRowResult = materializedRow.getFields(); appendFieldRowResult.add(null); List<Object> dropFieldRowResult = materializedRow.getFields().subList(0, materializedRow.getFields().size() - 1); result.add(appendFieldRowResult); result.add(Arrays.asList(appendFieldRowResult, null, appendFieldRowResult)); result.add(ImmutableMap.of(result.get(1), dropFieldRowResult)); result.add(result.get(9)); return new MaterializedRow(materializedRow.getPrecision(), result); }).collect(toList())) .build(); protected Set<HiveStorageFormat> createTableFormats = difference(ImmutableSet.copyOf(HiveStorageFormat.values()), ImmutableSet.of(AVRO)); private static final JoinCompiler JOIN_COMPILER = new JoinCompiler(MetadataManager.createTestMetadataManager(), new FeaturesConfig()); private static final List<ColumnMetadata> STATISTICS_TABLE_COLUMNS = ImmutableList.<ColumnMetadata>builder() .add(new ColumnMetadata("t_boolean", BOOLEAN)) .add(new ColumnMetadata("t_bigint", BIGINT)) .add(new ColumnMetadata("t_integer", INTEGER)) .add(new ColumnMetadata("t_smallint", SMALLINT)) .add(new ColumnMetadata("t_tinyint", TINYINT)) .add(new ColumnMetadata("t_double", DOUBLE)) .add(new ColumnMetadata("t_float", REAL)) .add(new ColumnMetadata("t_string", createUnboundedVarcharType())) .add(new ColumnMetadata("t_varchar", createVarcharType(100))) .add(new ColumnMetadata("t_char", createCharType(5))) .add(new ColumnMetadata("t_varbinary", VARBINARY)) .add(new ColumnMetadata("t_date", DATE)) .add(new ColumnMetadata("t_timestamp", TIMESTAMP)) .add(new ColumnMetadata("t_short_decimal", createDecimalType(5, 2))) .add(new ColumnMetadata("t_long_decimal", createDecimalType(20, 3))) .build(); private static final List<ColumnMetadata> STATISTICS_PARTITIONED_TABLE_COLUMNS = ImmutableList.<ColumnMetadata>builder() .addAll(STATISTICS_TABLE_COLUMNS) .add(new ColumnMetadata("ds", VARCHAR)) .build(); protected static final PartitionStatistics EMPTY_TABLE_STATISTICS = new PartitionStatistics(createZeroStatistics(), ImmutableMap.of()); protected static final PartitionStatistics BASIC_STATISTICS_1 = new PartitionStatistics(new HiveBasicStatistics(0, 2, 3, 0), ImmutableMap.of()); protected static final PartitionStatistics BASIC_STATISTICS_2 = new PartitionStatistics(new HiveBasicStatistics(0, 3, 2, 0), ImmutableMap.of()); private static final PartitionStatistics STATISTICS_1 = new PartitionStatistics( BASIC_STATISTICS_1.getBasicStatistics(), ImmutableMap.<String, HiveColumnStatistics>builder() .put("t_boolean", createBooleanColumnStatistics(OptionalLong.of(5), OptionalLong.of(6), OptionalLong.of(3))) .put("t_bigint", createIntegerColumnStatistics(OptionalLong.of(1234L), OptionalLong.of(5678L), OptionalLong.of(2), OptionalLong.of(5))) .put("t_integer", createIntegerColumnStatistics(OptionalLong.of(123L), OptionalLong.of(567L), OptionalLong.of(3), OptionalLong.of(4))) .put("t_smallint", createIntegerColumnStatistics(OptionalLong.of(12L), OptionalLong.of(56L), OptionalLong.of(2), OptionalLong.of(6))) .put("t_tinyint", createIntegerColumnStatistics(OptionalLong.of(1L), OptionalLong.of(2L), OptionalLong.of(1), OptionalLong.of(3))) .put("t_double", createDoubleColumnStatistics(OptionalDouble.of(1234.25), OptionalDouble.of(5678.58), OptionalLong.of(7), OptionalLong.of(8))) .put("t_float", createDoubleColumnStatistics(OptionalDouble.of(123.25), OptionalDouble.of(567.58), OptionalLong.of(9), OptionalLong.of(10))) .put("t_string", createStringColumnStatistics(OptionalLong.of(10), OptionalDouble.of(5.0), OptionalLong.of(3), OptionalLong.of(7))) .put("t_varchar", createStringColumnStatistics(OptionalLong.of(100), OptionalDouble.of(23.3), OptionalLong.of(5), OptionalLong.of(3))) .put("t_char", createStringColumnStatistics(OptionalLong.of(5), OptionalDouble.of(5.0), OptionalLong.of(1), OptionalLong.of(4))) .put("t_varbinary", createBinaryColumnStatistics(OptionalLong.of(4), OptionalDouble.of(3.0), OptionalLong.of(1))) .put("t_date", createDateColumnStatistics(Optional.of(java.time.LocalDate.ofEpochDay(1)), Optional.of(java.time.LocalDate.ofEpochDay(2)), OptionalLong.of(7), OptionalLong.of(6))) .put("t_timestamp", createIntegerColumnStatistics(OptionalLong.of(1234567L), OptionalLong.of(71234567L), OptionalLong.of(7), OptionalLong.of(5))) .put("t_short_decimal", createDecimalColumnStatistics(Optional.of(new BigDecimal(10)), Optional.of(new BigDecimal(12)), OptionalLong.of(3), OptionalLong.of(5))) .put("t_long_decimal", createDecimalColumnStatistics(Optional.of(new BigDecimal("12345678901234567.123")), Optional.of(new BigDecimal("81234567890123456.123")), OptionalLong.of(2), OptionalLong.of(1))) .build()); private static final PartitionStatistics STATISTICS_1_1 = new PartitionStatistics( new HiveBasicStatistics(OptionalLong.of(0), OptionalLong.of(2), OptionalLong.empty(), OptionalLong.of(0)), STATISTICS_1.getColumnStatistics().entrySet() .stream() .filter(entry -> entry.getKey().hashCode() % 2 == 0) .collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue))); private static final PartitionStatistics STATISTICS_1_2 = new PartitionStatistics( new HiveBasicStatistics(OptionalLong.of(0), OptionalLong.empty(), OptionalLong.of(3), OptionalLong.of(0)), STATISTICS_1.getColumnStatistics().entrySet() .stream() .filter(entry -> entry.getKey().hashCode() % 2 == 1) .collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue))); private static final PartitionStatistics STATISTICS_2 = new PartitionStatistics( BASIC_STATISTICS_2.getBasicStatistics(), ImmutableMap.<String, HiveColumnStatistics>builder() .put("t_boolean", createBooleanColumnStatistics(OptionalLong.of(4), OptionalLong.of(3), OptionalLong.of(2))) .put("t_bigint", createIntegerColumnStatistics(OptionalLong.of(2345L), OptionalLong.of(6789L), OptionalLong.of(4), OptionalLong.of(7))) .put("t_integer", createIntegerColumnStatistics(OptionalLong.of(234L), OptionalLong.of(678L), OptionalLong.of(5), OptionalLong.of(6))) .put("t_smallint", createIntegerColumnStatistics(OptionalLong.of(23L), OptionalLong.of(65L), OptionalLong.of(7), OptionalLong.of(5))) .put("t_tinyint", createIntegerColumnStatistics(OptionalLong.of(12), OptionalLong.of(3L), OptionalLong.of(2), OptionalLong.of(3))) .put("t_double", createDoubleColumnStatistics(OptionalDouble.of(2345.25), OptionalDouble.of(6785.58), OptionalLong.of(6), OptionalLong.of(3))) .put("t_float", createDoubleColumnStatistics(OptionalDouble.of(235.25), OptionalDouble.of(676.58), OptionalLong.of(7), OptionalLong.of(11))) .put("t_string", createStringColumnStatistics(OptionalLong.of(11), OptionalDouble.of(6.0), OptionalLong.of(2), OptionalLong.of(6))) .put("t_varchar", createStringColumnStatistics(OptionalLong.of(99), OptionalDouble.of(22.3), OptionalLong.of(7), OptionalLong.of(1))) .put("t_char", createStringColumnStatistics(OptionalLong.of(6), OptionalDouble.of(6.0), OptionalLong.of(0), OptionalLong.of(3))) .put("t_varbinary", createBinaryColumnStatistics(OptionalLong.of(2), OptionalDouble.of(1.0), OptionalLong.of(2))) .put("t_date", createDateColumnStatistics(Optional.of(java.time.LocalDate.ofEpochDay(2)), Optional.of(java.time.LocalDate.ofEpochDay(3)), OptionalLong.of(8), OptionalLong.of(7))) .put("t_timestamp", createIntegerColumnStatistics(OptionalLong.of(2345671L), OptionalLong.of(12345677L), OptionalLong.of(9), OptionalLong.of(1))) .put("t_short_decimal", createDecimalColumnStatistics(Optional.of(new BigDecimal(11)), Optional.of(new BigDecimal(14)), OptionalLong.of(5), OptionalLong.of(7))) .put("t_long_decimal", createDecimalColumnStatistics(Optional.of(new BigDecimal("71234567890123456.123")), Optional.of(new BigDecimal("78123456789012345.123")), OptionalLong.of(2), OptionalLong.of(1))) .build()); private static final PartitionStatistics STATISTICS_EMPTY_OPTIONAL_FIELDS = new PartitionStatistics( new HiveBasicStatistics(OptionalLong.of(0), OptionalLong.empty(), OptionalLong.empty(), OptionalLong.of(0)), ImmutableMap.<String, HiveColumnStatistics>builder() .put("t_boolean", createBooleanColumnStatistics(OptionalLong.of(4), OptionalLong.of(3), OptionalLong.of(2))) .put("t_bigint", createIntegerColumnStatistics(OptionalLong.empty(), OptionalLong.empty(), OptionalLong.of(4), OptionalLong.of(7))) .put("t_integer", createIntegerColumnStatistics(OptionalLong.empty(), OptionalLong.empty(), OptionalLong.of(5), OptionalLong.of(6))) .put("t_smallint", createIntegerColumnStatistics(OptionalLong.empty(), OptionalLong.empty(), OptionalLong.of(7), OptionalLong.of(5))) .put("t_tinyint", createIntegerColumnStatistics(OptionalLong.empty(), OptionalLong.empty(), OptionalLong.of(2), OptionalLong.of(3))) .put("t_double", createDoubleColumnStatistics(OptionalDouble.empty(), OptionalDouble.empty(), OptionalLong.of(6), OptionalLong.of(3))) .put("t_float", createDoubleColumnStatistics(OptionalDouble.empty(), OptionalDouble.empty(), OptionalLong.of(7), OptionalLong.of(11))) .put("t_string", createStringColumnStatistics(OptionalLong.of(0), OptionalDouble.of(0), OptionalLong.of(2), OptionalLong.of(6))) .put("t_varchar", createStringColumnStatistics(OptionalLong.of(0), OptionalDouble.of(0), OptionalLong.of(7), OptionalLong.of(1))) .put("t_char", createStringColumnStatistics(OptionalLong.of(0), OptionalDouble.of(0), OptionalLong.of(0), OptionalLong.of(3))) .put("t_varbinary", createBinaryColumnStatistics(OptionalLong.of(0), OptionalDouble.of(0), OptionalLong.of(2))) // https://issues.apache.org/jira/browse/HIVE-20098 // .put("t_date", createDateColumnStatistics(Optional.empty(), Optional.empty(), OptionalLong.of(8), OptionalLong.of(7))) .put("t_timestamp", createIntegerColumnStatistics(OptionalLong.empty(), OptionalLong.empty(), OptionalLong.of(9), OptionalLong.of(1))) .put("t_short_decimal", createDecimalColumnStatistics(Optional.empty(), Optional.empty(), OptionalLong.of(5), OptionalLong.of(7))) .put("t_long_decimal", createDecimalColumnStatistics(Optional.empty(), Optional.empty(), OptionalLong.of(2), OptionalLong.of(1))) .build()); protected String clientId; protected String database; protected SchemaTableName tablePartitionFormat; protected SchemaTableName tableUnpartitioned; protected SchemaTableName tableOffline; protected SchemaTableName tableOfflinePartition; protected SchemaTableName tableNotReadable; protected SchemaTableName view; protected SchemaTableName invalidTable; protected SchemaTableName tableBucketedStringInt; protected SchemaTableName tableBucketedBigintBoolean; protected SchemaTableName tableBucketedDoubleFloat; protected SchemaTableName tablePartitionSchemaChange; protected SchemaTableName tablePartitionSchemaChangeNonCanonical; protected SchemaTableName tableBucketEvolution; protected String invalidClientId; protected ConnectorTableHandle invalidTableHandle; protected ColumnHandle dsColumn; protected ColumnHandle fileFormatColumn; protected ColumnHandle dummyColumn; protected ColumnHandle intColumn; protected ColumnHandle invalidColumnHandle; protected int partitionCount; protected TupleDomain<ColumnHandle> tupleDomain; protected ConnectorTableLayout tableLayout; protected ConnectorTableLayout unpartitionedTableLayout; protected ConnectorTableLayoutHandle invalidTableLayoutHandle; protected DateTimeZone timeZone; protected HdfsEnvironment hdfsEnvironment; protected LocationService locationService; protected HiveMetadataFactory metadataFactory; protected HiveTransactionManager transactionManager; protected ExtendedHiveMetastore metastoreClient; protected ConnectorSplitManager splitManager; protected ConnectorPageSourceProvider pageSourceProvider; protected ConnectorPageSinkProvider pageSinkProvider; protected ExecutorService executor; @BeforeClass public void setupClass() { executor = newCachedThreadPool(daemonThreadsNamed("hive-%s")); } @AfterClass(alwaysRun = true) public void tearDown() { if (executor != null) { executor.shutdownNow(); executor = null; } } protected void setupHive(String connectorId, String databaseName, String timeZoneId) { clientId = connectorId; database = databaseName; tablePartitionFormat = new SchemaTableName(database, "presto_test_partition_format"); tableUnpartitioned = new SchemaTableName(database, "presto_test_unpartitioned"); tableOffline = new SchemaTableName(database, "presto_test_offline"); tableOfflinePartition = new SchemaTableName(database, "presto_test_offline_partition"); tableNotReadable = new SchemaTableName(database, "presto_test_not_readable"); view = new SchemaTableName(database, "presto_test_view"); invalidTable = new SchemaTableName(database, INVALID_TABLE); tableBucketedStringInt = new SchemaTableName(database, "presto_test_bucketed_by_string_int"); tableBucketedBigintBoolean = new SchemaTableName(database, "presto_test_bucketed_by_bigint_boolean"); tableBucketedDoubleFloat = new SchemaTableName(database, "presto_test_bucketed_by_double_float"); tablePartitionSchemaChange = new SchemaTableName(database, "presto_test_partition_schema_change"); tablePartitionSchemaChangeNonCanonical = new SchemaTableName(database, "presto_test_partition_schema_change_non_canonical"); tableBucketEvolution = new SchemaTableName(database, "presto_test_bucket_evolution"); invalidClientId = "hive"; invalidTableHandle = new HiveTableHandle(database, INVALID_TABLE); invalidTableLayoutHandle = new HiveTableLayoutHandle( invalidTable, ImmutableList.of(), ImmutableList.of(new HivePartition(invalidTable, "unknown", ImmutableMap.of())), TupleDomain.all(), TupleDomain.all(), Optional.empty(), Optional.empty()); dsColumn = new HiveColumnHandle("ds", HIVE_STRING, parseTypeSignature(StandardTypes.VARCHAR), -1, PARTITION_KEY, Optional.empty()); fileFormatColumn = new HiveColumnHandle("file_format", HIVE_STRING, parseTypeSignature(StandardTypes.VARCHAR), -1, PARTITION_KEY, Optional.empty()); dummyColumn = new HiveColumnHandle("dummy", HIVE_INT, parseTypeSignature(StandardTypes.INTEGER), -1, PARTITION_KEY, Optional.empty()); intColumn = new HiveColumnHandle("t_int", HIVE_INT, parseTypeSignature(StandardTypes.INTEGER), -1, PARTITION_KEY, Optional.empty()); invalidColumnHandle = new HiveColumnHandle(INVALID_COLUMN, HIVE_STRING, parseTypeSignature(StandardTypes.VARCHAR), 0, REGULAR, Optional.empty()); List<ColumnHandle> partitionColumns = ImmutableList.of(dsColumn, fileFormatColumn, dummyColumn); List<HivePartition> partitions = ImmutableList.<HivePartition>builder() .add(new HivePartition(tablePartitionFormat, "ds=2012-12-29/file_format=textfile/dummy=1", ImmutableMap.<ColumnHandle, NullableValue>builder() .put(dsColumn, NullableValue.of(createUnboundedVarcharType(), utf8Slice("2012-12-29"))) .put(fileFormatColumn, NullableValue.of(createUnboundedVarcharType(), utf8Slice("textfile"))) .put(dummyColumn, NullableValue.of(INTEGER, 1L)) .build())) .add(new HivePartition(tablePartitionFormat, "ds=2012-12-29/file_format=sequencefile/dummy=2", ImmutableMap.<ColumnHandle, NullableValue>builder() .put(dsColumn, NullableValue.of(createUnboundedVarcharType(), utf8Slice("2012-12-29"))) .put(fileFormatColumn, NullableValue.of(createUnboundedVarcharType(), utf8Slice("sequencefile"))) .put(dummyColumn, NullableValue.of(INTEGER, 2L)) .build())) .add(new HivePartition(tablePartitionFormat, "ds=2012-12-29/file_format=rctext/dummy=3", ImmutableMap.<ColumnHandle, NullableValue>builder() .put(dsColumn, NullableValue.of(createUnboundedVarcharType(), utf8Slice("2012-12-29"))) .put(fileFormatColumn, NullableValue.of(createUnboundedVarcharType(), utf8Slice("rctext"))) .put(dummyColumn, NullableValue.of(INTEGER, 3L)) .build())) .add(new HivePartition(tablePartitionFormat, "ds=2012-12-29/file_format=rcbinary/dummy=4", ImmutableMap.<ColumnHandle, NullableValue>builder() .put(dsColumn, NullableValue.of(createUnboundedVarcharType(), utf8Slice("2012-12-29"))) .put(fileFormatColumn, NullableValue.of(createUnboundedVarcharType(), utf8Slice("rcbinary"))) .put(dummyColumn, NullableValue.of(INTEGER, 4L)) .build())) .build(); partitionCount = partitions.size(); tupleDomain = TupleDomain.fromFixedValues(ImmutableMap.of(dsColumn, NullableValue.of(createUnboundedVarcharType(), utf8Slice("2012-12-29")))); tableLayout = new ConnectorTableLayout( new HiveTableLayoutHandle(tablePartitionFormat, partitionColumns, partitions, tupleDomain, tupleDomain, Optional.empty(), Optional.empty()), Optional.empty(), TupleDomain.withColumnDomains(ImmutableMap.of( dsColumn, Domain.create(ValueSet.ofRanges(Range.equal(createUnboundedVarcharType(), utf8Slice("2012-12-29"))), false), fileFormatColumn, Domain.create(ValueSet.ofRanges(Range.equal(createUnboundedVarcharType(), utf8Slice("textfile")), Range.equal(createUnboundedVarcharType(), utf8Slice("sequencefile")), Range.equal(createUnboundedVarcharType(), utf8Slice("rctext")), Range.equal(createUnboundedVarcharType(), utf8Slice("rcbinary"))), false), dummyColumn, Domain.create(ValueSet.ofRanges(Range.equal(INTEGER, 1L), Range.equal(INTEGER, 2L), Range.equal(INTEGER, 3L), Range.equal(INTEGER, 4L)), false))), Optional.empty(), Optional.empty(), Optional.of(new DiscretePredicates(partitionColumns, ImmutableList.of( TupleDomain.withColumnDomains(ImmutableMap.of( dsColumn, Domain.create(ValueSet.ofRanges(Range.equal(createUnboundedVarcharType(), utf8Slice("2012-12-29"))), false), fileFormatColumn, Domain.create(ValueSet.ofRanges(Range.equal(createUnboundedVarcharType(), utf8Slice("textfile"))), false), dummyColumn, Domain.create(ValueSet.ofRanges(Range.equal(INTEGER, 1L)), false))), TupleDomain.withColumnDomains(ImmutableMap.of( dsColumn, Domain.create(ValueSet.ofRanges(Range.equal(createUnboundedVarcharType(), utf8Slice("2012-12-29"))), false), fileFormatColumn, Domain.create(ValueSet.ofRanges(Range.equal(createUnboundedVarcharType(), utf8Slice("sequencefile"))), false), dummyColumn, Domain.create(ValueSet.ofRanges(Range.equal(INTEGER, 2L)), false))), TupleDomain.withColumnDomains(ImmutableMap.of( dsColumn, Domain.create(ValueSet.ofRanges(Range.equal(createUnboundedVarcharType(), utf8Slice("2012-12-29"))), false), fileFormatColumn, Domain.create(ValueSet.ofRanges(Range.equal(createUnboundedVarcharType(), utf8Slice("rctext"))), false), dummyColumn, Domain.create(ValueSet.ofRanges(Range.equal(INTEGER, 3L)), false))), TupleDomain.withColumnDomains(ImmutableMap.of( dsColumn, Domain.create(ValueSet.ofRanges(Range.equal(createUnboundedVarcharType(), utf8Slice("2012-12-29"))), false), fileFormatColumn, Domain.create(ValueSet.ofRanges(Range.equal(createUnboundedVarcharType(), utf8Slice("rcbinary"))), false), dummyColumn, Domain.create(ValueSet.ofRanges(Range.equal(INTEGER, 4L)), false)))))), ImmutableList.of()); List<HivePartition> unpartitionedPartitions = ImmutableList.of(new HivePartition(tableUnpartitioned)); unpartitionedTableLayout = new ConnectorTableLayout(new HiveTableLayoutHandle(tableUnpartitioned, ImmutableList.of(), unpartitionedPartitions, TupleDomain.all(), TupleDomain.all(), Optional.empty(), Optional.empty())); timeZone = DateTimeZone.forTimeZone(TimeZone.getTimeZone(timeZoneId)); } protected final void setup(String host, int port, String databaseName, String timeZone) { HiveClientConfig hiveClientConfig = getHiveClientConfig(); hiveClientConfig.setTimeZone(timeZone); String proxy = System.getProperty("hive.metastore.thrift.client.socks-proxy"); if (proxy != null) { hiveClientConfig.setMetastoreSocksProxy(HostAndPort.fromString(proxy)); } HiveCluster hiveCluster = new TestingHiveCluster(hiveClientConfig, host, port); ExtendedHiveMetastore metastore = new CachingHiveMetastore( new BridgingHiveMetastore(new ThriftHiveMetastore(hiveCluster)), executor, Duration.valueOf("1m"), Duration.valueOf("15s"), 10000); setup(databaseName, hiveClientConfig, metastore); } protected final void setup(String databaseName, HiveClientConfig hiveClientConfig, ExtendedHiveMetastore hiveMetastore) { HiveConnectorId connectorId = new HiveConnectorId("hive-test"); setupHive(connectorId.toString(), databaseName, hiveClientConfig.getTimeZone()); metastoreClient = hiveMetastore; HdfsConfiguration hdfsConfiguration = new HiveHdfsConfiguration(new HdfsConfigurationUpdater(hiveClientConfig)); hdfsEnvironment = new HdfsEnvironment(hdfsConfiguration, hiveClientConfig, new NoHdfsAuthentication()); locationService = new HiveLocationService(hdfsEnvironment); JsonCodec<PartitionUpdate> partitionUpdateCodec = JsonCodec.jsonCodec(PartitionUpdate.class); metadataFactory = new HiveMetadataFactory( metastoreClient, hdfsEnvironment, new HivePartitionManager(TYPE_MANAGER, hiveClientConfig), timeZone, 10, true, false, false, true, 1000, getHiveClientConfig().getMaxPartitionsPerScan(), TYPE_MANAGER, locationService, new TableParameterCodec(), partitionUpdateCodec, newFixedThreadPool(2), new HiveTypeTranslator(), TEST_SERVER_VERSION); transactionManager = new HiveTransactionManager(); splitManager = new HiveSplitManager( transactionHandle -> ((HiveMetadata) transactionManager.get(transactionHandle)).getMetastore(), new NamenodeStats(), hdfsEnvironment, new HadoopDirectoryLister(), directExecutor(), new HiveCoercionPolicy(TYPE_MANAGER), new CounterStat(), 100, hiveClientConfig.getMaxOutstandingSplitsSize(), hiveClientConfig.getMinPartitionBatchSize(), hiveClientConfig.getMaxPartitionBatchSize(), hiveClientConfig.getMaxInitialSplits(), hiveClientConfig.getSplitLoaderConcurrency(), false); pageSinkProvider = new HivePageSinkProvider( getDefaultHiveFileWriterFactories(hiveClientConfig), hdfsEnvironment, PAGE_SORTER, metastoreClient, new GroupByHashPageIndexerFactory(JOIN_COMPILER), TYPE_MANAGER, getHiveClientConfig(), locationService, partitionUpdateCodec, new TestingNodeManager("fake-environment"), new HiveEventClient(), new HiveSessionProperties(hiveClientConfig, new OrcFileWriterConfig()), new HiveWriterStats()); pageSourceProvider = new HivePageSourceProvider(hiveClientConfig, hdfsEnvironment, getDefaultHiveRecordCursorProvider(hiveClientConfig), getDefaultHiveDataStreamFactories(hiveClientConfig), TYPE_MANAGER); } /** * Allow subclass to change default configuration. */ protected HiveClientConfig getHiveClientConfig() { return new HiveClientConfig(); } protected ConnectorSession newSession() { return new TestingConnectorSession(new HiveSessionProperties(getHiveClientConfig(), new OrcFileWriterConfig()).getSessionProperties()); } protected Transaction newTransaction() { return new HiveTransaction(transactionManager, metadataFactory.create()); } interface Transaction extends AutoCloseable { ConnectorMetadata getMetadata(); SemiTransactionalHiveMetastore getMetastore(String schema); ConnectorTransactionHandle getTransactionHandle(); void commit(); void rollback(); @Override void close(); } static class HiveTransaction implements Transaction { private final HiveTransactionManager transactionManager; private final ConnectorTransactionHandle transactionHandle; private boolean closed; public HiveTransaction(HiveTransactionManager transactionManager, HiveMetadata hiveMetadata) { this.transactionManager = requireNonNull(transactionManager, "transactionManager is null"); this.transactionHandle = new HiveTransactionHandle(); transactionManager.put(transactionHandle, hiveMetadata); getMetastore().testOnlyThrowOnCleanupFailures(); } @Override public ConnectorMetadata getMetadata() { return transactionManager.get(transactionHandle); } @Override public SemiTransactionalHiveMetastore getMetastore(String schema) { return getMetastore(); } private SemiTransactionalHiveMetastore getMetastore() { return ((HiveMetadata) transactionManager.get(transactionHandle)).getMetastore(); } @Override public ConnectorTransactionHandle getTransactionHandle() { return transactionHandle; } @Override public void commit() { checkState(!closed); closed = true; HiveMetadata metadata = (HiveMetadata) transactionManager.remove(transactionHandle); checkArgument(metadata != null, "no such transaction: %s", transactionHandle); metadata.commit(); } @Override public void rollback() { checkState(!closed); closed = true; HiveMetadata metadata = (HiveMetadata) transactionManager.remove(transactionHandle); checkArgument(metadata != null, "no such transaction: %s", transactionHandle); metadata.rollback(); } @Override public void close() { if (!closed) { try { getMetastore().testOnlyCheckIsReadOnly(); // transactions in this test with writes in it must explicitly commit or rollback } finally { rollback(); } } } } @Test public void testGetDatabaseNames() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); List<String> databases = metadata.listSchemaNames(newSession()); assertTrue(databases.contains(database)); } } @Test public void testGetTableNames() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); List<SchemaTableName> tables = metadata.listTables(newSession(), database); assertTrue(tables.contains(tablePartitionFormat)); assertTrue(tables.contains(tableUnpartitioned)); } } @Test public void testGetAllTableNames() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); List<SchemaTableName> tables = metadata.listTables(newSession(), Optional.empty()); assertTrue(tables.contains(tablePartitionFormat)); assertTrue(tables.contains(tableUnpartitioned)); } } @Test public void testGetAllTableColumns() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); Map<SchemaTableName, List<ColumnMetadata>> allColumns = metadata.listTableColumns(newSession(), new SchemaTablePrefix()); assertTrue(allColumns.containsKey(tablePartitionFormat)); assertTrue(allColumns.containsKey(tableUnpartitioned)); } } @Test public void testGetAllTableColumnsInSchema() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); Map<SchemaTableName, List<ColumnMetadata>> allColumns = metadata.listTableColumns(newSession(), new SchemaTablePrefix(database)); assertTrue(allColumns.containsKey(tablePartitionFormat)); assertTrue(allColumns.containsKey(tableUnpartitioned)); } } @Test public void testListUnknownSchema() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); assertNull(metadata.getTableHandle(session, new SchemaTableName(INVALID_DATABASE, INVALID_TABLE))); assertEquals(metadata.listTables(session, INVALID_DATABASE), ImmutableList.of()); assertEquals(metadata.listTableColumns(session, new SchemaTablePrefix(INVALID_DATABASE, INVALID_TABLE)), ImmutableMap.of()); assertEquals(metadata.listViews(session, INVALID_DATABASE), ImmutableList.of()); assertEquals(metadata.getViews(session, new SchemaTablePrefix(INVALID_DATABASE, INVALID_TABLE)), ImmutableMap.of()); } } @Test public void testGetPartitions() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tablePartitionFormat); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(newSession(), tableHandle, Constraint.alwaysTrue(), Optional.empty()); assertExpectedTableLayout(getOnlyElement(tableLayoutResults).getTableLayout(), tableLayout); } } @Test public void testGetPartitionsWithBindings() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tablePartitionFormat); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(newSession(), tableHandle, new Constraint<>(TupleDomain.withColumnDomains(ImmutableMap.of(intColumn, Domain.singleValue(BIGINT, 5L)))), Optional.empty()); assertExpectedTableLayout(getOnlyElement(tableLayoutResults).getTableLayout(), tableLayout); } } @Test(expectedExceptions = TableNotFoundException.class) public void testGetPartitionsException() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); metadata.getTableLayouts(newSession(), invalidTableHandle, Constraint.alwaysTrue(), Optional.empty()); } } @Test public void testGetPartitionNames() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tablePartitionFormat); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(newSession(), tableHandle, Constraint.alwaysTrue(), Optional.empty()); assertExpectedTableLayout(getOnlyElement(tableLayoutResults).getTableLayout(), tableLayout); } } @Test public void testMismatchSchemaTable() throws Exception { for (HiveStorageFormat storageFormat : createTableFormats) { // TODO: fix coercion for JSON if (storageFormat == JSON) { continue; } SchemaTableName temporaryMismatchSchemaTable = temporaryTable("mismatch_schema"); try { doTestMismatchSchemaTable( temporaryMismatchSchemaTable, storageFormat, MISMATCH_SCHEMA_TABLE_BEFORE, MISMATCH_SCHEMA_TABLE_DATA_BEFORE, MISMATCH_SCHEMA_TABLE_AFTER, MISMATCH_SCHEMA_TABLE_DATA_AFTER); } finally { dropTable(temporaryMismatchSchemaTable); } } } protected void doTestMismatchSchemaTable( SchemaTableName schemaTableName, HiveStorageFormat storageFormat, List<ColumnMetadata> tableBefore, MaterializedResult dataBefore, List<ColumnMetadata> tableAfter, MaterializedResult dataAfter) throws Exception { String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); doCreateEmptyTable(schemaTableName, storageFormat, tableBefore); // insert the data try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, schemaTableName); ConnectorInsertTableHandle insertTableHandle = metadata.beginInsert(session, tableHandle); ConnectorPageSink sink = pageSinkProvider.createPageSink(transaction.getTransactionHandle(), session, insertTableHandle); sink.appendPage(dataBefore.toPage()); Collection<Slice> fragments = getFutureValue(sink.finish()); metadata.finishInsert(session, insertTableHandle, fragments); transaction.commit(); } // load the table and verify the data try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, schemaTableName); List<ColumnHandle> columnHandles = metadata.getColumnHandles(session, tableHandle).values().stream() .filter(columnHandle -> !((HiveColumnHandle) columnHandle).isHidden()) .collect(toList()); MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.empty()); assertEqualsIgnoreOrder(result.getMaterializedRows(), dataBefore.getMaterializedRows()); transaction.commit(); } // alter the table schema try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); PrincipalPrivileges principalPrivileges = testingPrincipalPrivilege(session.getUser()); Table oldTable = transaction.getMetastore(schemaName).getTable(schemaName, tableName).get(); HiveTypeTranslator hiveTypeTranslator = new HiveTypeTranslator(); List<Column> dataColumns = tableAfter.stream() .filter(columnMetadata -> !columnMetadata.getName().equals("ds")) .map(columnMetadata -> new Column(columnMetadata.getName(), toHiveType(hiveTypeTranslator, columnMetadata.getType()), Optional.empty())) .collect(toList()); Table.Builder newTable = Table.builder(oldTable) .setDataColumns(dataColumns); transaction.getMetastore(schemaName).replaceView(schemaName, tableName, newTable.build(), principalPrivileges); transaction.commit(); } // load the altered table and verify the data try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, schemaTableName); List<ColumnHandle> columnHandles = metadata.getColumnHandles(session, tableHandle).values().stream() .filter(columnHandle -> !((HiveColumnHandle) columnHandle).isHidden()) .collect(toList()); MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.empty()); assertEqualsIgnoreOrder(result.getMaterializedRows(), dataAfter.getMaterializedRows()); transaction.commit(); } // insertions to the partitions with type mismatches should fail try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, schemaTableName); ConnectorInsertTableHandle insertTableHandle = metadata.beginInsert(session, tableHandle); ConnectorPageSink sink = pageSinkProvider.createPageSink(transaction.getTransactionHandle(), session, insertTableHandle); sink.appendPage(dataAfter.toPage()); Collection<Slice> fragments = getFutureValue(sink.finish()); metadata.finishInsert(session, insertTableHandle, fragments); transaction.commit(); fail("expected exception"); } catch (PrestoException e) { // expected assertEquals(e.getErrorCode(), HIVE_PARTITION_SCHEMA_MISMATCH.toErrorCode()); } } protected void assertExpectedTableLayout(ConnectorTableLayout actualTableLayout, ConnectorTableLayout expectedTableLayout) { assertExpectedTableLayoutHandle(actualTableLayout.getHandle(), expectedTableLayout.getHandle()); assertEquals(actualTableLayout.getPredicate(), expectedTableLayout.getPredicate()); assertEquals(actualTableLayout.getDiscretePredicates().isPresent(), expectedTableLayout.getDiscretePredicates().isPresent()); actualTableLayout.getDiscretePredicates().ifPresent(actual -> { DiscretePredicates expected = expectedTableLayout.getDiscretePredicates().get(); assertEquals(actual.getColumns(), expected.getColumns()); assertEqualsIgnoreOrder(actual.getPredicates(), expected.getPredicates()); }); assertEquals(actualTableLayout.getStreamPartitioningColumns(), expectedTableLayout.getStreamPartitioningColumns()); assertEquals(actualTableLayout.getLocalProperties(), expectedTableLayout.getLocalProperties()); } protected void assertExpectedTableLayoutHandle(ConnectorTableLayoutHandle actualTableLayoutHandle, ConnectorTableLayoutHandle expectedTableLayoutHandle) { assertInstanceOf(actualTableLayoutHandle, HiveTableLayoutHandle.class); assertInstanceOf(expectedTableLayoutHandle, HiveTableLayoutHandle.class); HiveTableLayoutHandle actual = (HiveTableLayoutHandle) actualTableLayoutHandle; HiveTableLayoutHandle expected = (HiveTableLayoutHandle) expectedTableLayoutHandle; assertExpectedPartitions(actual.getPartitions().get(), expected.getPartitions().get()); } protected void assertExpectedPartitions(List<HivePartition> actualPartitions, Iterable<HivePartition> expectedPartitions) { Map<String, ?> actualById = uniqueIndex(actualPartitions, HivePartition::getPartitionId); for (Object expected : expectedPartitions) { assertInstanceOf(expected, HivePartition.class); HivePartition expectedPartition = (HivePartition) expected; Object actual = actualById.get(expectedPartition.getPartitionId()); assertEquals(actual, expected); assertInstanceOf(actual, HivePartition.class); HivePartition actualPartition = (HivePartition) actual; assertNotNull(actualPartition, "partition " + expectedPartition.getPartitionId()); assertEquals(actualPartition.getPartitionId(), expectedPartition.getPartitionId()); assertEquals(actualPartition.getKeys(), expectedPartition.getKeys()); assertEquals(actualPartition.getTableName(), expectedPartition.getTableName()); } } @Test public void testGetPartitionNamesUnpartitioned() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableUnpartitioned); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(newSession(), tableHandle, Constraint.alwaysTrue(), Optional.empty()); assertEquals(getAllPartitions(getOnlyElement(tableLayoutResults).getTableLayout().getHandle()).size(), 1); assertExpectedTableLayout(getOnlyElement(tableLayoutResults).getTableLayout(), unpartitionedTableLayout); } } @Test(expectedExceptions = TableNotFoundException.class) public void testGetPartitionNamesException() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); metadata.getTableLayouts(newSession(), invalidTableHandle, Constraint.alwaysTrue(), Optional.empty()); } } @SuppressWarnings({"ValueOfIncrementOrDecrementUsed", "UnusedAssignment"}) @Test public void testGetTableSchemaPartitionFormat() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(newSession(), getTableHandle(metadata, tablePartitionFormat)); Map<String, ColumnMetadata> map = uniqueIndex(tableMetadata.getColumns(), ColumnMetadata::getName); assertPrimitiveField(map, "t_string", createUnboundedVarcharType(), false); assertPrimitiveField(map, "t_tinyint", TINYINT, false); assertPrimitiveField(map, "t_smallint", SMALLINT, false); assertPrimitiveField(map, "t_int", INTEGER, false); assertPrimitiveField(map, "t_bigint", BIGINT, false); assertPrimitiveField(map, "t_float", REAL, false); assertPrimitiveField(map, "t_double", DOUBLE, false); assertPrimitiveField(map, "t_boolean", BOOLEAN, false); assertPrimitiveField(map, "ds", createUnboundedVarcharType(), true); assertPrimitiveField(map, "file_format", createUnboundedVarcharType(), true); assertPrimitiveField(map, "dummy", INTEGER, true); } } @Test public void testGetTableSchemaUnpartitioned() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableUnpartitioned); ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(newSession(), tableHandle); Map<String, ColumnMetadata> map = uniqueIndex(tableMetadata.getColumns(), ColumnMetadata::getName); assertPrimitiveField(map, "t_string", createUnboundedVarcharType(), false); assertPrimitiveField(map, "t_tinyint", TINYINT, false); } } @Test public void testGetTableSchemaOffline() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); Map<SchemaTableName, List<ColumnMetadata>> columns = metadata.listTableColumns(newSession(), tableOffline.toSchemaTablePrefix()); assertEquals(columns.size(), 1); Map<String, ColumnMetadata> map = uniqueIndex(getOnlyElement(columns.values()), ColumnMetadata::getName); assertPrimitiveField(map, "t_string", createUnboundedVarcharType(), false); } } @Test public void testGetTableSchemaOfflinePartition() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableOfflinePartition); ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(newSession(), tableHandle); Map<String, ColumnMetadata> map = uniqueIndex(tableMetadata.getColumns(), ColumnMetadata::getName); assertPrimitiveField(map, "t_string", createUnboundedVarcharType(), false); } } @Test public void testGetTableSchemaNotReadablePartition() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableNotReadable); ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(newSession(), tableHandle); Map<String, ColumnMetadata> map = uniqueIndex(tableMetadata.getColumns(), ColumnMetadata::getName); assertPrimitiveField(map, "t_string", createUnboundedVarcharType(), false); } } @Test public void testGetTableSchemaException() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); assertNull(metadata.getTableHandle(newSession(), invalidTable)); } } @Test public void testGetTableStatsBucketedStringInt() { assertTableStatsComputed( tableBucketedStringInt, ImmutableSet.of( "t_bigint", "t_boolean", "t_double", "t_float", "t_int", "t_smallint", "t_string", "t_tinyint", "ds")); } @Test public void testGetTableStatsUnpartitioned() { assertTableStatsComputed( tableUnpartitioned, ImmutableSet.of("t_string", "t_tinyint")); } private void assertTableStatsComputed( SchemaTableName tableName, Set<String> expectedColumnStatsColumns) { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); TableStatistics tableStatistics = metadata.getTableStatistics(session, tableHandle, Constraint.alwaysTrue()); assertFalse(tableStatistics.getRowCount().isValueUnknown(), "row count is unknown"); Map<String, ColumnStatistics> columnsStatistics = tableStatistics .getColumnStatistics() .entrySet() .stream() .collect( toImmutableMap( entry -> ((HiveColumnHandle) entry.getKey()).getName(), Map.Entry::getValue)); assertEquals(columnsStatistics.keySet(), expectedColumnStatsColumns, "columns with statistics"); columnsStatistics.forEach((columnName, columnStatistics) -> { assertFalse( columnStatistics.getNullsFraction().isValueUnknown(), "unknown nulls fraction for " + columnName); RangeColumnStatistics rangeColumnStatistics = columnStatistics.getOnlyRangeColumnStatistics(); assertFalse( rangeColumnStatistics.getDistinctValuesCount().isValueUnknown(), "unknown range distinct values count for " + columnName); assertFalse( rangeColumnStatistics.getFraction().isValueUnknown(), "unknown range non-null fraction for " + columnName); }); } } @Test public void testGetPartitionSplitsBatch() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tablePartitionFormat); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(session, tableHandle, Constraint.alwaysTrue(), Optional.empty()); ConnectorSplitSource splitSource = splitManager.getSplits(transaction.getTransactionHandle(), session, getOnlyElement(tableLayoutResults).getTableLayout().getHandle(), UNGROUPED_SCHEDULING); assertEquals(getSplitCount(splitSource), partitionCount); } } @Test public void testGetPartitionSplitsBatchUnpartitioned() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableUnpartitioned); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(session, tableHandle, Constraint.alwaysTrue(), Optional.empty()); ConnectorSplitSource splitSource = splitManager.getSplits(transaction.getTransactionHandle(), session, getOnlyElement(tableLayoutResults).getTableLayout().getHandle(), UNGROUPED_SCHEDULING); assertEquals(getSplitCount(splitSource), 1); } } @Test(expectedExceptions = TableNotFoundException.class) public void testGetPartitionSplitsBatchInvalidTable() { try (Transaction transaction = newTransaction()) { splitManager.getSplits(transaction.getTransactionHandle(), newSession(), invalidTableLayoutHandle, UNGROUPED_SCHEDULING); } } @Test public void testGetPartitionTableOffline() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); try { getTableHandle(metadata, tableOffline); fail("expected TableOfflineException"); } catch (TableOfflineException e) { assertEquals(e.getTableName(), tableOffline); } } } @Test public void testGetPartitionSplitsTableOfflinePartition() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableOfflinePartition); assertNotNull(tableHandle); ColumnHandle dsColumn = metadata.getColumnHandles(session, tableHandle).get("ds"); assertNotNull(dsColumn); Domain domain = Domain.singleValue(createUnboundedVarcharType(), utf8Slice("2012-12-30")); TupleDomain<ColumnHandle> tupleDomain = TupleDomain.withColumnDomains(ImmutableMap.of(dsColumn, domain)); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(session, tableHandle, new Constraint<>(tupleDomain), Optional.empty()); try { getSplitCount(splitManager.getSplits(transaction.getTransactionHandle(), session, getOnlyElement(tableLayoutResults).getTableLayout().getHandle(), UNGROUPED_SCHEDULING)); fail("Expected PartitionOfflineException"); } catch (PartitionOfflineException e) { assertEquals(e.getTableName(), tableOfflinePartition); assertEquals(e.getPartition(), "ds=2012-12-30"); } } } @Test public void testGetPartitionSplitsTableNotReadablePartition() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableNotReadable); assertNotNull(tableHandle); ColumnHandle dsColumn = metadata.getColumnHandles(session, tableHandle).get("ds"); assertNotNull(dsColumn); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(session, tableHandle, Constraint.alwaysTrue(), Optional.empty()); try { getSplitCount(splitManager.getSplits(transaction.getTransactionHandle(), session, getOnlyElement(tableLayoutResults).getTableLayout().getHandle(), UNGROUPED_SCHEDULING)); fail("Expected HiveNotReadableException"); } catch (HiveNotReadableException e) { assertThat(e).hasMessageMatching("Table '.*\\.presto_test_not_readable' is not readable: reason for not readable"); assertEquals(e.getTableName(), tableNotReadable); assertEquals(e.getPartition(), Optional.empty()); } } } @Test public void testBucketedTableStringInt() throws Exception { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableBucketedStringInt); List<ColumnHandle> columnHandles = ImmutableList.copyOf(metadata.getColumnHandles(session, tableHandle).values()); Map<String, Integer> columnIndex = indexColumns(columnHandles); assertTableIsBucketed(tableHandle); String testString = "test"; Integer testInt = 13; Short testSmallint = 12; // Reverse the order of bindings as compared to bucketing order ImmutableMap<ColumnHandle, NullableValue> bindings = ImmutableMap.<ColumnHandle, NullableValue>builder() .put(columnHandles.get(columnIndex.get("t_int")), NullableValue.of(INTEGER, (long) testInt)) .put(columnHandles.get(columnIndex.get("t_string")), NullableValue.of(createUnboundedVarcharType(), utf8Slice(testString))) .put(columnHandles.get(columnIndex.get("t_smallint")), NullableValue.of(SMALLINT, (long) testSmallint)) .build(); MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.fromFixedValues(bindings), OptionalInt.of(1), Optional.empty()); boolean rowFound = false; for (MaterializedRow row : result) { if (testString.equals(row.getField(columnIndex.get("t_string"))) && testInt.equals(row.getField(columnIndex.get("t_int"))) && testSmallint.equals(row.getField(columnIndex.get("t_smallint")))) { rowFound = true; } } assertTrue(rowFound); } } @SuppressWarnings("ConstantConditions") @Test public void testBucketedTableBigintBoolean() throws Exception { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableBucketedBigintBoolean); List<ColumnHandle> columnHandles = ImmutableList.copyOf(metadata.getColumnHandles(session, tableHandle).values()); Map<String, Integer> columnIndex = indexColumns(columnHandles); assertTableIsBucketed(tableHandle); String testString = "test"; Long testBigint = 89L; Boolean testBoolean = true; ImmutableMap<ColumnHandle, NullableValue> bindings = ImmutableMap.<ColumnHandle, NullableValue>builder() .put(columnHandles.get(columnIndex.get("t_string")), NullableValue.of(createUnboundedVarcharType(), utf8Slice(testString))) .put(columnHandles.get(columnIndex.get("t_bigint")), NullableValue.of(BIGINT, testBigint)) .put(columnHandles.get(columnIndex.get("t_boolean")), NullableValue.of(BOOLEAN, testBoolean)) .build(); MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.fromFixedValues(bindings), OptionalInt.of(1), Optional.empty()); boolean rowFound = false; for (MaterializedRow row : result) { if (testString.equals(row.getField(columnIndex.get("t_string"))) && testBigint.equals(row.getField(columnIndex.get("t_bigint"))) && testBoolean.equals(row.getField(columnIndex.get("t_boolean")))) { rowFound = true; break; } } assertTrue(rowFound); } } @Test public void testBucketedTableDoubleFloat() throws Exception { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableBucketedDoubleFloat); List<ColumnHandle> columnHandles = ImmutableList.copyOf(metadata.getColumnHandles(session, tableHandle).values()); Map<String, Integer> columnIndex = indexColumns(columnHandles); assertTableIsBucketed(tableHandle); ImmutableMap<ColumnHandle, NullableValue> bindings = ImmutableMap.<ColumnHandle, NullableValue>builder() .put(columnHandles.get(columnIndex.get("t_float")), NullableValue.of(REAL, (long) floatToRawIntBits(87.1f))) .put(columnHandles.get(columnIndex.get("t_double")), NullableValue.of(DOUBLE, 88.2)) .build(); // floats and doubles are not supported, so we should see all splits MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.fromFixedValues(bindings), OptionalInt.of(32), Optional.empty()); assertEquals(result.getRowCount(), 100); } } @Test public void testBucketedTableEvolution() throws Exception { for (HiveStorageFormat storageFormat : createTableFormats) { SchemaTableName temporaryBucketEvolutionTable = temporaryTable("bucket_evolution"); try { doTestBucketedTableEvolution(storageFormat, temporaryBucketEvolutionTable); } finally { dropTable(temporaryBucketEvolutionTable); } } } private void doTestBucketedTableEvolution(HiveStorageFormat storageFormat, SchemaTableName tableName) throws Exception { int rowCount = 100; // // Produce a table with 8 buckets. // The table has 3 partitions of 3 different bucket count (4, 8, 16). createEmptyTable( tableName, storageFormat, ImmutableList.of( new Column("id", HIVE_LONG, Optional.empty()), new Column("name", HIVE_STRING, Optional.empty())), ImmutableList.of(new Column("pk", HIVE_STRING, Optional.empty())), Optional.of(new HiveBucketProperty(ImmutableList.of("id"), 4, ImmutableList.of()))); // write a 4-bucket partition MaterializedResult.Builder bucket4Builder = MaterializedResult.resultBuilder(SESSION, BIGINT, VARCHAR, VARCHAR); IntStream.range(0, rowCount).forEach(i -> bucket4Builder.row((long) i, String.valueOf(i), "four")); insertData(tableName, bucket4Builder.build()); // write a 16-bucket partition alterBucketProperty(tableName, Optional.of(new HiveBucketProperty(ImmutableList.of("id"), 16, ImmutableList.of()))); MaterializedResult.Builder bucket16Builder = MaterializedResult.resultBuilder(SESSION, BIGINT, VARCHAR, VARCHAR); IntStream.range(0, rowCount).forEach(i -> bucket16Builder.row((long) i, String.valueOf(i), "sixteen")); insertData(tableName, bucket16Builder.build()); // write an 8-bucket partition alterBucketProperty(tableName, Optional.of(new HiveBucketProperty(ImmutableList.of("id"), 8, ImmutableList.of()))); MaterializedResult.Builder bucket8Builder = MaterializedResult.resultBuilder(SESSION, BIGINT, VARCHAR, VARCHAR); IntStream.range(0, rowCount).forEach(i -> bucket8Builder.row((long) i, String.valueOf(i), "eight")); insertData(tableName, bucket8Builder.build()); try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); // read entire table List<ColumnHandle> columnHandles = ImmutableList.<ColumnHandle>builder() .addAll(metadata.getColumnHandles(session, tableHandle).values()) .build(); MaterializedResult result = readTable( transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.empty()); assertBucketTableEvolutionResult(result, columnHandles, ImmutableSet.of(0, 1, 2, 3, 4, 5, 6, 7), rowCount); // read single bucket (table/logical bucket) result = readTable( transaction, tableHandle, columnHandles, session, TupleDomain.fromFixedValues(ImmutableMap.of(bucketColumnHandle(), NullableValue.of(INTEGER, 6L))), OptionalInt.empty(), Optional.empty()); assertBucketTableEvolutionResult(result, columnHandles, ImmutableSet.of(6), rowCount); // read single bucket, without selecting the bucketing column (i.e. id column) columnHandles = ImmutableList.<ColumnHandle>builder() .addAll(metadata.getColumnHandles(session, tableHandle).values().stream() .filter(columnHandle -> !"id".equals(((HiveColumnHandle) columnHandle).getName())) .collect(toImmutableList())) .build(); result = readTable( transaction, tableHandle, columnHandles, session, TupleDomain.fromFixedValues(ImmutableMap.of(bucketColumnHandle(), NullableValue.of(INTEGER, 6L))), OptionalInt.empty(), Optional.empty()); assertBucketTableEvolutionResult(result, columnHandles, ImmutableSet.of(6), rowCount); } } private static void assertBucketTableEvolutionResult(MaterializedResult result, List<ColumnHandle> columnHandles, Set<Integer> bucketIds, int rowCount) { // Assert that only elements in the specified bucket shows up, and each element shows up 3 times. int bucketCount = 8; Set<Long> expectedIds = LongStream.range(0, rowCount) .filter(x -> bucketIds.contains(toIntExact(x % bucketCount))) .boxed() .collect(toImmutableSet()); // assert that content from all three buckets are the same Map<String, Integer> columnIndex = indexColumns(columnHandles); OptionalInt idColumnIndex = columnIndex.containsKey("id") ? OptionalInt.of(columnIndex.get("id")) : OptionalInt.empty(); int nameColumnIndex = columnIndex.get("name"); int bucketColumnIndex = columnIndex.get(BUCKET_COLUMN_NAME); Map<Long, Integer> idCount = new HashMap<>(); for (MaterializedRow row : result.getMaterializedRows()) { String name = (String) row.getField(nameColumnIndex); int bucket = (int) row.getField(bucketColumnIndex); idCount.compute(Long.parseLong(name), (key, oldValue) -> oldValue == null ? 1 : oldValue + 1); assertEquals(bucket, Integer.parseInt(name) % bucketCount); if (idColumnIndex.isPresent()) { long id = (long) row.getField(idColumnIndex.getAsInt()); assertEquals(Integer.parseInt(name), id); } } assertEquals( (int) idCount.values().stream() .distinct() .collect(onlyElement()), 3); assertEquals(idCount.keySet(), expectedIds); } private void assertTableIsBucketed(ConnectorTableHandle tableHandle) { // the bucketed test tables should have exactly 32 splits List<ConnectorSplit> splits = getAllSplits(tableHandle, TupleDomain.all()); assertEquals(splits.size(), 32); // verify all paths are unique Set<String> paths = new HashSet<>(); for (ConnectorSplit split : splits) { assertTrue(paths.add(((HiveSplit) split).getPath())); } } @Test public void testGetRecords() throws Exception { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tablePartitionFormat); ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(session, tableHandle); List<ColumnHandle> columnHandles = ImmutableList.copyOf(metadata.getColumnHandles(session, tableHandle).values()); Map<String, Integer> columnIndex = indexColumns(columnHandles); List<ConnectorSplit> splits = getAllSplits(tableHandle, TupleDomain.all()); assertEquals(splits.size(), partitionCount); for (ConnectorSplit split : splits) { HiveSplit hiveSplit = (HiveSplit) split; List<HivePartitionKey> partitionKeys = hiveSplit.getPartitionKeys(); String ds = partitionKeys.get(0).getValue(); String fileFormat = partitionKeys.get(1).getValue(); HiveStorageFormat fileType = HiveStorageFormat.valueOf(fileFormat.toUpperCase()); int dummyPartition = Integer.parseInt(partitionKeys.get(2).getValue()); long rowNumber = 0; long completedBytes = 0; try (ConnectorPageSource pageSource = pageSourceProvider.createPageSource(transaction.getTransactionHandle(), session, hiveSplit, columnHandles)) { MaterializedResult result = materializeSourceDataStream(session, pageSource, getTypes(columnHandles)); assertPageSourceType(pageSource, fileType); for (MaterializedRow row : result) { try { assertValueTypes(row, tableMetadata.getColumns()); } catch (RuntimeException e) { throw new RuntimeException("row " + rowNumber, e); } rowNumber++; Object value; value = row.getField(columnIndex.get("t_string")); if (rowNumber % 19 == 0) { assertNull(value); } else if (rowNumber % 19 == 1) { assertEquals(value, ""); } else { assertEquals(value, "test"); } assertEquals(row.getField(columnIndex.get("t_tinyint")), (byte) (1 + rowNumber)); assertEquals(row.getField(columnIndex.get("t_smallint")), (short) (2 + rowNumber)); assertEquals(row.getField(columnIndex.get("t_int")), 3 + (int) rowNumber); if (rowNumber % 13 == 0) { assertNull(row.getField(columnIndex.get("t_bigint"))); } else { assertEquals(row.getField(columnIndex.get("t_bigint")), 4 + rowNumber); } assertEquals((Float) row.getField(columnIndex.get("t_float")), 5.1f + rowNumber, 0.001); assertEquals(row.getField(columnIndex.get("t_double")), 6.2 + rowNumber); if (rowNumber % 3 == 2) { assertNull(row.getField(columnIndex.get("t_boolean"))); } else { assertEquals(row.getField(columnIndex.get("t_boolean")), rowNumber % 3 != 0); } assertEquals(row.getField(columnIndex.get("ds")), ds); assertEquals(row.getField(columnIndex.get("file_format")), fileFormat); assertEquals(row.getField(columnIndex.get("dummy")), dummyPartition); long newCompletedBytes = pageSource.getCompletedBytes(); assertTrue(newCompletedBytes >= completedBytes); assertTrue(newCompletedBytes <= hiveSplit.getLength()); completedBytes = newCompletedBytes; } assertTrue(completedBytes <= hiveSplit.getLength()); assertEquals(rowNumber, 100); } } } } @Test public void testGetPartialRecords() throws Exception { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tablePartitionFormat); List<ColumnHandle> columnHandles = ImmutableList.copyOf(metadata.getColumnHandles(session, tableHandle).values()); Map<String, Integer> columnIndex = indexColumns(columnHandles); List<ConnectorSplit> splits = getAllSplits(tableHandle, TupleDomain.all()); assertEquals(splits.size(), partitionCount); for (ConnectorSplit split : splits) { HiveSplit hiveSplit = (HiveSplit) split; List<HivePartitionKey> partitionKeys = hiveSplit.getPartitionKeys(); String ds = partitionKeys.get(0).getValue(); String fileFormat = partitionKeys.get(1).getValue(); HiveStorageFormat fileType = HiveStorageFormat.valueOf(fileFormat.toUpperCase()); int dummyPartition = Integer.parseInt(partitionKeys.get(2).getValue()); long rowNumber = 0; try (ConnectorPageSource pageSource = pageSourceProvider.createPageSource(transaction.getTransactionHandle(), session, hiveSplit, columnHandles)) { assertPageSourceType(pageSource, fileType); MaterializedResult result = materializeSourceDataStream(session, pageSource, getTypes(columnHandles)); for (MaterializedRow row : result) { rowNumber++; assertEquals(row.getField(columnIndex.get("t_double")), 6.2 + rowNumber); assertEquals(row.getField(columnIndex.get("ds")), ds); assertEquals(row.getField(columnIndex.get("file_format")), fileFormat); assertEquals(row.getField(columnIndex.get("dummy")), dummyPartition); } } assertEquals(rowNumber, 100); } } } @Test public void testGetRecordsUnpartitioned() throws Exception { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableUnpartitioned); List<ColumnHandle> columnHandles = ImmutableList.copyOf(metadata.getColumnHandles(session, tableHandle).values()); Map<String, Integer> columnIndex = indexColumns(columnHandles); List<ConnectorSplit> splits = getAllSplits(tableHandle, TupleDomain.all()); assertEquals(splits.size(), 1); for (ConnectorSplit split : splits) { HiveSplit hiveSplit = (HiveSplit) split; assertEquals(hiveSplit.getPartitionKeys(), ImmutableList.of()); long rowNumber = 0; try (ConnectorPageSource pageSource = pageSourceProvider.createPageSource(transaction.getTransactionHandle(), session, split, columnHandles)) { assertPageSourceType(pageSource, TEXTFILE); MaterializedResult result = materializeSourceDataStream(session, pageSource, getTypes(columnHandles)); for (MaterializedRow row : result) { rowNumber++; if (rowNumber % 19 == 0) { assertNull(row.getField(columnIndex.get("t_string"))); } else if (rowNumber % 19 == 1) { assertEquals(row.getField(columnIndex.get("t_string")), ""); } else { assertEquals(row.getField(columnIndex.get("t_string")), "unpartitioned"); } assertEquals(row.getField(columnIndex.get("t_tinyint")), (byte) (1 + rowNumber)); } } assertEquals(rowNumber, 100); } } } @Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = ".*" + INVALID_COLUMN + ".*") public void testGetRecordsInvalidColumn() throws Exception { try (Transaction transaction = newTransaction()) { ConnectorMetadata connectorMetadata = transaction.getMetadata(); ConnectorTableHandle table = getTableHandle(connectorMetadata, tableUnpartitioned); readTable(transaction, table, ImmutableList.of(invalidColumnHandle), newSession(), TupleDomain.all(), OptionalInt.empty(), Optional.empty()); } } @Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = ".*The column 't_data' in table '.*\\.presto_test_partition_schema_change' is declared as type 'double', but partition 'ds=2012-12-29' declared column 't_data' as type 'string'.") public void testPartitionSchemaMismatch() throws Exception { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle table = getTableHandle(metadata, tablePartitionSchemaChange); readTable(transaction, table, ImmutableList.of(dsColumn), newSession(), TupleDomain.all(), OptionalInt.empty(), Optional.empty()); } } // TODO coercion of non-canonical values should be supported @Test(enabled = false) public void testPartitionSchemaNonCanonical() throws Exception { try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle table = getTableHandle(metadata, tablePartitionSchemaChangeNonCanonical); ColumnHandle column = metadata.getColumnHandles(session, table).get("t_boolean"); assertNotNull(column); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(session, table, new Constraint<>(TupleDomain.fromFixedValues(ImmutableMap.of(column, NullableValue.of(BOOLEAN, false)))), Optional.empty()); ConnectorTableLayoutHandle layoutHandle = getOnlyElement(tableLayoutResults).getTableLayout().getHandle(); assertEquals(getAllPartitions(layoutHandle).size(), 1); assertEquals(getPartitionId(getAllPartitions(layoutHandle).get(0)), "t_boolean=0"); ConnectorSplitSource splitSource = splitManager.getSplits(transaction.getTransactionHandle(), session, layoutHandle, UNGROUPED_SCHEDULING); ConnectorSplit split = getOnlyElement(getAllSplits(splitSource)); ImmutableList<ColumnHandle> columnHandles = ImmutableList.of(column); try (ConnectorPageSource ignored = pageSourceProvider.createPageSource(transaction.getTransactionHandle(), session, split, columnHandles)) { fail("expected exception"); } catch (PrestoException e) { assertEquals(e.getErrorCode(), HIVE_INVALID_PARTITION_VALUE.toErrorCode()); } } } @Test public void testTypesTextFile() throws Exception { assertGetRecords("presto_test_types_textfile", TEXTFILE); } @Test public void testTypesSequenceFile() throws Exception { assertGetRecords("presto_test_types_sequencefile", SEQUENCEFILE); } @Test public void testTypesRcText() throws Exception { assertGetRecords("presto_test_types_rctext", RCTEXT); } @Test public void testTypesRcBinary() throws Exception { assertGetRecords("presto_test_types_rcbinary", RCBINARY); } @Test public void testTypesOrc() throws Exception { assertGetRecordsOptional("presto_test_types_orc", ORC); } @Test public void testTypesParquet() throws Exception { assertGetRecordsOptional("presto_test_types_parquet", PARQUET); } @Test public void testEmptyTextFile() throws Exception { assertEmptyFile(TEXTFILE); } @Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = "Error opening Hive split .*SequenceFile.*EOFException") public void testEmptySequenceFile() throws Exception { assertEmptyFile(SEQUENCEFILE); } @Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = "RCFile is empty: .*") public void testEmptyRcTextFile() throws Exception { assertEmptyFile(RCTEXT); } @Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = "RCFile is empty: .*") public void testEmptyRcBinaryFile() throws Exception { assertEmptyFile(RCBINARY); } @Test public void testEmptyOrcFile() throws Exception { assertEmptyFile(ORC); } @Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = "ORC file is empty: .*") public void testEmptyDwrfFile() throws Exception { assertEmptyFile(DWRF); } private void assertEmptyFile(HiveStorageFormat format) throws Exception { SchemaTableName tableName = temporaryTable("empty_file"); try { List<Column> columns = ImmutableList.of(new Column("test", HIVE_STRING, Optional.empty())); createEmptyTable(tableName, format, columns, ImmutableList.of()); try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); Table table = transaction.getMetastore(tableName.getSchemaName()) .getTable(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(AssertionError::new); // verify directory is empty HdfsContext context = new HdfsContext(session, tableName.getSchemaName(), tableName.getTableName()); Path location = new Path(table.getStorage().getLocation()); assertTrue(listDirectory(context, location).isEmpty()); // read table with empty directory readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.of(0), Optional.of(ORC)); // create empty file FileSystem fileSystem = hdfsEnvironment.getFileSystem(context, location); assertTrue(fileSystem.createNewFile(new Path(location, "empty-file"))); assertEquals(listDirectory(context, location), ImmutableList.of("empty-file")); // read table with empty file MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.of(1), Optional.empty()); assertEquals(result.getRowCount(), 0); } } finally { dropTable(tableName); } } @Test public void testHiveViewsAreNotSupported() { try (Transaction transaction = newTransaction()) { try { ConnectorMetadata metadata = transaction.getMetadata(); getTableHandle(metadata, view); fail("Expected HiveViewNotSupportedException"); } catch (HiveViewNotSupportedException e) { assertEquals(e.getTableName(), view); } } } @Test public void testHiveViewsHaveNoColumns() { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); assertEquals(metadata.listTableColumns(newSession(), new SchemaTablePrefix(view.getSchemaName(), view.getTableName())), ImmutableMap.of()); } } @Test public void testRenameTable() { SchemaTableName temporaryRenameTableOld = temporaryTable("rename_old"); SchemaTableName temporaryRenameTableNew = temporaryTable("rename_new"); try { createDummyTable(temporaryRenameTableOld); try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); metadata.renameTable(session, getTableHandle(metadata, temporaryRenameTableOld), temporaryRenameTableNew); transaction.commit(); } try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); assertNull(metadata.getTableHandle(session, temporaryRenameTableOld)); assertNotNull(metadata.getTableHandle(session, temporaryRenameTableNew)); } } finally { dropTable(temporaryRenameTableOld); dropTable(temporaryRenameTableNew); } } @Test public void testTableCreation() throws Exception { for (HiveStorageFormat storageFormat : createTableFormats) { SchemaTableName temporaryCreateTable = temporaryTable("create"); try { doCreateTable(temporaryCreateTable, storageFormat); } finally { dropTable(temporaryCreateTable); } } } @Test public void testTableCreationRollback() throws Exception { SchemaTableName temporaryCreateRollbackTable = temporaryTable("create_rollback"); try { Path stagingPathRoot; try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); // begin creating the table ConnectorTableMetadata tableMetadata = new ConnectorTableMetadata(temporaryCreateRollbackTable, CREATE_TABLE_COLUMNS, createTableProperties(RCBINARY)); ConnectorOutputTableHandle outputHandle = metadata.beginCreateTable(session, tableMetadata, Optional.empty()); // write the data ConnectorPageSink sink = pageSinkProvider.createPageSink(transaction.getTransactionHandle(), session, outputHandle); sink.appendPage(CREATE_TABLE_DATA.toPage()); getFutureValue(sink.finish()); // verify we have data files stagingPathRoot = getStagingPathRoot(outputHandle); HdfsContext context = new HdfsContext(session, temporaryCreateRollbackTable.getSchemaName(), temporaryCreateRollbackTable.getTableName()); assertFalse(listAllDataFiles(context, stagingPathRoot).isEmpty()); // rollback the table transaction.rollback(); } // verify all files have been deleted HdfsContext context = new HdfsContext(newSession(), temporaryCreateRollbackTable.getSchemaName(), temporaryCreateRollbackTable.getTableName()); assertTrue(listAllDataFiles(context, stagingPathRoot).isEmpty()); // verify table is not in the metastore try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); assertNull(metadata.getTableHandle(session, temporaryCreateRollbackTable)); } } finally { dropTable(temporaryCreateRollbackTable); } } @Test public void testTableCreationIgnoreExisting() { List<Column> columns = ImmutableList.of(new Column("dummy", HiveType.valueOf("uniontype<smallint,tinyint>"), Optional.empty())); SchemaTableName schemaTableName = temporaryTable("create"); ConnectorSession session = newSession(); String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); PrincipalPrivileges privileges = testingPrincipalPrivilege(session.getUser()); Path targetPath; try { try (Transaction transaction = newTransaction()) { LocationService locationService = getLocationService(schemaName); LocationHandle locationHandle = locationService.forNewTable(transaction.getMetastore(schemaName), session, schemaName, tableName); targetPath = locationService.getQueryWriteInfo(locationHandle).getTargetPath(); Table table = createSimpleTable(schemaTableName, columns, session, targetPath, "q1"); transaction.getMetastore(schemaName) .createTable(session, table, privileges, Optional.empty(), false, EMPTY_TABLE_STATISTICS); Optional<Table> tableHandle = transaction.getMetastore(schemaName).getTable(schemaName, tableName); assertTrue(tableHandle.isPresent()); transaction.commit(); } // try creating it again from another transaction with ignoreExisting=false try (Transaction transaction = newTransaction()) { Table table = createSimpleTable(schemaTableName, columns, session, targetPath.suffix("_2"), "q2"); transaction.getMetastore(schemaName) .createTable(session, table, privileges, Optional.empty(), false, EMPTY_TABLE_STATISTICS); transaction.commit(); fail("Expected exception"); } catch (PrestoException e) { assertInstanceOf(e, TableAlreadyExistsException.class); } // try creating it again from another transaction with ignoreExisting=true try (Transaction transaction = newTransaction()) { Table table = createSimpleTable(schemaTableName, columns, session, targetPath.suffix("_3"), "q3"); transaction.getMetastore(schemaName) .createTable(session, table, privileges, Optional.empty(), true, EMPTY_TABLE_STATISTICS); transaction.commit(); } // at this point the table should exist, now try creating the table again with a different table definition columns = ImmutableList.of(new Column("new_column", HiveType.valueOf("string"), Optional.empty())); try (Transaction transaction = newTransaction()) { Table table = createSimpleTable(schemaTableName, columns, session, targetPath.suffix("_4"), "q4"); transaction.getMetastore(schemaName) .createTable(session, table, privileges, Optional.empty(), true, EMPTY_TABLE_STATISTICS); transaction.commit(); fail("Expected exception"); } catch (PrestoException e) { assertEquals(e.getErrorCode(), TRANSACTION_CONFLICT.toErrorCode()); assertEquals(e.getMessage(), format("Table already exists with a different schema: '%s'", schemaTableName.getTableName())); } } finally { dropTable(schemaTableName); } } private static Table createSimpleTable(SchemaTableName schemaTableName, List<Column> columns, ConnectorSession session, Path targetPath, String queryId) { String tableOwner = session.getUser(); String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); return Table.builder() .setDatabaseName(schemaName) .setTableName(tableName) .setOwner(tableOwner) .setTableType(TableType.MANAGED_TABLE.name()) .setParameters(ImmutableMap.of( PRESTO_VERSION_NAME, TEST_SERVER_VERSION, PRESTO_QUERY_ID_NAME, queryId)) .setDataColumns(columns) .withStorage(storage -> storage .setLocation(targetPath.toString()) .setStorageFormat(fromHiveStorageFormat(ORC)) .setSerdeParameters(ImmutableMap.of())) .build(); } @Test public void testBucketSortedTables() throws Exception { SchemaTableName table = temporaryTable("create_sorted"); try { doTestBucketSortedTables(table); } finally { dropTable(table); } } private void doTestBucketSortedTables(SchemaTableName table) throws IOException { int bucketCount = 3; try (Transaction transaction = newTransaction()) { HiveClientConfig hiveConfig = getHiveClientConfig() .setSortedWritingEnabled(true) .setWriterSortBufferSize(new DataSize(1, MEGABYTE)); ConnectorSession session = new TestingConnectorSession(new HiveSessionProperties(hiveConfig, new OrcFileWriterConfig()).getSessionProperties()); ConnectorMetadata metadata = transaction.getMetadata(); // begin creating the table ConnectorTableMetadata tableMetadata = new ConnectorTableMetadata( table, ImmutableList.<ColumnMetadata>builder() .add(new ColumnMetadata("id", VARCHAR)) .add(new ColumnMetadata("value_asc", VARCHAR)) .add(new ColumnMetadata("value_desc", BIGINT)) .add(new ColumnMetadata("ds", VARCHAR)) .build(), ImmutableMap.<String, Object>builder() .put(STORAGE_FORMAT_PROPERTY, RCBINARY) .put(PARTITIONED_BY_PROPERTY, ImmutableList.of("ds")) .put(BUCKETED_BY_PROPERTY, ImmutableList.of("id")) .put(BUCKET_COUNT_PROPERTY, bucketCount) .put(SORTED_BY_PROPERTY, ImmutableList.builder() .add(new SortingColumn("value_asc", SortingColumn.Order.ASCENDING)) .add(new SortingColumn("value_desc", SortingColumn.Order.DESCENDING)) .build()) .build()); ConnectorOutputTableHandle outputHandle = metadata.beginCreateTable(session, tableMetadata, Optional.empty()); // write the data ConnectorPageSink sink = pageSinkProvider.createPageSink(transaction.getTransactionHandle(), session, outputHandle); List<Type> types = tableMetadata.getColumns().stream() .map(ColumnMetadata::getType) .collect(toList()); ThreadLocalRandom random = ThreadLocalRandom.current(); for (int i = 0; i < 200; i++) { MaterializedResult.Builder builder = MaterializedResult.resultBuilder(session, types); for (int j = 0; j < 1000; j++) { builder.row( sha256().hashLong(random.nextLong()).toString(), "test" + random.nextInt(100), random.nextLong(100_000), "2018-04-01"); } sink.appendPage(builder.build().toPage()); } // verify we have several temporary files per bucket Path stagingPathRoot = getStagingPathRoot(outputHandle); HdfsContext context = new HdfsContext(session, table.getSchemaName(), table.getTableName()); assertThat(listAllDataFiles(context, stagingPathRoot)) .filteredOn(file -> file.contains(".tmp-sort.")) .size().isGreaterThanOrEqualTo(bucketCount * 3); // finish the write Collection<Slice> fragments = getFutureValue(sink.finish()); // verify there are no temporary files for (String file : listAllDataFiles(context, stagingPathRoot)) { assertThat(file).doesNotStartWith(".tmp-sort."); } // finish creating table metadata.finishCreateTable(session, outputHandle, fragments); transaction.commit(); } // verify that bucket files are sorted try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, table); List<ColumnHandle> columnHandles = ImmutableList.copyOf(metadata.getColumnHandles(session, tableHandle).values()); List<ConnectorSplit> splits = getAllSplits(tableHandle, TupleDomain.all()); assertThat(splits).hasSize(bucketCount); for (ConnectorSplit split : splits) { try (ConnectorPageSource pageSource = pageSourceProvider.createPageSource(transaction.getTransactionHandle(), session, split, columnHandles)) { String lastValueAsc = null; long lastValueDesc = -1; while (!pageSource.isFinished()) { Page page = pageSource.getNextPage(); if (page == null) { continue; } for (int i = 0; i < page.getPositionCount(); i++) { Block blockAsc = page.getBlock(1); Block blockDesc = page.getBlock(2); assertFalse(blockAsc.isNull(i)); assertFalse(blockDesc.isNull(i)); String valueAsc = VARCHAR.getSlice(blockAsc, i).toStringUtf8(); if (lastValueAsc != null) { assertGreaterThanOrEqual(valueAsc, lastValueAsc); if (valueAsc.equals(lastValueAsc)) { long valueDesc = BIGINT.getLong(blockDesc, i); if (lastValueDesc != -1) { assertLessThanOrEqual(valueDesc, lastValueDesc); } lastValueDesc = valueDesc; } else { lastValueDesc = -1; } } lastValueAsc = valueAsc; } } } } } } @Test public void testInsert() throws Exception { for (HiveStorageFormat storageFormat : createTableFormats) { SchemaTableName temporaryInsertTable = temporaryTable("insert"); try { doInsert(storageFormat, temporaryInsertTable); } finally { dropTable(temporaryInsertTable); } } } @Test public void testInsertIntoNewPartition() throws Exception { for (HiveStorageFormat storageFormat : createTableFormats) { SchemaTableName temporaryInsertIntoNewPartitionTable = temporaryTable("insert_new_partitioned"); try { doInsertIntoNewPartition(storageFormat, temporaryInsertIntoNewPartitionTable); } finally { dropTable(temporaryInsertIntoNewPartitionTable); } } } @Test public void testInsertIntoExistingPartition() throws Exception { for (HiveStorageFormat storageFormat : createTableFormats) { SchemaTableName temporaryInsertIntoExistingPartitionTable = temporaryTable("insert_existing_partitioned"); try { doInsertIntoExistingPartition(storageFormat, temporaryInsertIntoExistingPartitionTable); } finally { dropTable(temporaryInsertIntoExistingPartitionTable); } } } @Test public void testInsertIntoExistingPartitionEmptyStatistics() throws Exception { for (HiveStorageFormat storageFormat : createTableFormats) { SchemaTableName temporaryInsertIntoExistingPartitionTable = temporaryTable("insert_existing_partitioned_empty_statistics"); try { doInsertIntoExistingPartitionEmptyStatistics(storageFormat, temporaryInsertIntoExistingPartitionTable); } finally { dropTable(temporaryInsertIntoExistingPartitionTable); } } } @Test public void testInsertUnsupportedWriteType() throws Exception { SchemaTableName temporaryInsertUnsupportedWriteType = temporaryTable("insert_unsupported_type"); try { doInsertUnsupportedWriteType(ORC, temporaryInsertUnsupportedWriteType); } finally { dropTable(temporaryInsertUnsupportedWriteType); } } @Test public void testMetadataDelete() throws Exception { for (HiveStorageFormat storageFormat : createTableFormats) { SchemaTableName temporaryMetadataDeleteTable = temporaryTable("metadata_delete"); try { doTestMetadataDelete(storageFormat, temporaryMetadataDeleteTable); } finally { dropTable(temporaryMetadataDeleteTable); } } } @Test public void testEmptyTableCreation() throws Exception { for (HiveStorageFormat storageFormat : createTableFormats) { SchemaTableName temporaryCreateEmptyTable = temporaryTable("create_empty"); try { doCreateEmptyTable(temporaryCreateEmptyTable, storageFormat, CREATE_TABLE_COLUMNS); } finally { dropTable(temporaryCreateEmptyTable); } } } @Test public void testViewCreation() { SchemaTableName temporaryCreateView = temporaryTable("create_view"); try { verifyViewCreation(temporaryCreateView); } finally { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); metadata.dropView(newSession(), temporaryCreateView); transaction.commit(); } catch (RuntimeException e) { // this usually occurs because the view was not created } } } @Test public void testCreateTableUnsupportedType() { for (HiveStorageFormat storageFormat : createTableFormats) { try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); List<ColumnMetadata> columns = ImmutableList.of(new ColumnMetadata("dummy", HYPER_LOG_LOG)); ConnectorTableMetadata tableMetadata = new ConnectorTableMetadata(invalidTable, columns, createTableProperties(storageFormat)); metadata.beginCreateTable(session, tableMetadata, Optional.empty()); fail("create table with unsupported type should fail for storage format " + storageFormat); } catch (PrestoException e) { assertEquals(e.getErrorCode(), NOT_SUPPORTED.toErrorCode()); } } } @Test public void testUpdateTableParameters() throws Exception { SchemaTableName tableName = temporaryTable("compare_and_set_table_parameters"); try { doCreateEmptyTable(tableName, ORC, CREATE_TABLE_COLUMNS); ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); metastoreClient.updateTableParameters(tableName.getSchemaName(), tableName.getTableName(), parameters -> { Map<String, String> updated = new HashMap<>(parameters); updated.put("test_key", "test_value"); return updated; }); Table table = metastoreClient.getTable(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(() -> new TableNotFoundException(tableName)); assertThat(table.getParameters()).contains(entry("test_key", "test_value")); } finally { dropTable(tableName); } } @Test public void testUpdatePartitionParameters() throws Exception { SchemaTableName tableName = temporaryTable("compare_and_set_partition_parameters"); try { doCreateEmptyTable(tableName, ORC, CREATE_TABLE_COLUMNS_PARTITIONED); insertData(tableName, CREATE_TABLE_PARTITIONED_DATA); ImmutableList<String> partitionValues = ImmutableList.of("2015-07-01"); ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); metastoreClient.updatePartitionParameters(tableName.getSchemaName(), tableName.getTableName(), partitionValues, parameters -> { Map<String, String> updated = new HashMap<>(parameters); updated.put("test_key", "test_value"); return updated; }); Partition partition = metastoreClient.getPartition(tableName.getSchemaName(), tableName.getTableName(), partitionValues) .orElseThrow(() -> new PartitionNotFoundException(tableName, partitionValues)); assertThat(partition.getParameters()).contains(entry("test_key", "test_value")); } finally { dropTable(tableName); } } @Test public void testUpdateBasicTableStatistics() throws Exception { SchemaTableName tableName = temporaryTable("update_basic_table_statistics"); try { doCreateEmptyTable(tableName, ORC, STATISTICS_TABLE_COLUMNS); testUpdateTableStatistics(tableName, EMPTY_TABLE_STATISTICS, BASIC_STATISTICS_1, BASIC_STATISTICS_2); } finally { dropTable(tableName); } } @Test public void testUpdateTableColumnStatistics() throws Exception { SchemaTableName tableName = temporaryTable("update_table_column_statistics"); ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); if (!metastoreClient.supportsColumnStatistics()) { throw new SkipException("column level statistics are not supported"); } try { doCreateEmptyTable(tableName, ORC, STATISTICS_TABLE_COLUMNS); testUpdateTableStatistics(tableName, EMPTY_TABLE_STATISTICS, STATISTICS_1_1, STATISTICS_1_2, STATISTICS_2); } finally { dropTable(tableName); } } @Test public void testUpdateTableColumnStatisticsEmptyOptionalFields() throws Exception { SchemaTableName tableName = temporaryTable("update_table_column_statistics_empty_optional_fields"); ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); if (!metastoreClient.supportsColumnStatistics()) { throw new SkipException("column level statistics are not supported"); } try { doCreateEmptyTable(tableName, ORC, STATISTICS_TABLE_COLUMNS); testUpdateTableStatistics(tableName, EMPTY_TABLE_STATISTICS, STATISTICS_EMPTY_OPTIONAL_FIELDS); } finally { dropTable(tableName); } } protected void testUpdateTableStatistics(SchemaTableName tableName, PartitionStatistics initialStatistics, PartitionStatistics... statistics) { ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); assertThat(metastoreClient.getTableStatistics(tableName.getSchemaName(), tableName.getTableName())) .isEqualTo(initialStatistics); AtomicReference<PartitionStatistics> expectedStatistics = new AtomicReference<>(initialStatistics); for (PartitionStatistics partitionStatistics : statistics) { metastoreClient.updateTableStatistics(tableName.getSchemaName(), tableName.getTableName(), actualStatistics -> { assertThat(actualStatistics).isEqualTo(expectedStatistics.get()); return partitionStatistics; }); assertThat(metastoreClient.getTableStatistics(tableName.getSchemaName(), tableName.getTableName())) .isEqualTo(partitionStatistics); expectedStatistics.set(partitionStatistics); } assertThat(metastoreClient.getTableStatistics(tableName.getSchemaName(), tableName.getTableName())) .isEqualTo(expectedStatistics.get()); metastoreClient.updateTableStatistics(tableName.getSchemaName(), tableName.getTableName(), actualStatistics -> { assertThat(actualStatistics).isEqualTo(expectedStatistics.get()); return initialStatistics; }); assertThat(metastoreClient.getTableStatistics(tableName.getSchemaName(), tableName.getTableName())) .isEqualTo(initialStatistics); } @Test public void testUpdateBasicPartitionStatistics() throws Exception { SchemaTableName tableName = temporaryTable("update_basic_partition_statistics"); try { createDummyPartitionedTable(tableName, STATISTICS_PARTITIONED_TABLE_COLUMNS); testUpdatePartitionStatistics( tableName, EMPTY_TABLE_STATISTICS, ImmutableList.of(BASIC_STATISTICS_1, BASIC_STATISTICS_2), ImmutableList.of(BASIC_STATISTICS_2, BASIC_STATISTICS_1)); } finally { dropTable(tableName); } } @Test public void testUpdatePartitionColumnStatistics() throws Exception { SchemaTableName tableName = temporaryTable("update_partition_column_statistics"); ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); if (!metastoreClient.supportsColumnStatistics()) { throw new SkipException("column level statistics are not supported"); } try { createDummyPartitionedTable(tableName, STATISTICS_PARTITIONED_TABLE_COLUMNS); testUpdatePartitionStatistics( tableName, EMPTY_TABLE_STATISTICS, ImmutableList.of(STATISTICS_1_1, STATISTICS_1_2, STATISTICS_2), ImmutableList.of(STATISTICS_1_2, STATISTICS_1_1, STATISTICS_2)); } finally { dropTable(tableName); } } @Test public void testUpdatePartitionColumnStatisticsEmptyOptionalFields() throws Exception { SchemaTableName tableName = temporaryTable("update_partition_column_statistics"); ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); if (!metastoreClient.supportsColumnStatistics()) { throw new SkipException("column level statistics are not supported"); } try { createDummyPartitionedTable(tableName, STATISTICS_PARTITIONED_TABLE_COLUMNS); testUpdatePartitionStatistics( tableName, EMPTY_TABLE_STATISTICS, ImmutableList.of(STATISTICS_EMPTY_OPTIONAL_FIELDS), ImmutableList.of(STATISTICS_EMPTY_OPTIONAL_FIELDS)); } finally { dropTable(tableName); } } private void createDummyTable(SchemaTableName tableName) { try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); List<ColumnMetadata> columns = ImmutableList.of(new ColumnMetadata("dummy", createUnboundedVarcharType())); ConnectorTableMetadata tableMetadata = new ConnectorTableMetadata(tableName, columns, createTableProperties(TEXTFILE)); ConnectorOutputTableHandle handle = metadata.beginCreateTable(session, tableMetadata, Optional.empty()); metadata.finishCreateTable(session, handle, ImmutableList.of()); transaction.commit(); } } protected void createDummyPartitionedTable(SchemaTableName tableName, List<ColumnMetadata> columns) throws Exception { doCreateEmptyTable(tableName, ORC, columns); ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); Table table = metastoreClient.getTable(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(() -> new TableNotFoundException(tableName)); List<String> firstPartitionValues = ImmutableList.of("2016-01-01"); List<String> secondPartitionValues = ImmutableList.of("2016-01-02"); String firstPartitionName = makePartName(ImmutableList.of("ds"), firstPartitionValues); String secondPartitionName = makePartName(ImmutableList.of("ds"), secondPartitionValues); List<Partition> partitions = ImmutableList.of(firstPartitionValues, secondPartitionValues) .stream() .map(values -> Partition.builder() .setDatabaseName(tableName.getSchemaName()) .setTableName(tableName.getTableName()) .setColumns(table.getDataColumns()) .setValues(values) .withStorage(storage -> storage .setStorageFormat(fromHiveStorageFormat(HiveStorageFormat.ORC)) .setLocation(table.getStorage().getLocation() + "/" + makePartName(ImmutableList.of("ds"), values))) .build()) .collect(toImmutableList()); metastoreClient.addPartitions(tableName.getSchemaName(), tableName.getTableName(), partitions); metastoreClient.updatePartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), firstPartitionName, currentStatistics -> EMPTY_TABLE_STATISTICS); metastoreClient.updatePartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), secondPartitionName, currentStatistics -> EMPTY_TABLE_STATISTICS); } protected void testUpdatePartitionStatistics( SchemaTableName tableName, PartitionStatistics initialStatistics, List<PartitionStatistics> firstPartitionStatistics, List<PartitionStatistics> secondPartitionStatistics) { verify(firstPartitionStatistics.size() == secondPartitionStatistics.size()); String firstPartitionName = "ds=2016-01-01"; String secondPartitionName = "ds=2016-01-02"; ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); assertThat(metastoreClient.getPartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), ImmutableSet.of(firstPartitionName, secondPartitionName))) .isEqualTo(ImmutableMap.of(firstPartitionName, initialStatistics, secondPartitionName, initialStatistics)); AtomicReference<PartitionStatistics> expectedStatisticsPartition1 = new AtomicReference<>(initialStatistics); AtomicReference<PartitionStatistics> expectedStatisticsPartition2 = new AtomicReference<>(initialStatistics); for (int i = 0; i < firstPartitionStatistics.size(); i++) { PartitionStatistics statisticsPartition1 = firstPartitionStatistics.get(i); PartitionStatistics statisticsPartition2 = secondPartitionStatistics.get(i); metastoreClient.updatePartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), firstPartitionName, actualStatistics -> { assertThat(actualStatistics).isEqualTo(expectedStatisticsPartition1.get()); return statisticsPartition1; }); metastoreClient.updatePartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), secondPartitionName, actualStatistics -> { assertThat(actualStatistics).isEqualTo(expectedStatisticsPartition2.get()); return statisticsPartition2; }); assertThat(metastoreClient.getPartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), ImmutableSet.of(firstPartitionName, secondPartitionName))) .isEqualTo(ImmutableMap.of(firstPartitionName, statisticsPartition1, secondPartitionName, statisticsPartition2)); expectedStatisticsPartition1.set(statisticsPartition1); expectedStatisticsPartition2.set(statisticsPartition2); } assertThat(metastoreClient.getPartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), ImmutableSet.of(firstPartitionName, secondPartitionName))) .isEqualTo(ImmutableMap.of(firstPartitionName, expectedStatisticsPartition1.get(), secondPartitionName, expectedStatisticsPartition2.get())); metastoreClient.updatePartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), firstPartitionName, currentStatistics -> { assertThat(currentStatistics).isEqualTo(expectedStatisticsPartition1.get()); return initialStatistics; }); metastoreClient.updatePartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), secondPartitionName, currentStatistics -> { assertThat(currentStatistics).isEqualTo(expectedStatisticsPartition2.get()); return initialStatistics; }); assertThat(metastoreClient.getPartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), ImmutableSet.of(firstPartitionName, secondPartitionName))) .isEqualTo(ImmutableMap.of(firstPartitionName, initialStatistics, secondPartitionName, initialStatistics)); } /** * This test creates 2 identical partitions and verifies that the statistics projected based on * a single partition sample are equal to the statistics computed in a fair way */ @Test public void testPartitionStatisticsSampling() throws Exception { SchemaTableName tableName = temporaryTable("test_partition_statistics_sampling"); try { createDummyPartitionedTable(tableName, STATISTICS_PARTITIONED_TABLE_COLUMNS); metastoreClient.updatePartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), "ds=2016-01-01", actualStatistics -> STATISTICS_1); metastoreClient.updatePartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), "ds=2016-01-02", actualStatistics -> STATISTICS_1); try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = metadata.getTableHandle(session, tableName); TableStatistics unsampledStatistics = metadata.getTableStatistics(sampleSize(2), tableHandle, Constraint.alwaysTrue()); TableStatistics sampledStatistics = metadata.getTableStatistics(sampleSize(1), tableHandle, Constraint.alwaysTrue()); assertEquals(sampledStatistics, unsampledStatistics); } } finally { dropTable(tableName); } } private ConnectorSession sampleSize(int sampleSize) { HiveSessionProperties properties = new HiveSessionProperties( getHiveClientConfig().setPartitionStatisticsSampleSize(sampleSize), new OrcFileWriterConfig()); return new TestingConnectorSession(properties.getSessionProperties()); } private void verifyViewCreation(SchemaTableName temporaryCreateView) { // replace works for new view doCreateView(temporaryCreateView, true); // replace works for existing view doCreateView(temporaryCreateView, true); // create fails for existing view try { doCreateView(temporaryCreateView, false); fail("create existing should fail"); } catch (ViewAlreadyExistsException e) { assertEquals(e.getViewName(), temporaryCreateView); } try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); // drop works when view exists metadata.dropView(newSession(), temporaryCreateView); transaction.commit(); } try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); assertEquals(metadata.getViews(newSession(), temporaryCreateView.toSchemaTablePrefix()).size(), 0); assertFalse(metadata.listViews(newSession(), temporaryCreateView.getSchemaName()).contains(temporaryCreateView)); } // drop fails when view does not exist try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); metadata.dropView(newSession(), temporaryCreateView); fail("drop non-existing should fail"); } catch (ViewNotFoundException e) { assertEquals(e.getViewName(), temporaryCreateView); } // create works for new view doCreateView(temporaryCreateView, false); } private void doCreateView(SchemaTableName viewName, boolean replace) { String viewData = "test data"; try (Transaction transaction = newTransaction()) { transaction.getMetadata().createView(newSession(), viewName, viewData, replace); transaction.commit(); } try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); Map<SchemaTableName, ConnectorViewDefinition> views = metadata.getViews(newSession(), viewName.toSchemaTablePrefix()); assertEquals(views.size(), 1); assertEquals(views.get(viewName).getViewData(), viewData); assertTrue(metadata.listViews(newSession(), viewName.getSchemaName()).contains(viewName)); } } protected void doCreateTable(SchemaTableName tableName, HiveStorageFormat storageFormat) throws Exception { String queryId; try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); queryId = session.getQueryId(); // begin creating the table ConnectorTableMetadata tableMetadata = new ConnectorTableMetadata(tableName, CREATE_TABLE_COLUMNS, createTableProperties(storageFormat)); ConnectorOutputTableHandle outputHandle = metadata.beginCreateTable(session, tableMetadata, Optional.empty()); // write the data ConnectorPageSink sink = pageSinkProvider.createPageSink(transaction.getTransactionHandle(), session, outputHandle); sink.appendPage(CREATE_TABLE_DATA.toPage()); Collection<Slice> fragments = getFutureValue(sink.finish()); // verify all new files start with the unique prefix HdfsContext context = new HdfsContext(session, tableName.getSchemaName(), tableName.getTableName()); for (String filePath : listAllDataFiles(context, getStagingPathRoot(outputHandle))) { assertTrue(new Path(filePath).getName().startsWith(getFilePrefix(outputHandle))); } // commit the table metadata.finishCreateTable(session, outputHandle, fragments); transaction.commit(); } try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); // load the new table ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); // verify the metadata ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(session, getTableHandle(metadata, tableName)); assertEquals(filterNonHiddenColumnMetadata(tableMetadata.getColumns()), CREATE_TABLE_COLUMNS); // verify the data MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.of(storageFormat)); assertEqualsIgnoreOrder(result.getMaterializedRows(), CREATE_TABLE_DATA.getMaterializedRows()); // verify the node version and query ID in table Table table = getMetastoreClient(tableName.getSchemaName()).getTable(tableName.getSchemaName(), tableName.getTableName()).get(); assertEquals(table.getParameters().get(PRESTO_VERSION_NAME), TEST_SERVER_VERSION); assertEquals(table.getParameters().get(PRESTO_QUERY_ID_NAME), queryId); // verify basic statistics HiveBasicStatistics statistics = getBasicStatisticsForTable(transaction, tableName); assertEquals(statistics.getRowCount().getAsLong(), CREATE_TABLE_DATA.getRowCount()); assertEquals(statistics.getFileCount().getAsLong(), 1L); assertGreaterThan(statistics.getInMemoryDataSizeInBytes().getAsLong(), 0L); assertGreaterThan(statistics.getOnDiskDataSizeInBytes().getAsLong(), 0L); } } protected void doCreateEmptyTable(SchemaTableName tableName, HiveStorageFormat storageFormat, List<ColumnMetadata> createTableColumns) throws Exception { List<String> partitionedBy = createTableColumns.stream() .filter(column -> column.getName().equals("ds")) .map(ColumnMetadata::getName) .collect(toList()); String queryId; try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); queryId = session.getQueryId(); ConnectorTableMetadata tableMetadata = new ConnectorTableMetadata(tableName, createTableColumns, createTableProperties(storageFormat, partitionedBy)); metadata.createTable(session, tableMetadata, false); transaction.commit(); } try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); // load the new table ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); // verify the metadata ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(session, getTableHandle(metadata, tableName)); List<ColumnMetadata> expectedColumns = createTableColumns.stream() .map(column -> new ColumnMetadata( column.getName(), column.getType(), column.getComment(), columnExtraInfo(partitionedBy.contains(column.getName())), false)) .collect(toList()); assertEquals(filterNonHiddenColumnMetadata(tableMetadata.getColumns()), expectedColumns); // verify table format Table table = transaction.getMetastore(tableName.getSchemaName()).getTable(tableName.getSchemaName(), tableName.getTableName()).get(); assertEquals(table.getStorage().getStorageFormat().getInputFormat(), storageFormat.getInputFormat()); // verify the node version and query ID assertEquals(table.getParameters().get(PRESTO_VERSION_NAME), TEST_SERVER_VERSION); assertEquals(table.getParameters().get(PRESTO_QUERY_ID_NAME), queryId); // verify the table is empty List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.of(storageFormat)); assertEquals(result.getRowCount(), 0); // verify basic statistics if (partitionedBy.isEmpty()) { HiveBasicStatistics statistics = getBasicStatisticsForTable(transaction, tableName); assertEquals(statistics.getRowCount().getAsLong(), 0L); assertEquals(statistics.getFileCount().getAsLong(), 0L); assertEquals(statistics.getInMemoryDataSizeInBytes().getAsLong(), 0L); assertEquals(statistics.getOnDiskDataSizeInBytes().getAsLong(), 0L); } } } private void doInsert(HiveStorageFormat storageFormat, SchemaTableName tableName) throws Exception { // creating the table doCreateEmptyTable(tableName, storageFormat, CREATE_TABLE_COLUMNS); MaterializedResult.Builder resultBuilder = MaterializedResult.resultBuilder(SESSION, CREATE_TABLE_DATA.getTypes()); for (int i = 0; i < 3; i++) { insertData(tableName, CREATE_TABLE_DATA); try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); // load the new table ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); // verify the metadata ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(session, getTableHandle(metadata, tableName)); assertEquals(filterNonHiddenColumnMetadata(tableMetadata.getColumns()), CREATE_TABLE_COLUMNS); // verify the data resultBuilder.rows(CREATE_TABLE_DATA.getMaterializedRows()); MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.empty()); assertEqualsIgnoreOrder(result.getMaterializedRows(), resultBuilder.build().getMaterializedRows()); // statistics HiveBasicStatistics tableStatistics = getBasicStatisticsForTable(transaction, tableName); assertEquals(tableStatistics.getRowCount().getAsLong(), CREATE_TABLE_DATA.getRowCount() * (i + 1)); assertEquals(tableStatistics.getFileCount().getAsLong(), i + 1L); assertGreaterThan(tableStatistics.getInMemoryDataSizeInBytes().getAsLong(), 0L); assertGreaterThan(tableStatistics.getOnDiskDataSizeInBytes().getAsLong(), 0L); } } // test rollback Set<String> existingFiles; try (Transaction transaction = newTransaction()) { existingFiles = listAllDataFiles(transaction, tableName.getSchemaName(), tableName.getTableName()); assertFalse(existingFiles.isEmpty()); } Path stagingPathRoot; try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); // "stage" insert data ConnectorInsertTableHandle insertTableHandle = metadata.beginInsert(session, tableHandle); ConnectorPageSink sink = pageSinkProvider.createPageSink(transaction.getTransactionHandle(), session, insertTableHandle); sink.appendPage(CREATE_TABLE_DATA.toPage()); sink.appendPage(CREATE_TABLE_DATA.toPage()); Collection<Slice> fragments = getFutureValue(sink.finish()); metadata.finishInsert(session, insertTableHandle, fragments); // statistics, visible from within transaction HiveBasicStatistics tableStatistics = getBasicStatisticsForTable(transaction, tableName); assertEquals(tableStatistics.getRowCount().getAsLong(), CREATE_TABLE_DATA.getRowCount() * 5L); try (Transaction otherTransaction = newTransaction()) { // statistics, not visible from outside transaction HiveBasicStatistics otherTableStatistics = getBasicStatisticsForTable(otherTransaction, tableName); assertEquals(otherTableStatistics.getRowCount().getAsLong(), CREATE_TABLE_DATA.getRowCount() * 3L); } // verify we did not modify the table directory assertEquals(listAllDataFiles(transaction, tableName.getSchemaName(), tableName.getTableName()), existingFiles); // verify all temp files start with the unique prefix stagingPathRoot = getStagingPathRoot(insertTableHandle); HdfsContext context = new HdfsContext(session, tableName.getSchemaName(), tableName.getTableName()); Set<String> tempFiles = listAllDataFiles(context, stagingPathRoot); assertTrue(!tempFiles.isEmpty()); for (String filePath : tempFiles) { assertTrue(new Path(filePath).getName().startsWith(getFilePrefix(insertTableHandle))); } // rollback insert transaction.rollback(); } // verify temp directory is empty HdfsContext context = new HdfsContext(newSession(), tableName.getSchemaName(), tableName.getTableName()); assertTrue(listAllDataFiles(context, stagingPathRoot).isEmpty()); // verify the data is unchanged try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.empty()); assertEqualsIgnoreOrder(result.getMaterializedRows(), resultBuilder.build().getMaterializedRows()); // verify we did not modify the table directory assertEquals(listAllDataFiles(transaction, tableName.getSchemaName(), tableName.getTableName()), existingFiles); } // verify statistics unchanged try (Transaction transaction = newTransaction()) { HiveBasicStatistics statistics = getBasicStatisticsForTable(transaction, tableName); assertEquals(statistics.getRowCount().getAsLong(), CREATE_TABLE_DATA.getRowCount() * 3L); assertEquals(statistics.getFileCount().getAsLong(), 3L); } } // These are protected so extensions to the hive connector can replace the handle classes protected String getFilePrefix(ConnectorOutputTableHandle outputTableHandle) { return ((HiveWritableTableHandle) outputTableHandle).getFilePrefix(); } protected String getFilePrefix(ConnectorInsertTableHandle insertTableHandle) { return ((HiveWritableTableHandle) insertTableHandle).getFilePrefix(); } protected Path getStagingPathRoot(ConnectorInsertTableHandle insertTableHandle) { HiveInsertTableHandle handle = (HiveInsertTableHandle) insertTableHandle; WriteInfo writeInfo = getLocationService(handle.getSchemaName()).getQueryWriteInfo(handle.getLocationHandle()); if (writeInfo.getWriteMode() != STAGE_AND_MOVE_TO_TARGET_DIRECTORY) { throw new AssertionError("writeMode is not STAGE_AND_MOVE_TO_TARGET_DIRECTORY"); } return writeInfo.getWritePath(); } protected Path getStagingPathRoot(ConnectorOutputTableHandle outputTableHandle) { HiveOutputTableHandle handle = (HiveOutputTableHandle) outputTableHandle; return getLocationService(handle.getSchemaName()) .getQueryWriteInfo(handle.getLocationHandle()) .getWritePath(); } protected Path getTargetPathRoot(ConnectorInsertTableHandle insertTableHandle) { HiveInsertTableHandle hiveInsertTableHandle = (HiveInsertTableHandle) insertTableHandle; return getLocationService(hiveInsertTableHandle.getSchemaName()) .getQueryWriteInfo(hiveInsertTableHandle.getLocationHandle()) .getTargetPath(); } protected Set<String> listAllDataFiles(Transaction transaction, String schemaName, String tableName) throws IOException { HdfsContext context = new HdfsContext(newSession(), schemaName, tableName); Set<String> existingFiles = new HashSet<>(); for (String location : listAllDataPaths(transaction.getMetastore(schemaName), schemaName, tableName)) { existingFiles.addAll(listAllDataFiles(context, new Path(location))); } return existingFiles; } public static List<String> listAllDataPaths(SemiTransactionalHiveMetastore metastore, String schemaName, String tableName) { ImmutableList.Builder<String> locations = ImmutableList.builder(); Table table = metastore.getTable(schemaName, tableName).get(); if (table.getStorage().getLocation() != null) { // For partitioned table, there should be nothing directly under this directory. // But including this location in the set makes the directory content assert more // extensive, which is desirable. locations.add(table.getStorage().getLocation()); } Optional<List<String>> partitionNames = metastore.getPartitionNames(schemaName, tableName); if (partitionNames.isPresent()) { metastore.getPartitionsByNames(schemaName, tableName, partitionNames.get()).values().stream() .map(Optional::get) .map(partition -> partition.getStorage().getLocation()) .filter(location -> !location.startsWith(table.getStorage().getLocation())) .forEach(locations::add); } return locations.build(); } protected Set<String> listAllDataFiles(HdfsContext context, Path path) throws IOException { Set<String> result = new HashSet<>(); FileSystem fileSystem = hdfsEnvironment.getFileSystem(context, path); if (fileSystem.exists(path)) { for (FileStatus fileStatus : fileSystem.listStatus(path)) { if (fileStatus.getPath().getName().startsWith(".presto")) { // skip hidden files } else if (fileStatus.isFile()) { result.add(fileStatus.getPath().toString()); } else if (fileStatus.isDirectory()) { result.addAll(listAllDataFiles(context, fileStatus.getPath())); } } } return result; } private void doInsertIntoNewPartition(HiveStorageFormat storageFormat, SchemaTableName tableName) throws Exception { // creating the table doCreateEmptyTable(tableName, storageFormat, CREATE_TABLE_COLUMNS_PARTITIONED); // insert the data String queryId = insertData(tableName, CREATE_TABLE_PARTITIONED_DATA); Set<String> existingFiles; try (Transaction transaction = newTransaction()) { // verify partitions were created List<String> partitionNames = transaction.getMetastore(tableName.getSchemaName()).getPartitionNames(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(() -> new AssertionError("Table does not exist: " + tableName)); assertEqualsIgnoreOrder(partitionNames, CREATE_TABLE_PARTITIONED_DATA.getMaterializedRows().stream() .map(row -> "ds=" + row.getField(CREATE_TABLE_PARTITIONED_DATA.getTypes().size() - 1)) .collect(toList())); // verify the node versions in partitions Map<String, Optional<Partition>> partitions = getMetastoreClient(tableName.getSchemaName()).getPartitionsByNames(tableName.getSchemaName(), tableName.getTableName(), partitionNames); assertEquals(partitions.size(), partitionNames.size()); for (String partitionName : partitionNames) { Partition partition = partitions.get(partitionName).get(); assertEquals(partition.getParameters().get(PRESTO_VERSION_NAME), TEST_SERVER_VERSION); assertEquals(partition.getParameters().get(PRESTO_QUERY_ID_NAME), queryId); } // load the new table ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); // verify the data MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.of(storageFormat)); assertEqualsIgnoreOrder(result.getMaterializedRows(), CREATE_TABLE_PARTITIONED_DATA.getMaterializedRows()); // test rollback existingFiles = listAllDataFiles(transaction, tableName.getSchemaName(), tableName.getTableName()); assertFalse(existingFiles.isEmpty()); // test statistics for (String partitionName : partitionNames) { HiveBasicStatistics partitionStatistics = getBasicStatisticsForPartition(transaction, tableName, partitionName); assertEquals(partitionStatistics.getRowCount().getAsLong(), 1L); assertEquals(partitionStatistics.getFileCount().getAsLong(), 1L); assertGreaterThan(partitionStatistics.getInMemoryDataSizeInBytes().getAsLong(), 0L); assertGreaterThan(partitionStatistics.getOnDiskDataSizeInBytes().getAsLong(), 0L); } } Path stagingPathRoot; try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); // "stage" insert data ConnectorInsertTableHandle insertTableHandle = metadata.beginInsert(session, tableHandle); stagingPathRoot = getStagingPathRoot(insertTableHandle); ConnectorPageSink sink = pageSinkProvider.createPageSink(transaction.getTransactionHandle(), session, insertTableHandle); sink.appendPage(CREATE_TABLE_PARTITIONED_DATA_2ND.toPage()); Collection<Slice> fragments = getFutureValue(sink.finish()); metadata.finishInsert(session, insertTableHandle, fragments); // verify all temp files start with the unique prefix HdfsContext context = new HdfsContext(session, tableName.getSchemaName(), tableName.getTableName()); Set<String> tempFiles = listAllDataFiles(context, getStagingPathRoot(insertTableHandle)); assertTrue(!tempFiles.isEmpty()); for (String filePath : tempFiles) { assertTrue(new Path(filePath).getName().startsWith(getFilePrefix(insertTableHandle))); } // rollback insert transaction.rollback(); } // verify the data is unchanged try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); MaterializedResult result = readTable(transaction, tableHandle, columnHandles, newSession(), TupleDomain.all(), OptionalInt.empty(), Optional.empty()); assertEqualsIgnoreOrder(result.getMaterializedRows(), CREATE_TABLE_PARTITIONED_DATA.getMaterializedRows()); // verify we did not modify the table directory assertEquals(listAllDataFiles(transaction, tableName.getSchemaName(), tableName.getTableName()), existingFiles); // verify temp directory is empty HdfsContext context = new HdfsContext(session, tableName.getSchemaName(), tableName.getTableName()); assertTrue(listAllDataFiles(context, stagingPathRoot).isEmpty()); } } private void doInsertUnsupportedWriteType(HiveStorageFormat storageFormat, SchemaTableName tableName) throws Exception { List<Column> columns = ImmutableList.of(new Column("dummy", HiveType.valueOf("uniontype<smallint,tinyint>"), Optional.empty())); List<Column> partitionColumns = ImmutableList.of(new Column("name", HIVE_STRING, Optional.empty())); createEmptyTable(tableName, storageFormat, columns, partitionColumns); try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); metadata.beginInsert(session, tableHandle); fail("expected failure"); } catch (PrestoException e) { assertThat(e).hasMessageMatching("Inserting into Hive table .* with column type uniontype<smallint,tinyint> not supported"); } } private void doInsertIntoExistingPartition(HiveStorageFormat storageFormat, SchemaTableName tableName) throws Exception { // creating the table doCreateEmptyTable(tableName, storageFormat, CREATE_TABLE_COLUMNS_PARTITIONED); MaterializedResult.Builder resultBuilder = MaterializedResult.resultBuilder(SESSION, CREATE_TABLE_PARTITIONED_DATA.getTypes()); for (int i = 0; i < 3; i++) { // insert the data insertData(tableName, CREATE_TABLE_PARTITIONED_DATA); try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); // verify partitions were created List<String> partitionNames = transaction.getMetastore(tableName.getSchemaName()).getPartitionNames(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(() -> new AssertionError("Table does not exist: " + tableName)); assertEqualsIgnoreOrder(partitionNames, CREATE_TABLE_PARTITIONED_DATA.getMaterializedRows().stream() .map(row -> "ds=" + row.getField(CREATE_TABLE_PARTITIONED_DATA.getTypes().size() - 1)) .collect(toList())); // load the new table List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); // verify the data resultBuilder.rows(CREATE_TABLE_PARTITIONED_DATA.getMaterializedRows()); MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.of(storageFormat)); assertEqualsIgnoreOrder(result.getMaterializedRows(), resultBuilder.build().getMaterializedRows()); // test statistics for (String partitionName : partitionNames) { HiveBasicStatistics statistics = getBasicStatisticsForPartition(transaction, tableName, partitionName); assertEquals(statistics.getRowCount().getAsLong(), i + 1L); assertEquals(statistics.getFileCount().getAsLong(), i + 1L); assertGreaterThan(statistics.getInMemoryDataSizeInBytes().getAsLong(), 0L); assertGreaterThan(statistics.getOnDiskDataSizeInBytes().getAsLong(), 0L); } } } // test rollback Set<String> existingFiles; Path stagingPathRoot; try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); existingFiles = listAllDataFiles(transaction, tableName.getSchemaName(), tableName.getTableName()); assertFalse(existingFiles.isEmpty()); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); // "stage" insert data ConnectorInsertTableHandle insertTableHandle = metadata.beginInsert(session, tableHandle); stagingPathRoot = getStagingPathRoot(insertTableHandle); ConnectorPageSink sink = pageSinkProvider.createPageSink(transaction.getTransactionHandle(), session, insertTableHandle); sink.appendPage(CREATE_TABLE_PARTITIONED_DATA.toPage()); sink.appendPage(CREATE_TABLE_PARTITIONED_DATA.toPage()); Collection<Slice> fragments = getFutureValue(sink.finish()); metadata.finishInsert(session, insertTableHandle, fragments); // verify all temp files start with the unique prefix HdfsContext context = new HdfsContext(session, tableName.getSchemaName(), tableName.getTableName()); Set<String> tempFiles = listAllDataFiles(context, getStagingPathRoot(insertTableHandle)); assertTrue(!tempFiles.isEmpty()); for (String filePath : tempFiles) { assertTrue(new Path(filePath).getName().startsWith(getFilePrefix(insertTableHandle))); } // verify statistics are visible from within of the current transaction List<String> partitionNames = transaction.getMetastore(tableName.getSchemaName()).getPartitionNames(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(() -> new AssertionError("Table does not exist: " + tableName)); for (String partitionName : partitionNames) { HiveBasicStatistics partitionStatistics = getBasicStatisticsForPartition(transaction, tableName, partitionName); assertEquals(partitionStatistics.getRowCount().getAsLong(), 5L); } // rollback insert transaction.rollback(); } try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); // verify the data is unchanged MaterializedResult result = readTable(transaction, tableHandle, columnHandles, newSession(), TupleDomain.all(), OptionalInt.empty(), Optional.empty()); assertEqualsIgnoreOrder(result.getMaterializedRows(), resultBuilder.build().getMaterializedRows()); // verify we did not modify the table directory assertEquals(listAllDataFiles(transaction, tableName.getSchemaName(), tableName.getTableName()), existingFiles); // verify temp directory is empty HdfsContext context = new HdfsContext(session, tableName.getSchemaName(), tableName.getTableName()); assertTrue(listAllDataFiles(context, stagingPathRoot).isEmpty()); // verify statistics have been rolled back List<String> partitionNames = transaction.getMetastore(tableName.getSchemaName()).getPartitionNames(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(() -> new AssertionError("Table does not exist: " + tableName)); for (String partitionName : partitionNames) { HiveBasicStatistics partitionStatistics = getBasicStatisticsForPartition(transaction, tableName, partitionName); assertEquals(partitionStatistics.getRowCount().getAsLong(), 3L); } } } private void doInsertIntoExistingPartitionEmptyStatistics(HiveStorageFormat storageFormat, SchemaTableName tableName) throws Exception { doCreateEmptyTable(tableName, storageFormat, CREATE_TABLE_COLUMNS_PARTITIONED); insertData(tableName, CREATE_TABLE_PARTITIONED_DATA); eraseStatistics(tableName); insertData(tableName, CREATE_TABLE_PARTITIONED_DATA); try (Transaction transaction = newTransaction()) { List<String> partitionNames = transaction.getMetastore(tableName.getSchemaName()).getPartitionNames(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(() -> new AssertionError("Table does not exist: " + tableName)); for (String partitionName : partitionNames) { HiveBasicStatistics statistics = getBasicStatisticsForPartition(transaction, tableName, partitionName); assertThat(statistics.getRowCount()).isNotPresent(); assertThat(statistics.getInMemoryDataSizeInBytes()).isNotPresent(); // fileCount and rawSize statistics are computed on the fly by the metastore, thus cannot be erased } } } private static HiveBasicStatistics getBasicStatisticsForTable(Transaction transaction, SchemaTableName table) { return transaction .getMetastore(table.getSchemaName()) .getTableStatistics(table.getSchemaName(), table.getTableName()) .getBasicStatistics(); } private static HiveBasicStatistics getBasicStatisticsForPartition(Transaction transaction, SchemaTableName table, String partitionName) { return transaction .getMetastore(table.getSchemaName()) .getPartitionStatistics(table.getSchemaName(), table.getTableName(), ImmutableSet.of(partitionName)) .get(partitionName) .getBasicStatistics(); } private void eraseStatistics(SchemaTableName schemaTableName) { ExtendedHiveMetastore metastoreClient = getMetastoreClient(schemaTableName.getSchemaName()); metastoreClient.updateTableStatistics(schemaTableName.getSchemaName(), schemaTableName.getTableName(), statistics -> new PartitionStatistics(createEmptyStatistics(), ImmutableMap.of())); Table table = metastoreClient.getTable(schemaTableName.getSchemaName(), schemaTableName.getTableName()) .orElseThrow(() -> new TableNotFoundException(schemaTableName)); List<String> partitionColumns = table.getPartitionColumns().stream() .map(Column::getName) .collect(toImmutableList()); if (!table.getPartitionColumns().isEmpty()) { List<String> partitionNames = metastoreClient.getPartitionNames(schemaTableName.getSchemaName(), schemaTableName.getTableName()) .orElse(ImmutableList.of()); List<Partition> partitions = metastoreClient .getPartitionsByNames(schemaTableName.getSchemaName(), schemaTableName.getTableName(), partitionNames) .entrySet() .stream() .map(Map.Entry::getValue) .filter(Optional::isPresent) .map(Optional::get) .collect(toImmutableList()); for (Partition partition : partitions) { metastoreClient.updatePartitionStatistics( schemaTableName.getSchemaName(), schemaTableName.getTableName(), makePartName(partitionColumns, partition.getValues()), statistics -> new PartitionStatistics(createEmptyStatistics(), ImmutableMap.of())); } } } /** * @return query id */ private String insertData(SchemaTableName tableName, MaterializedResult data) throws Exception { Path writePath; Path targetPath; String queryId; try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); ConnectorInsertTableHandle insertTableHandle = metadata.beginInsert(session, tableHandle); queryId = session.getQueryId(); writePath = getStagingPathRoot(insertTableHandle); targetPath = getTargetPathRoot(insertTableHandle); ConnectorPageSink sink = pageSinkProvider.createPageSink(transaction.getTransactionHandle(), session, insertTableHandle); // write data sink.appendPage(data.toPage()); Collection<Slice> fragments = getFutureValue(sink.finish()); // commit the insert metadata.finishInsert(session, insertTableHandle, fragments); transaction.commit(); } // check that temporary files are removed if (!writePath.equals(targetPath)) { HdfsContext context = new HdfsContext(newSession(), tableName.getSchemaName(), tableName.getTableName()); FileSystem fileSystem = hdfsEnvironment.getFileSystem(context, writePath); assertFalse(fileSystem.exists(writePath)); } return queryId; } private void doTestMetadataDelete(HiveStorageFormat storageFormat, SchemaTableName tableName) throws Exception { // creating the table doCreateEmptyTable(tableName, storageFormat, CREATE_TABLE_COLUMNS_PARTITIONED); insertData(tableName, CREATE_TABLE_PARTITIONED_DATA); MaterializedResult.Builder expectedResultBuilder = MaterializedResult.resultBuilder(SESSION, CREATE_TABLE_PARTITIONED_DATA.getTypes()); expectedResultBuilder.rows(CREATE_TABLE_PARTITIONED_DATA.getMaterializedRows()); try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); // verify partitions were created List<String> partitionNames = transaction.getMetastore(tableName.getSchemaName()).getPartitionNames(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(() -> new AssertionError("Table does not exist: " + tableName)); assertEqualsIgnoreOrder(partitionNames, CREATE_TABLE_PARTITIONED_DATA.getMaterializedRows().stream() .map(row -> "ds=" + row.getField(CREATE_TABLE_PARTITIONED_DATA.getTypes().size() - 1)) .collect(toList())); // verify table directory is not empty Set<String> filesAfterInsert = listAllDataFiles(transaction, tableName.getSchemaName(), tableName.getTableName()); assertFalse(filesAfterInsert.isEmpty()); // verify the data ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.of(storageFormat)); assertEqualsIgnoreOrder(result.getMaterializedRows(), expectedResultBuilder.build().getMaterializedRows()); } try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); // get ds column handle ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); HiveColumnHandle dsColumnHandle = (HiveColumnHandle) metadata.getColumnHandles(session, tableHandle).get("ds"); // delete ds=2015-07-03 session = newSession(); TupleDomain<ColumnHandle> tupleDomain = TupleDomain.fromFixedValues(ImmutableMap.of(dsColumnHandle, NullableValue.of(createUnboundedVarcharType(), utf8Slice("2015-07-03")))); Constraint<ColumnHandle> constraint = new Constraint<>(tupleDomain, convertToPredicate(tupleDomain)); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(session, tableHandle, constraint, Optional.empty()); ConnectorTableLayoutHandle tableLayoutHandle = getOnlyElement(tableLayoutResults).getTableLayout().getHandle(); metadata.metadataDelete(session, tableHandle, tableLayoutHandle); transaction.commit(); } try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); HiveColumnHandle dsColumnHandle = (HiveColumnHandle) metadata.getColumnHandles(session, tableHandle).get("ds"); int dsColumnOrdinalPosition = columnHandles.indexOf(dsColumnHandle); // verify the data session = newSession(); ImmutableList<MaterializedRow> expectedRows = expectedResultBuilder.build().getMaterializedRows().stream() .filter(row -> !"2015-07-03".equals(row.getField(dsColumnOrdinalPosition))) .collect(toImmutableList()); MaterializedResult actualAfterDelete = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.of(storageFormat)); assertEqualsIgnoreOrder(actualAfterDelete.getMaterializedRows(), expectedRows); } try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); HiveColumnHandle dsColumnHandle = (HiveColumnHandle) metadata.getColumnHandles(session, tableHandle).get("ds"); // delete ds=2015-07-01 and 2015-07-02 session = newSession(); TupleDomain<ColumnHandle> tupleDomain2 = TupleDomain.withColumnDomains( ImmutableMap.of(dsColumnHandle, Domain.create(ValueSet.ofRanges(Range.range(createUnboundedVarcharType(), utf8Slice("2015-07-01"), true, utf8Slice("2015-07-02"), true)), false))); Constraint<ColumnHandle> constraint2 = new Constraint<>(tupleDomain2, convertToPredicate(tupleDomain2)); List<ConnectorTableLayoutResult> tableLayoutResults2 = metadata.getTableLayouts(session, tableHandle, constraint2, Optional.empty()); ConnectorTableLayoutHandle tableLayoutHandle2 = getOnlyElement(tableLayoutResults2).getTableLayout().getHandle(); metadata.metadataDelete(session, tableHandle, tableLayoutHandle2); transaction.commit(); } try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = ImmutableList.copyOf(metadata.getColumnHandles(session, tableHandle).values()); // verify the data session = newSession(); MaterializedResult actualAfterDelete2 = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.of(storageFormat)); assertEqualsIgnoreOrder(actualAfterDelete2.getMaterializedRows(), ImmutableList.of()); // verify table directory is empty Set<String> filesAfterDelete = listAllDataFiles(transaction, tableName.getSchemaName(), tableName.getTableName()); assertTrue(filesAfterDelete.isEmpty()); } } protected void assertGetRecordsOptional(String tableName, HiveStorageFormat hiveStorageFormat) throws Exception { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); if (metadata.getTableHandle(newSession(), new SchemaTableName(database, tableName)) != null) { assertGetRecords(tableName, hiveStorageFormat); } } } protected void assertGetRecords(String tableName, HiveStorageFormat hiveStorageFormat) throws Exception { try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, new SchemaTableName(database, tableName)); ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(session, tableHandle); HiveSplit hiveSplit = getHiveSplit(tableHandle); List<ColumnHandle> columnHandles = ImmutableList.copyOf(metadata.getColumnHandles(session, tableHandle).values()); ConnectorPageSource pageSource = pageSourceProvider.createPageSource(transaction.getTransactionHandle(), session, hiveSplit, columnHandles); assertGetRecords(hiveStorageFormat, tableMetadata, hiveSplit, pageSource, columnHandles); } } protected HiveSplit getHiveSplit(ConnectorTableHandle tableHandle) { List<ConnectorSplit> splits = getAllSplits(tableHandle, TupleDomain.all()); assertEquals(splits.size(), 1); return (HiveSplit) getOnlyElement(splits); } protected void assertGetRecords( HiveStorageFormat hiveStorageFormat, ConnectorTableMetadata tableMetadata, HiveSplit hiveSplit, ConnectorPageSource pageSource, List<? extends ColumnHandle> columnHandles) throws IOException { try { MaterializedResult result = materializeSourceDataStream(newSession(), pageSource, getTypes(columnHandles)); assertPageSourceType(pageSource, hiveStorageFormat); ImmutableMap<String, Integer> columnIndex = indexColumns(tableMetadata); long rowNumber = 0; long completedBytes = 0; for (MaterializedRow row : result) { try { assertValueTypes(row, tableMetadata.getColumns()); } catch (RuntimeException e) { throw new RuntimeException("row " + rowNumber, e); } rowNumber++; Integer index; Object value; // STRING index = columnIndex.get("t_string"); value = row.getField(index); if (rowNumber % 19 == 0) { assertNull(value); } else if (rowNumber % 19 == 1) { assertEquals(value, ""); } else { assertEquals(value, "test"); } // NUMBERS assertEquals(row.getField(columnIndex.get("t_tinyint")), (byte) (1 + rowNumber)); assertEquals(row.getField(columnIndex.get("t_smallint")), (short) (2 + rowNumber)); assertEquals(row.getField(columnIndex.get("t_int")), (int) (3 + rowNumber)); index = columnIndex.get("t_bigint"); if ((rowNumber % 13) == 0) { assertNull(row.getField(index)); } else { assertEquals(row.getField(index), 4 + rowNumber); } assertEquals((Float) row.getField(columnIndex.get("t_float")), 5.1f + rowNumber, 0.001); assertEquals(row.getField(columnIndex.get("t_double")), 6.2 + rowNumber); // BOOLEAN index = columnIndex.get("t_boolean"); if ((rowNumber % 3) == 2) { assertNull(row.getField(index)); } else { assertEquals(row.getField(index), (rowNumber % 3) != 0); } // TIMESTAMP index = columnIndex.get("t_timestamp"); if (index != null) { if ((rowNumber % 17) == 0) { assertNull(row.getField(index)); } else { SqlTimestamp expected = sqlTimestampOf(2011, 5, 6, 7, 8, 9, 123, timeZone, UTC_KEY, SESSION); assertEquals(row.getField(index), expected); } } // BINARY index = columnIndex.get("t_binary"); if (index != null) { if ((rowNumber % 23) == 0) { assertNull(row.getField(index)); } else { assertEquals(row.getField(index), new SqlVarbinary("test binary".getBytes(UTF_8))); } } // DATE index = columnIndex.get("t_date"); if (index != null) { if ((rowNumber % 37) == 0) { assertNull(row.getField(index)); } else { SqlDate expected = new SqlDate(toIntExact(MILLISECONDS.toDays(new DateTime(2013, 8, 9, 0, 0, 0, UTC).getMillis()))); assertEquals(row.getField(index), expected); } } // VARCHAR(50) index = columnIndex.get("t_varchar"); if (index != null) { value = row.getField(index); if (rowNumber % 39 == 0) { assertNull(value); } else if (rowNumber % 39 == 1) { // https://issues.apache.org/jira/browse/HIVE-13289 // RCBINARY reads empty VARCHAR as null if (hiveStorageFormat == RCBINARY) { assertNull(value); } else { assertEquals(value, ""); } } else { assertEquals(value, "test varchar"); } } //CHAR(25) index = columnIndex.get("t_char"); if (index != null) { value = row.getField(index); if ((rowNumber % 41) == 0) { assertNull(value); } else { assertEquals(value, (rowNumber % 41) == 1 ? " " : "test char "); } } // MAP<STRING, STRING> index = columnIndex.get("t_map"); if (index != null) { if ((rowNumber % 27) == 0) { assertNull(row.getField(index)); } else { assertEquals(row.getField(index), ImmutableMap.of("test key", "test value")); } } // ARRAY<STRING> index = columnIndex.get("t_array_string"); if (index != null) { if ((rowNumber % 29) == 0) { assertNull(row.getField(index)); } else { assertEquals(row.getField(index), ImmutableList.of("abc", "xyz", "data")); } } // ARRAY<STRUCT<s_string: STRING, s_double:DOUBLE>> index = columnIndex.get("t_array_struct"); if (index != null) { if ((rowNumber % 31) == 0) { assertNull(row.getField(index)); } else { List<Object> expected1 = ImmutableList.of("test abc", 0.1); List<Object> expected2 = ImmutableList.of("test xyz", 0.2); assertEquals(row.getField(index), ImmutableList.of(expected1, expected2)); } } // STRUCT<s_string: STRING, s_double:DOUBLE> index = columnIndex.get("t_struct"); if (index != null) { if ((rowNumber % 31) == 0) { assertNull(row.getField(index)); } else { assertTrue(row.getField(index) instanceof List); List values = (List) row.getField(index); assertEquals(values.size(), 2); assertEquals(values.get(0), "test abc"); assertEquals(values.get(1), 0.1); } } // MAP<INT, ARRAY<STRUCT<s_string: STRING, s_double:DOUBLE>>> index = columnIndex.get("t_complex"); if (index != null) { if ((rowNumber % 33) == 0) { assertNull(row.getField(index)); } else { List<Object> expected1 = ImmutableList.of("test abc", 0.1); List<Object> expected2 = ImmutableList.of("test xyz", 0.2); assertEquals(row.getField(index), ImmutableMap.of(1, ImmutableList.of(expected1, expected2))); } } // NEW COLUMN assertNull(row.getField(columnIndex.get("new_column"))); long newCompletedBytes = pageSource.getCompletedBytes(); assertTrue(newCompletedBytes >= completedBytes); assertTrue(newCompletedBytes <= hiveSplit.getLength()); completedBytes = newCompletedBytes; } assertTrue(completedBytes <= hiveSplit.getLength()); assertEquals(rowNumber, 100); } finally { pageSource.close(); } } protected void dropTable(SchemaTableName table) { try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorSession session = newSession(); ConnectorTableHandle handle = metadata.getTableHandle(session, table); if (handle == null) { return; } metadata.dropTable(session, handle); try { // todo I have no idea why this is needed... maybe there is a propagation delay in the metastore? metadata.dropTable(session, handle); fail("expected NotFoundException"); } catch (TableNotFoundException expected) { } transaction.commit(); } catch (Exception e) { Logger.get(getClass()).warn(e, "failed to drop table"); } } protected ConnectorTableHandle getTableHandle(ConnectorMetadata metadata, SchemaTableName tableName) { ConnectorTableHandle handle = metadata.getTableHandle(newSession(), tableName); checkArgument(handle != null, "table not found: %s", tableName); return handle; } private MaterializedResult readTable( Transaction transaction, ConnectorTableHandle tableHandle, List<ColumnHandle> columnHandles, ConnectorSession session, TupleDomain<ColumnHandle> tupleDomain, OptionalInt expectedSplitCount, Optional<HiveStorageFormat> expectedStorageFormat) throws Exception { List<ConnectorTableLayoutResult> tableLayoutResults = transaction.getMetadata().getTableLayouts( session, tableHandle, new Constraint<>(tupleDomain), Optional.empty()); ConnectorTableLayoutHandle layoutHandle = getOnlyElement(tableLayoutResults).getTableLayout().getHandle(); List<ConnectorSplit> splits = getAllSplits(splitManager.getSplits(transaction.getTransactionHandle(), session, layoutHandle, UNGROUPED_SCHEDULING)); if (expectedSplitCount.isPresent()) { assertEquals(splits.size(), expectedSplitCount.getAsInt()); } ImmutableList.Builder<MaterializedRow> allRows = ImmutableList.builder(); for (ConnectorSplit split : splits) { try (ConnectorPageSource pageSource = pageSourceProvider.createPageSource(transaction.getTransactionHandle(), session, split, columnHandles)) { expectedStorageFormat.ifPresent(format -> assertPageSourceType(pageSource, format)); MaterializedResult result = materializeSourceDataStream(session, pageSource, getTypes(columnHandles)); allRows.addAll(result.getMaterializedRows()); } } return new MaterializedResult(allRows.build(), getTypes(columnHandles)); } public ExtendedHiveMetastore getMetastoreClient(String namespace) { return metastoreClient; } public LocationService getLocationService(String namespace) { return locationService; } protected static int getSplitCount(ConnectorSplitSource splitSource) { int splitCount = 0; while (!splitSource.isFinished()) { splitCount += getFutureValue(splitSource.getNextBatch(NOT_PARTITIONED, 1000)).getSplits().size(); } return splitCount; } private List<ConnectorSplit> getAllSplits(ConnectorTableHandle tableHandle, TupleDomain<ColumnHandle> tupleDomain) { try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(session, tableHandle, new Constraint<>(tupleDomain), Optional.empty()); ConnectorTableLayoutHandle layoutHandle = getOnlyElement(tableLayoutResults).getTableLayout().getHandle(); return getAllSplits(splitManager.getSplits(transaction.getTransactionHandle(), session, layoutHandle, UNGROUPED_SCHEDULING)); } } protected static List<ConnectorSplit> getAllSplits(ConnectorSplitSource splitSource) { ImmutableList.Builder<ConnectorSplit> splits = ImmutableList.builder(); while (!splitSource.isFinished()) { splits.addAll(getFutureValue(splitSource.getNextBatch(NOT_PARTITIONED, 1000)).getSplits()); } return splits.build(); } protected List<?> getAllPartitions(ConnectorTableLayoutHandle layoutHandle) { return ((HiveTableLayoutHandle) layoutHandle).getPartitions() .orElseThrow(() -> new AssertionError("layout has no partitions")); } protected String getPartitionId(Object partition) { return ((HivePartition) partition).getPartitionId(); } protected static void assertPageSourceType(ConnectorPageSource pageSource, HiveStorageFormat hiveStorageFormat) { if (pageSource instanceof RecordPageSource) { RecordCursor hiveRecordCursor = ((RecordPageSource) pageSource).getCursor(); hiveRecordCursor = ((HiveRecordCursor) hiveRecordCursor).getRegularColumnRecordCursor(); if (hiveRecordCursor instanceof HiveCoercionRecordCursor) { hiveRecordCursor = ((HiveCoercionRecordCursor) hiveRecordCursor).getRegularColumnRecordCursor(); } assertInstanceOf(hiveRecordCursor, recordCursorType(hiveStorageFormat), hiveStorageFormat.name()); } else { assertInstanceOf(((HivePageSource) pageSource).getPageSource(), pageSourceType(hiveStorageFormat), hiveStorageFormat.name()); } } private static Class<? extends RecordCursor> recordCursorType(HiveStorageFormat hiveStorageFormat) { switch (hiveStorageFormat) { case PARQUET: return ParquetHiveRecordCursor.class; } return GenericHiveRecordCursor.class; } private static Class<? extends ConnectorPageSource> pageSourceType(HiveStorageFormat hiveStorageFormat) { switch (hiveStorageFormat) { case RCTEXT: case RCBINARY: return RcFilePageSource.class; case ORC: case DWRF: return OrcPageSource.class; case PARQUET: return ParquetPageSource.class; default: throw new AssertionError("File type does not use a PageSource: " + hiveStorageFormat); } } private static void assertValueTypes(MaterializedRow row, List<ColumnMetadata> schema) { for (int columnIndex = 0; columnIndex < schema.size(); columnIndex++) { ColumnMetadata column = schema.get(columnIndex); Object value = row.getField(columnIndex); if (value != null) { if (BOOLEAN.equals(column.getType())) { assertInstanceOf(value, Boolean.class); } else if (TINYINT.equals(column.getType())) { assertInstanceOf(value, Byte.class); } else if (SMALLINT.equals(column.getType())) { assertInstanceOf(value, Short.class); } else if (INTEGER.equals(column.getType())) { assertInstanceOf(value, Integer.class); } else if (BIGINT.equals(column.getType())) { assertInstanceOf(value, Long.class); } else if (DOUBLE.equals(column.getType())) { assertInstanceOf(value, Double.class); } else if (REAL.equals(column.getType())) { assertInstanceOf(value, Float.class); } else if (isVarcharType(column.getType())) { assertInstanceOf(value, String.class); } else if (isCharType(column.getType())) { assertInstanceOf(value, String.class); } else if (VARBINARY.equals(column.getType())) { assertInstanceOf(value, SqlVarbinary.class); } else if (TIMESTAMP.equals(column.getType())) { assertInstanceOf(value, SqlTimestamp.class); } else if (DATE.equals(column.getType())) { assertInstanceOf(value, SqlDate.class); } else if (column.getType() instanceof ArrayType || column.getType() instanceof RowType) { assertInstanceOf(value, List.class); } else if (column.getType() instanceof MapType) { assertInstanceOf(value, Map.class); } else { fail("Unknown primitive type " + columnIndex); } } } } private static void assertPrimitiveField(Map<String, ColumnMetadata> map, String name, Type type, boolean partitionKey) { assertTrue(map.containsKey(name)); ColumnMetadata column = map.get(name); assertEquals(column.getType(), type, name); assertEquals(column.getExtraInfo(), columnExtraInfo(partitionKey)); } protected static ImmutableMap<String, Integer> indexColumns(List<ColumnHandle> columnHandles) { ImmutableMap.Builder<String, Integer> index = ImmutableMap.builder(); int i = 0; for (ColumnHandle columnHandle : columnHandles) { HiveColumnHandle hiveColumnHandle = (HiveColumnHandle) columnHandle; index.put(hiveColumnHandle.getName(), i); i++; } return index.build(); } protected static ImmutableMap<String, Integer> indexColumns(ConnectorTableMetadata tableMetadata) { ImmutableMap.Builder<String, Integer> index = ImmutableMap.builder(); int i = 0; for (ColumnMetadata columnMetadata : tableMetadata.getColumns()) { index.put(columnMetadata.getName(), i); i++; } return index.build(); } protected SchemaTableName temporaryTable(String tableName) { return temporaryTable(database, tableName); } protected static SchemaTableName temporaryTable(String database, String tableName) { String randomName = UUID.randomUUID().toString().toLowerCase(ENGLISH).replace("-", ""); return new SchemaTableName(database, TEMPORARY_TABLE_PREFIX + tableName + "_" + randomName); } protected static Map<String, Object> createTableProperties(HiveStorageFormat storageFormat) { return createTableProperties(storageFormat, ImmutableList.of()); } private static Map<String, Object> createTableProperties(HiveStorageFormat storageFormat, Iterable<String> parititonedBy) { return ImmutableMap.<String, Object>builder() .put(STORAGE_FORMAT_PROPERTY, storageFormat) .put(PARTITIONED_BY_PROPERTY, ImmutableList.copyOf(parititonedBy)) .put(BUCKETED_BY_PROPERTY, ImmutableList.of()) .put(BUCKET_COUNT_PROPERTY, 0) .put(SORTED_BY_PROPERTY, ImmutableList.of()) .build(); } protected static List<ColumnHandle> filterNonHiddenColumnHandles(Collection<ColumnHandle> columnHandles) { return columnHandles.stream() .filter(columnHandle -> !((HiveColumnHandle) columnHandle).isHidden()) .collect(toList()); } protected static List<ColumnMetadata> filterNonHiddenColumnMetadata(Collection<ColumnMetadata> columnMetadatas) { return columnMetadatas.stream() .filter(columnMetadata -> !columnMetadata.isHidden()) .collect(toList()); } private void createEmptyTable(SchemaTableName schemaTableName, HiveStorageFormat hiveStorageFormat, List<Column> columns, List<Column> partitionColumns) throws Exception { createEmptyTable(schemaTableName, hiveStorageFormat, columns, partitionColumns, Optional.empty()); } private void createEmptyTable(SchemaTableName schemaTableName, HiveStorageFormat hiveStorageFormat, List<Column> columns, List<Column> partitionColumns, Optional<HiveBucketProperty> bucketProperty) throws Exception { Path targetPath; try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); String tableOwner = session.getUser(); String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); LocationService locationService = getLocationService(schemaName); LocationHandle locationHandle = locationService.forNewTable(transaction.getMetastore(schemaName), session, schemaName, tableName); targetPath = locationService.getQueryWriteInfo(locationHandle).getTargetPath(); Table.Builder tableBuilder = Table.builder() .setDatabaseName(schemaName) .setTableName(tableName) .setOwner(tableOwner) .setTableType(TableType.MANAGED_TABLE.name()) .setParameters(ImmutableMap.of( PRESTO_VERSION_NAME, TEST_SERVER_VERSION, PRESTO_QUERY_ID_NAME, session.getQueryId())) .setDataColumns(columns) .setPartitionColumns(partitionColumns); tableBuilder.getStorageBuilder() .setLocation(targetPath.toString()) .setStorageFormat(StorageFormat.create(hiveStorageFormat.getSerDe(), hiveStorageFormat.getInputFormat(), hiveStorageFormat.getOutputFormat())) .setBucketProperty(bucketProperty) .setSerdeParameters(ImmutableMap.of()); PrincipalPrivileges principalPrivileges = testingPrincipalPrivilege(tableOwner); transaction.getMetastore(schemaName).createTable(session, tableBuilder.build(), principalPrivileges, Optional.empty(), true, EMPTY_TABLE_STATISTICS); transaction.commit(); } HdfsContext context = new HdfsContext(newSession(), schemaTableName.getSchemaName(), schemaTableName.getTableName()); List<String> targetDirectoryList = listDirectory(context, targetPath); assertEquals(targetDirectoryList, ImmutableList.of()); } private void alterBucketProperty(SchemaTableName schemaTableName, Optional<HiveBucketProperty> bucketProperty) { try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); String tableOwner = session.getUser(); String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); Optional<Table> table = transaction.getMetastore(schemaName).getTable(schemaName, tableName); Table.Builder tableBuilder = Table.builder(table.get()); tableBuilder.getStorageBuilder().setBucketProperty(bucketProperty); PrincipalPrivileges principalPrivileges = testingPrincipalPrivilege(tableOwner); // hack: replaceView can be used as replaceTable despite its name transaction.getMetastore(schemaName).replaceView(schemaName, tableName, tableBuilder.build(), principalPrivileges); transaction.commit(); } } private PrincipalPrivileges testingPrincipalPrivilege(String tableOwner) { return new PrincipalPrivileges( ImmutableMultimap.<String, HivePrivilegeInfo>builder() .put(tableOwner, new HivePrivilegeInfo(HivePrivilege.SELECT, true)) .put(tableOwner, new HivePrivilegeInfo(HivePrivilege.INSERT, true)) .put(tableOwner, new HivePrivilegeInfo(HivePrivilege.UPDATE, true)) .put(tableOwner, new HivePrivilegeInfo(HivePrivilege.DELETE, true)) .build(), ImmutableMultimap.of()); } private List<String> listDirectory(HdfsContext context, Path path) throws IOException { FileSystem fileSystem = hdfsEnvironment.getFileSystem(context, path); return Arrays.stream(fileSystem.listStatus(path)) .map(FileStatus::getPath) .map(Path::getName) .filter(name -> !name.startsWith(".presto")) .collect(toList()); } @Test public void testTransactionDeleteInsert() throws Exception { doTestTransactionDeleteInsert( RCBINARY, true, ImmutableList.<TransactionDeleteInsertTestCase>builder() .add(new TransactionDeleteInsertTestCase(false, false, ROLLBACK_RIGHT_AWAY, Optional.empty())) .add(new TransactionDeleteInsertTestCase(false, false, ROLLBACK_AFTER_DELETE, Optional.empty())) .add(new TransactionDeleteInsertTestCase(false, false, ROLLBACK_AFTER_BEGIN_INSERT, Optional.empty())) .add(new TransactionDeleteInsertTestCase(false, false, ROLLBACK_AFTER_APPEND_PAGE, Optional.empty())) .add(new TransactionDeleteInsertTestCase(false, false, ROLLBACK_AFTER_SINK_FINISH, Optional.empty())) .add(new TransactionDeleteInsertTestCase(false, false, ROLLBACK_AFTER_FINISH_INSERT, Optional.empty())) .add(new TransactionDeleteInsertTestCase(false, false, COMMIT, Optional.of(new AddPartitionFailure()))) .add(new TransactionDeleteInsertTestCase(false, false, COMMIT, Optional.of(new DirectoryRenameFailure()))) .add(new TransactionDeleteInsertTestCase(false, false, COMMIT, Optional.of(new FileRenameFailure()))) .add(new TransactionDeleteInsertTestCase(true, false, COMMIT, Optional.of(new DropPartitionFailure()))) .add(new TransactionDeleteInsertTestCase(true, true, COMMIT, Optional.empty())) .build()); } protected void doTestTransactionDeleteInsert(HiveStorageFormat storageFormat, boolean allowInsertExisting, List<TransactionDeleteInsertTestCase> testCases) throws Exception { // There are 4 types of operations on a partition: add, drop, alter (drop then add), insert existing. // There are 12 partitions in this test, 3 for each type. // 3 is chosen to verify that cleanups, commit aborts, rollbacks are always as complete as possible regardless of failure. MaterializedResult beforeData = MaterializedResult.resultBuilder(SESSION, BIGINT, createUnboundedVarcharType(), createUnboundedVarcharType()) .row(110L, "a", "alter1") .row(120L, "a", "insert1") .row(140L, "a", "drop1") .row(210L, "b", "drop2") .row(310L, "c", "alter2") .row(320L, "c", "alter3") .row(510L, "e", "drop3") .row(610L, "f", "insert2") .row(620L, "f", "insert3") .build(); Domain domainToDrop = Domain.create(ValueSet.of( createUnboundedVarcharType(), utf8Slice("alter1"), utf8Slice("alter2"), utf8Slice("alter3"), utf8Slice("drop1"), utf8Slice("drop2"), utf8Slice("drop3")), false); List<MaterializedRow> extraRowsForInsertExisting = ImmutableList.of(); if (allowInsertExisting) { extraRowsForInsertExisting = MaterializedResult.resultBuilder(SESSION, BIGINT, createUnboundedVarcharType(), createUnboundedVarcharType()) .row(121L, "a", "insert1") .row(611L, "f", "insert2") .row(621L, "f", "insert3") .build() .getMaterializedRows(); } MaterializedResult insertData = MaterializedResult.resultBuilder(SESSION, BIGINT, createUnboundedVarcharType(), createUnboundedVarcharType()) .row(111L, "a", "alter1") .row(131L, "a", "add1") .row(221L, "b", "add2") .row(311L, "c", "alter2") .row(321L, "c", "alter3") .row(411L, "d", "add3") .rows(extraRowsForInsertExisting) .build(); MaterializedResult afterData = MaterializedResult.resultBuilder(SESSION, BIGINT, createUnboundedVarcharType(), createUnboundedVarcharType()) .row(120L, "a", "insert1") .row(610L, "f", "insert2") .row(620L, "f", "insert3") .rows(insertData.getMaterializedRows()) .build(); for (TransactionDeleteInsertTestCase testCase : testCases) { SchemaTableName temporaryDeleteInsert = temporaryTable("delete_insert"); try { createEmptyTable( temporaryDeleteInsert, storageFormat, ImmutableList.of(new Column("col1", HIVE_LONG, Optional.empty())), ImmutableList.of(new Column("pk1", HIVE_STRING, Optional.empty()), new Column("pk2", HIVE_STRING, Optional.empty()))); insertData(temporaryDeleteInsert, beforeData); try { doTestTransactionDeleteInsert( storageFormat, temporaryDeleteInsert, domainToDrop, insertData, testCase.isExpectCommitedData() ? afterData : beforeData, testCase.getTag(), testCase.isExpectQuerySucceed(), testCase.getConflictTrigger()); } catch (AssertionError e) { throw new AssertionError(format("Test case: %s", testCase.toString()), e); } } finally { dropTable(temporaryDeleteInsert); } } } private void doTestTransactionDeleteInsert( HiveStorageFormat storageFormat, SchemaTableName tableName, Domain domainToDrop, MaterializedResult insertData, MaterializedResult expectedData, TransactionDeleteInsertTestTag tag, boolean expectQuerySucceed, Optional<ConflictTrigger> conflictTrigger) throws Exception { Path writePath = null; Path targetPath = null; try (Transaction transaction = newTransaction()) { try { ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); ConnectorSession session; rollbackIfEquals(tag, ROLLBACK_RIGHT_AWAY); // Query 1: delete session = newSession(); HiveColumnHandle dsColumnHandle = (HiveColumnHandle) metadata.getColumnHandles(session, tableHandle).get("pk2"); TupleDomain<ColumnHandle> tupleDomain = TupleDomain.withColumnDomains(ImmutableMap.of( dsColumnHandle, domainToDrop)); Constraint<ColumnHandle> constraint = new Constraint<>(tupleDomain, convertToPredicate(tupleDomain)); List<ConnectorTableLayoutResult> tableLayoutResults = metadata.getTableLayouts(session, tableHandle, constraint, Optional.empty()); ConnectorTableLayoutHandle tableLayoutHandle = getOnlyElement(tableLayoutResults).getTableLayout().getHandle(); metadata.metadataDelete(session, tableHandle, tableLayoutHandle); rollbackIfEquals(tag, ROLLBACK_AFTER_DELETE); // Query 2: insert session = newSession(); ConnectorInsertTableHandle insertTableHandle = metadata.beginInsert(session, tableHandle); rollbackIfEquals(tag, ROLLBACK_AFTER_BEGIN_INSERT); writePath = getStagingPathRoot(insertTableHandle); targetPath = getTargetPathRoot(insertTableHandle); ConnectorPageSink sink = pageSinkProvider.createPageSink(transaction.getTransactionHandle(), session, insertTableHandle); sink.appendPage(insertData.toPage()); rollbackIfEquals(tag, ROLLBACK_AFTER_APPEND_PAGE); Collection<Slice> fragments = getFutureValue(sink.finish()); rollbackIfEquals(tag, ROLLBACK_AFTER_SINK_FINISH); metadata.finishInsert(session, insertTableHandle, fragments); rollbackIfEquals(tag, ROLLBACK_AFTER_FINISH_INSERT); assertEquals(tag, COMMIT); if (conflictTrigger.isPresent()) { JsonCodec<PartitionUpdate> partitionUpdateCodec = JsonCodec.jsonCodec(PartitionUpdate.class); List<PartitionUpdate> partitionUpdates = fragments.stream() .map(Slice::getBytes) .map(partitionUpdateCodec::fromJson) .collect(toList()); conflictTrigger.get().triggerConflict(session, tableName, insertTableHandle, partitionUpdates); } transaction.commit(); if (conflictTrigger.isPresent()) { assertTrue(expectQuerySucceed); conflictTrigger.get().verifyAndCleanup(tableName); } } catch (TestingRollbackException e) { transaction.rollback(); } catch (PrestoException e) { assertFalse(expectQuerySucceed); if (conflictTrigger.isPresent()) { conflictTrigger.get().verifyAndCleanup(tableName); } } } // check that temporary files are removed if (writePath != null && !writePath.equals(targetPath)) { HdfsContext context = new HdfsContext(newSession(), tableName.getSchemaName(), tableName.getTableName()); FileSystem fileSystem = hdfsEnvironment.getFileSystem(context, writePath); assertFalse(fileSystem.exists(writePath)); } try (Transaction transaction = newTransaction()) { // verify partitions List<String> partitionNames = transaction.getMetastore(tableName.getSchemaName()) .getPartitionNames(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(() -> new AssertionError("Table does not exist: " + tableName)); assertEqualsIgnoreOrder( partitionNames, expectedData.getMaterializedRows().stream() .map(row -> format("pk1=%s/pk2=%s", row.getField(1), row.getField(2))) .distinct() .collect(toList())); // load the new table ConnectorSession session = newSession(); ConnectorMetadata metadata = transaction.getMetadata(); ConnectorTableHandle tableHandle = getTableHandle(metadata, tableName); List<ColumnHandle> columnHandles = filterNonHiddenColumnHandles(metadata.getColumnHandles(session, tableHandle).values()); // verify the data MaterializedResult result = readTable(transaction, tableHandle, columnHandles, session, TupleDomain.all(), OptionalInt.empty(), Optional.of(storageFormat)); assertEqualsIgnoreOrder(result.getMaterializedRows(), expectedData.getMaterializedRows()); } } private static void rollbackIfEquals(TransactionDeleteInsertTestTag tag, TransactionDeleteInsertTestTag expectedTag) { if (expectedTag == tag) { throw new TestingRollbackException(); } } private static class TestingRollbackException extends RuntimeException { } protected static class TransactionDeleteInsertTestCase { private final boolean expectCommitedData; private final boolean expectQuerySucceed; private final TransactionDeleteInsertTestTag tag; private final Optional<ConflictTrigger> conflictTrigger; public TransactionDeleteInsertTestCase(boolean expectCommitedData, boolean expectQuerySucceed, TransactionDeleteInsertTestTag tag, Optional<ConflictTrigger> conflictTrigger) { this.expectCommitedData = expectCommitedData; this.expectQuerySucceed = expectQuerySucceed; this.tag = tag; this.conflictTrigger = conflictTrigger; } public boolean isExpectCommitedData() { return expectCommitedData; } public boolean isExpectQuerySucceed() { return expectQuerySucceed; } public TransactionDeleteInsertTestTag getTag() { return tag; } public Optional<ConflictTrigger> getConflictTrigger() { return conflictTrigger; } @Override public String toString() { return toStringHelper(this) .add("tag", tag) .add("conflictTrigger", conflictTrigger.map(conflictTrigger -> conflictTrigger.getClass().getName())) .add("expectCommitedData", expectCommitedData) .add("expectQuerySucceed", expectQuerySucceed) .toString(); } } protected enum TransactionDeleteInsertTestTag { ROLLBACK_RIGHT_AWAY, ROLLBACK_AFTER_DELETE, ROLLBACK_AFTER_BEGIN_INSERT, ROLLBACK_AFTER_APPEND_PAGE, ROLLBACK_AFTER_SINK_FINISH, ROLLBACK_AFTER_FINISH_INSERT, COMMIT, } protected interface ConflictTrigger { void triggerConflict(ConnectorSession session, SchemaTableName tableName, ConnectorInsertTableHandle insertTableHandle, List<PartitionUpdate> partitionUpdates) throws IOException; void verifyAndCleanup(SchemaTableName tableName) throws IOException; } protected class AddPartitionFailure implements ConflictTrigger { private final ImmutableList<String> copyPartitionFrom = ImmutableList.of("a", "insert1"); private final ImmutableList<String> partitionValueToConflict = ImmutableList.of("b", "add2"); private Partition conflictPartition; @Override public void triggerConflict(ConnectorSession session, SchemaTableName tableName, ConnectorInsertTableHandle insertTableHandle, List<PartitionUpdate> partitionUpdates) { // This method bypasses transaction interface because this method is inherently hacky and doesn't work well with the transaction abstraction. // Additionally, this method is not part of a test. Its purpose is to set up an environment for another test. ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); Optional<Partition> partition = metastoreClient.getPartition(tableName.getSchemaName(), tableName.getTableName(), copyPartitionFrom); conflictPartition = Partition.builder(partition.get()) .setValues(partitionValueToConflict) .build(); metastoreClient.addPartitions(tableName.getSchemaName(), tableName.getTableName(), ImmutableList.of(conflictPartition)); } @Override public void verifyAndCleanup(SchemaTableName tableName) { // This method bypasses transaction interface because this method is inherently hacky and doesn't work well with the transaction abstraction. // Additionally, this method is not part of a test. Its purpose is to set up an environment for another test. ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); Optional<Partition> actualPartition = metastoreClient.getPartition(tableName.getSchemaName(), tableName.getTableName(), partitionValueToConflict); // Make sure the partition inserted to trigger conflict was not overwritten // Checking storage location is sufficient because implement never uses .../pk1=a/pk2=a2 as the directory for partition [b, b2]. assertEquals(actualPartition.get().getStorage().getLocation(), conflictPartition.getStorage().getLocation()); metastoreClient.dropPartition(tableName.getSchemaName(), tableName.getTableName(), conflictPartition.getValues(), false); } } protected class DropPartitionFailure implements ConflictTrigger { private final ImmutableList<String> partitionValueToConflict = ImmutableList.of("b", "drop2"); @Override public void triggerConflict(ConnectorSession session, SchemaTableName tableName, ConnectorInsertTableHandle insertTableHandle, List<PartitionUpdate> partitionUpdates) { // This method bypasses transaction interface because this method is inherently hacky and doesn't work well with the transaction abstraction. // Additionally, this method is not part of a test. Its purpose is to set up an environment for another test. ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); metastoreClient.dropPartition(tableName.getSchemaName(), tableName.getTableName(), partitionValueToConflict, false); } @Override public void verifyAndCleanup(SchemaTableName tableName) { // Do not add back the deleted partition because the implementation is expected to move forward instead of backward when delete fails } } protected class DirectoryRenameFailure implements ConflictTrigger { private HdfsContext context; private Path path; @Override public void triggerConflict(ConnectorSession session, SchemaTableName tableName, ConnectorInsertTableHandle insertTableHandle, List<PartitionUpdate> partitionUpdates) { Path writePath = getStagingPathRoot(insertTableHandle); Path targetPath = getTargetPathRoot(insertTableHandle); if (writePath.equals(targetPath)) { // This conflict does not apply. Trigger a rollback right away so that this test case passes. throw new TestingRollbackException(); } path = new Path(targetPath + "/pk1=b/pk2=add2"); context = new HdfsContext(session, tableName.getSchemaName(), tableName.getTableName()); createDirectory(context, hdfsEnvironment, path); } @Override public void verifyAndCleanup(SchemaTableName tableName) throws IOException { assertEquals(listDirectory(context, path), ImmutableList.of()); hdfsEnvironment.getFileSystem(context, path).delete(path, false); } } protected class FileRenameFailure implements ConflictTrigger { private HdfsContext context; private Path path; @Override public void triggerConflict(ConnectorSession session, SchemaTableName tableName, ConnectorInsertTableHandle insertTableHandle, List<PartitionUpdate> partitionUpdates) throws IOException { for (PartitionUpdate partitionUpdate : partitionUpdates) { if ("pk2=insert2".equals(partitionUpdate.getTargetPath().getName())) { path = new Path(partitionUpdate.getTargetPath(), partitionUpdate.getFileNames().get(0)); break; } } assertNotNull(path); context = new HdfsContext(session, tableName.getSchemaName(), tableName.getTableName()); FileSystem fileSystem = hdfsEnvironment.getFileSystem(context, path); fileSystem.createNewFile(path); } @Override public void verifyAndCleanup(SchemaTableName tableName) throws IOException { // The file we added to trigger a conflict was cleaned up because it matches the query prefix. // Consider this the same as a network failure that caused the successful creation of file not reported to the caller. assertFalse(hdfsEnvironment.getFileSystem(context, path).exists(path)); } } }
Allow override testPartitionStatisticsSampling
presto-hive/src/test/java/com/facebook/presto/hive/AbstractTestHiveClient.java
Allow override testPartitionStatisticsSampling
<ide><path>resto-hive/src/test/java/com/facebook/presto/hive/AbstractTestHiveClient.java <ide> public void testPartitionStatisticsSampling() <ide> throws Exception <ide> { <add> testPartitionStatisticsSampling(STATISTICS_PARTITIONED_TABLE_COLUMNS, STATISTICS_1); <add> } <add> <add> protected void testPartitionStatisticsSampling(List<ColumnMetadata> columns, PartitionStatistics statistics) <add> throws Exception <add> { <ide> SchemaTableName tableName = temporaryTable("test_partition_statistics_sampling"); <ide> <ide> try { <del> createDummyPartitionedTable(tableName, STATISTICS_PARTITIONED_TABLE_COLUMNS); <del> <del> metastoreClient.updatePartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), "ds=2016-01-01", actualStatistics -> STATISTICS_1); <del> metastoreClient.updatePartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), "ds=2016-01-02", actualStatistics -> STATISTICS_1); <add> createDummyPartitionedTable(tableName, columns); <add> ExtendedHiveMetastore metastoreClient = getMetastoreClient(tableName.getSchemaName()); <add> metastoreClient.updatePartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), "ds=2016-01-01", actualStatistics -> statistics); <add> metastoreClient.updatePartitionStatistics(tableName.getSchemaName(), tableName.getTableName(), "ds=2016-01-02", actualStatistics -> statistics); <ide> <ide> try (Transaction transaction = newTransaction()) { <ide> ConnectorSession session = newSession();
Java
apache-2.0
8d29a3884c85c020c73fba84aa70c46bf288a27b
0
mohanaraosv/commons-email,mohanaraosv/commons-email,apache/commons-email,apache/commons-email,apache/commons-email,mohanaraosv/commons-email
/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.activation.URLDataSource; import javax.mail.MessagingException; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMultipart; import org.apache.commons.lang.StringUtils; /** * A multipart email. * * <p>This class is used to send multi-part internet email like * messages with attachments. * * <p>To create a multi-part email, call the default constructor and * then you can call setMsg() to set the message and call the * different attach() methods. * * @author <a href="mailto:[email protected]">Quinton McCombs</a> * @author <a href="mailto:[email protected]">Jon S. Stevens</a> * @author <a href="mailto:[email protected]">Frank Y. Kim</a> * @author <a href="mailto:[email protected]">Brett McLaughlin</a> * @author <a href="mailto:unknown">Regis Koenig</a> * @author <a href="mailto:[email protected]">Corey Scott</a> * @version $Id$ */ public class MultiPartEmail extends Email { /** Body portion of the email. */ private MimeMultipart container; /** The message container. */ private MimeBodyPart primaryBodyPart; /** The MIME subtype. */ private String subType; /** Indicates if the message has been initialized */ private boolean initialized; /** Indicates if attachments have been added to the message */ private boolean boolHasAttachments; /** * Set the MIME subtype of the email. * * @param aSubType MIME subtype of the email */ public void setSubType(String aSubType) { this.subType = aSubType; } /** * Get the MIME subtype of the email. * * @return MIME subtype of the email */ public String getSubType() { return subType; } /** * Add a new part to the email. * * @param content The content. * @param contentType The content type. * @return An Email. * @throws EmailException see javax.mail.internet.MimeBodyPart * for defintions */ public Email addPart(String content, String contentType) throws EmailException { MimeBodyPart bodyPart = new MimeBodyPart(); try { bodyPart.setContent(content, contentType); getContainer().addBodyPart(bodyPart); } catch (MessagingException me) { throw new EmailException(me); } return this; } /** * Add a new part to the email. * * @param multipart The MimeMultipart. * @return An Email. * @throws EmailException see javax.mail.internet.MimeBodyPart * for defintions */ public Email addPart(MimeMultipart multipart) throws EmailException { try { return addPart(multipart, getContainer().getCount()); } catch (MessagingException me) { throw new EmailException(me); } } /** * Add a new part to the email. * * @param multipart The part to add. * @param index The index to add at. * @return The email. * @throws EmailException An error occured while adding the part. */ public Email addPart(MimeMultipart multipart, int index) throws EmailException { MimeBodyPart bodyPart = new MimeBodyPart(); try { bodyPart.setContent(multipart); getContainer().addBodyPart(bodyPart, index); } catch (MessagingException me) { throw new EmailException(me); } return this; } /** * Initialize the multipart email. */ protected void init() { if (initialized) { throw new IllegalStateException("Already initialized"); } container = new MimeMultipart(); super.setContent(container); initialized = true; } /** * Set the message of the email. * * @param msg A String. * @return An Email. * @throws EmailException see javax.mail.internet.MimeBodyPart * for defintions */ public Email setMsg(String msg) throws EmailException { // throw exception on null message if (StringUtils.isEmpty(msg)) { throw new EmailException("Invalid message supplied"); } try { if (StringUtils.isNotEmpty(charset)) { getPrimaryBodyPart().setText(msg, charset); } else { getPrimaryBodyPart().setText(msg); } } catch (MessagingException me) { throw new EmailException(me); } return this; } /** * Sends the mail message * * @throws EmailException see javax.mail.internet.MimeBodyPart * for defintions */ public void send() throws EmailException { try { if (primaryBodyPart != null) { // before a multipart message can be sent, we must make sure that // the content for the main body part was actually set. If not, // an IOException will be thrown during super.send(). MimeBodyPart body = this.getPrimaryBodyPart(); Object content = null; try { content = body.getContent(); } catch (IOException e) { // do nothing here. content will be set to an empty string // as a result. content = null; } } if (subType != null) { getContainer().setSubType(subType); } super.send(); } catch (MessagingException me) { throw new EmailException(me); } } /** * Attach an EmailAttachement. * * @param attachment An EmailAttachment. * @return A MultiPartEmail. * @throws EmailException see javax.mail.internet.MimeBodyPart * for defintions */ public MultiPartEmail attach(EmailAttachment attachment) throws EmailException { MultiPartEmail result = null; if (attachment == null) { throw new EmailException("Invalid attachment supplied"); } URL url = attachment.getURL(); if (url == null) { String fileName = null; try { fileName = attachment.getPath(); File file = new File(fileName); if (!file.exists()) { throw new IOException( "\"" + fileName + "\" does not exist"); } result = attach( new FileDataSource(file), attachment.getName(), attachment.getDescription(), attachment.getDisposition()); } catch (Exception e) { throw new EmailException( "Cannot attach file \"" + fileName + "\"", e); } } else { result = attach( url, attachment.getName(), attachment.getDescription(), attachment.getDisposition()); } return result; } /** * Attach a file located by its URL. The disposition of the file * is set to mixed. * * @param url The URL of the file (may be any valid URL). * @param name The name field for the attachment. * @param description A description for the attachment. * @return A MultiPartEmail. * @throws EmailException see javax.mail.internet.MimeBodyPart * for defintions */ public MultiPartEmail attach(URL url, String name, String description) throws EmailException { return attach(url, name, description, EmailAttachment.ATTACHMENT); } /** * Attach a file located by its URL. * * @param url The URL of the file (may be any valid URL). * @param name The name field for the attachment. * @param description A description for the attachment. * @param disposition Either mixed or inline. * @return A MultiPartEmail. * @throws EmailException see javax.mail.internet.MimeBodyPart * for defintions */ public MultiPartEmail attach( URL url, String name, String description, String disposition) throws EmailException { // verify that the URL is valid try { InputStream is = url.openStream(); is.close(); } catch (IOException e) { throw new EmailException("Invalid URL set"); } return attach(new URLDataSource(url), name, description, disposition); } /** * Attach a file specified as a DataSource interface. * * @param ds A DataSource interface for the file. * @param name The name field for the attachment. * @param description A description for the attachment. * @return A MultiPartEmail. * @throws EmailException see javax.mail.internet.MimeBodyPart * for defintions */ public MultiPartEmail attach( DataSource ds, String name, String description) throws EmailException { // verify that the DataSource is valid try { if (ds == null || ds.getInputStream() == null) { throw new EmailException("Invalid Datasource"); } } catch (IOException e) { throw new EmailException("Invalid Datasource"); } return attach(ds, name, description, EmailAttachment.ATTACHMENT); } /** * Attach a file specified as a DataSource interface. * * @param ds A DataSource interface for the file. * @param name The name field for the attachment. * @param description A description for the attachement. * @param disposition Either mixed or inline. * @return A MultiPartEmail. * @throws EmailException see javax.mail.internet.MimeBodyPart * for defintions */ public MultiPartEmail attach( DataSource ds, String name, String description, String disposition) throws EmailException { if (StringUtils.isEmpty(name)) { name = ds.getName(); } MimeBodyPart mbp = new MimeBodyPart(); try { getContainer().addBodyPart(mbp); mbp.setDisposition(disposition); mbp.setFileName(name); mbp.setDescription(description); mbp.setDataHandler(new DataHandler(ds)); } catch (MessagingException me) { throw new EmailException(me); } this.boolHasAttachments = true; return this; } /** * Gets first body part of the message. * * @return The primary body part. * @throws MessagingException An error occured while getting the primary body part. */ protected MimeBodyPart getPrimaryBodyPart() throws MessagingException { if (!initialized) { init(); } // Add the first body part to the message. The fist body part must be if (this.primaryBodyPart == null) { primaryBodyPart = new MimeBodyPart(); getContainer().addBodyPart(primaryBodyPart, 0); } return primaryBodyPart; } /** * Gets the message container. * * @return The message container. */ protected MimeMultipart getContainer() { if (!initialized) { init(); } return container; } /** * @return boolHasAttachments */ public boolean isBoolHasAttachments() { return boolHasAttachments; } /** * @param b boolHasAttachments */ public void setBoolHasAttachments(boolean b) { boolHasAttachments = b; } }
src/java/org/apache/commons/mail/MultiPartEmail.java
/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.activation.URLDataSource; import javax.mail.MessagingException; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMultipart; import org.apache.commons.lang.StringUtils; /** * A multipart email. * * <p>This class is used to send multi-part internet email like * messages with attachments. * * <p>To create a multi-part email, call the default constructor and * then you can call setMsg() to set the message and call the * different attach() methods. * * @author <a href="mailto:[email protected]">Quinton McCombs</a> * @author <a href="mailto:[email protected]">Jon S. Stevens</a> * @author <a href="mailto:[email protected]">Frank Y. Kim</a> * @author <a href="mailto:[email protected]">Brett McLaughlin</a> * @author <a href="mailto:unknown">Regis Koenig</a> * @author <a href="mailto:[email protected]">Corey Scott</a> * @version $Id$ */ public class MultiPartEmail extends Email { /** Body portion of the email. */ private MimeMultipart container; /** The message container. */ private MimeBodyPart primaryBodyPart; /** The MIME subtype. */ private String subType; /** Indicates if the message has been initialized */ private boolean initialized; /** Indicates if attachments have been added to the message */ private boolean boolHasAttachments; /** * Set the MIME subtype of the email. * * @param aSubType MIME subtype of the email */ public void setSubType(String aSubType) { this.subType = aSubType; } /** * Get the MIME subtype of the email. * * @return MIME subtype of the email */ public String getSubType() { return subType; } /** * Add a new part to the email. * * @param content The content. * @param contentType The content type. * @return An Email. * @throws EmailException see javax.mail.internet.MimeBodyPart * for defintions */ public Email addPart(String content, String contentType) throws EmailException { MimeBodyPart bodyPart = new MimeBodyPart(); try { bodyPart.setContent(content, contentType); getContainer().addBodyPart(bodyPart); } catch (MessagingException me) { throw new EmailException(me); } return this; } /** * Add a new part to the email. * * @param multipart The MimeMultipart. * @return An Email. * @throws EmailException see javax.mail.internet.MimeBodyPart * for defintions */ public Email addPart(MimeMultipart multipart) throws EmailException { try { return addPart(multipart, getContainer().getCount()); } catch (MessagingException me) { throw new EmailException(me); } } /** * Add a new part to the email. * * @param multipart The part to add. * @param index The index to add at. * @return The email. * @throws EmailException An error occured while adding the part. */ public Email addPart(MimeMultipart multipart, int index) throws EmailException { MimeBodyPart bodyPart = new MimeBodyPart(); try { bodyPart.setContent(multipart); getContainer().addBodyPart(bodyPart, index); } catch (MessagingException me) { throw new EmailException(me); } return this; } /** * Initialize the multipart email. */ protected void init() { if (initialized) { throw new IllegalStateException("Already initialized"); } container = new MimeMultipart(); super.setContent(container); initialized = true; } /** * Set the message of the email. * * @param msg A String. * @return An Email. * @throws EmailException see javax.mail.internet.MimeBodyPart * for defintions */ public Email setMsg(String msg) throws EmailException { // throw exception on null message if (StringUtils.isEmpty(msg)) { throw new EmailException("Invalid message supplied"); } try { if (StringUtils.isNotEmpty(charset)) { getPrimaryBodyPart().setText(msg, charset); } else { getPrimaryBodyPart().setText(msg); } } catch (MessagingException me) { throw new EmailException(me); } return this; } /** * Sends the mail message * * @throws EmailException see javax.mail.internet.MimeBodyPart * for defintions */ public void send() throws EmailException { try { if (primaryBodyPart != null) { // before a multipart message can be sent, we must make sure that // the content for the main body part was actually set. If not, // an IOException will be thrown during super.send(). MimeBodyPart body = this.getPrimaryBodyPart(); Object content = null; try { content = body.getContent(); } catch (IOException e) { // do nothing here. content will be set to an empty string // as a result. content = null; } } if (subType != null) { getContainer().setSubType(subType); } super.send(); } catch (MessagingException me) { throw new EmailException(me); } } /** * Attach an EmailAttachement. * * @param attachment An EmailAttachment. * @return A MultiPartEmail. * @throws EmailException see javax.mail.internet.MimeBodyPart * for defintions */ public MultiPartEmail attach(EmailAttachment attachment) throws EmailException { MultiPartEmail result = null; if (attachment == null) { throw new EmailException("Invalid attachment supplied"); } URL url = attachment.getURL(); if (url == null) { String fileName = null; try { fileName = attachment.getPath(); File file = new File(fileName); if (!file.exists()) { throw new IOException( "\"" + fileName + "\" does not exist"); } result = attach( new FileDataSource(file), attachment.getName(), attachment.getDescription(), attachment.getDisposition()); } catch (Exception e) { throw new EmailException( "Cannot attach file \"" + fileName + "\"", e); } } else { result = attach( url, attachment.getName(), attachment.getDescription(), attachment.getDisposition()); } return result; } /** * Attach a file located by its URL. The disposition of the file * is set to mixed. * * @param url The URL of the file (may be any valid URL). * @param name The name field for the attachment. * @param description A description for the attachment. * @return A MultiPartEmail. * @throws EmailException see javax.mail.internet.MimeBodyPart * for defintions */ public MultiPartEmail attach(URL url, String name, String description) throws EmailException { return attach(url, name, description, EmailAttachment.ATTACHMENT); } /** * Attach a file located by its URL. * * @param url The URL of the file (may be any valid URL). * @param name The name field for the attachment. * @param description A description for the attachment. * @param disposition Either mixed or inline. * @return A MultiPartEmail. * @throws EmailException see javax.mail.internet.MimeBodyPart * for defintions */ public MultiPartEmail attach( URL url, String name, String description, String disposition) throws EmailException { // verify that the URL is valid try { InputStream is = url.openStream(); is.close(); } catch (IOException e) { throw new EmailException("Invalid URL set"); } return attach(new URLDataSource(url), name, description, disposition); } /** * Attach a file specified as a DataSource interface. * * @param ds A DataSource interface for the file. * @param name The name field for the attachment. * @param description A description for the attachment. * @return A MultiPartEmail. * @throws EmailException see javax.mail.internet.MimeBodyPart * for defintions */ public MultiPartEmail attach( DataSource ds, String name, String description) throws EmailException { // verify that the DataSource is valid try { if (ds == null || ds.getInputStream() == null) { throw new EmailException("Invalid Datasource"); } } catch (IOException e) { throw new EmailException("Invalid Datasource"); } return attach(ds, name, description, EmailAttachment.ATTACHMENT); } /** * Attach a file specified as a DataSource interface. * * @param ds A DataSource interface for the file. * @param name The name field for the attachment. * @param description A description for the attachement. * @param disposition Either mixed or inline. * @return A MultiPartEmail. * @throws EmailException see javax.mail.internet.MimeBodyPart * for defintions */ public MultiPartEmail attach( DataSource ds, String name, String description, String disposition) throws EmailException { if (StringUtils.isEmpty(name)) { name = ds.getName(); } MimeBodyPart mbp = new MimeBodyPart(); try { getContainer().addBodyPart(mbp); mbp.setDisposition(disposition); mbp.setFileName(name); mbp.setDescription(description); mbp.setDataHandler(new DataHandler(ds)); } catch (MessagingException me) { throw new EmailException(me); } this.boolHasAttachments = true; return this; } /** * Gets first body part of the message. * * @return The primary body part. * @throws MessagingException An error occured while getting the primary body part. */ protected MimeBodyPart getPrimaryBodyPart() throws MessagingException { if (!initialized) { init(); } // Add the first body part to the message. The fist body part must be if (this.primaryBodyPart == null) { primaryBodyPart = new MimeBodyPart(); getContainer().addBodyPart(primaryBodyPart, 0); } return primaryBodyPart; } /** * Gets the message container. * * @return The message container. */ protected MimeMultipart getContainer() { if (!initialized) { init(); } return container; } /** * @return boolHasAttachments */ public boolean isBoolHasAttachments() { return boolHasAttachments; } /** * @param b boolHasAttachments */ public void setBoolHasAttachments(boolean b) { boolHasAttachments = b; } }
Checkstyle report git-svn-id: 821da8aee58e30b7d4c6085e5bc85eaed807bb40@192936 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/commons/mail/MultiPartEmail.java
Checkstyle report
Java
apache-2.0
130bf3e19febd694a4104679b74a7260b6a17a81
0
DataReply/kafka-connect-jdbc,cotedm/kafka-connect-jdbc,DataReply/kafka-connect-jdbc,cotedm/kafka-connect-jdbc
/** * Copyright 2015 Confluent Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package io.confluent.connect.jdbc; import org.apache.kafka.connect.errors.ConnectException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TimeZone; /** * Utilties for interacting with a JDBC database. */ public class JdbcUtils { private static final Logger log = LoggerFactory.getLogger(JdbcSourceTask.class); /** * The default table types to include when listing tables if none are specified. Valid values * are those specified by the @{java.sql.DatabaseMetaData#getTables} method's TABLE_TYPE column. * The default only includes standard, user-defined tables. */ public static final Set<String> DEFAULT_TABLE_TYPES = Collections.unmodifiableSet( new HashSet<>(Arrays.asList("TABLE")) ); private static final int GET_TABLES_TYPE_COLUMN = 4; private static final int GET_TABLES_NAME_COLUMN = 3; private static final int GET_COLUMNS_COLUMN_NAME = 4; private static final int GET_COLUMNS_IS_NULLABLE = 18; private static final int GET_COLUMNS_IS_AUTOINCREMENT = 23; private static final ThreadLocal<SimpleDateFormat> DATE_FORMATTER = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); return sdf; } }; /** * Get a list of tables in the database. This uses the default filters, which only include * user-defined tables. * @param conn database connection * @return a list of tables * @throws SQLException */ public static List<String> getTables(Connection conn) throws SQLException { return getTables(conn, DEFAULT_TABLE_TYPES); } /** * Get a list of table names in the database. * @param conn database connection * @param types a set of table types that should be included in the results * @throws SQLException */ public static List<String> getTables(Connection conn, Set<String> types) throws SQLException { DatabaseMetaData metadata = conn.getMetaData(); try (ResultSet rs = metadata.getTables(null, null, "%", null)) { List<String> tableNames = new ArrayList<>(); while (rs.next()) { if (types.contains(rs.getString(GET_TABLES_TYPE_COLUMN))) { String colName = rs.getString(GET_TABLES_NAME_COLUMN); // SQLite JDBC driver does not correctly mark these as system tables if (metadata.getDatabaseProductName().equals("SQLite") && colName.startsWith("sqlite_")) { continue; } tableNames.add(colName); } } return tableNames; } } /** * Look up the autoincrement column for the specified table. * @param conn database connection * @param table the table to * @return the name of the column that is an autoincrement column, or null if there is no * autoincrement column or more than one exists * @throws SQLException */ public static String getAutoincrementColumn(Connection conn, String table) throws SQLException { String result = null; int matches = 0; try (ResultSet rs = conn.getMetaData().getColumns(null, null, table, "%")) { // Some database drivers (SQLite) don't include all the columns if (rs.getMetaData().getColumnCount() >= GET_COLUMNS_IS_AUTOINCREMENT) { while (rs.next()) { if (rs.getString(GET_COLUMNS_IS_AUTOINCREMENT).equals("YES")) { result = rs.getString(GET_COLUMNS_COLUMN_NAME); matches++; } } return (matches == 1 ? result : null); } } // Fallback approach is to query for a single row. This unfortunately does not work with any // empty table log.trace("Falling back to SELECT detection of auto-increment column for {}:{}", conn, table); try (Statement stmt = conn.createStatement()) { String quoteString = getIdentifierQuoteString(conn); ResultSet rs = stmt.executeQuery("SELECT * FROM " + quoteString + table + quoteString + " LIMIT 1"); ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 1; i < rsmd.getColumnCount(); i++) { if (rsmd.isAutoIncrement(i)) { result = rsmd.getColumnName(i); matches++; } } } return (matches == 1 ? result : null); } public static boolean isColumnNullable(Connection conn, String table, String column) throws SQLException { try (ResultSet rs = conn.getMetaData().getColumns(null, null, table, column)) { if (rs.getMetaData().getColumnCount() > GET_COLUMNS_IS_NULLABLE) { // Should only be one match if (!rs.next()) { return false; } return rs.getString(GET_COLUMNS_IS_NULLABLE).equals("YES"); } } return false; } /** * Format the given Date assuming UTC timezone in a format supported by SQL. * @param date the date to convert to a String * @return the formatted string */ public static String formatUTC(Date date) { return DATE_FORMATTER.get().format(date); } /** * Get the string used for quoting identifiers in this database's SQL dialect. * @param connection the database connection * @return the quote string * @throws SQLException */ public static String getIdentifierQuoteString(Connection connection) throws SQLException { String quoteString = connection.getMetaData().getIdentifierQuoteString(); quoteString = quoteString == null ? "" : quoteString; return quoteString; } /** * Quote the given string. * @param orig the string to quote * @param quote the quote character * @return the quoted string */ public static String quoteString(String orig, String quote) { return quote + orig + quote; } /** * Return current time at the database * @param conn * @param cal * @return */ public static Timestamp getCurrentTimeOnDB(Connection conn, Calendar cal) throws SQLException, ConnectException { String query; // This is ugly, but to run a function, everyone does 'select function()' // except Oracle that does 'select function() from dual' // and Derby uses either the dummy table SYSIBM.SYSDUMMY1 or values expression (I chose to use values) String dbProduct = conn.getMetaData().getDatabaseProductName(); if ("Oracle".equals(dbProduct)) query = "select CURRENT_TIMESTAMP from dual"; else if ("Apache Derby".equals(dbProduct)) query = "values(CURRENT_TIMESTAMP)"; else query = "select CURRENT_TIMESTAMP;"; try (Statement stmt = conn.createStatement()) { log.debug("executing query " + query + " to get current time from database"); ResultSet rs = stmt.executeQuery(query); if (rs.next()) return rs.getTimestamp(1, cal); else throw new ConnectException("Unable to get current time from DB using query " + query + " on database " + dbProduct); } catch (SQLException e) { log.error("Failed to get current time from DB using query " + query + " on database " + dbProduct, e); throw e; } } }
src/main/java/io/confluent/connect/jdbc/JdbcUtils.java
/** * Copyright 2015 Confluent Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package io.confluent.connect.jdbc; import org.apache.kafka.connect.errors.ConnectException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TimeZone; /** * Utilties for interacting with a JDBC database. */ public class JdbcUtils { private static final Logger log = LoggerFactory.getLogger(JdbcSourceTask.class); /** * The default table types to include when listing tables if none are specified. Valid values * are those specified by the @{java.sql.DatabaseMetaData#getTables} method's TABLE_TYPE column. * The default only includes standard, user-defined tables. */ public static final Set<String> DEFAULT_TABLE_TYPES = Collections.unmodifiableSet( new HashSet<>(Arrays.asList("TABLE")) ); private static final int GET_TABLES_TYPE_COLUMN = 4; private static final int GET_TABLES_NAME_COLUMN = 3; private static final int GET_COLUMNS_COLUMN_NAME = 4; private static final int GET_COLUMNS_IS_NULLABLE = 18; private static final int GET_COLUMNS_IS_AUTOINCREMENT = 23; private static final ThreadLocal<SimpleDateFormat> DATE_FORMATTER = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); return sdf; } }; /** * Get a list of tables in the database. This uses the default filters, which only include * user-defined tables. * @param conn database connection * @return a list of tables * @throws SQLException */ public static List<String> getTables(Connection conn) throws SQLException { return getTables(conn, DEFAULT_TABLE_TYPES); } /** * Get a list of table names in the database. * @param conn database connection * @param types a set of table types that should be included in the results * @throws SQLException */ public static List<String> getTables(Connection conn, Set<String> types) throws SQLException { DatabaseMetaData metadata = conn.getMetaData(); ResultSet rs = metadata.getTables(null, null, "%", null); List<String> tableNames = new ArrayList<>(); try { while (rs.next()) { if (types.contains(rs.getString(GET_TABLES_TYPE_COLUMN))) { String colName = rs.getString(GET_TABLES_NAME_COLUMN); // SQLite JDBC driver does not correctly mark these as system tables if (metadata.getDatabaseProductName().equals("SQLite") && colName.startsWith("sqlite_")) { continue; } tableNames.add(colName); } } } finally { rs.close(); } return tableNames; } /** * Look up the autoincrement column for the specified table. * @param conn database connection * @param table the table to * @return the name of the column that is an autoincrement column, or null if there is no * autoincrement column or more than one exists * @throws SQLException */ public static String getAutoincrementColumn(Connection conn, String table) throws SQLException { String result = null; int matches = 0; ResultSet rs = conn.getMetaData().getColumns(null, null, table, "%"); try { // Some database drivers (SQLite) don't include all the columns if (rs.getMetaData().getColumnCount() >= GET_COLUMNS_IS_AUTOINCREMENT) { while (rs.next()) { if (rs.getString(GET_COLUMNS_IS_AUTOINCREMENT).equals("YES")) { result = rs.getString(GET_COLUMNS_COLUMN_NAME); matches++; } } return (matches == 1 ? result : null); } } finally { rs.close(); } // Fallback approach is to query for a single row. This unfortunately does not work with any // empty table log.trace("Falling back to SELECT detection of auto-increment column for {}:{}", conn, table); Statement stmt = conn.createStatement(); try { String quoteString = getIdentifierQuoteString(conn); rs = stmt.executeQuery("SELECT * FROM " + quoteString + table + quoteString + " LIMIT 1"); ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 1; i < rsmd.getColumnCount(); i++) { if (rsmd.isAutoIncrement(i)) { result = rsmd.getColumnName(i); matches++; } } } finally { rs.close(); stmt.close(); } return (matches == 1 ? result : null); } public static boolean isColumnNullable(Connection conn, String table, String column) throws SQLException { ResultSet rs = conn.getMetaData().getColumns(null, null, table, column); try { if (rs.getMetaData().getColumnCount() > GET_COLUMNS_IS_NULLABLE) { // Should only be one match if (!rs.next()) { return false; } return rs.getString(GET_COLUMNS_IS_NULLABLE).equals("YES"); } } finally { rs.close(); } return false; } /** * Format the given Date assuming UTC timezone in a format supported by SQL. * @param date the date to convert to a String * @return the formatted string */ public static String formatUTC(Date date) { return DATE_FORMATTER.get().format(date); } /** * Get the string used for quoting identifiers in this database's SQL dialect. * @param connection the database connection * @return the quote string * @throws SQLException */ public static String getIdentifierQuoteString(Connection connection) throws SQLException { String quoteString = connection.getMetaData().getIdentifierQuoteString(); quoteString = quoteString == null ? "" : quoteString; return quoteString; } /** * Quote the given string. * @param orig the string to quote * @param quote the quote character * @return the quoted string */ public static String quoteString(String orig, String quote) { return quote + orig + quote; } /** * Return current time at the database * @param conn * @param cal * @return */ public static Timestamp getCurrentTimeOnDB(Connection conn, Calendar cal) throws SQLException, ConnectException { Statement stmt = conn.createStatement(); ResultSet rs = null; String query; // This is ugly, but to run a function, everyone does 'select function()' // except Oracle that does 'select function() from dual' // and Derby uses either the dummy table SYSIBM.SYSDUMMY1 or values expression (I chose to use values) String dbProduct = conn.getMetaData().getDatabaseProductName(); if ("Oracle".equals(dbProduct)) query = "select CURRENT_TIMESTAMP from dual"; else if ("Apache Derby".equals(dbProduct)) query = "values(CURRENT_TIMESTAMP)"; else query = "select CURRENT_TIMESTAMP;"; try { log.debug("executing query " + query + " to get current time from database"); rs = stmt.executeQuery(query); if (rs.next()) return rs.getTimestamp(1, cal); else throw new ConnectException("Unable to get current time from DB using query " + query + " on database " + dbProduct); } catch (SQLException e) { log.error("Failed to get current time from DB using query " + query + " on database " + dbProduct, e); throw e; } finally { if (rs != null) rs.close(); if (stmt != null) stmt.close(); } } }
Simplify exception handling in JdbcUtils to use try-with-resources and only close Statements where they are used since any ResultSets they generate will be auto-closed.
src/main/java/io/confluent/connect/jdbc/JdbcUtils.java
Simplify exception handling in JdbcUtils to use try-with-resources and only close Statements where they are used since any ResultSets they generate will be auto-closed.
<ide><path>rc/main/java/io/confluent/connect/jdbc/JdbcUtils.java <ide> */ <ide> public static List<String> getTables(Connection conn, Set<String> types) throws SQLException { <ide> DatabaseMetaData metadata = conn.getMetaData(); <del> ResultSet rs = metadata.getTables(null, null, "%", null); <del> List<String> tableNames = new ArrayList<>(); <del> try { <add> try (ResultSet rs = metadata.getTables(null, null, "%", null)) { <add> List<String> tableNames = new ArrayList<>(); <ide> while (rs.next()) { <ide> if (types.contains(rs.getString(GET_TABLES_TYPE_COLUMN))) { <ide> String colName = rs.getString(GET_TABLES_NAME_COLUMN); <ide> tableNames.add(colName); <ide> } <ide> } <del> } finally { <del> rs.close(); <del> } <del> return tableNames; <add> return tableNames; <add> } <ide> } <ide> <ide> /** <ide> String result = null; <ide> int matches = 0; <ide> <del> ResultSet rs = conn.getMetaData().getColumns(null, null, table, "%"); <del> try { <add> try (ResultSet rs = conn.getMetaData().getColumns(null, null, table, "%")) { <ide> // Some database drivers (SQLite) don't include all the columns <ide> if (rs.getMetaData().getColumnCount() >= GET_COLUMNS_IS_AUTOINCREMENT) { <ide> while (rs.next()) { <ide> } <ide> return (matches == 1 ? result : null); <ide> } <del> } finally { <del> rs.close(); <ide> } <ide> <ide> // Fallback approach is to query for a single row. This unfortunately does not work with any <ide> // empty table <ide> log.trace("Falling back to SELECT detection of auto-increment column for {}:{}", conn, table); <del> Statement stmt = conn.createStatement(); <del> try { <add> try (Statement stmt = conn.createStatement()) { <ide> String quoteString = getIdentifierQuoteString(conn); <del> rs = stmt.executeQuery("SELECT * FROM " + quoteString + table + quoteString + " LIMIT 1"); <add> ResultSet rs = stmt.executeQuery("SELECT * FROM " + quoteString + table + quoteString + " LIMIT 1"); <ide> ResultSetMetaData rsmd = rs.getMetaData(); <ide> for (int i = 1; i < rsmd.getColumnCount(); i++) { <ide> if (rsmd.isAutoIncrement(i)) { <ide> matches++; <ide> } <ide> } <del> } finally { <del> rs.close(); <del> stmt.close(); <ide> } <ide> return (matches == 1 ? result : null); <ide> } <ide> <ide> public static boolean isColumnNullable(Connection conn, String table, String column) <ide> throws SQLException { <del> ResultSet rs = conn.getMetaData().getColumns(null, null, table, column); <del> try { <add> try (ResultSet rs = conn.getMetaData().getColumns(null, null, table, column)) { <ide> if (rs.getMetaData().getColumnCount() > GET_COLUMNS_IS_NULLABLE) { <ide> // Should only be one match <ide> if (!rs.next()) { <ide> } <ide> return rs.getString(GET_COLUMNS_IS_NULLABLE).equals("YES"); <ide> } <del> } finally { <del> rs.close(); <ide> } <ide> <ide> return false; <ide> * @return <ide> */ <ide> public static Timestamp getCurrentTimeOnDB(Connection conn, Calendar cal) throws SQLException, ConnectException { <del> <del> Statement stmt = conn.createStatement(); <del> ResultSet rs = null; <ide> String query; <ide> <ide> // This is ugly, but to run a function, everyone does 'select function()' <ide> else <ide> query = "select CURRENT_TIMESTAMP;"; <ide> <del> try { <add> try (Statement stmt = conn.createStatement()) { <ide> log.debug("executing query " + query + " to get current time from database"); <del> rs = stmt.executeQuery(query); <add> ResultSet rs = stmt.executeQuery(query); <ide> if (rs.next()) <ide> return rs.getTimestamp(1, cal); <ide> else <ide> } catch (SQLException e) { <ide> log.error("Failed to get current time from DB using query " + query + " on database " + dbProduct, e); <ide> throw e; <del> } finally { <del> if (rs != null) <del> rs.close(); <del> if (stmt != null) <del> stmt.close(); <del> } <del> <add> } <ide> } <ide> } <ide>
Java
apache-2.0
df3fa88b22a3837a4b091a0c11de3b564d3e3333
0
hheg/jitstatic,hheg/jitstatic
package jitstatic; /*- * #%L * jitstatic * %% * Copyright (C) 2017 - 2018 H.Hegardt * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Base64; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.SortedMap; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jgit.api.CheckoutCommand; import org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.ResetCommand.ResetType; import org.eclipse.jgit.api.errors.CheckoutConflictException; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.InvalidRefNameException; import org.eclipse.jgit.api.errors.InvalidRemoteException; import org.eclipse.jgit.api.errors.NoFilepatternException; import org.eclipse.jgit.api.errors.RefAlreadyExistsException; import org.eclipse.jgit.api.errors.RefNotFoundException; import org.eclipse.jgit.api.errors.TransportException; import org.eclipse.jgit.dircache.DirCache; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.transport.PushResult; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.RemoteRefUpdate.Status; import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider; import org.hamcrest.Matchers; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.RuleChain; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.health.HealthCheck.Result; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.dropwizard.client.HttpClientBuilder; import io.dropwizard.client.JerseyClientBuilder; import io.dropwizard.setup.Environment; import io.dropwizard.testing.ConfigOverride; import io.dropwizard.testing.ResourceHelpers; import io.dropwizard.testing.junit.DropwizardAppRule; import jitstatic.api.ModifyKeyData; import jitstatic.hosted.HostedFactory; /* * This test is a stress test, and the expected behavior is that the commits will end up in order. * Below is a composition of seen errors that might occur. * * Following errors might show: * * "Socket closed" * Sometimes when JGit is pushing or pulling it could end with a "Socket closed" exception. This seems to be a bug in JGit. However * I suspect it might have to do with an commit which doesn't contain any "changed" file, but still is a commit and this causes the * stream to "close". It's fairly common, but I don't have an air tight test case for it. * * "Cannot delete file ..." * Rarely JGit seems to want to delete a file on disk, but it can't somehow. * */ @RunWith(Parameterized.class) public class LoadTesterTest { private static final Pattern PAT = Pattern.compile("^\\w:\\w:\\d+$"); private static final String METADATA = ".metadata"; private static final String MASTER = "master"; private static final Logger LOG = LoggerFactory.getLogger(LoadTesterTest.class); private static final String USER = "suser"; private static final String PASSWORD = "ssecret"; private static final String S_STORAGE = "%s/storage/"; private static final String UTF_8 = "UTF-8"; private static final TemporaryFolder TMP_FOLDER = new TemporaryFolder(); private static final ObjectMapper MAPPER = new ObjectMapper(); private static final AtomicInteger GITUPDATES = new AtomicInteger(0); private static final AtomicInteger PUTUPDATES = new AtomicInteger(0); private static final AtomicInteger GITFAILIURES = new AtomicInteger(0); private static final AtomicInteger PUTFAILIURES = new AtomicInteger(0); private static final int A_CLIENTS = 10; private static final int A_UPDTRS = 10; private final DropwizardAppRule<JitstaticConfiguration> DW; private final BlockingQueue<Client> clients = new LinkedBlockingDeque<>(A_CLIENTS); private final BlockingQueue<ClientUpdater> updaters = new LinkedBlockingQueue<>(A_UPDTRS); private final String[] names; private final String[] branches; @Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { { new String[] { "a" }, new String[] { MASTER } }, { new String[] { "a", "b", "c" }, new String[] { MASTER, "develop", "something" } } }); } public LoadTesterTest(String[] names, String[] branches) { this.names = names; this.branches = branches; this.versions = new ConcurrentHashMap<>(); for (String branch : branches) { for (String name : names) { Map<String, String> m = new ConcurrentHashMap<>(); m.put(name, "nothing"); versions.put(branch, m); } } } @Rule public final RuleChain chain = RuleChain.outerRule(TMP_FOLDER).around((DW = new DropwizardAppRule<>(JitstaticApplication.class, ResourceHelpers.resourceFilePath("simpleserver.yaml"), ConfigOverride.config("hosted.basePath", getFolder())))); private final Map<String, Map<String, String>> versions; private UsernamePasswordCredentialsProvider provider; private String basic; private String gitAdress; private String storageAdress; private String adminAdress; @Before public synchronized void setup() throws InvalidRemoteException, TransportException, GitAPIException, IOException, InterruptedException { final HostedFactory hf = DW.getConfiguration().getHostedFactory(); provider = new UsernamePasswordCredentialsProvider(hf.getUserName(), hf.getSecret()); basic = getBasicAuth(); int localPort = DW.getLocalPort(); gitAdress = String.format("http://localhost:%d/application/%s/%s", localPort, hf.getServletName(), hf.getHostedEndpoint()); storageAdress = String.format("http://localhost:%d/application", localPort); adminAdress = String.format("http://localhost:%d/admin", localPort); for (int i = 0; i < A_CLIENTS; i++) { clients.add(buildClient("c " + i)); } initRepo(); for (int i = 0; i < A_UPDTRS; i++) { updaters.put(new ClientUpdater(gitAdress, provider)); } GITFAILIURES.set(0); GITUPDATES.set(0); PUTFAILIURES.set(0); PUTUPDATES.set(0); } @After public void after() throws InvalidRemoteException, TransportException, GitAPIException, IOException { SortedMap<String, Result> healthChecks = DW.getEnvironment().healthChecks().runHealthChecks(); List<Throwable> errors = healthChecks.entrySet().stream().map(e -> e.getValue().getError()).filter(Objects::nonNull) .collect(Collectors.toList()); errors.stream().forEach(e -> e.printStackTrace()); assertThat(errors.toString(), errors.isEmpty(), Matchers.is(true)); Client statsClient = buildClient("stats"); Response response = statsClient.target(adminAdress + "/metrics").queryParam("pretty", true).request().get(); LOG.info(response.readEntity(String.class)); File workingFolder = TMP_FOLDER.newFolder(); try (Git git = Git.cloneRepository().setDirectory(workingFolder).setURI(gitAdress).setCredentialsProvider(provider).call()) { for (String branch : branches) { checkoutBranch(branch, git); LOG.info("##### {} #####", branch); Map<String, Integer> data = new HashMap<>(); for (String name : names) { int d = readData(Paths.get(workingFolder.toURI()).resolve(name)); data.put(name, d); LOG.info("{} contains {}", name, d); } Map<String, Integer> cnt = new HashMap<>(); for (RevCommit rc : git.log().call()) { String msg = rc.getShortMessage(); Matcher matcher = PAT.matcher(msg); if (matcher.matches()) { String[] split = msg.split(":"); Integer value = cnt.get(split[1]); Integer newValue = Integer.valueOf(split[2]); if (value != null) { assertEquals(Integer.valueOf(value.intValue() - 1), newValue); } else { assertEquals(data.get(split[1]), newValue); } cnt.put(split[1], newValue); } else { LOG.info("Message prints something else {}", msg); } LOG.info("{}-{}--{}", rc.getId(), msg, rc.getAuthorIdent()); } } } LOG.info("Git updates: {}", GITUPDATES.get()); LOG.info("Git Failiures: {}", GITFAILIURES.get()); LOG.info("Put updates: {}", PUTUPDATES.get()); LOG.info("Put failiures: {}", PUTFAILIURES.get()); clients.stream().forEach(c -> c.close()); } @Test public void testLoad() { ExecutorService clientPool = Executors.newFixedThreadPool(A_CLIENTS); ExecutorService updaterPool = Executors.newFixedThreadPool(A_UPDTRS); Future<?>[] clientJobs = new Future[A_CLIENTS]; Future<?>[] updaterJobs = new Future[A_UPDTRS]; long start = System.currentTimeMillis(); do { execClientJobs(clientPool, clientJobs); execUpdatersJobs(updaterPool, updaterJobs); } while (System.currentTimeMillis() - start < 10_000); waitForJobstoFinish(clientJobs, updaterJobs); updaterPool.shutdown(); clientPool.shutdown(); } private void waitForJobstoFinish(Future<?>[] clientJobs, Future<?>[] updaterJobs) { int idx = clientJobs.length + updaterJobs.length; while (idx > 0) { for (int i = 0; i < clientJobs.length; i++) { Future<?> f = clientJobs[i]; if (f != null && f.isDone()) { clientJobs[i] = null; idx--; } } for (int i = 0; i < updaterJobs.length; i++) { Future<?> f = updaterJobs[i]; if (f != null && f.isDone()) { updaterJobs[i] = null; idx--; } } } } private void execUpdatersJobs(ExecutorService updaterPool, Future<?>[] updaterJobs) { for (int i = 0; i < updaterJobs.length; i++) { Future<?> f = updaterJobs[i]; if (f == null || f.isDone()) { updaterJobs[i] = updaterPool.submit(() -> { ClientUpdater cu; try { cu = updaters.take(); try { for (String branch : branches) { for (String name : names) { cu.updateClient(name, branch); } } } catch (GitAPIException | IOException e) { LOG.error("TestSuiteError: Repo error ", e); } finally { updaters.put(cu); } } catch (InterruptedException e1) { LOG.error("TestSuiteError: Updater interrupted and killed", e1); } }); } } } private void execClientJobs(ExecutorService clientPool, Future<?>[] clientJobs) { for (int i = 0; i < clientJobs.length; i++) { Future<?> f = clientJobs[i]; if (f == null || f.isDone()) { clientJobs[i] = clientPool.submit(() -> { try { clientCode(); } catch (InterruptedException | IOException e) { LOG.error("TestSuiteError: Interrupted ", e); } }); } } } private void initRepo() throws InvalidRemoteException, TransportException, GitAPIException, IOException { File workingFolder = TMP_FOLDER.newFolder(); try (Git git = Git.cloneRepository().setDirectory(workingFolder).setURI(gitAdress).setCredentialsProvider(provider).call()) { int c = 0; byte[] data = getData(c); String v = new String(data); for (String name : names) { Files.write(Paths.get(workingFolder.toURI()).resolve(name), data, StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING); Files.write(Paths.get(workingFolder.toURI()).resolve(name + METADATA), getMetaData(), StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING); } git.add().addFilepattern(".").call(); git.commit().setMessage("i:a:0").call(); verifyOkPush(git.push().setCredentialsProvider(provider).call(), MASTER, c); for (String branch : branches) { if (!MASTER.equals(branch)) { git.checkout().setName(branch).setCreateBranch(true).setUpstreamMode(SetupUpstreamMode.TRACK).call(); verifyOkPush(git.push().setCredentialsProvider(provider).call(), branch, c); } for (String name : names) { versions.get(branch).put(name, v); } } } } private static byte[] getMetaData() throws UnsupportedEncodingException { String md = "{\"users\":[{\"password\":\"" + PASSWORD + "\",\"user\":\"" + USER + "\"}]}"; return md.getBytes(UTF_8); } private static byte[] getData(int c) throws UnsupportedEncodingException { String s = "{\"data\":\"" + c + "\"}"; return s.getBytes(UTF_8); } private void clientCode() throws InterruptedException, JsonParseException, JsonMappingException, IOException { Client client = clients.take(); try { for (String branch : branches) { for (String name : names) { String ref = "?ref=refs/heads/" + branch; Response callTarget = getTarget(client, name, ref); if (callTarget.getStatus() == HttpStatus.OK_200) { JsonNode entity = callTarget.readEntity(JsonNode.class); String v = versions.get(branch).get(name); if (!v.equals(entity.toString())) { LOG.error("TestSuiteError: Version comparison " + name + ":" + branch + " failed version=" + v + " actual=" + entity.toString()); } else { if (Math.random() < 0.1) { int c = entity.get("data").asInt() + 1; Response modify = modifyTarget(client, name, ref, callTarget.getEntityTag().getValue(), c); if (modify.getStatus() != HttpStatus.OK_200) { LOG.error("TestSuiteError: Failed to modify " + c + " " + modify); PUTFAILIURES.incrementAndGet(); } else { PUTUPDATES.incrementAndGet(); versions.get(branch).put(name, new String(getData(c))); LOG.info("Ok modified " + name + ":" + branch + " with " + c); } modify.close(); } } } else { LOG.error("TestSuiteError: Failed with " + callTarget); } callTarget.close(); } } } finally { clients.put(client); } } private Response modifyTarget(Client client, String store, String ref, String oldVersion, int c) throws JsonParseException, JsonMappingException, IOException { ModifyKeyData data = new ModifyKeyData(); JsonNode newData = MAPPER.readValue(getData(c), JsonNode.class); data.setData(newData); data.setMessage("m:" + store + ":" + c); return client.target(String.format(S_STORAGE + store + ref, storageAdress)).request() .header(HttpHeader.AUTHORIZATION.asString(), basic).header(HttpHeaders.IF_MATCH, "\"" + oldVersion + "\"") .buildPut(Entity.json(data)).invoke(); } private Response getTarget(Client client, String store2, String ref) { return client.target(String.format(S_STORAGE + store2 + ref, storageAdress)).request() .header(HttpHeader.AUTHORIZATION.asString(), basic).get(); } private static boolean verifyOkPush(Iterable<PushResult> iterable, String branch, int c) throws UnsupportedEncodingException { PushResult pushResult = iterable.iterator().next(); RemoteRefUpdate remoteUpdate = pushResult.getRemoteUpdate("refs/heads/" + branch); if (Status.OK == remoteUpdate.getStatus()) { GITUPDATES.incrementAndGet(); return true; } else { GITFAILIURES.incrementAndGet(); LOG.error("TestSuiteError: FAILED push " + c + " with " + remoteUpdate); } return false; } private static String getBasicAuth() throws UnsupportedEncodingException { return "Basic " + Base64.getEncoder().encodeToString((USER + ":" + PASSWORD).getBytes(UTF_8)); } private Client buildClient(final String name) { Environment environment = DW.getEnvironment(); JerseyClientBuilder jerseyClientBuilder = new JerseyClientBuilder(environment); jerseyClientBuilder.setApacheHttpClientBuilder(new HttpClientBuilder(environment)); return jerseyClientBuilder.build(name); } private static Supplier<String> getFolder() { return () -> { try { return TMP_FOLDER.newFolder().toString(); } catch (IOException e) { throw new RuntimeException(e); } }; } private Ref checkoutBranch(String branch, Git git) throws IOException, GitAPIException, RefAlreadyExistsException, RefNotFoundException, InvalidRefNameException, CheckoutConflictException { git.checkout().setAllPaths(true).call(); Ref head = git.getRepository().findRef(branch); CheckoutCommand checkout = git.checkout().setName(branch).setUpstreamMode(SetupUpstreamMode.TRACK) .setStartPoint("origin/" + branch); if (head == null) { checkout.setCreateBranch(true); } checkout.call(); head = git.getRepository().findRef(branch); return head; } private int readData(Path filedata) throws IOException, JsonParseException, JsonMappingException { try { JsonNode readValue = MAPPER.readValue(filedata.toFile(), JsonNode.class); return readValue.get("data").asInt(); } catch (Exception e) { LOG.error("Failed file looks like:" + new String(Files.readAllBytes(filedata))); throw e; } } private class ClientUpdater { private final File workingFolder; private final UsernamePasswordCredentialsProvider provider; public ClientUpdater(final String gitAdress, final UsernamePasswordCredentialsProvider provider) throws InvalidRemoteException, TransportException, GitAPIException, IOException { this.workingFolder = TMP_FOLDER.newFolder(); Git.cloneRepository().setDirectory(workingFolder).setURI(gitAdress).setCredentialsProvider(provider).call(); this.provider = provider; } public void updateClient(String name, String branch) throws UnsupportedEncodingException, IOException, NoFilepatternException, GitAPIException { try (Git git = Git.open(workingFolder)) { Ref head = checkoutBranch(branch, git); git.pull().setCredentialsProvider(provider).call(); Path filedata = Paths.get(workingFolder.toURI()).resolve(name); int c = readData(filedata) + 1; byte[] data = getData(c); Files.write(filedata, data, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); DirCache dc = git.add().addFilepattern(".").call(); if (dc.getEntryCount() > 0) { String message = "g:" + name + ":" + c; git.commit().setMessage(message).call(); if (!verifyOkPush(git.push().setCredentialsProvider(provider).call(), branch, c)) { git.reset().setMode(ResetType.HARD).setRef(head.getObjectId().name()).call(); git.clean().setCleanDirectories(true).setForce(true).call(); } else { String v = new String(data); LOG.info("OK push " + c + " " + name + ":" + branch + " from " + versions.get(branch).get(name) + " to " + v + " commit " + message); versions.get(branch).put(name, v); } } } } } }
jitstatic-IT/src/test/java/jitstatic/LoadTesterTest.java
package jitstatic; /*- * #%L * jitstatic * %% * Copyright (C) 2017 - 2018 H.Hegardt * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Base64; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.SortedMap; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import java.util.stream.Collectors; import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jgit.api.CheckoutCommand; import org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.ResetCommand.ResetType; import org.eclipse.jgit.api.errors.CheckoutConflictException; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.InvalidRefNameException; import org.eclipse.jgit.api.errors.InvalidRemoteException; import org.eclipse.jgit.api.errors.NoFilepatternException; import org.eclipse.jgit.api.errors.RefAlreadyExistsException; import org.eclipse.jgit.api.errors.RefNotFoundException; import org.eclipse.jgit.api.errors.TransportException; import org.eclipse.jgit.dircache.DirCache; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.transport.PushResult; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.RemoteRefUpdate.Status; import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider; import org.hamcrest.Matchers; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.RuleChain; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.health.HealthCheck.Result; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.dropwizard.client.HttpClientBuilder; import io.dropwizard.client.JerseyClientBuilder; import io.dropwizard.setup.Environment; import io.dropwizard.testing.ConfigOverride; import io.dropwizard.testing.ResourceHelpers; import io.dropwizard.testing.junit.DropwizardAppRule; import jitstatic.api.ModifyKeyData; import jitstatic.hosted.HostedFactory; /* * This test is a stress test, and the expected behavior is that the commits will end up in order. * Below is a composition of seen errors that might occur. * * Following errors might show: * * "Socket closed" * Sometimes when JGit is pushing or pulling it could end with a "Socket closed" exception. This seems to be a bug in JGit. However * I suspect it might have to do with an commit which doesn't contain any "changed" file, but still is a commit and this causes the * stream to "close". It's fairly common, but I don't have an air tight test case for it. * * "Cannot delete file ..." * Rarely JGit seems to want to delete a file on disk, but it can't somehow. * */ @RunWith(Parameterized.class) public class LoadTesterTest { private static final String METADATA = ".metadata"; private static final String MASTER = "master"; private static final Logger LOG = LoggerFactory.getLogger(LoadTesterTest.class); private static final String USER = "suser"; private static final String PASSWORD = "ssecret"; private static final String S_STORAGE = "%s/storage/"; private static final String UTF_8 = "UTF-8"; private static final TemporaryFolder TMP_FOLDER = new TemporaryFolder(); private static final ObjectMapper MAPPER = new ObjectMapper(); private static final AtomicInteger GITUPDATES = new AtomicInteger(0); private static final AtomicInteger PUTUPDATES = new AtomicInteger(0); private static final AtomicInteger GITFAILIURES = new AtomicInteger(0); private static final AtomicInteger PUTFAILIURES = new AtomicInteger(0); private static final int A_CLIENTS = 10; private static final int A_UPDTRS = 10; private final DropwizardAppRule<JitstaticConfiguration> DW; private final BlockingQueue<Client> clients = new LinkedBlockingDeque<>(A_CLIENTS); private final BlockingQueue<ClientUpdater> updaters = new LinkedBlockingQueue<>(A_UPDTRS); private final String[] names; private final String[] branches; @Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { { new String[] { "a" }, new String[] { MASTER } }, { new String[] { "a", "b", "c" }, new String[] { MASTER, "develop", "something" } } }); } public LoadTesterTest(String[] names, String[] branches) { this.names = names; this.branches = branches; this.versions = new ConcurrentHashMap<>(); for (String branch : branches) { for (String name : names) { Map<String, String> m = new ConcurrentHashMap<>(); m.put(name, "nothing"); versions.put(branch, m); } } } @Rule public final RuleChain chain = RuleChain.outerRule(TMP_FOLDER).around((DW = new DropwizardAppRule<>(JitstaticApplication.class, ResourceHelpers.resourceFilePath("simpleserver.yaml"), ConfigOverride.config("hosted.basePath", getFolder())))); private final Map<String, Map<String, String>> versions; private UsernamePasswordCredentialsProvider provider; private String basic; private String gitAdress; private String storageAdress; private String adminAdress; @Before public synchronized void setup() throws InvalidRemoteException, TransportException, GitAPIException, IOException, InterruptedException { final HostedFactory hf = DW.getConfiguration().getHostedFactory(); provider = new UsernamePasswordCredentialsProvider(hf.getUserName(), hf.getSecret()); basic = getBasicAuth(); int localPort = DW.getLocalPort(); gitAdress = String.format("http://localhost:%d/application/%s/%s", localPort, hf.getServletName(), hf.getHostedEndpoint()); storageAdress = String.format("http://localhost:%d/application", localPort); adminAdress = String.format("http://localhost:%d/admin", localPort); for (int i = 0; i < A_CLIENTS; i++) { clients.add(buildClient("c " + i)); } initRepo(); for (int i = 0; i < A_UPDTRS; i++) { updaters.put(new ClientUpdater(gitAdress, provider)); } GITFAILIURES.set(0); GITUPDATES.set(0); PUTFAILIURES.set(0); PUTUPDATES.set(0); } @After public void after() throws InvalidRemoteException, TransportException, GitAPIException, IOException { SortedMap<String, Result> healthChecks = DW.getEnvironment().healthChecks().runHealthChecks(); List<Throwable> errors = healthChecks.entrySet().stream().map(e -> e.getValue().getError()).filter(Objects::nonNull) .collect(Collectors.toList()); errors.stream().forEach(e -> e.printStackTrace()); assertThat(errors.toString(), errors.isEmpty(), Matchers.is(true)); Client statsClient = buildClient("stats"); Response response = statsClient.target(adminAdress + "/metrics").queryParam("pretty", true).request().get(); LOG.info(response.readEntity(String.class)); File workingFolder = TMP_FOLDER.newFolder(); try (Git git = Git.cloneRepository().setDirectory(workingFolder).setURI(gitAdress).setCredentialsProvider(provider).call()) { for (String branch : branches) { checkoutBranch(branch, git); LOG.info("##### {} #####", branch); Map<String, Integer> data = new HashMap<>(); for (String name : names) { int d = readData(Paths.get(workingFolder.toURI()).resolve(name)); data.put(name, d); LOG.info("{} contains {}", name, d); } Map<String, Integer> cnt = new HashMap<>(); for (RevCommit rc : git.log().call()) { String msg = rc.getShortMessage(); String[] split = msg.split(":"); Integer value = cnt.get(split[1]); Integer newValue = Integer.valueOf(split[2]); if (value != null) { assertEquals(Integer.valueOf(value.intValue() - 1), newValue); } else { assertEquals(data.get(split[1]), newValue); } cnt.put(split[1], newValue); LOG.info("{}-{}--{}", rc.getId(), msg, rc.getAuthorIdent()); } } } LOG.info("Git updates: {}", GITUPDATES.get()); LOG.info("Git Failiures: {}", GITFAILIURES.get()); LOG.info("Put updates: {}", PUTUPDATES.get()); LOG.info("Put failiures: {}", PUTFAILIURES.get()); clients.stream().forEach(c -> c.close()); } @Test public void testLoad() { ExecutorService clientPool = Executors.newFixedThreadPool(A_CLIENTS); ExecutorService updaterPool = Executors.newFixedThreadPool(A_UPDTRS); Future<?>[] clientJobs = new Future[A_CLIENTS]; Future<?>[] updaterJobs = new Future[A_UPDTRS]; long start = System.currentTimeMillis(); do { execClientJobs(clientPool, clientJobs); execUpdatersJobs(updaterPool, updaterJobs); } while (System.currentTimeMillis() - start < 10_000); waitForJobstoFinish(clientJobs, updaterJobs); updaterPool.shutdown(); clientPool.shutdown(); } private void waitForJobstoFinish(Future<?>[] clientJobs, Future<?>[] updaterJobs) { int idx = clientJobs.length + updaterJobs.length; while (idx > 0) { for (int i = 0; i < clientJobs.length; i++) { Future<?> f = clientJobs[i]; if (f != null && f.isDone()) { clientJobs[i] = null; idx--; } } for (int i = 0; i < updaterJobs.length; i++) { Future<?> f = updaterJobs[i]; if (f != null && f.isDone()) { updaterJobs[i] = null; idx--; } } } } private void execUpdatersJobs(ExecutorService updaterPool, Future<?>[] updaterJobs) { for (int i = 0; i < updaterJobs.length; i++) { Future<?> f = updaterJobs[i]; if (f == null || f.isDone()) { updaterJobs[i] = updaterPool.submit(() -> { ClientUpdater cu; try { cu = updaters.take(); try { for (String branch : branches) { for (String name : names) { cu.updateClient(name, branch); } } } catch (GitAPIException | IOException e) { LOG.error("TestSuiteError: Repo error ", e); } finally { updaters.put(cu); } } catch (InterruptedException e1) { LOG.error("TestSuiteError: Updater interrupted and killed", e1); } }); } } } private void execClientJobs(ExecutorService clientPool, Future<?>[] clientJobs) { for (int i = 0; i < clientJobs.length; i++) { Future<?> f = clientJobs[i]; if (f == null || f.isDone()) { clientJobs[i] = clientPool.submit(() -> { try { clientCode(); } catch (InterruptedException | IOException e) { LOG.error("TestSuiteError: Interrupted ", e); } }); } } } private void initRepo() throws InvalidRemoteException, TransportException, GitAPIException, IOException { File workingFolder = TMP_FOLDER.newFolder(); try (Git git = Git.cloneRepository().setDirectory(workingFolder).setURI(gitAdress).setCredentialsProvider(provider).call()) { int c = 0; byte[] data = getData(c); String v = new String(data); for (String name : names) { Files.write(Paths.get(workingFolder.toURI()).resolve(name), data, StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING); Files.write(Paths.get(workingFolder.toURI()).resolve(name + METADATA), getMetaData(), StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING); } git.add().addFilepattern(".").call(); git.commit().setMessage("i:a:0").call(); verifyOkPush(git.push().setCredentialsProvider(provider).call(), MASTER, c); for (String branch : branches) { if (!MASTER.equals(branch)) { git.checkout().setName(branch).setCreateBranch(true).setUpstreamMode(SetupUpstreamMode.TRACK).call(); verifyOkPush(git.push().setCredentialsProvider(provider).call(), branch, c); } for (String name : names) { versions.get(branch).put(name, v); } } } } private static byte[] getMetaData() throws UnsupportedEncodingException { String md = "{\"users\":[{\"password\":\"" + PASSWORD + "\",\"user\":\"" + USER + "\"}]}"; return md.getBytes(UTF_8); } private static byte[] getData(int c) throws UnsupportedEncodingException { String s = "{\"data\":\"" + c + "\"}"; return s.getBytes(UTF_8); } private void clientCode() throws InterruptedException, JsonParseException, JsonMappingException, IOException { Client client = clients.take(); try { for (String branch : branches) { for (String name : names) { String ref = "?ref=refs/heads/" + branch; Response callTarget = getTarget(client, name, ref); if (callTarget.getStatus() == HttpStatus.OK_200) { JsonNode entity = callTarget.readEntity(JsonNode.class); String v = versions.get(branch).get(name); if (!v.equals(entity.toString())) { LOG.error("TestSuiteError: Version comparison " + name + ":" + branch + " failed version=" + v + " actual=" + entity.toString()); } else { if (Math.random() < 0.1) { int c = entity.get("data").asInt() + 1; Response modify = modifyTarget(client, name, ref, callTarget.getEntityTag().getValue(), c); if (modify.getStatus() != HttpStatus.OK_200) { LOG.error("TestSuiteError: Failed to modify " + c + " " + modify); PUTFAILIURES.incrementAndGet(); } else { PUTUPDATES.incrementAndGet(); versions.get(branch).put(name, new String(getData(c))); LOG.info("Ok modified " + name + ":" + branch + " with " + c); } modify.close(); } } } else { LOG.error("TestSuiteError: Failed with " + callTarget); } callTarget.close(); } } } finally { clients.put(client); } } private Response modifyTarget(Client client, String store, String ref, String oldVersion, int c) throws JsonParseException, JsonMappingException, IOException { ModifyKeyData data = new ModifyKeyData(); JsonNode newData = MAPPER.readValue(getData(c), JsonNode.class); data.setData(newData); data.setMessage("m:" + store + ":" + c); return client.target(String.format(S_STORAGE + store + ref, storageAdress)).request() .header(HttpHeader.AUTHORIZATION.asString(), basic).header(HttpHeaders.IF_MATCH, "\"" + oldVersion + "\"") .buildPut(Entity.json(data)).invoke(); } private Response getTarget(Client client, String store2, String ref) { return client.target(String.format(S_STORAGE + store2 + ref, storageAdress)).request() .header(HttpHeader.AUTHORIZATION.asString(), basic).get(); } private static boolean verifyOkPush(Iterable<PushResult> iterable, String branch, int c) throws UnsupportedEncodingException { PushResult pushResult = iterable.iterator().next(); RemoteRefUpdate remoteUpdate = pushResult.getRemoteUpdate("refs/heads/" + branch); if (Status.OK == remoteUpdate.getStatus()) { GITUPDATES.incrementAndGet(); return true; } else { GITFAILIURES.incrementAndGet(); LOG.error("TestSuiteError: FAILED push " + c + " with " + remoteUpdate); } return false; } private static String getBasicAuth() throws UnsupportedEncodingException { return "Basic " + Base64.getEncoder().encodeToString((USER + ":" + PASSWORD).getBytes(UTF_8)); } private Client buildClient(final String name) { Environment environment = DW.getEnvironment(); JerseyClientBuilder jerseyClientBuilder = new JerseyClientBuilder(environment); jerseyClientBuilder.setApacheHttpClientBuilder(new HttpClientBuilder(environment)); return jerseyClientBuilder.build(name); } private static Supplier<String> getFolder() { return () -> { try { return TMP_FOLDER.newFolder().toString(); } catch (IOException e) { throw new RuntimeException(e); } }; } private Ref checkoutBranch(String branch, Git git) throws IOException, GitAPIException, RefAlreadyExistsException, RefNotFoundException, InvalidRefNameException, CheckoutConflictException { git.checkout().setAllPaths(true).call(); Ref head = git.getRepository().findRef(branch); CheckoutCommand checkout = git.checkout().setName(branch).setUpstreamMode(SetupUpstreamMode.TRACK) .setStartPoint("origin/" + branch); if (head == null) { checkout.setCreateBranch(true); } checkout.call(); head = git.getRepository().findRef(branch); return head; } private int readData(Path filedata) throws IOException, JsonParseException, JsonMappingException { JsonNode readValue = MAPPER.readValue(filedata.toFile(), JsonNode.class); int c = readValue.get("data").asInt(); return c; } private class ClientUpdater { private final File workingFolder; private final UsernamePasswordCredentialsProvider provider; public ClientUpdater(final String gitAdress, final UsernamePasswordCredentialsProvider provider) throws InvalidRemoteException, TransportException, GitAPIException, IOException { this.workingFolder = TMP_FOLDER.newFolder(); Git.cloneRepository().setDirectory(workingFolder).setURI(gitAdress).setCredentialsProvider(provider).call(); this.provider = provider; } public void updateClient(String name, String branch) throws UnsupportedEncodingException, IOException, NoFilepatternException, GitAPIException { try (Git git = Git.open(workingFolder)) { Ref head = checkoutBranch(branch, git); git.pull().setCredentialsProvider(provider).call(); Path filedata = Paths.get(workingFolder.toURI()).resolve(name); int c = readData(filedata) + 1; byte[] data = getData(c); Files.write(filedata, data, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); DirCache dc = git.add().addFilepattern(".").call(); if (dc.getEntryCount() > 0) { String message = "g:" + name + ":" + c; git.commit().setMessage(message).call(); if (!verifyOkPush(git.push().setCredentialsProvider(provider).call(), branch, c)) { git.reset().setMode(ResetType.HARD).setRef(head.getObjectId().name()).call(); git.clean().setCleanDirectories(true).setForce(true).call(); } else { String v = new String(data); LOG.info("OK push " + c + " " + name + ":" + branch + " from " + versions.get(branch).get(name) + " to " + v + " commit " + message); versions.get(branch).put(name, v); } } } } } }
Fixed test to be more tolerant
jitstatic-IT/src/test/java/jitstatic/LoadTesterTest.java
Fixed test to be more tolerant
<ide><path>itstatic-IT/src/test/java/jitstatic/LoadTesterTest.java <ide> import java.util.concurrent.LinkedBlockingQueue; <ide> import java.util.concurrent.atomic.AtomicInteger; <ide> import java.util.function.Supplier; <add>import java.util.regex.Matcher; <add>import java.util.regex.Pattern; <ide> import java.util.stream.Collectors; <ide> <ide> import javax.ws.rs.client.Client; <ide> @RunWith(Parameterized.class) <ide> public class LoadTesterTest { <ide> <add> private static final Pattern PAT = Pattern.compile("^\\w:\\w:\\d+$"); <ide> private static final String METADATA = ".metadata"; <ide> private static final String MASTER = "master"; <ide> private static final Logger LOG = LoggerFactory.getLogger(LoadTesterTest.class); <ide> Map<String, Integer> cnt = new HashMap<>(); <ide> for (RevCommit rc : git.log().call()) { <ide> String msg = rc.getShortMessage(); <del> String[] split = msg.split(":"); <del> Integer value = cnt.get(split[1]); <del> Integer newValue = Integer.valueOf(split[2]); <del> if (value != null) { <del> assertEquals(Integer.valueOf(value.intValue() - 1), newValue); <add> Matcher matcher = PAT.matcher(msg); <add> if (matcher.matches()) { <add> String[] split = msg.split(":"); <add> Integer value = cnt.get(split[1]); <add> Integer newValue = Integer.valueOf(split[2]); <add> if (value != null) { <add> assertEquals(Integer.valueOf(value.intValue() - 1), newValue); <add> } else { <add> assertEquals(data.get(split[1]), newValue); <add> } <add> cnt.put(split[1], newValue); <ide> } else { <del> assertEquals(data.get(split[1]), newValue); <add> LOG.info("Message prints something else {}", msg); <ide> } <del> cnt.put(split[1], newValue); <ide> LOG.info("{}-{}--{}", rc.getId(), msg, rc.getAuthorIdent()); <ide> } <ide> } <ide> } <ide> <ide> private int readData(Path filedata) throws IOException, JsonParseException, JsonMappingException { <del> JsonNode readValue = MAPPER.readValue(filedata.toFile(), JsonNode.class); <del> int c = readValue.get("data").asInt(); <del> return c; <add> try { <add> JsonNode readValue = MAPPER.readValue(filedata.toFile(), JsonNode.class); <add> return readValue.get("data").asInt(); <add> } catch (Exception e) { <add> LOG.error("Failed file looks like:" + new String(Files.readAllBytes(filedata))); <add> throw e; <add> } <add> <ide> } <ide> <ide> private class ClientUpdater {
Java
epl-1.0
4f93a203d5afd6718225079130b2dfb086781f59
0
djelinek/reddeer,jboss-reddeer/reddeer,djelinek/reddeer,jboss-reddeer/reddeer
package org.jboss.reddeer.swt.test.impl.ctab; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.jboss.reddeer.swt.api.CTabItem; import org.jboss.reddeer.swt.exception.SWTLayerException; import org.jboss.reddeer.swt.impl.ctab.DefaultCTabItem; import org.jboss.reddeer.swt.impl.text.DefaultText; import org.jboss.reddeer.swt.test.RedDeerTest; import org.jboss.reddeer.swt.util.Display; import org.junit.After; import org.junit.Test; public class CTabFolderTest extends RedDeerTest{ private static final String ITEM_LABEL_PREFIX = "Item "; private static final String TOOLTIP_PREFIX = "Tool for Item "; private static final String CONTENT_PREFIX = "Content for Item "; @Override public void setUp() { super.setUp(); Display.syncExec(new Runnable() { @Override public void run() { Shell shell = new Shell(org.eclipse.swt.widgets.Display.getDefault()); shell.setText("Testing shell"); createControls(shell); shell.open(); shell.setFocus(); } }); } private void createControls(Shell shell){ shell.setLayout(new FillLayout()); CTabFolder folder = new CTabFolder(shell, SWT.BORDER); for (int i = 0; i < 4; i++) { org.eclipse.swt.custom.CTabItem item = new org.eclipse.swt.custom.CTabItem(folder, SWT.CLOSE); item.setText(CTabFolderTest.ITEM_LABEL_PREFIX + i); item.setToolTipText(CTabFolderTest.TOOLTIP_PREFIX + i); Text text = new Text(folder, SWT.MULTI); text.setText(CTabFolderTest.CONTENT_PREFIX +i); item.setControl(text); } } @After public void cleanup() { Display.syncExec(new Runnable() { @Override public void run() { for (Shell shell : org.jboss.reddeer.swt. util.Display.getDisplay().getShells()) { if (shell.getText().equals("Testing shell")) { shell.dispose(); break; } } } }); } @Test public void findByIndexAndActivate(){ int index = 2; new DefaultCTabItem(index).activate(); String expectedCTabItemContent = CTabFolderTest.CONTENT_PREFIX + index; String cTabItemContent = new DefaultText(0).getText(); assertTrue("cTabItem content is " + cTabItemContent + "\nbut expected CTabItem content is " + expectedCTabItemContent, cTabItemContent.equals(expectedCTabItemContent)); } @Test public void findByNameAndActivate(){ int index = 1; new DefaultCTabItem(CTabFolderTest.ITEM_LABEL_PREFIX + index).activate(); String expectedCTabItemContent = CTabFolderTest.CONTENT_PREFIX + index; String cTabItemContent = new DefaultText(0).getText(); assertTrue("cTabItem content is " + cTabItemContent + "\nbut expected CTabItem content is " + expectedCTabItemContent, cTabItemContent.equals(expectedCTabItemContent)); } @Test(expected = SWTLayerException.class) public void findNonExistingByIndex(){ new DefaultCTabItem(5); } @Test(expected = SWTLayerException.class) public void findNonExistingByLabel(){ new DefaultCTabItem("NON_EXISTING_#$"); } @Test public void close(){ int index = 3; CTabItem cTabItem = new DefaultCTabItem(index); cTabItem.close(); try{ new DefaultCTabItem(index); fail("CTabItem with index " + index + " was found but has to be closed"); } catch (SWTLayerException sle){ // do nothing closed CTabItem should not be found } } }
org.jboss.reddeer.swt.test/src/org/jboss/reddeer/swt/test/impl/ctab/CTabFolderTest.java
package org.jboss.reddeer.swt.test.impl.ctab; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swtbot.swt.finder.finders.UIThreadRunnable; import org.eclipse.swtbot.swt.finder.results.VoidResult; import org.jboss.reddeer.swt.api.CTabItem; import org.jboss.reddeer.swt.exception.SWTLayerException; import org.jboss.reddeer.swt.impl.ctab.DefaultCTabItem; import org.jboss.reddeer.swt.impl.text.DefaultText; import org.jboss.reddeer.swt.test.RedDeerTest; import org.junit.After; import org.junit.Test; public class CTabFolderTest extends RedDeerTest{ private static final String ITEM_LABEL_PREFIX = "Item "; private static final String TOOLTIP_PREFIX = "Tool for Item "; private static final String CONTENT_PREFIX = "Content for Item "; @Override public void setUp() { super.setUp(); UIThreadRunnable.syncExec(new VoidResult() { @Override public void run() { Display display = Display.getDefault(); Shell shell = new Shell(display); shell.setText("Testing shell"); createControls(shell); shell.open(); shell.setFocus(); } }); } private void createControls(Shell shell){ shell.setLayout(new FillLayout()); CTabFolder folder = new CTabFolder(shell, SWT.BORDER); for (int i = 0; i < 4; i++) { org.eclipse.swt.custom.CTabItem item = new org.eclipse.swt.custom.CTabItem(folder, SWT.CLOSE); item.setText(CTabFolderTest.ITEM_LABEL_PREFIX + i); item.setToolTipText(CTabFolderTest.TOOLTIP_PREFIX + i); Text text = new Text(folder, SWT.MULTI); text.setText(CTabFolderTest.CONTENT_PREFIX +i); item.setControl(text); } } @After public void cleanup() { UIThreadRunnable.syncExec(new VoidResult() { @Override public void run() { for (Shell shell : org.jboss.reddeer.swt. util.Display.getDisplay().getShells()) { if (shell.getText().equals("Testing shell")) { shell.dispose(); break; } } } }); } @Test public void findByIndexAndActivate(){ int index = 2; new DefaultCTabItem(index).activate(); String expectedCTabItemContent = CTabFolderTest.CONTENT_PREFIX + index; String cTabItemContent = new DefaultText(0).getText(); assertTrue("cTabItem content is " + cTabItemContent + "\nbut expected CTabItem content is " + expectedCTabItemContent, cTabItemContent.equals(expectedCTabItemContent)); } @Test public void findByNameAndActivate(){ int index = 1; new DefaultCTabItem(CTabFolderTest.ITEM_LABEL_PREFIX + index).activate(); String expectedCTabItemContent = CTabFolderTest.CONTENT_PREFIX + index; String cTabItemContent = new DefaultText(0).getText(); assertTrue("cTabItem content is " + cTabItemContent + "\nbut expected CTabItem content is " + expectedCTabItemContent, cTabItemContent.equals(expectedCTabItemContent)); } @Test(expected = SWTLayerException.class) public void findNonExistingByIndex(){ new DefaultCTabItem(5); } @Test(expected = SWTLayerException.class) public void findNonExistingByLabel(){ new DefaultCTabItem("NON_EXISTING_#$"); } @Test public void close(){ int index = 3; CTabItem cTabItem = new DefaultCTabItem(index); cTabItem.close(); try{ new DefaultCTabItem(index); fail("CTabItem with index " + index + " was found but has to be closed"); } catch (SWTLayerException sle){ // do nothing closed CTabItem should not be found } } }
SWTBot dependencies removed from CTabFolderTest
org.jboss.reddeer.swt.test/src/org/jboss/reddeer/swt/test/impl/ctab/CTabFolderTest.java
SWTBot dependencies removed from CTabFolderTest
<ide><path>rg.jboss.reddeer.swt.test/src/org/jboss/reddeer/swt/test/impl/ctab/CTabFolderTest.java <ide> import org.eclipse.swt.SWT; <ide> import org.eclipse.swt.custom.CTabFolder; <ide> import org.eclipse.swt.layout.FillLayout; <del>import org.eclipse.swt.widgets.Display; <ide> import org.eclipse.swt.widgets.Shell; <ide> import org.eclipse.swt.widgets.Text; <del>import org.eclipse.swtbot.swt.finder.finders.UIThreadRunnable; <del>import org.eclipse.swtbot.swt.finder.results.VoidResult; <ide> import org.jboss.reddeer.swt.api.CTabItem; <ide> import org.jboss.reddeer.swt.exception.SWTLayerException; <ide> import org.jboss.reddeer.swt.impl.ctab.DefaultCTabItem; <ide> import org.jboss.reddeer.swt.impl.text.DefaultText; <ide> import org.jboss.reddeer.swt.test.RedDeerTest; <add>import org.jboss.reddeer.swt.util.Display; <ide> import org.junit.After; <ide> import org.junit.Test; <ide> <ide> @Override <ide> public void setUp() { <ide> super.setUp(); <del> UIThreadRunnable.syncExec(new VoidResult() { <add> Display.syncExec(new Runnable() { <ide> <ide> @Override <ide> public void run() { <del> Display display = Display.getDefault(); <del> Shell shell = new Shell(display); <add> Shell shell = new Shell(org.eclipse.swt.widgets.Display.getDefault()); <ide> shell.setText("Testing shell"); <ide> createControls(shell); <ide> shell.open(); <ide> } <ide> @After <ide> public void cleanup() { <del> UIThreadRunnable.syncExec(new VoidResult() { <add> Display.syncExec(new Runnable() { <ide> @Override <ide> public void run() { <ide> for (Shell shell : org.jboss.reddeer.swt.
Java
mit
65d0675a4e972c044414400f83b371189ec82c91
0
iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable
package org.broadinstitute.sting.secondarybase; import org.broadinstitute.sting.utils.BaseUtils; import org.broadinstitute.sting.utils.QualityUtils; import java.io.File; import java.util.ArrayList; /** * BasecallingReadModel represents the statistical models for * all bases in all cycles. It allows for easy training via * the addTrainingPoint() method, and for the computation of * the 4x4 likelihood matrix or the 1x4 probability vector * (with contextual components marginalized out of the * likelihood matrix). * * @author Kiran Garimella */ public class BasecallingReadModel { private BasecallingBaseModel[] basemodels = null; private boolean correctForContext = true; /** * Constructs a BasecallingReadModel with space for a given read length. * * @param readLength the length of the reads to which this model will apply. */ public BasecallingReadModel(int readLength) { initialize(readLength); } /** * Constructs a BasecallingReadModel and trains it using the specified training data. * * @param trainingData a set of RawReads from which the model will be trained. */ public BasecallingReadModel(ArrayList<RawRead> trainingData) { initialize(trainingData.get(0).getReadLength()); train(trainingData); } /** * Initialize the model and set default parameters for each cycle appropriately. * * @param readLength the length of the reads to which this model will apply. */ public void initialize(int readLength) { basemodels = new BasecallingBaseModel[readLength]; for (int cycle = 0; cycle < readLength; cycle++) { basemodels[cycle] = new BasecallingBaseModel(cycle != 0 && correctForContext); } } /** * Train the model using the specified training data. * * @param trainingData a set of RawReads from which the model will be trained. */ public void train(ArrayList<RawRead> trainingData) { for ( RawRead read : trainingData ) { addMeanPoints(read); } for ( RawRead read : trainingData ) { addCovariancePoints(read); } } /** * Add a training point for the mean intensity values per base and per cycle. * * @param cycle the cycle number (0-based) * @param probMatrix the probability matrix for the base * @param fourintensity the four raw intensities for the base */ public void addMeanPoint(int cycle, double[][] probMatrix, double[] fourintensity) { basemodels[cycle].addMeanPoint(probMatrix, fourintensity); } /** * Add a training point for the mean intensity values per base in all cycles. * * @param read the raw read */ public void addMeanPoints(RawRead read) { byte[] seqs = read.getSequence(); byte[] quals = read.getQuals(); short[][] ints = read.getIntensities(); for (int cycle = 0; cycle < seqs.length; cycle++) { char basePrev = (char) ((cycle == 0) ? '.' : seqs[cycle - 1]); char baseCur = (char) seqs[cycle]; double probCur = QualityUtils.qualToProb(quals[cycle]); double[][] probMatrix = getBaseProbabilityMatrix(cycle, basePrev, baseCur, probCur); double[] fourIntensity = new double[4]; for (int channel = 0; channel < 4; channel++) { fourIntensity[channel] = (double) ints[cycle][channel]; } basemodels[cycle].addMeanPoint(probMatrix, fourIntensity); } } /** * Add a training point for the intensity covariance matrix per base and per cycle. * * @param cycle the cycle number (0-based) * @param probMatrix the probability matrix for the base * @param fourintensity the four raw intensities for the base */ public void addCovariancePoint(int cycle, double[][] probMatrix, double[] fourintensity) { basemodels[cycle].addCovariancePoint(probMatrix, fourintensity); } /** * Add a training point for the intensity covariance matrix per base in all cycles. * * @param read the raw read */ public void addCovariancePoints(RawRead read) { byte[] seqs = read.getSequence(); byte[] quals = read.getQuals(); short[][] ints = read.getIntensities(); for (int cycle = 0; cycle < seqs.length; cycle++) { char basePrev = (char) ((cycle == 0) ? '.' : seqs[cycle - 1]); char baseCur = (char) seqs[cycle]; double probCur = QualityUtils.qualToProb(quals[cycle]); double[][] probMatrix = getBaseProbabilityMatrix(cycle, basePrev, baseCur, probCur); double[] fourIntensity = new double[4]; for (int channel = 0; channel < 4; channel++) { fourIntensity[channel] = (double) ints[cycle][channel]; } basemodels[cycle].addCovariancePoint(probMatrix, fourIntensity); } } /** * Compute the likelihoods that a given set of intensities yields each possible base. * * @param cycle the cycle number (0-based) * @param fourintensity the four raw intensities for the base * @return the matrix of likelihoods */ public double[][] computeLikelihoods(int cycle, double[] fourintensity) { return basemodels[cycle].computeLikelihoods(cycle, fourintensity); } /** * Compute the probabilities that a given set of intensities yields each possible base. * * @param cycle the cycle number (0-based) * @param basePrev the previous base * @param qualPrev the previous base's quality score * @param fourintensity the four raw intensities for the base * @return the probability distribution over the four base possibilities */ public FourProb computeProbabilities(int cycle, char basePrev, byte qualPrev, double[] fourintensity) { double[][] likes = computeLikelihoods(cycle, fourintensity); double total = 0; for (int basePrevIndex = 0; basePrevIndex < likes.length; basePrevIndex++) { for (int baseCurIndex = 0; baseCurIndex < 4; baseCurIndex++) { double prior = 1.0; if (correctForContext) { double prob = QualityUtils.qualToProb(qualPrev); if (basePrevIndex == BaseUtils.simpleBaseToBaseIndex(basePrev)) { prior = prob; } else { prior = (1.0 - prob)/((double) (4*likes.length - 1)); } } likes[basePrevIndex][baseCurIndex] = prior*likes[basePrevIndex][baseCurIndex]; total += likes[basePrevIndex][baseCurIndex]; } } for (int basePrevIndex = 0; basePrevIndex < likes.length; basePrevIndex++) { for (int baseCurIndex = 0; baseCurIndex < 4; baseCurIndex++) { likes[basePrevIndex][baseCurIndex] /= total; } } return new FourProb(likes); } /** * Call the bases in the given RawRead. * * @param read the RawRead * @return the basecalled read */ public FourProbRead call(RawRead read) { FourProbRead fpr = new FourProbRead(read.getReadLength()); for (int cycle = 0; cycle < read.getReadLength(); cycle++) { char basePrev = (char) ((cycle == 0) ? '.' : read.getSequence()[cycle - 1]); byte qualPrev = ((cycle == 0) ? 0 : read.getQuals()[cycle - 1]); double[] fourIntensity = new double[4]; for (int channel = 0; channel < 4; channel++) { fourIntensity[channel] = (double) read.getIntensities()[cycle][channel]; } fpr.add(cycle, computeProbabilities(cycle, basePrev, qualPrev, fourIntensity)); } return fpr; } /** * Return the probability matrix given the previous cycle's base, the current cycle's base, and the current base's probability. * * @param cycle the cycle number (0-based) * @param basePrev the previous base * @param baseCur the current base * @param probCur the probability of the current base * @return the probability matrix of the base */ public double[][] getBaseProbabilityMatrix(int cycle, char basePrev, char baseCur, double probCur) { double[][] dist = new double[(correctForContext && cycle > 0) ? 4 : 1][4]; int actualBasePrevIndex = (correctForContext && cycle > 0) ? BaseUtils.simpleBaseToBaseIndex(basePrev) : 0; int actualBaseCurIndex = BaseUtils.simpleBaseToBaseIndex(baseCur); if (actualBasePrevIndex == -1) { actualBasePrevIndex = BaseUtils.getRandomBaseIndex(); } if (actualBaseCurIndex == -1) { actualBaseCurIndex = BaseUtils.getRandomBaseIndex(); } double residualTheories = (double) (dist.length*dist[0].length - 1); for (int basePrevIndex = 0; basePrevIndex < dist.length; basePrevIndex++) { for (int baseCurIndex = 0; baseCurIndex < dist[basePrevIndex].length; baseCurIndex++) { dist[basePrevIndex][baseCurIndex] = (basePrevIndex == actualBasePrevIndex && baseCurIndex == actualBaseCurIndex) ? probCur : ((1.0 - probCur)/residualTheories); } } return dist; } /** * Write model parameters to disk. * * @param dir the directory in which model parameters should be stored. */ public void write(File dir) { for (int cycle = 0; cycle < basemodels.length; cycle++) { File outparam = new File(dir.getPath() + "/param." + cycle + ".r"); basemodels[cycle].write(outparam); } } }
java/src/org/broadinstitute/sting/secondarybase/BasecallingReadModel.java
package org.broadinstitute.sting.secondarybase; import org.broadinstitute.sting.utils.BaseUtils; import org.broadinstitute.sting.utils.QualityUtils; import java.io.File; import java.util.ArrayList; /** * BasecallingReadModel represents the statistical models for * all bases in all cycles. It allows for easy training via * the addTrainingPoint() method, and for the computation of * the 4x4 likelihood matrix or the 1x4 probability vector * (with contextual components marginalized out of the * likelihood matrix). * * @author Kiran Garimella */ public class BasecallingReadModel { private BasecallingBaseModel[] basemodels = null; private boolean correctForContext = true; /** * Constructs a BasecallingReadModel with space for a given read length. * * @param readLength the length of the reads to which this model will apply. */ public BasecallingReadModel(int readLength) { initialize(readLength); } /** * Constructs a BasecallingReadModel and trains it using the specified training data. * * @param trainingData a set of RawReads from which the model will be trained. */ public BasecallingReadModel(ArrayList<RawRead> trainingData) { initialize(trainingData.get(0).getReadLength()); train(trainingData); } /** * Initialize the model and set default parameters for each cycle appropriately. * * @param readLength the length of the reads to which this model will apply. */ public void initialize(int readLength) { basemodels = new BasecallingBaseModel[readLength]; for (int cycle = 0; cycle < readLength; cycle++) { basemodels[cycle] = new BasecallingBaseModel(cycle != 0 && correctForContext); } } /** * Train the model using the specified training data. * * @param trainingData a set of RawReads from which the model will be trained. */ public void train(ArrayList<RawRead> trainingData) { for ( RawRead read : trainingData ) { addMeanPoints(read); } for ( RawRead read : trainingData ) { addCovariancePoints(read); } } /** * Add a training point for the mean intensity values per base and per cycle. * * @param cycle the cycle number (0-based) * @param probMatrix the probability matrix for the base * @param fourintensity the four raw intensities for the base */ public void addMeanPoint(int cycle, double[][] probMatrix, double[] fourintensity) { basemodels[cycle].addMeanPoint(probMatrix, fourintensity); } /** * Add a training point for the mean intensity values per base in all cycles. * * @param read the raw read */ public void addMeanPoints(RawRead read) { byte[] seqs = read.getSequence(); byte[] quals = read.getQuals(); short[][] ints = read.getIntensities(); for (int cycle = 0; cycle < seqs.length; cycle++) { char basePrev = (char) ((cycle == 0) ? '.' : seqs[cycle - 1]); char baseCur = (char) seqs[cycle]; double probCur = QualityUtils.qualToProb(quals[cycle]); double[][] probMatrix = getBaseProbabilityMatrix(cycle, basePrev, baseCur, probCur); double[] fourIntensity = new double[4]; for (int channel = 0; channel < 4; channel++) { fourIntensity[channel] = (double) ints[cycle][channel]; } basemodels[cycle].addMeanPoint(probMatrix, fourIntensity); } } /** * Add a training point for the intensity covariance matrix per base and per cycle. * * @param cycle the cycle number (0-based) * @param probMatrix the probability matrix for the base * @param fourintensity the four raw intensities for the base */ public void addCovariancePoint(int cycle, double[][] probMatrix, double[] fourintensity) { basemodels[cycle].addCovariancePoint(probMatrix, fourintensity); } /** * Add a training point for the intensity covariance matrix per base in all cycles. * * @param read the raw read */ public void addCovariancePoints(RawRead read) { byte[] seqs = read.getSequence(); byte[] quals = read.getQuals(); short[][] ints = read.getIntensities(); for (int cycle = 0; cycle < seqs.length; cycle++) { char basePrev = (char) ((cycle == 0) ? '.' : seqs[cycle - 1]); char baseCur = (char) seqs[cycle]; double probCur = QualityUtils.qualToProb(quals[cycle]); double[][] probMatrix = getBaseProbabilityMatrix(cycle, basePrev, baseCur, probCur); double[] fourIntensity = new double[4]; for (int channel = 0; channel < 4; channel++) { fourIntensity[channel] = (double) ints[cycle][channel]; } basemodels[cycle].addCovariancePoint(probMatrix, fourIntensity); } } /** * Compute the likelihoods that a given set of intensities yields each possible base. * * @param cycle the cycle number (0-based) * @param fourintensity the four raw intensities for the base * @return the matrix of likelihoods */ public double[][] computeLikelihoods(int cycle, double[] fourintensity) { return basemodels[cycle].computeLikelihoods(cycle, fourintensity); } /** * Compute the probabilities that a given set of intensities yields each possible base. * * @param cycle the cycle number (0-based) * @param basePrev the previous base * @param qualPrev the previous base's quality score * @param fourintensity the four raw intensities for the base * @return the probability distribution over the four base possibilities */ public FourProb computeProbabilities(int cycle, char basePrev, byte qualPrev, double[] fourintensity) { double[][] likes = computeLikelihoods(cycle, fourintensity); double total = 0; for (int basePrevIndex = 0; basePrevIndex < likes.length; basePrevIndex++) { for (int baseCurIndex = 0; baseCurIndex < 4; baseCurIndex++) { double prior = 1.0; if (correctForContext) { double prob = QualityUtils.qualToProb(qualPrev); if (basePrevIndex == BaseUtils.simpleBaseToBaseIndex(basePrev)) { prior = prob; } else { prior = (1.0 - prob)/((double) (4*likes.length - 1)); } } likes[basePrevIndex][baseCurIndex] = prior*likes[basePrevIndex][baseCurIndex]; total += likes[basePrevIndex][baseCurIndex]; } } for (int basePrevIndex = 0; basePrevIndex < likes.length; basePrevIndex++) { for (int baseCurIndex = 0; baseCurIndex < 4; baseCurIndex++) { likes[basePrevIndex][baseCurIndex] /= total; } } return new FourProb(likes); } /** * Call the bases in the given RawRead. * * @param read the RawRead * @return the basecalled read */ public FourProbRead call(RawRead read) { FourProbRead fpr = new FourProbRead(read.getReadLength()); for (int cycle = 0; cycle < read.getReadLength(); cycle++) { char basePrev = (char) ((cycle == 0) ? '.' : read.getSequence()[cycle - 1]); byte qualPrev = ((cycle == 0) ? 0 : read.getQuals()[cycle - 1]); double[] fourIntensity = new double[4]; for (int channel = 0; channel < 4; channel++) { fourIntensity[channel] = (double) read.getIntensities()[cycle][channel]; } fpr.add(cycle, computeProbabilities(cycle, basePrev, qualPrev, fourIntensity)); } return fpr; } /** * Return the probability matrix given the previous cycle's base, the current cycle's base, and the current base's probability. * * @param cycle the cycle number (0-based) * @param basePrev the previous base * @param baseCur the current base * @param probCur the probability of the current base * @return the probability matrix of the base */ public double[][] getBaseProbabilityMatrix(int cycle, char basePrev, char baseCur, double probCur) { double[][] dist = new double[(correctForContext && cycle > 0) ? 4 : 1][4]; int actualBasePrevIndex = (correctForContext && cycle > 0) ? BaseUtils.simpleBaseToBaseIndex(basePrev) : 0; int actualBaseCurIndex = BaseUtils.simpleBaseToBaseIndex(baseCur); double residualTheories = (double) (dist.length*dist[0].length - 1); for (int basePrevIndex = 0; basePrevIndex < dist.length; basePrevIndex++) { for (int baseCurIndex = 0; baseCurIndex < dist[basePrevIndex].length; baseCurIndex++) { dist[basePrevIndex][baseCurIndex] = (basePrevIndex == actualBasePrevIndex && baseCurIndex == actualBaseCurIndex) ? probCur : ((1.0 - probCur)/residualTheories); } } return dist; } /** * Write model parameters to disk. * * @param dir the directory in which model parameters should be stored. */ public void write(File dir) { for (int cycle = 0; cycle < basemodels.length; cycle++) { File outparam = new File(dir.getPath() + "/param." + cycle + ".r"); basemodels[cycle].write(outparam); } } }
Some changes regarding what to do when a cycle is completely busted. git-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@946 348d0f76-0448-11de-a6fe-93d51630548a
java/src/org/broadinstitute/sting/secondarybase/BasecallingReadModel.java
Some changes regarding what to do when a cycle is completely busted.
<ide><path>ava/src/org/broadinstitute/sting/secondarybase/BasecallingReadModel.java <ide> int actualBasePrevIndex = (correctForContext && cycle > 0) ? BaseUtils.simpleBaseToBaseIndex(basePrev) : 0; <ide> int actualBaseCurIndex = BaseUtils.simpleBaseToBaseIndex(baseCur); <ide> <add> if (actualBasePrevIndex == -1) { actualBasePrevIndex = BaseUtils.getRandomBaseIndex(); } <add> if (actualBaseCurIndex == -1) { actualBaseCurIndex = BaseUtils.getRandomBaseIndex(); } <add> <ide> double residualTheories = (double) (dist.length*dist[0].length - 1); <ide> <ide> for (int basePrevIndex = 0; basePrevIndex < dist.length; basePrevIndex++) {
Java
apache-2.0
d3cf1c7e3c558f9a7e4c14575bd7d0b13cc5edd6
0
davide-maestroni/jroutine,davide-maestroni/jroutine
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gh.bmd.jrt.processor.core; import com.gh.bmd.jrt.annotation.Bind; import com.gh.bmd.jrt.annotation.Pass; import com.gh.bmd.jrt.annotation.Pass.PassMode; import com.gh.bmd.jrt.annotation.Timeout; import com.gh.bmd.jrt.annotation.TimeoutAction; import com.gh.bmd.jrt.builder.RoutineConfiguration; import com.gh.bmd.jrt.builder.RoutineConfiguration.Builder; import com.gh.bmd.jrt.builder.RoutineConfiguration.OrderType; import com.gh.bmd.jrt.builder.RoutineConfiguration.TimeoutActionType; import com.gh.bmd.jrt.channel.OutputChannel; import com.gh.bmd.jrt.channel.StandaloneChannel; import com.gh.bmd.jrt.common.AbortException; import com.gh.bmd.jrt.common.ClassToken; import com.gh.bmd.jrt.core.JRoutine; import com.gh.bmd.jrt.log.Log; import com.gh.bmd.jrt.log.Log.LogLevel; import com.gh.bmd.jrt.log.NullLog; import com.gh.bmd.jrt.processor.annotation.Wrap; import com.gh.bmd.jrt.processor.builder.WrapperRoutineBuilder; import com.gh.bmd.jrt.runner.Runner; import com.gh.bmd.jrt.runner.Runners; import com.gh.bmd.jrt.time.TimeDuration; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import static com.gh.bmd.jrt.builder.RoutineConfiguration.builder; import static com.gh.bmd.jrt.builder.RoutineConfiguration.onReadTimeout; import static com.gh.bmd.jrt.builder.RoutineConfiguration.withAsyncRunner; import static com.gh.bmd.jrt.builder.RoutineConfiguration.withReadTimeout; import static com.gh.bmd.jrt.builder.RoutineConfiguration.withSyncRunner; import static com.gh.bmd.jrt.builder.ShareConfiguration.withGroup; import static com.gh.bmd.jrt.time.TimeDuration.INFINITY; import static com.gh.bmd.jrt.time.TimeDuration.seconds; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; /** * Processor unit tests. * <p/> * Created by davide on 3/6/15. */ public class ProcessorTest { @Test public void testGenericWrapperCache() { final TestList<String> testList = new TestList<String>(); final WrapperRoutineBuilder builder = JRoutineProcessor.on(testList).configure(withAsyncRunner(Runners.queuedRunner())); final TestListItf<String> testListItf1 = builder.buildWrapper(new ClassToken<TestListItf<String>>() {}); testListItf1.add("test"); assertThat(testListItf1.get(0)).isEqualTo("test"); assertThat(builder.buildWrapper(new ClassToken<TestListItf<Integer>>() {})).isSameAs( testListItf1); final TestListItf<Integer> testListItf2 = builder.buildWrapper(new ClassToken<TestListItf<Integer>>() {}); assertThat(testListItf2).isSameAs(testListItf1); assertThat(builder.buildWrapper(new ClassToken<TestListItf<Integer>>() {})).isSameAs( testListItf2); testListItf2.add(3); assertThat(testListItf2.get(1)).isEqualTo(3); assertThat(testListItf2.getAsync(1).readNext()).isEqualTo(3); assertThat(testListItf2.getList(1)).containsExactly(3); } @Test public void testInterface() { final TestClass test = new TestClass(); final ClassToken<TestInterfaceWrapper> token = ClassToken.tokenOf(TestInterfaceWrapper.class); final Builder configuration = withSyncRunner(Runners.sequentialRunner()); final TestInterfaceWrapper testWrapper = JRoutineProcessor.on(test).configure(configuration).buildWrapper(token); assertThat(testWrapper.getOne().readNext()).isEqualTo(1); } @Test @SuppressWarnings("ConstantConditions") public void testNullPointerError() { final TestClass test = new TestClass(); try { JRoutineProcessor.on(test).buildWrapper((Class<?>) null); fail(); } catch (final NullPointerException ignored) { } try { JRoutineProcessor.on(test).buildWrapper((ClassToken<?>) null); fail(); } catch (final NullPointerException ignored) { } } @Test public void testShareGroup() { final TestClass2 test = new TestClass2(); final WrapperRoutineBuilder builder = JRoutineProcessor.on(test).configure(withReadTimeout(seconds(2))); long startTime = System.currentTimeMillis(); OutputChannel<Integer> getOne = builder.share(withGroup("1")).buildWrapper(TestClassAsync.class).getOne(); OutputChannel<Integer> getTwo = builder.share(withGroup("2")).buildWrapper(TestClassAsync.class).getTwo(); assertThat(getOne.checkComplete()).isTrue(); assertThat(getTwo.checkComplete()).isTrue(); assertThat(System.currentTimeMillis() - startTime).isLessThan(1000); startTime = System.currentTimeMillis(); getOne = builder.buildWrapper(TestClassAsync.class).getOne(); getTwo = builder.buildWrapper(TestClassAsync.class).getTwo(); assertThat(getOne.checkComplete()).isTrue(); assertThat(getTwo.checkComplete()).isTrue(); assertThat(System.currentTimeMillis() - startTime).isGreaterThanOrEqualTo(1000); } @Test @SuppressWarnings("unchecked") public void testTemplates() { final Impl impl = new Impl(); final Itf itf = JRoutineProcessor.on(impl).configure(withReadTimeout(INFINITY)) .buildWrapper(Itf.class); assertThat(itf.add0('c')).isEqualTo((int) 'c'); final StandaloneChannel<Character> channel1 = JRoutine.standalone().buildChannel(); channel1.input().pass('a').close(); assertThat(itf.add1(channel1.output())).isEqualTo((int) 'a'); final StandaloneChannel<Character> channel2 = JRoutine.standalone().buildChannel(); channel2.input().pass('d', 'e', 'f').close(); assertThat(itf.add2(channel2.output())).isIn((int) 'd', (int) 'e', (int) 'f'); assertThat(itf.add3('c').readAll()).containsExactly((int) 'c'); final StandaloneChannel<Character> channel3 = JRoutine.standalone().buildChannel(); channel3.input().pass('a').close(); assertThat(itf.add4(channel3.output()).readAll()).containsExactly((int) 'a'); final StandaloneChannel<Character> channel4 = JRoutine.standalone().buildChannel(); channel4.input().pass('d', 'e', 'f').close(); assertThat(itf.add5(channel4.output()).readAll()).containsOnly((int) 'd', (int) 'e', (int) 'f'); assertThat(itf.addA00(new char[]{'c', 'z'})).isEqualTo(new int[]{'c', 'z'}); final StandaloneChannel<char[]> channel5 = JRoutine.standalone().buildChannel(); channel5.input().pass(new char[]{'a', 'z'}).close(); assertThat(itf.addA01(channel5.output())).isEqualTo(new int[]{'a', 'z'}); final StandaloneChannel<Character> channel6 = JRoutine.standalone().buildChannel(); channel6.input().pass('d', 'e', 'f').close(); assertThat(itf.addA02(channel6.output())).isEqualTo(new int[]{'d', 'e', 'f'}); final StandaloneChannel<char[]> channel7 = JRoutine.standalone().buildChannel(); channel7.input() .pass(new char[]{'d', 'z'}, new char[]{'e', 'z'}, new char[]{'f', 'z'}) .close(); assertThat(itf.addA03(channel7.output())).isIn(new int[]{'d', 'z'}, new int[]{'e', 'z'}, new int[]{'f', 'z'}); assertThat(itf.addA04(new char[]{'c', 'z'}).readAll()).containsExactly(new int[]{'c', 'z'}); final StandaloneChannel<char[]> channel8 = JRoutine.standalone().buildChannel(); channel8.input().pass(new char[]{'a', 'z'}).close(); assertThat(itf.addA05(channel8.output()).readAll()).containsExactly(new int[]{'a', 'z'}); final StandaloneChannel<Character> channel9 = JRoutine.standalone().buildChannel(); channel9.input().pass('d', 'e', 'f').close(); assertThat(itf.addA06(channel9.output()).readAll()).containsExactly( new int[]{'d', 'e', 'f'}); final StandaloneChannel<char[]> channel10 = JRoutine.standalone().buildChannel(); channel10.input() .pass(new char[]{'d', 'z'}, new char[]{'e', 'z'}, new char[]{'f', 'z'}) .close(); assertThat(itf.addA07(channel10.output()).readAll()).containsOnly(new int[]{'d', 'z'}, new int[]{'e', 'z'}, new int[]{'f', 'z'}); assertThat(itf.addA08(new char[]{'c', 'z'}).readAll()).containsExactly((int) 'c', (int) 'z'); final StandaloneChannel<char[]> channel11 = JRoutine.standalone().buildChannel(); channel11.input().pass(new char[]{'a', 'z'}).close(); assertThat(itf.addA09(channel11.output()).readAll()).containsExactly((int) 'a', (int) 'z'); final StandaloneChannel<Character> channel12 = JRoutine.standalone().buildChannel(); channel12.input().pass('d', 'e', 'f').close(); assertThat(itf.addA10(channel12.output()).readAll()).containsExactly((int) 'd', (int) 'e', (int) 'f'); final StandaloneChannel<char[]> channel13 = JRoutine.standalone().buildChannel(); channel13.input() .pass(new char[]{'d', 'z'}, new char[]{'e', 'z'}, new char[]{'f', 'z'}) .close(); assertThat(itf.addA11(channel13.output()).readAll()).containsOnly((int) 'd', (int) 'e', (int) 'f', (int) 'z'); assertThat(itf.addA12(new char[]{'c', 'z'})).containsExactly(new int[]{'c', 'z'}); final StandaloneChannel<char[]> channel14 = JRoutine.standalone().buildChannel(); channel14.input().pass(new char[]{'a', 'z'}).close(); assertThat(itf.addA13(channel14.output())).containsExactly(new int[]{'a', 'z'}); final StandaloneChannel<Character> channel15 = JRoutine.standalone().buildChannel(); channel15.input().pass('d', 'e', 'f').close(); assertThat(itf.addA14(channel15.output())).containsExactly(new int[]{'d', 'e', 'f'}); final StandaloneChannel<char[]> channel16 = JRoutine.standalone().buildChannel(); channel16.input() .pass(new char[]{'d', 'z'}, new char[]{'e', 'z'}, new char[]{'f', 'z'}) .close(); assertThat(itf.addA15(channel16.output())).containsOnly(new int[]{'d', 'z'}, new int[]{'e', 'z'}, new int[]{'f', 'z'}); assertThat(itf.addA16(new char[]{'c', 'z'})).containsExactly(new int[]{'c', 'z'}); final StandaloneChannel<char[]> channel17 = JRoutine.standalone().buildChannel(); channel17.input().pass(new char[]{'a', 'z'}).close(); assertThat(itf.addA17(channel17.output())).containsExactly(new int[]{'a', 'z'}); final StandaloneChannel<Character> channel18 = JRoutine.standalone().buildChannel(); channel18.input().pass('d', 'e', 'f').close(); assertThat(itf.addA18(channel18.output())).containsExactly(new int[]{'d', 'e', 'f'}); final StandaloneChannel<char[]> channel19 = JRoutine.standalone().buildChannel(); channel19.input() .pass(new char[]{'d', 'z'}, new char[]{'e', 'z'}, new char[]{'f', 'z'}) .close(); assertThat(itf.addA19(channel19.output())).containsOnly(new int[]{'d', 'z'}, new int[]{'e', 'z'}, new int[]{'f', 'z'}); assertThat(itf.addL00(Arrays.asList('c', 'z'))).isEqualTo( Arrays.asList((int) 'c', (int) 'z')); final StandaloneChannel<List<Character>> channel20 = JRoutine.standalone().buildChannel(); channel20.input().pass(Arrays.asList('a', 'z')).close(); assertThat(itf.addL01(channel20.output())).isEqualTo(Arrays.asList((int) 'a', (int) 'z')); final StandaloneChannel<Character> channel21 = JRoutine.standalone().buildChannel(); channel21.input().pass('d', 'e', 'f').close(); assertThat(itf.addL02(channel21.output())).isEqualTo( Arrays.asList((int) 'd', (int) 'e', (int) 'f')); final StandaloneChannel<List<Character>> channel22 = JRoutine.standalone().buildChannel(); channel22.input() .pass(Arrays.asList('d', 'z'), Arrays.asList('e', 'z'), Arrays.asList('f', 'z')) .close(); assertThat(itf.addL03(channel22.output())).isIn(Arrays.asList((int) 'd', (int) 'z'), Arrays.asList((int) 'e', (int) 'z'), Arrays.asList((int) 'f', (int) 'z')); assertThat(itf.addL04(Arrays.asList('c', 'z')).readAll()).containsExactly( Arrays.asList((int) 'c', (int) 'z')); final StandaloneChannel<List<Character>> channel23 = JRoutine.standalone().buildChannel(); channel23.input().pass(Arrays.asList('a', 'z')).close(); assertThat(itf.addL05(channel23.output()).readAll()).containsExactly( Arrays.asList((int) 'a', (int) 'z')); final StandaloneChannel<Character> channel24 = JRoutine.standalone().buildChannel(); channel24.input().pass('d', 'e', 'f').close(); assertThat(itf.addL06(channel24.output()).readAll()).containsExactly( Arrays.asList((int) 'd', (int) 'e', (int) 'f')); final StandaloneChannel<List<Character>> channel25 = JRoutine.standalone().buildChannel(); channel25.input() .pass(Arrays.asList('d', 'z'), Arrays.asList('e', 'z'), Arrays.asList('f', 'z')) .close(); assertThat(itf.addL07(channel25.output()).readAll()).containsOnly( Arrays.asList((int) 'd', (int) 'z'), Arrays.asList((int) 'e', (int) 'z'), Arrays.asList((int) 'f', (int) 'z')); assertThat(itf.addL08(Arrays.asList('c', 'z')).readAll()).containsExactly((int) 'c', (int) 'z'); final StandaloneChannel<List<Character>> channel26 = JRoutine.standalone().buildChannel(); channel26.input().pass(Arrays.asList('a', 'z')).close(); assertThat(itf.addL09(channel26.output()).readAll()).containsExactly((int) 'a', (int) 'z'); final StandaloneChannel<Character> channel27 = JRoutine.standalone().buildChannel(); channel27.input().pass('d', 'e', 'f').close(); assertThat(itf.addL10(channel27.output()).readAll()).containsExactly((int) 'd', (int) 'e', (int) 'f'); final StandaloneChannel<List<Character>> channel28 = JRoutine.standalone().buildChannel(); channel28.input() .pass(Arrays.asList('d', 'z'), Arrays.asList('e', 'z'), Arrays.asList('f', 'z')) .close(); assertThat(itf.addL11(channel28.output()).readAll()).containsOnly((int) 'd', (int) 'e', (int) 'f', (int) 'z'); assertThat(itf.addL12(Arrays.asList('c', 'z'))).containsExactly( Arrays.asList((int) 'c', (int) 'z')); final StandaloneChannel<List<Character>> channel29 = JRoutine.standalone().buildChannel(); channel29.input().pass(Arrays.asList('a', 'z')).close(); assertThat(itf.addL13(channel29.output())).containsExactly( Arrays.asList((int) 'a', (int) 'z')); final StandaloneChannel<Character> channel30 = JRoutine.standalone().buildChannel(); channel30.input().pass('d', 'e', 'f').close(); assertThat(itf.addL14(channel30.output())).containsExactly( Arrays.asList((int) 'd', (int) 'e', (int) 'f')); final StandaloneChannel<List<Character>> channel31 = JRoutine.standalone().buildChannel(); channel31.input() .pass(Arrays.asList('d', 'z'), Arrays.asList('e', 'z'), Arrays.asList('f', 'z')) .close(); assertThat(itf.addL15(channel31.output())).containsOnly(Arrays.asList((int) 'd', (int) 'z'), Arrays.asList((int) 'e', (int) 'z'), Arrays.asList((int) 'f', (int) 'z')); assertThat(itf.addL16(Arrays.asList('c', 'z'))).containsExactly( Arrays.asList((int) 'c', (int) 'z')); final StandaloneChannel<List<Character>> channel32 = JRoutine.standalone().buildChannel(); channel32.input().pass(Arrays.asList('a', 'z')).close(); assertThat(itf.addL17(channel32.output())).containsExactly( Arrays.asList((int) 'a', (int) 'z')); final StandaloneChannel<Character> channel33 = JRoutine.standalone().buildChannel(); channel33.input().pass('d', 'e', 'f').close(); assertThat(itf.addL18(channel33.output())).containsExactly( Arrays.asList((int) 'd', (int) 'e', (int) 'f')); final StandaloneChannel<List<Character>> channel34 = JRoutine.standalone().buildChannel(); channel34.input() .pass(Arrays.asList('d', 'z'), Arrays.asList('e', 'z'), Arrays.asList('f', 'z')) .close(); assertThat(itf.addL19(channel34.output())).containsOnly(Arrays.asList((int) 'd', (int) 'z'), Arrays.asList((int) 'e', (int) 'z'), Arrays.asList((int) 'f', (int) 'z')); assertThat(itf.get0()).isEqualTo(31); assertThat(itf.get1().readAll()).containsExactly(31); assertThat(itf.getA0()).isEqualTo(new int[]{1, 2, 3}); assertThat(itf.getA1().readAll()).containsExactly(1, 2, 3); assertThat(itf.getA2()).containsExactly(new int[]{1, 2, 3}); assertThat(itf.getA3()).containsExactly(new int[]{1, 2, 3}); assertThat(itf.getL0()).isEqualTo(Arrays.asList(1, 2, 3)); assertThat(itf.getL1().readAll()).containsExactly(1, 2, 3); assertThat(itf.getL2()).containsExactly(Arrays.asList(1, 2, 3)); assertThat(itf.getL3()).containsExactly(Arrays.asList(1, 2, 3)); itf.set0(-17); final StandaloneChannel<Integer> channel35 = JRoutine.standalone().buildChannel(); channel35.input().pass(-17).close(); itf.set1(channel35.output()); final StandaloneChannel<Integer> channel36 = JRoutine.standalone().buildChannel(); channel36.input().pass(-17).close(); itf.set2(channel36.output()); itf.setA0(new int[]{1, 2, 3}); final StandaloneChannel<int[]> channel37 = JRoutine.standalone().buildChannel(); channel37.input().pass(new int[]{1, 2, 3}).close(); itf.setA1(channel37.output()); final StandaloneChannel<Integer> channel38 = JRoutine.standalone().buildChannel(); channel38.input().pass(1, 2, 3).close(); itf.setA2(channel38.output()); final StandaloneChannel<int[]> channel39 = JRoutine.standalone().buildChannel(); channel39.input().pass(new int[]{1, 2, 3}).close(); itf.setA3(channel39.output()); itf.setL0(Arrays.asList(1, 2, 3)); final StandaloneChannel<List<Integer>> channel40 = JRoutine.standalone().buildChannel(); channel40.input().pass(Arrays.asList(1, 2, 3)).close(); itf.setL1(channel40.output()); final StandaloneChannel<Integer> channel41 = JRoutine.standalone().buildChannel(); channel41.input().pass(1, 2, 3).close(); itf.setL2(channel41.output()); final StandaloneChannel<List<Integer>> channel42 = JRoutine.standalone().buildChannel(); channel42.input().pass(Arrays.asList(1, 2, 3)).close(); itf.setL3(channel42.output()); } @Test public void testTimeoutActionAnnotation() throws NoSuchMethodException { final TestTimeout testTimeout = new TestTimeout(); assertThat(JRoutineProcessor.on(testTimeout).configure(withReadTimeout(seconds(1))) .buildWrapper(TestTimeoutItf.class) .getInt()).containsExactly(31); try { JRoutineProcessor.on(testTimeout).configure(onReadTimeout(TimeoutActionType.DEADLOCK)) .buildWrapper(TestTimeoutItf.class) .getInt(); fail(); } catch (final AbortException ignored) { } } @Test public void testWrapper() { final NullLog log = new NullLog(); final Runner runner = Runners.poolRunner(); final TestClass test = new TestClass(); final RoutineConfiguration configuration = builder().withSyncRunner(Runners.sequentialRunner()) .withAsyncRunner(runner) .withLogLevel(LogLevel.DEBUG) .withLog(log) .buildConfiguration(); final TestWrapper testWrapper = JRoutineProcessor.on(test).configure(configuration) .buildWrapper(ClassToken.tokenOf( TestWrapper.class)); assertThat(testWrapper.getOne().readNext()).isEqualTo(1); assertThat(testWrapper.getString(1, 2, 3)).isIn("1", "2", "3"); assertThat(testWrapper.getString(new HashSet<Integer>(Arrays.asList(1, 2, 3))) .readAll()).containsOnly("1", "2", "3"); assertThat(testWrapper.getString(Arrays.asList(1, 2, 3))).containsOnly("1", "2", "3"); assertThat(testWrapper.getString((Iterable<Integer>) Arrays.asList(1, 2, 3))).containsOnly( "1", "2", "3"); assertThat( testWrapper.getString((Collection<Integer>) Arrays.asList(1, 2, 3))).containsOnly( "1", "2", "3"); final ArrayList<String> list = new ArrayList<String>(); assertThat(testWrapper.getList(Collections.singletonList(list))).containsExactly(list); final StandaloneChannel<Integer> standaloneChannel = JRoutine.standalone().buildChannel(); standaloneChannel.input().pass(3).close(); assertThat(testWrapper.getString(standaloneChannel.output())).isEqualTo("3"); } @Test public void testWrapperBuilder() { final NullLog log = new NullLog(); final Runner runner = Runners.poolRunner(); final TestClass test = new TestClass(); final RoutineConfiguration configuration = builder().withSyncRunner(Runners.sequentialRunner()) .withAsyncRunner(runner) .withLogLevel(LogLevel.DEBUG) .withLog(log) .buildConfiguration(); final TestWrapper testWrapper = JRoutine_TestWrapper.on(test).configure(configuration).buildWrapper(); assertThat(testWrapper.getOne().readNext()).isEqualTo(1); assertThat(testWrapper.getString(1, 2, 3)).isIn("1", "2", "3"); assertThat(testWrapper.getString(new HashSet<Integer>(Arrays.asList(1, 2, 3))) .readAll()).containsOnly("1", "2", "3"); assertThat(testWrapper.getString(Arrays.asList(1, 2, 3))).containsOnly("1", "2", "3"); assertThat(testWrapper.getString((Iterable<Integer>) Arrays.asList(1, 2, 3))).containsOnly( "1", "2", "3"); assertThat( testWrapper.getString((Collection<Integer>) Arrays.asList(1, 2, 3))).containsOnly( "1", "2", "3"); final ArrayList<String> list = new ArrayList<String>(); assertThat(testWrapper.getList(Collections.singletonList(list))).containsExactly(list); final StandaloneChannel<Integer> standaloneChannel = JRoutine.standalone().buildChannel(); standaloneChannel.input().pass(3).close(); assertThat(testWrapper.getString(standaloneChannel.output())).isEqualTo("3"); assertThat(JRoutineProcessor.on(test).configure(configuration) .buildWrapper(ClassToken.tokenOf(TestWrapper.class))).isSameAs( testWrapper); } @Test public void testWrapperBuilderWarnings() { final CountLog countLog = new CountLog(); final RoutineConfiguration configuration = builder().withInputOrder(OrderType.NONE) .withInputSize(3) .withInputTimeout(seconds(1)) .withOutputOrder(OrderType.NONE) .withOutputSize(3) .withOutputTimeout(seconds(1)) .withLogLevel(LogLevel.DEBUG) .withLog(countLog) .buildConfiguration(); final TestClass test = new TestClass(); JRoutineProcessor.on(test).configure(configuration) .buildWrapper(TestWrapper.class) .getOne(); assertThat(countLog.getWrnCount()).isEqualTo(6); } @Test public void testWrapperCache() { final NullLog log = new NullLog(); final Runner runner = Runners.poolRunner(); final TestClass test = new TestClass(); final RoutineConfiguration configuration = builder().withSyncRunner(Runners.sequentialRunner()) .withAsyncRunner(runner) .withLogLevel(LogLevel.DEBUG) .withLog(log) .buildConfiguration(); final TestWrapper testWrapper = JRoutineProcessor.on(test).configure(configuration) .buildWrapper(ClassToken.tokenOf( TestWrapper.class)); assertThat(JRoutineProcessor.on(test).configure(configuration) .buildWrapper(ClassToken.tokenOf(TestWrapper.class))).isSameAs( testWrapper); } @Test public void testWrapperError() { final TestClass test = new TestClass(); try { JRoutineProcessor.on(test).buildWrapper(TestClass.class); fail(); } catch (final IllegalArgumentException ignored) { } try { JRoutineProcessor.on(test).buildWrapper(ClassToken.tokenOf(TestClass.class)); fail(); } catch (final IllegalArgumentException ignored) { } } @Wrap(Impl.class) public interface Itf { @Bind("a") int add0(char c); @Bind("a") int add1(@Pass(value = char.class, mode = PassMode.OBJECT) OutputChannel<Character> c); @Bind("a") int add2(@Pass(value = char.class, mode = PassMode.PARALLEL) OutputChannel<Character> c); @Bind("a") @Pass(value = int.class, mode = PassMode.OBJECT) OutputChannel<Integer> add3(char c); @Bind("a") @Pass(value = int.class, mode = PassMode.OBJECT) OutputChannel<Integer> add4( @Pass(value = char.class, mode = PassMode.OBJECT) OutputChannel<Character> c); @Bind("a") @Pass(value = int.class, mode = PassMode.OBJECT) OutputChannel<Integer> add5( @Pass(value = char.class, mode = PassMode.PARALLEL) OutputChannel<Character> c); @Bind("aa") int[] addA00(char[] c); @Bind("aa") int[] addA01(@Pass(value = char[].class, mode = PassMode.OBJECT) OutputChannel<char[]> c); @Bind("aa") int[] addA02(@Pass(value = char[].class, mode = PassMode.COLLECTION) OutputChannel<Character> c); @Bind("aa") int[] addA03(@Pass(value = char[].class, mode = PassMode.PARALLEL) OutputChannel<char[]> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.OBJECT) OutputChannel<int[]> addA04(char[] c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.OBJECT) OutputChannel<int[]> addA05( @Pass(value = char[].class, mode = PassMode.OBJECT) OutputChannel<char[]> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.OBJECT) OutputChannel<int[]> addA06(@Pass(value = char[].class, mode = PassMode.COLLECTION) OutputChannel<Character> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.OBJECT) OutputChannel<int[]> addA07(@Pass(value = char[].class, mode = PassMode.PARALLEL) OutputChannel<char[]> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.COLLECTION) OutputChannel<Integer> addA08(char[] c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.COLLECTION) OutputChannel<Integer> addA09( @Pass(value = char[].class, mode = PassMode.OBJECT) OutputChannel<char[]> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.COLLECTION) OutputChannel<Integer> addA10(@Pass(value = char[].class, mode = PassMode.COLLECTION) OutputChannel<Character> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.COLLECTION) OutputChannel<Integer> addA11(@Pass(value = char[].class, mode = PassMode.PARALLEL) OutputChannel<char[]> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.PARALLEL) List<int[]> addA12(char[] c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.PARALLEL) List<int[]> addA13( @Pass(value = char[].class, mode = PassMode.OBJECT) OutputChannel<char[]> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.PARALLEL) List<int[]> addA14(@Pass(value = char[].class, mode = PassMode.COLLECTION) OutputChannel<Character> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.PARALLEL) List<int[]> addA15(@Pass(value = char[].class, mode = PassMode.PARALLEL) OutputChannel<char[]> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.PARALLEL) int[][] addA16(char[] c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.PARALLEL) int[][] addA17(@Pass(value = char[].class, mode = PassMode.OBJECT) OutputChannel<char[]> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.PARALLEL) int[][] addA18(@Pass(value = char[].class, mode = PassMode.COLLECTION) OutputChannel<Character> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.PARALLEL) int[][] addA19(@Pass(value = char[].class, mode = PassMode.PARALLEL) OutputChannel<char[]> c); @Bind("al") List<Integer> addL00(List<Character> c); @Bind("al") List<Integer> addL01(@Pass(value = List.class, mode = PassMode.OBJECT) OutputChannel<List<Character>> c); @Bind("al") List<Integer> addL02(@Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Character> c); @Bind("al") List<Integer> addL03(@Pass(value = List.class, mode = PassMode.PARALLEL) OutputChannel<List<Character>> c); @Bind("al") @Pass(value = List.class, mode = PassMode.OBJECT) OutputChannel<List<Integer>> addL04(List<Character> c); @Bind("al") @Pass(value = List.class, mode = PassMode.OBJECT) OutputChannel<List<Integer>> addL05(@Pass(value = List.class, mode = PassMode.OBJECT) OutputChannel<List<Character>> c); @Bind("al") @Pass(value = List.class, mode = PassMode.OBJECT) OutputChannel<List<Integer>> addL06(@Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Character> c); @Bind("al") @Pass(value = List.class, mode = PassMode.OBJECT) OutputChannel<List<Integer>> addL07(@Pass(value = List.class, mode = PassMode.PARALLEL) OutputChannel<List<Character>> c); @Bind("al") @Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Integer> addL08(List<Character> c); @Bind("al") @Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Integer> addL09(@Pass(value = List.class, mode = PassMode.OBJECT) OutputChannel<List<Character>> c); @Bind("al") @Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Integer> addL10(@Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Character> c); @Bind("al") @Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Integer> addL11(@Pass(value = List.class, mode = PassMode.PARALLEL) OutputChannel<List<Character>> c); @Bind("al") @Pass(value = List.class, mode = PassMode.PARALLEL) List<List<Integer>> addL12(List<Character> c); @Bind("al") @Pass(value = List.class, mode = PassMode.PARALLEL) List<List<Integer>> addL13(@Pass(value = List.class, mode = PassMode.OBJECT) OutputChannel<List<Character>> c); @Bind("al") @Pass(value = List.class, mode = PassMode.PARALLEL) List<List<Integer>> addL14(@Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Character> c); @Bind("al") @Pass(value = List.class, mode = PassMode.PARALLEL) List<List<Integer>> addL15(@Pass(value = List.class, mode = PassMode.PARALLEL) OutputChannel<List<Character>> c); @Bind("al") @Pass(value = List.class, mode = PassMode.PARALLEL) List[] addL16(List<Character> c); @Bind("al") @Pass(value = List.class, mode = PassMode.PARALLEL) List[] addL17(@Pass(value = List.class, mode = PassMode.OBJECT) OutputChannel<List<Character>> c); @Bind("al") @Pass(value = List.class, mode = PassMode.PARALLEL) List[] addL18(@Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Character> c); @Bind("al") @Pass(value = List.class, mode = PassMode.PARALLEL) List[] addL19(@Pass(value = List.class, mode = PassMode.PARALLEL) OutputChannel<List<Character>> c); @Bind("g") int get0(); @Bind("s") void set0(int i); @Bind("g") @Pass(value = int.class, mode = PassMode.OBJECT) OutputChannel<Integer> get1(); @Bind("s") void set1(@Pass(value = int.class, mode = PassMode.OBJECT) OutputChannel<Integer> i); @Bind("ga") int[] getA0(); @Bind("sa") void setA0(int[] i); @Bind("ga") @Pass(value = int[].class, mode = PassMode.COLLECTION) OutputChannel<Integer> getA1(); @Bind("sa") void setA1(@Pass(value = int[].class, mode = PassMode.OBJECT) OutputChannel<int[]> i); @Bind("ga") @Pass(value = int[].class, mode = PassMode.PARALLEL) List<int[]> getA2(); @Bind("sa") void setA2(@Pass(value = int[].class, mode = PassMode.COLLECTION) OutputChannel<Integer> i); @Bind("ga") @Pass(value = int[].class, mode = PassMode.PARALLEL) int[][] getA3(); @Bind("sa") void setA3(@Pass(value = int[].class, mode = PassMode.PARALLEL) OutputChannel<int[]> i); @Bind("gl") List<Integer> getL0(); @Bind("sl") void setL0(List<Integer> i); @Bind("gl") @Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Integer> getL1(); @Bind("sl") void setL1(@Pass(value = List.class, mode = PassMode.OBJECT) OutputChannel<List<Integer>> i); @Bind("gl") @Pass(value = List.class, mode = PassMode.PARALLEL) List<List<Integer>> getL2(); @Bind("sl") void setL2(@Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Integer> i); @Bind("gl") @Pass(value = List.class, mode = PassMode.PARALLEL) List[] getL3(); @Bind("sl") void setL3(@Pass(value = List.class, mode = PassMode.PARALLEL) OutputChannel<List<Integer>> i); @Bind("s") void set2(@Pass(value = int.class, mode = PassMode.PARALLEL) OutputChannel<Integer> i); } @Wrap(TestClass2.class) public interface TestClassAsync { @Pass(int.class) OutputChannel<Integer> getOne(); @Pass(int.class) OutputChannel<Integer> getTwo(); } @SuppressWarnings("unused") public interface TestClassInterface { int getOne(); } @Wrap(TestClassInterface.class) public interface TestInterfaceWrapper { @Timeout(300) @Pass(int.class) OutputChannel<Integer> getOne(); } @Wrap(TestList.class) public interface TestListItf<TYPE> { void add(Object t); TYPE get(int i); @Bind("get") @Pass(Object.class) OutputChannel<TYPE> getAsync(int i); @Bind("get") @Pass(Object.class) List<TYPE> getList(int i); } @Wrap(TestTimeout.class) public interface TestTimeoutItf { @Pass(int.class) @TimeoutAction(TimeoutActionType.ABORT) List<Integer> getInt(); } @Wrap(TestClass.class) public interface TestWrapper { @Timeout(300) @Pass(List.class) Iterable<Iterable> getList(@Pass(List.class) List<? extends List<String>> i); @Timeout(300) @Pass(int.class) OutputChannel<Integer> getOne(); @Timeout(300) String getString(@Pass(int.class) int... i); @Timeout(300) @Pass(String.class) OutputChannel<String> getString(@Pass(int.class) HashSet<Integer> i); @Timeout(300) @Pass(String.class) List<String> getString(@Pass(int.class) List<Integer> i); @Timeout(300) @Pass(String.class) Iterable<String> getString(@Pass(int.class) Iterable<Integer> i); @Timeout(300) @Pass(String.class) String[] getString(@Pass(int.class) Collection<Integer> i); @Timeout(300) String getString(@Pass(int.class) OutputChannel<Integer> i); } @SuppressWarnings("unused") public static class Impl { @Bind("a") public int add(char c) { return c; } @Bind("aa") public int[] addArray(char[] c) { final int[] array = new int[c.length]; for (int i = 0; i < c.length; i++) { array[i] = c[i]; } return array; } @Bind("al") public List<Integer> addList(List<Character> c) { final ArrayList<Integer> list = new ArrayList<Integer>(c.size()); for (final Character character : c) { list.add((int) character); } return list; } @Bind("g") public int get() { return 31; } @Bind("ga") public int[] getArray() { return new int[]{1, 2, 3}; } @Bind("sa") public void setArray(int[] i) { assertThat(i).containsExactly(1, 2, 3); } @Bind("gl") public List<Integer> getList() { return Arrays.asList(1, 2, 3); } @Bind("sl") public void setList(List<Integer> l) { assertThat(l).containsExactly(1, 2, 3); } @Bind("s") public void set(int i) { assertThat(i).isEqualTo(-17); } } @SuppressWarnings("unused") public static class TestClass implements TestClassInterface { public List<String> getList(final List<String> list) { return list; } public int getOne() { return 1; } public String getString(final int i) { return Integer.toString(i); } } @SuppressWarnings("unused") public static class TestList<TYPE> { private final ArrayList<TYPE> mList = new ArrayList<TYPE>(); public void add(TYPE t) { mList.add(t); } public TYPE get(int i) { return mList.get(i); } } @SuppressWarnings("unused") public static class TestTimeout { public int getInt() throws InterruptedException { Thread.sleep(100); return 31; } } @SuppressWarnings("unused") private static class CountLog implements Log { private int mDgbCount; private int mErrCount; private int mWrnCount; public void dbg(@Nonnull final List<Object> contexts, @Nullable final String message, @Nullable final Throwable throwable) { ++mDgbCount; } public void err(@Nonnull final List<Object> contexts, @Nullable final String message, @Nullable final Throwable throwable) { ++mErrCount; } public void wrn(@Nonnull final List<Object> contexts, @Nullable final String message, @Nullable final Throwable throwable) { ++mWrnCount; } public int getDgbCount() { return mDgbCount; } public int getErrCount() { return mErrCount; } public int getWrnCount() { return mWrnCount; } } @SuppressWarnings("unused") public class TestClass2 { public int getOne() throws InterruptedException { TimeDuration.millis(500).sleepAtLeast(); return 1; } public int getTwo() throws InterruptedException { TimeDuration.millis(500).sleepAtLeast(); return 2; } } }
processor/src/test/java/com/gh/bmd/jrt/processor/core/ProcessorTest.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gh.bmd.jrt.processor.core; import com.gh.bmd.jrt.annotation.Bind; import com.gh.bmd.jrt.annotation.Pass; import com.gh.bmd.jrt.annotation.Pass.PassMode; import com.gh.bmd.jrt.annotation.Timeout; import com.gh.bmd.jrt.annotation.TimeoutAction; import com.gh.bmd.jrt.builder.RoutineConfiguration; import com.gh.bmd.jrt.builder.RoutineConfiguration.Builder; import com.gh.bmd.jrt.builder.RoutineConfiguration.OrderType; import com.gh.bmd.jrt.builder.RoutineConfiguration.TimeoutActionType; import com.gh.bmd.jrt.channel.OutputChannel; import com.gh.bmd.jrt.channel.StandaloneChannel; import com.gh.bmd.jrt.common.AbortException; import com.gh.bmd.jrt.common.ClassToken; import com.gh.bmd.jrt.core.JRoutine; import com.gh.bmd.jrt.log.Log; import com.gh.bmd.jrt.log.Log.LogLevel; import com.gh.bmd.jrt.log.NullLog; import com.gh.bmd.jrt.processor.annotation.Wrap; import com.gh.bmd.jrt.processor.builder.WrapperRoutineBuilder; import com.gh.bmd.jrt.runner.Runner; import com.gh.bmd.jrt.runner.Runners; import com.gh.bmd.jrt.time.TimeDuration; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import static com.gh.bmd.jrt.builder.RoutineConfiguration.builder; import static com.gh.bmd.jrt.builder.RoutineConfiguration.onReadTimeout; import static com.gh.bmd.jrt.builder.RoutineConfiguration.withAsyncRunner; import static com.gh.bmd.jrt.builder.RoutineConfiguration.withReadTimeout; import static com.gh.bmd.jrt.builder.RoutineConfiguration.withSyncRunner; import static com.gh.bmd.jrt.builder.ShareConfiguration.withGroup; import static com.gh.bmd.jrt.time.TimeDuration.INFINITY; import static com.gh.bmd.jrt.time.TimeDuration.seconds; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; /** * Processor unit tests. * <p/> * Created by davide on 3/6/15. */ public class ProcessorTest { @Test public void testGenericWrapperCache() { final TestList<String> testList = new TestList<String>(); final WrapperRoutineBuilder builder = JRoutineProcessor.on(testList).configure(withAsyncRunner(Runners.queuedRunner())); final TestListItf<String> testListItf1 = builder.buildWrapper(new ClassToken<TestListItf<String>>() {}); testListItf1.add("test"); assertThat(testListItf1.get(0)).isEqualTo("test"); assertThat(builder.buildWrapper(new ClassToken<TestListItf<Integer>>() {})).isSameAs( testListItf1); final TestListItf<Integer> testListItf2 = builder.buildWrapper(new ClassToken<TestListItf<Integer>>() {}); assertThat(testListItf2).isSameAs(testListItf1); assertThat(builder.buildWrapper(new ClassToken<TestListItf<Integer>>() {})).isSameAs( testListItf2); testListItf2.add(3); assertThat(testListItf2.get(1)).isEqualTo(3); assertThat(testListItf2.getAsync(1).readNext()).isEqualTo(3); assertThat(testListItf2.getList(1)).containsExactly(3); } @Test public void testInterface() { final TestClass test = new TestClass(); final ClassToken<TestInterfaceWrapper> token = ClassToken.tokenOf(TestInterfaceWrapper.class); final Builder configuration = withSyncRunner(Runners.sequentialRunner()); final TestInterfaceWrapper testWrapper = JRoutineProcessor.on(test).configure(configuration).buildWrapper(token); assertThat(testWrapper.getOne().readNext()).isEqualTo(1); } @Test @SuppressWarnings("ConstantConditions") public void testNullPointerError() { final TestClass test = new TestClass(); try { JRoutineProcessor.on(test).buildWrapper((Class<?>) null); fail(); } catch (final NullPointerException ignored) { } try { JRoutineProcessor.on(test).buildWrapper((ClassToken<?>) null); fail(); } catch (final NullPointerException ignored) { } } @Test public void testShareGroup() { final TestClass2 test = new TestClass2(); final WrapperRoutineBuilder builder = JRoutineProcessor.on(test).configure(withReadTimeout(seconds(2))); long startTime = System.currentTimeMillis(); OutputChannel<Integer> getOne = builder.share(withGroup("1")).buildWrapper(TestClassAsync.class).getOne(); OutputChannel<Integer> getTwo = builder.share(withGroup("2")).buildWrapper(TestClassAsync.class).getTwo(); assertThat(getOne.checkComplete()).isTrue(); assertThat(getTwo.checkComplete()).isTrue(); assertThat(System.currentTimeMillis() - startTime).isLessThan(1000); startTime = System.currentTimeMillis(); getOne = builder.buildWrapper(TestClassAsync.class).getOne(); getTwo = builder.buildWrapper(TestClassAsync.class).getTwo(); assertThat(getOne.checkComplete()).isTrue(); assertThat(getTwo.checkComplete()).isTrue(); assertThat(System.currentTimeMillis() - startTime).isGreaterThanOrEqualTo(1000); } @Test @SuppressWarnings("unchecked") public void testTemplates() { final Impl impl = new Impl(); final Itf itf = JRoutineProcessor.on(impl).configure(withReadTimeout(INFINITY)) .buildWrapper(Itf.class); assertThat(itf.add0('c')).isEqualTo((int) 'c'); final StandaloneChannel<Character> channel1 = JRoutine.standalone().buildChannel(); channel1.input().pass('a').close(); assertThat(itf.add1(channel1.output())).isEqualTo((int) 'a'); final StandaloneChannel<Character> channel2 = JRoutine.standalone().buildChannel(); channel2.input().pass('d', 'e', 'f').close(); assertThat(itf.add2(channel2.output())).isIn((int) 'd', (int) 'e', (int) 'f'); assertThat(itf.add3('c').readAll()).containsExactly((int) 'c'); final StandaloneChannel<Character> channel3 = JRoutine.standalone().buildChannel(); channel3.input().pass('a').close(); assertThat(itf.add4(channel3.output()).readAll()).containsExactly((int) 'a'); final StandaloneChannel<Character> channel4 = JRoutine.standalone().buildChannel(); channel4.input().pass('d', 'e', 'f').close(); assertThat(itf.add5(channel4.output()).readAll()).containsOnly((int) 'd', (int) 'e', (int) 'f'); assertThat(itf.addA00(new char[]{'c', 'z'})).isEqualTo(new int[]{'c', 'z'}); final StandaloneChannel<char[]> channel5 = JRoutine.standalone().buildChannel(); channel5.input().pass(new char[]{'a', 'z'}).close(); assertThat(itf.addA01(channel5.output())).isEqualTo(new int[]{'a', 'z'}); final StandaloneChannel<Character> channel6 = JRoutine.standalone().buildChannel(); channel6.input().pass('d', 'e', 'f').close(); assertThat(itf.addA02(channel6.output())).isEqualTo(new int[]{'d', 'e', 'f'}); final StandaloneChannel<char[]> channel7 = JRoutine.standalone().buildChannel(); channel7.input() .pass(new char[]{'d', 'z'}, new char[]{'e', 'z'}, new char[]{'f', 'z'}) .close(); assertThat(itf.addA03(channel7.output())).isIn(new int[]{'d', 'z'}, new int[]{'e', 'z'}, new int[]{'f', 'z'}); assertThat(itf.addA04(new char[]{'c', 'z'}).readAll()).containsExactly(new int[]{'c', 'z'}); final StandaloneChannel<char[]> channel8 = JRoutine.standalone().buildChannel(); channel8.input().pass(new char[]{'a', 'z'}).close(); assertThat(itf.addA05(channel8.output()).readAll()).containsExactly(new int[]{'a', 'z'}); final StandaloneChannel<Character> channel9 = JRoutine.standalone().buildChannel(); channel9.input().pass('d', 'e', 'f').close(); assertThat(itf.addA06(channel9.output()).readAll()).containsExactly( new int[]{'d', 'e', 'f'}); final StandaloneChannel<char[]> channel10 = JRoutine.standalone().buildChannel(); channel10.input() .pass(new char[]{'d', 'z'}, new char[]{'e', 'z'}, new char[]{'f', 'z'}) .close(); assertThat(itf.addA07(channel10.output()).readAll()).containsOnly(new int[]{'d', 'z'}, new int[]{'e', 'z'}, new int[]{'f', 'z'}); assertThat(itf.addA08(new char[]{'c', 'z'}).readAll()).containsExactly((int) 'c', (int) 'z'); final StandaloneChannel<char[]> channel11 = JRoutine.standalone().buildChannel(); channel11.input().pass(new char[]{'a', 'z'}).close(); assertThat(itf.addA09(channel11.output()).readAll()).containsExactly((int) 'a', (int) 'z'); final StandaloneChannel<Character> channel12 = JRoutine.standalone().buildChannel(); channel12.input().pass('d', 'e', 'f').close(); assertThat(itf.addA10(channel12.output()).readAll()).containsExactly((int) 'd', (int) 'e', (int) 'f'); final StandaloneChannel<char[]> channel13 = JRoutine.standalone().buildChannel(); channel13.input() .pass(new char[]{'d', 'z'}, new char[]{'e', 'z'}, new char[]{'f', 'z'}) .close(); assertThat(itf.addA11(channel13.output()).readAll()).containsOnly((int) 'd', (int) 'e', (int) 'f', (int) 'z'); assertThat(itf.addA12(new char[]{'c', 'z'})).containsExactly(new int[]{'c', 'z'}); final StandaloneChannel<char[]> channel14 = JRoutine.standalone().buildChannel(); channel14.input().pass(new char[]{'a', 'z'}).close(); assertThat(itf.addA13(channel14.output())).containsExactly(new int[]{'a', 'z'}); final StandaloneChannel<Character> channel15 = JRoutine.standalone().buildChannel(); channel15.input().pass('d', 'e', 'f').close(); assertThat(itf.addA14(channel15.output())).containsExactly(new int[]{'d', 'e', 'f'}); final StandaloneChannel<char[]> channel16 = JRoutine.standalone().buildChannel(); channel16.input() .pass(new char[]{'d', 'z'}, new char[]{'e', 'z'}, new char[]{'f', 'z'}) .close(); assertThat(itf.addA15(channel16.output())).containsOnly(new int[]{'d', 'z'}, new int[]{'e', 'z'}, new int[]{'f', 'z'}); assertThat(itf.addA16(new char[]{'c', 'z'})).containsExactly(new int[]{'c', 'z'}); final StandaloneChannel<char[]> channel17 = JRoutine.standalone().buildChannel(); channel17.input().pass(new char[]{'a', 'z'}).close(); assertThat(itf.addA17(channel17.output())).containsExactly(new int[]{'a', 'z'}); final StandaloneChannel<Character> channel18 = JRoutine.standalone().buildChannel(); channel18.input().pass('d', 'e', 'f').close(); assertThat(itf.addA18(channel18.output())).containsExactly(new int[]{'d', 'e', 'f'}); final StandaloneChannel<char[]> channel19 = JRoutine.standalone().buildChannel(); channel19.input() .pass(new char[]{'d', 'z'}, new char[]{'e', 'z'}, new char[]{'f', 'z'}) .close(); assertThat(itf.addA19(channel19.output())).containsOnly(new int[]{'d', 'z'}, new int[]{'e', 'z'}, new int[]{'f', 'z'}); assertThat(itf.addL00(Arrays.asList('c', 'z'))).isEqualTo( Arrays.asList((int) 'c', (int) 'z')); final StandaloneChannel<List<Character>> channel20 = JRoutine.standalone().buildChannel(); channel20.input().pass(Arrays.asList('a', 'z')).close(); assertThat(itf.addL01(channel20.output())).isEqualTo(Arrays.asList((int) 'a', (int) 'z')); final StandaloneChannel<Character> channel21 = JRoutine.standalone().buildChannel(); channel21.input().pass('d', 'e', 'f').close(); assertThat(itf.addL02(channel21.output())).isEqualTo( Arrays.asList((int) 'd', (int) 'e', (int) 'f')); final StandaloneChannel<List<Character>> channel22 = JRoutine.standalone().buildChannel(); channel22.input() .pass(Arrays.asList('d', 'z'), Arrays.asList('e', 'z'), Arrays.asList('f', 'z')) .close(); assertThat(itf.addL03(channel22.output())).isIn(Arrays.asList((int) 'd', (int) 'z'), Arrays.asList((int) 'e', (int) 'z'), Arrays.asList((int) 'f', (int) 'z')); assertThat(itf.addL04(Arrays.asList('c', 'z')).readAll()).containsExactly( Arrays.asList((int) 'c', (int) 'z')); final StandaloneChannel<List<Character>> channel23 = JRoutine.standalone().buildChannel(); channel23.input().pass(Arrays.asList('a', 'z')).close(); assertThat(itf.addL05(channel23.output()).readAll()).containsExactly( Arrays.asList((int) 'a', (int) 'z')); final StandaloneChannel<Character> channel24 = JRoutine.standalone().buildChannel(); channel24.input().pass('d', 'e', 'f').close(); assertThat(itf.addL06(channel24.output()).readAll()).containsExactly( Arrays.asList((int) 'd', (int) 'e', (int) 'f')); final StandaloneChannel<List<Character>> channel25 = JRoutine.standalone().buildChannel(); channel25.input() .pass(Arrays.asList('d', 'z'), Arrays.asList('e', 'z'), Arrays.asList('f', 'z')) .close(); assertThat(itf.addL07(channel25.output()).readAll()).containsOnly( Arrays.asList((int) 'd', (int) 'z'), Arrays.asList((int) 'e', (int) 'z'), Arrays.asList((int) 'f', (int) 'z')); assertThat(itf.addL08(Arrays.asList('c', 'z')).readAll()).containsExactly((int) 'c', (int) 'z'); final StandaloneChannel<List<Character>> channel26 = JRoutine.standalone().buildChannel(); channel26.input().pass(Arrays.asList('a', 'z')).close(); assertThat(itf.addL09(channel26.output()).readAll()).containsExactly((int) 'a', (int) 'z'); final StandaloneChannel<Character> channel27 = JRoutine.standalone().buildChannel(); channel27.input().pass('d', 'e', 'f').close(); assertThat(itf.addL10(channel27.output()).readAll()).containsExactly((int) 'd', (int) 'e', (int) 'f'); final StandaloneChannel<List<Character>> channel28 = JRoutine.standalone().buildChannel(); channel28.input() .pass(Arrays.asList('d', 'z'), Arrays.asList('e', 'z'), Arrays.asList('f', 'z')) .close(); assertThat(itf.addL11(channel28.output()).readAll()).containsOnly((int) 'd', (int) 'e', (int) 'f', (int) 'z'); assertThat(itf.addL12(Arrays.asList('c', 'z'))).containsExactly( Arrays.asList((int) 'c', (int) 'z')); final StandaloneChannel<List<Character>> channel29 = JRoutine.standalone().buildChannel(); channel29.input().pass(Arrays.asList('a', 'z')).close(); assertThat(itf.addL13(channel29.output())).containsExactly( Arrays.asList((int) 'a', (int) 'z')); final StandaloneChannel<Character> channel30 = JRoutine.standalone().buildChannel(); channel30.input().pass('d', 'e', 'f').close(); assertThat(itf.addL14(channel30.output())).containsExactly( Arrays.asList((int) 'd', (int) 'e', (int) 'f')); final StandaloneChannel<List<Character>> channel31 = JRoutine.standalone().buildChannel(); channel31.input() .pass(Arrays.asList('d', 'z'), Arrays.asList('e', 'z'), Arrays.asList('f', 'z')) .close(); assertThat(itf.addL15(channel31.output())).containsOnly(Arrays.asList((int) 'd', (int) 'z'), Arrays.asList((int) 'e', (int) 'z'), Arrays.asList((int) 'f', (int) 'z')); assertThat(itf.addL16(Arrays.asList('c', 'z'))).containsExactly( Arrays.asList((int) 'c', (int) 'z')); final StandaloneChannel<List<Character>> channel32 = JRoutine.standalone().buildChannel(); channel32.input().pass(Arrays.asList('a', 'z')).close(); assertThat(itf.addL17(channel32.output())).containsExactly( Arrays.asList((int) 'a', (int) 'z')); final StandaloneChannel<Character> channel33 = JRoutine.standalone().buildChannel(); channel33.input().pass('d', 'e', 'f').close(); assertThat(itf.addL18(channel33.output())).containsExactly( Arrays.asList((int) 'd', (int) 'e', (int) 'f')); final StandaloneChannel<List<Character>> channel34 = JRoutine.standalone().buildChannel(); channel34.input() .pass(Arrays.asList('d', 'z'), Arrays.asList('e', 'z'), Arrays.asList('f', 'z')) .close(); assertThat(itf.addL19(channel34.output())).containsOnly(Arrays.asList((int) 'd', (int) 'z'), Arrays.asList((int) 'e', (int) 'z'), Arrays.asList((int) 'f', (int) 'z')); assertThat(itf.get0()).isEqualTo(31); assertThat(itf.get1().readAll()).containsExactly(31); assertThat(itf.getA0()).isEqualTo(new int[]{1, 2, 3}); assertThat(itf.getA1().readAll()).containsExactly(1, 2, 3); assertThat(itf.getA2()).containsExactly(new int[]{1, 2, 3}); assertThat(itf.getA3()).containsExactly(new int[]{1, 2, 3}); assertThat(itf.getL0()).isEqualTo(Arrays.asList(1, 2, 3)); assertThat(itf.getL1().readAll()).containsExactly(1, 2, 3); assertThat(itf.getL2()).containsExactly(Arrays.asList(1, 2, 3)); assertThat(itf.getL3()).containsExactly(Arrays.asList(1, 2, 3)); itf.set0(-17); final StandaloneChannel<Integer> channel35 = JRoutine.standalone().buildChannel(); channel35.input().pass(-17).close(); itf.set1(channel35.output()); final StandaloneChannel<Integer> channel36 = JRoutine.standalone().buildChannel(); channel36.input().pass(-17).close(); itf.set2(channel36.output()); itf.setA0(new int[]{1, 2, 3}); final StandaloneChannel<int[]> channel37 = JRoutine.standalone().buildChannel(); channel37.input().pass(new int[]{1, 2, 3}).close(); itf.setA1(channel37.output()); final StandaloneChannel<Integer> channel38 = JRoutine.standalone().buildChannel(); channel38.input().pass(1, 2, 3).close(); itf.setA2(channel38.output()); final StandaloneChannel<int[]> channel39 = JRoutine.standalone().buildChannel(); channel39.input().pass(new int[]{1, 2, 3}).close(); itf.setA3(channel39.output()); itf.setL0(Arrays.asList(1, 2, 3)); final StandaloneChannel<List<Integer>> channel40 = JRoutine.standalone().buildChannel(); channel40.input().pass(Arrays.asList(1, 2, 3)).close(); itf.setL1(channel40.output()); final StandaloneChannel<Integer> channel41 = JRoutine.standalone().buildChannel(); channel41.input().pass(1, 2, 3).close(); itf.setL2(channel41.output()); final StandaloneChannel<List<Integer>> channel42 = JRoutine.standalone().buildChannel(); channel42.input().pass(Arrays.asList(1, 2, 3)).close(); itf.setL3(channel42.output()); } @Test public void testTimeoutActionAnnotation() throws NoSuchMethodException { final TestTimeout testTimeout = new TestTimeout(); assertThat(JRoutineProcessor.on(testTimeout).configure(withReadTimeout(seconds(1))) .buildWrapper(TestTimeoutItf.class) .getInt()).containsExactly(31); try { JRoutineProcessor.on(testTimeout).configure(onReadTimeout(TimeoutActionType.DEADLOCK)) .buildWrapper(TestTimeoutItf.class) .getInt(); fail(); } catch (final AbortException ignored) { } } @Test public void testWrapper() { final NullLog log = new NullLog(); final Runner runner = Runners.poolRunner(); final TestClass test = new TestClass(); final RoutineConfiguration configuration = builder().withSyncRunner(Runners.sequentialRunner()) .withAsyncRunner(runner) .withLogLevel(LogLevel.DEBUG) .withLog(log) .buildConfiguration(); final TestWrapper testWrapper = JRoutineProcessor.on(test).configure(configuration) .buildWrapper(ClassToken.tokenOf( TestWrapper.class)); assertThat(testWrapper.getOne().readNext()).isEqualTo(1); assertThat(testWrapper.getString(1, 2, 3)).isIn("1", "2", "3"); assertThat(testWrapper.getString(new HashSet<Integer>(Arrays.asList(1, 2, 3))) .readAll()).containsOnly("1", "2", "3"); assertThat(testWrapper.getString(Arrays.asList(1, 2, 3))).containsOnly("1", "2", "3"); assertThat(testWrapper.getString((Iterable<Integer>) Arrays.asList(1, 2, 3))).containsOnly( "1", "2", "3"); assertThat( testWrapper.getString((Collection<Integer>) Arrays.asList(1, 2, 3))).containsOnly( "1", "2", "3"); final ArrayList<String> list = new ArrayList<String>(); assertThat(testWrapper.getList(Collections.singletonList(list))).containsExactly(list); final StandaloneChannel<Integer> standaloneChannel = JRoutine.standalone().buildChannel(); standaloneChannel.input().pass(3).close(); assertThat(testWrapper.getString(standaloneChannel.output())).isEqualTo("3"); } @Test public void testWrapperBuilder() { final NullLog log = new NullLog(); final Runner runner = Runners.poolRunner(); final TestClass test = new TestClass(); final RoutineConfiguration configuration = builder().withSyncRunner(Runners.sequentialRunner()) .withAsyncRunner(runner) .withLogLevel(LogLevel.DEBUG) .withLog(log) .buildConfiguration(); final TestWrapper testWrapper = JRoutine_TestWrapper.on(test).withConfig(configuration).buildWrapper(); assertThat(testWrapper.getOne().readNext()).isEqualTo(1); assertThat(testWrapper.getString(1, 2, 3)).isIn("1", "2", "3"); assertThat(testWrapper.getString(new HashSet<Integer>(Arrays.asList(1, 2, 3))) .readAll()).containsOnly("1", "2", "3"); assertThat(testWrapper.getString(Arrays.asList(1, 2, 3))).containsOnly("1", "2", "3"); assertThat(testWrapper.getString((Iterable<Integer>) Arrays.asList(1, 2, 3))).containsOnly( "1", "2", "3"); assertThat( testWrapper.getString((Collection<Integer>) Arrays.asList(1, 2, 3))).containsOnly( "1", "2", "3"); final ArrayList<String> list = new ArrayList<String>(); assertThat(testWrapper.getList(Collections.singletonList(list))).containsExactly(list); final StandaloneChannel<Integer> standaloneChannel = JRoutine.standalone().buildChannel(); standaloneChannel.input().pass(3).close(); assertThat(testWrapper.getString(standaloneChannel.output())).isEqualTo("3"); assertThat(JRoutineProcessor.on(test).configure(configuration) .buildWrapper(ClassToken.tokenOf(TestWrapper.class))).isSameAs( testWrapper); } @Test public void testWrapperBuilderWarnings() { final CountLog countLog = new CountLog(); final RoutineConfiguration configuration = builder().withInputOrder(OrderType.NONE) .withInputSize(3) .withInputTimeout(seconds(1)) .withOutputOrder(OrderType.NONE) .withOutputSize(3) .withOutputTimeout(seconds(1)) .withLogLevel(LogLevel.DEBUG) .withLog(countLog) .buildConfiguration(); final TestClass test = new TestClass(); JRoutineProcessor.on(test).configure(configuration) .buildWrapper(TestWrapper.class) .getOne(); assertThat(countLog.getWrnCount()).isEqualTo(6); } @Test public void testWrapperCache() { final NullLog log = new NullLog(); final Runner runner = Runners.poolRunner(); final TestClass test = new TestClass(); final RoutineConfiguration configuration = builder().withSyncRunner(Runners.sequentialRunner()) .withAsyncRunner(runner) .withLogLevel(LogLevel.DEBUG) .withLog(log) .buildConfiguration(); final TestWrapper testWrapper = JRoutineProcessor.on(test).configure(configuration) .buildWrapper(ClassToken.tokenOf( TestWrapper.class)); assertThat(JRoutineProcessor.on(test).configure(configuration) .buildWrapper(ClassToken.tokenOf(TestWrapper.class))).isSameAs( testWrapper); } @Test public void testWrapperError() { final TestClass test = new TestClass(); try { JRoutineProcessor.on(test).buildWrapper(TestClass.class); fail(); } catch (final IllegalArgumentException ignored) { } try { JRoutineProcessor.on(test).buildWrapper(ClassToken.tokenOf(TestClass.class)); fail(); } catch (final IllegalArgumentException ignored) { } } @Wrap(Impl.class) public interface Itf { @Bind("a") int add0(char c); @Bind("a") int add1(@Pass(value = char.class, mode = PassMode.OBJECT) OutputChannel<Character> c); @Bind("a") int add2(@Pass(value = char.class, mode = PassMode.PARALLEL) OutputChannel<Character> c); @Bind("a") @Pass(value = int.class, mode = PassMode.OBJECT) OutputChannel<Integer> add3(char c); @Bind("a") @Pass(value = int.class, mode = PassMode.OBJECT) OutputChannel<Integer> add4( @Pass(value = char.class, mode = PassMode.OBJECT) OutputChannel<Character> c); @Bind("a") @Pass(value = int.class, mode = PassMode.OBJECT) OutputChannel<Integer> add5( @Pass(value = char.class, mode = PassMode.PARALLEL) OutputChannel<Character> c); @Bind("aa") int[] addA00(char[] c); @Bind("aa") int[] addA01(@Pass(value = char[].class, mode = PassMode.OBJECT) OutputChannel<char[]> c); @Bind("aa") int[] addA02(@Pass(value = char[].class, mode = PassMode.COLLECTION) OutputChannel<Character> c); @Bind("aa") int[] addA03(@Pass(value = char[].class, mode = PassMode.PARALLEL) OutputChannel<char[]> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.OBJECT) OutputChannel<int[]> addA04(char[] c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.OBJECT) OutputChannel<int[]> addA05( @Pass(value = char[].class, mode = PassMode.OBJECT) OutputChannel<char[]> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.OBJECT) OutputChannel<int[]> addA06(@Pass(value = char[].class, mode = PassMode.COLLECTION) OutputChannel<Character> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.OBJECT) OutputChannel<int[]> addA07(@Pass(value = char[].class, mode = PassMode.PARALLEL) OutputChannel<char[]> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.COLLECTION) OutputChannel<Integer> addA08(char[] c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.COLLECTION) OutputChannel<Integer> addA09( @Pass(value = char[].class, mode = PassMode.OBJECT) OutputChannel<char[]> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.COLLECTION) OutputChannel<Integer> addA10(@Pass(value = char[].class, mode = PassMode.COLLECTION) OutputChannel<Character> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.COLLECTION) OutputChannel<Integer> addA11(@Pass(value = char[].class, mode = PassMode.PARALLEL) OutputChannel<char[]> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.PARALLEL) List<int[]> addA12(char[] c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.PARALLEL) List<int[]> addA13( @Pass(value = char[].class, mode = PassMode.OBJECT) OutputChannel<char[]> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.PARALLEL) List<int[]> addA14(@Pass(value = char[].class, mode = PassMode.COLLECTION) OutputChannel<Character> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.PARALLEL) List<int[]> addA15(@Pass(value = char[].class, mode = PassMode.PARALLEL) OutputChannel<char[]> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.PARALLEL) int[][] addA16(char[] c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.PARALLEL) int[][] addA17(@Pass(value = char[].class, mode = PassMode.OBJECT) OutputChannel<char[]> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.PARALLEL) int[][] addA18(@Pass(value = char[].class, mode = PassMode.COLLECTION) OutputChannel<Character> c); @Bind("aa") @Pass(value = int[].class, mode = PassMode.PARALLEL) int[][] addA19(@Pass(value = char[].class, mode = PassMode.PARALLEL) OutputChannel<char[]> c); @Bind("al") List<Integer> addL00(List<Character> c); @Bind("al") List<Integer> addL01(@Pass(value = List.class, mode = PassMode.OBJECT) OutputChannel<List<Character>> c); @Bind("al") List<Integer> addL02(@Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Character> c); @Bind("al") List<Integer> addL03(@Pass(value = List.class, mode = PassMode.PARALLEL) OutputChannel<List<Character>> c); @Bind("al") @Pass(value = List.class, mode = PassMode.OBJECT) OutputChannel<List<Integer>> addL04(List<Character> c); @Bind("al") @Pass(value = List.class, mode = PassMode.OBJECT) OutputChannel<List<Integer>> addL05(@Pass(value = List.class, mode = PassMode.OBJECT) OutputChannel<List<Character>> c); @Bind("al") @Pass(value = List.class, mode = PassMode.OBJECT) OutputChannel<List<Integer>> addL06(@Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Character> c); @Bind("al") @Pass(value = List.class, mode = PassMode.OBJECT) OutputChannel<List<Integer>> addL07(@Pass(value = List.class, mode = PassMode.PARALLEL) OutputChannel<List<Character>> c); @Bind("al") @Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Integer> addL08(List<Character> c); @Bind("al") @Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Integer> addL09(@Pass(value = List.class, mode = PassMode.OBJECT) OutputChannel<List<Character>> c); @Bind("al") @Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Integer> addL10(@Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Character> c); @Bind("al") @Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Integer> addL11(@Pass(value = List.class, mode = PassMode.PARALLEL) OutputChannel<List<Character>> c); @Bind("al") @Pass(value = List.class, mode = PassMode.PARALLEL) List<List<Integer>> addL12(List<Character> c); @Bind("al") @Pass(value = List.class, mode = PassMode.PARALLEL) List<List<Integer>> addL13(@Pass(value = List.class, mode = PassMode.OBJECT) OutputChannel<List<Character>> c); @Bind("al") @Pass(value = List.class, mode = PassMode.PARALLEL) List<List<Integer>> addL14(@Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Character> c); @Bind("al") @Pass(value = List.class, mode = PassMode.PARALLEL) List<List<Integer>> addL15(@Pass(value = List.class, mode = PassMode.PARALLEL) OutputChannel<List<Character>> c); @Bind("al") @Pass(value = List.class, mode = PassMode.PARALLEL) List[] addL16(List<Character> c); @Bind("al") @Pass(value = List.class, mode = PassMode.PARALLEL) List[] addL17(@Pass(value = List.class, mode = PassMode.OBJECT) OutputChannel<List<Character>> c); @Bind("al") @Pass(value = List.class, mode = PassMode.PARALLEL) List[] addL18(@Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Character> c); @Bind("al") @Pass(value = List.class, mode = PassMode.PARALLEL) List[] addL19(@Pass(value = List.class, mode = PassMode.PARALLEL) OutputChannel<List<Character>> c); @Bind("g") int get0(); @Bind("s") void set0(int i); @Bind("g") @Pass(value = int.class, mode = PassMode.OBJECT) OutputChannel<Integer> get1(); @Bind("s") void set1(@Pass(value = int.class, mode = PassMode.OBJECT) OutputChannel<Integer> i); @Bind("ga") int[] getA0(); @Bind("sa") void setA0(int[] i); @Bind("ga") @Pass(value = int[].class, mode = PassMode.COLLECTION) OutputChannel<Integer> getA1(); @Bind("sa") void setA1(@Pass(value = int[].class, mode = PassMode.OBJECT) OutputChannel<int[]> i); @Bind("ga") @Pass(value = int[].class, mode = PassMode.PARALLEL) List<int[]> getA2(); @Bind("sa") void setA2(@Pass(value = int[].class, mode = PassMode.COLLECTION) OutputChannel<Integer> i); @Bind("ga") @Pass(value = int[].class, mode = PassMode.PARALLEL) int[][] getA3(); @Bind("sa") void setA3(@Pass(value = int[].class, mode = PassMode.PARALLEL) OutputChannel<int[]> i); @Bind("gl") List<Integer> getL0(); @Bind("sl") void setL0(List<Integer> i); @Bind("gl") @Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Integer> getL1(); @Bind("sl") void setL1(@Pass(value = List.class, mode = PassMode.OBJECT) OutputChannel<List<Integer>> i); @Bind("gl") @Pass(value = List.class, mode = PassMode.PARALLEL) List<List<Integer>> getL2(); @Bind("sl") void setL2(@Pass(value = List.class, mode = PassMode.COLLECTION) OutputChannel<Integer> i); @Bind("gl") @Pass(value = List.class, mode = PassMode.PARALLEL) List[] getL3(); @Bind("sl") void setL3(@Pass(value = List.class, mode = PassMode.PARALLEL) OutputChannel<List<Integer>> i); @Bind("s") void set2(@Pass(value = int.class, mode = PassMode.PARALLEL) OutputChannel<Integer> i); } @Wrap(TestClass2.class) public interface TestClassAsync { @Pass(int.class) OutputChannel<Integer> getOne(); @Pass(int.class) OutputChannel<Integer> getTwo(); } @SuppressWarnings("unused") public interface TestClassInterface { int getOne(); } @Wrap(TestClassInterface.class) public interface TestInterfaceWrapper { @Timeout(300) @Pass(int.class) OutputChannel<Integer> getOne(); } @Wrap(TestList.class) public interface TestListItf<TYPE> { void add(Object t); TYPE get(int i); @Bind("get") @Pass(Object.class) OutputChannel<TYPE> getAsync(int i); @Bind("get") @Pass(Object.class) List<TYPE> getList(int i); } @Wrap(TestTimeout.class) public interface TestTimeoutItf { @Pass(int.class) @TimeoutAction(TimeoutActionType.ABORT) List<Integer> getInt(); } @Wrap(TestClass.class) public interface TestWrapper { @Timeout(300) @Pass(List.class) Iterable<Iterable> getList(@Pass(List.class) List<? extends List<String>> i); @Timeout(300) @Pass(int.class) OutputChannel<Integer> getOne(); @Timeout(300) String getString(@Pass(int.class) int... i); @Timeout(300) @Pass(String.class) OutputChannel<String> getString(@Pass(int.class) HashSet<Integer> i); @Timeout(300) @Pass(String.class) List<String> getString(@Pass(int.class) List<Integer> i); @Timeout(300) @Pass(String.class) Iterable<String> getString(@Pass(int.class) Iterable<Integer> i); @Timeout(300) @Pass(String.class) String[] getString(@Pass(int.class) Collection<Integer> i); @Timeout(300) String getString(@Pass(int.class) OutputChannel<Integer> i); } @SuppressWarnings("unused") public static class Impl { @Bind("a") public int add(char c) { return c; } @Bind("aa") public int[] addArray(char[] c) { final int[] array = new int[c.length]; for (int i = 0; i < c.length; i++) { array[i] = c[i]; } return array; } @Bind("al") public List<Integer> addList(List<Character> c) { final ArrayList<Integer> list = new ArrayList<Integer>(c.size()); for (final Character character : c) { list.add((int) character); } return list; } @Bind("g") public int get() { return 31; } @Bind("ga") public int[] getArray() { return new int[]{1, 2, 3}; } @Bind("sa") public void setArray(int[] i) { assertThat(i).containsExactly(1, 2, 3); } @Bind("gl") public List<Integer> getList() { return Arrays.asList(1, 2, 3); } @Bind("sl") public void setList(List<Integer> l) { assertThat(l).containsExactly(1, 2, 3); } @Bind("s") public void set(int i) { assertThat(i).isEqualTo(-17); } } @SuppressWarnings("unused") public static class TestClass implements TestClassInterface { public List<String> getList(final List<String> list) { return list; } public int getOne() { return 1; } public String getString(final int i) { return Integer.toString(i); } } @SuppressWarnings("unused") public static class TestList<TYPE> { private final ArrayList<TYPE> mList = new ArrayList<TYPE>(); public void add(TYPE t) { mList.add(t); } public TYPE get(int i) { return mList.get(i); } } @SuppressWarnings("unused") public static class TestTimeout { public int getInt() throws InterruptedException { Thread.sleep(100); return 31; } } @SuppressWarnings("unused") private static class CountLog implements Log { private int mDgbCount; private int mErrCount; private int mWrnCount; public void dbg(@Nonnull final List<Object> contexts, @Nullable final String message, @Nullable final Throwable throwable) { ++mDgbCount; } public void err(@Nonnull final List<Object> contexts, @Nullable final String message, @Nullable final Throwable throwable) { ++mErrCount; } public void wrn(@Nonnull final List<Object> contexts, @Nullable final String message, @Nullable final Throwable throwable) { ++mWrnCount; } public int getDgbCount() { return mDgbCount; } public int getErrCount() { return mErrCount; } public int getWrnCount() { return mWrnCount; } } @SuppressWarnings("unused") public class TestClass2 { public int getOne() throws InterruptedException { TimeDuration.millis(500).sleepAtLeast(); return 1; } public int getTwo() throws InterruptedException { TimeDuration.millis(500).sleepAtLeast(); return 2; } } }
Fixed unit tests
processor/src/test/java/com/gh/bmd/jrt/processor/core/ProcessorTest.java
Fixed unit tests
<ide><path>rocessor/src/test/java/com/gh/bmd/jrt/processor/core/ProcessorTest.java <ide> .withLog(log) <ide> .buildConfiguration(); <ide> final TestWrapper testWrapper = <del> JRoutine_TestWrapper.on(test).withConfig(configuration).buildWrapper(); <add> JRoutine_TestWrapper.on(test).configure(configuration).buildWrapper(); <ide> <ide> assertThat(testWrapper.getOne().readNext()).isEqualTo(1); <ide> assertThat(testWrapper.getString(1, 2, 3)).isIn("1", "2", "3");
JavaScript
mit
dcfd3e5b2dd17ec3997da92e69039994384e9506
0
hoovercj/phantom-password-resetter
#!/usr/bin/env node var express = require("express"); var app = express(); var Spooky = require('spooky'); // adoped from Heroku's [Getting Started][] and [Spooky][]'s sample // [Getting Started]: https://devcenter.heroku.com/articles/getting-started-with-nodejs // [Spooky]: https://github.com/WaterfallEngineering/SpookyJS var websitesOld = { dropbox: { url: 'https://www.dropbox.com/forgot', form: 'form.password-reset-form', input: "input[name='email']" }, ifttt: { url: 'https://ifttt.com/forgot', form: "form[action='/forgot']", input: "input[name='user[email]']" } }; var websites = { ifttt: { url: 'https://ifttt.com/forgot', form: "form[action='/forgot']", input: "input[name='user[email]']" } }; var spooky = new Spooky({ child: { transport: 'http' }, casper: { logLevel: 'debug', verbose: true } }, function (err) { if (err) { e = new Error('Failed to initialize SpookyJS'); e.details = err; throw e; } }); spooky.on('error', function (e, stack) { console.error(e); if (stack) { console.log(stack); } }); function resetAllWebsitesOLD(email) { console.log('In resetAllWebsites for: ' + email); spooky.start('https://ifttt.com/forgot'); spooky.then([{ email: email }, function () { this.fill('form[action="/forgot"]', { 'user[email]': email }, true); }]); spooky.then(function () { this.echo(this.getCurrentUrl()); }); spooky.thenOpen('https://www.dropbox.com/forgot'); spooky.then([{ email: email }, function () { this.fillSelectors('form.password-reset-form', { 'input[name="email"]': email }, true); }]); spooky.then(function () { this.echo(this.getCurrentUrl()); }); spooky.run(); console.log('Spooky.run called'); } function addWebsiteStep(email, website) { var data = {}; data[website.input] = email; console.log('addWebsiteStep for ' + email + " - " + website.url + " - " + JSON.stringify(data)); spooky.thenOpen(website.url); spooky.then([{ form: website.form, data: data, }, function() { console.log("FILL: " + form + " WITH: " + JSON.stringify(data)); this.fillSelectors(form, data, true); }]); spooky.then(function () { this.echo(this.getCurrentUrl()); }); } function resetAllWebsites(email) { spooky.start(); var keys = Object.keys(websites); for (var i=keys.length; i--;) { addWebsiteStep(email, websites[keys[i]]); } spooky.run(); } /* // Uncomment this block to see all of the things Casper has to say. // There are a lot. // He has opinions. spooky.on('console', function (line) { console.log(line); }); */ var gGreeting = 'Hello World'; spooky.on('hello', function (greeting) { console.log(greeting); gGreeting = greeting; }); spooky.on('log', function (log) { if (log.space === 'remote') { console.log(log.message.replace(/ \- .*/, '')); } }); app.use(express.logger()); // Web Server Method Block app.get('/', function(reques, response) { response.send('Hello. Use the endpoint /resetpassword/:email to reset emails'); }); app.get('/resetpassword/:email', function(request, response) { resetEmail = request.param('email'); resetAllWebsites(resetEmail); console.log('Resetting all passwords for: ' + resetEmail); response.send('Resetting all passwords for: ' + resetEmail); }); var port = process.env.PORT || 5000; app.listen(port, function() { console.log("Listening on " + port); });
web.js
#!/usr/bin/env node var express = require("express"); var app = express(); var Spooky = require('spooky'); // adoped from Heroku's [Getting Started][] and [Spooky][]'s sample // [Getting Started]: https://devcenter.heroku.com/articles/getting-started-with-nodejs // [Spooky]: https://github.com/WaterfallEngineering/SpookyJS var websitesOld = { dropbox: { url: 'https://www.dropbox.com/forgot', form: 'form.password-reset-form', input: "input[name='email']" }, ifttt: { url: 'https://ifttt.com/forgot', form: "form[action='/forgot']", input: "input[name='user[email]']" } }; var websites = { ifttt: { url: 'https://ifttt.com/forgot', form: "form[action='/forgot']", input: "input[name='user[email]']" } }; var spooky = new Spooky({ child: { transport: 'http' }, casper: { logLevel: 'debug', verbose: true } }, function (err) { if (err) { e = new Error('Failed to initialize SpookyJS'); e.details = err; throw e; } }); spooky.on('error', function (e, stack) { console.error(e); if (stack) { console.log(stack); } }); function resetAllWebsitesOLD(email) { console.log('In resetAllWebsites for: ' + email); spooky.start('https://ifttt.com/forgot'); spooky.then([{ email: email }, function () { this.fill('form[action="/forgot"]', { 'user[email]': email }, true); }]); spooky.then(function () { this.echo(this.getCurrentUrl()); }); spooky.thenOpen('https://www.dropbox.com/forgot'); spooky.then([{ email: email }, function () { this.fillSelectors('form.password-reset-form', { 'input[name="email"]': email }, true); }]); spooky.then(function () { this.echo(this.getCurrentUrl()); }); spooky.run(); console.log('Spooky.run called'); } function addWebsiteStep(email, website) { var data = {}; data[website.input] = email; console.log('addWebsiteStep for ' + email + " - " + website.url + " - " + JSON.stringify(data)); spooky.thenOpen(website.url); spooky.then([{ form: website.form, data: data, }, function() { console.log("FILL: " + form + " WITH: " + JSON.stringify(data)); this.fillSelectors(form, data, true); }]); } function resetAllWebsites(email) { spooky.start(); var keys = Object.keys(websites); for (var i=keys.length; i--;) { addWebsiteStep(email, websites[keys[i]]); } spooky.run(); } /* // Uncomment this block to see all of the things Casper has to say. // There are a lot. // He has opinions. spooky.on('console', function (line) { console.log(line); }); */ var gGreeting = 'Hello World'; spooky.on('hello', function (greeting) { console.log(greeting); gGreeting = greeting; }); spooky.on('log', function (log) { if (log.space === 'remote') { console.log(log.message.replace(/ \- .*/, '')); } }); app.use(express.logger()); // Web Server Method Block app.get('/', function(reques, response) { response.send('Hello. Use the endpoint /resetpassword/:email to reset emails'); }); app.get('/resetpassword/:email', function(request, response) { resetEmail = request.param('email'); resetAllWebsites(resetEmail); console.log('Resetting all passwords for: ' + resetEmail); response.send('Resetting all passwords for: ' + resetEmail); }); var port = process.env.PORT || 5000; app.listen(port, function() { console.log("Listening on " + port); });
Trying to generalize the solution
web.js
Trying to generalize the solution
<ide><path>eb.js <ide> console.log("FILL: " + form + " WITH: " + JSON.stringify(data)); <ide> this.fillSelectors(form, data, true); <ide> }]); <add> spooky.then(function () { <add> this.echo(this.getCurrentUrl()); <add> }); <ide> } <ide> <ide> function resetAllWebsites(email) {
Java
mit
error: pathspec 'BOJ/15778/Main.java' did not match any file(s) known to git
54b0d4b396e970fc8578a33839be0aaaaa28c1f0
1
ISKU/Algorithm
/* * Author: Minho Kim (ISKU) * Date: May 22, 2018 * E-mail: [email protected] * * https://github.com/ISKU/Algorithm * https://www.acmicpc.net/problem/15778 */ import java.util.*; import java.io.*; public class Main { private static char[][] board = { { '.', '.', '-', '-', '-', '-', '.', '.', '-', '-', '-', '-', '.', '.', '-', '-', '-', '-', '.', '.', '-', '-', '-', '-', '.', '.', '-', '-', '-', '-', '.', '.' }, { '.', '.', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', '.', '.' }, { '|', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', '|' }, { '|', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', '|' }, { '|', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', '|' }, { '|', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', '|' }, { '.', '.', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', '.', '.' }, { '.', '.', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', '.', '.' }, { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, { '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.' }, { '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.' }, { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, { '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.' }, { '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.' }, { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, { '.', '.', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', '.', '.' }, { '.', '.', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', '.', '.' }, { '|', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', '|' }, { '|', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', '|' }, { '|', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', '|' }, { '|', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', '|' }, { '.', '.', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', '.', '.' }, { '.', '.', '-', '-', '-', '-', '.', '.', '-', '-', '-', '-', '.', '.', '-', '-', '-', '-', '.', '.', '-', '-', '-', '-', '.', '.', '-', '-', '-', '-', '.', '.' } }; private static Location[] location; private static int[] upperLocation, lowerLocation; public static void main(String... args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int N = Integer.parseInt(br.readLine()); location = new Location[33]; for (int i = 0; i < location.length; i++) location[i] = new Location(); upperLocation = new int[4]; lowerLocation = new int[4]; for (int i = 0; i < 4; i++) { upperLocation[i] = 1; lowerLocation[i] = 1; location[1].upper[i] = true; location[1].lower[i] = true; } while (N-- > 0) { StringTokenizer st = new StringTokenizer(br.readLine()); char turn = st.nextToken().charAt(0); int move = count(st.nextToken()); if (turn <= 'Z') { int mal = turn - 'A'; int start = upperLocation[mal]; int end = direction(start, move); if (end >= 32) end = 32; upperLocation[mal] = end; location[start].upper[mal] = false; location[end].upper[mal] = true; for (int i = 0; i < 4; i++) { if (start == 1 || !location[start].upper[i]) continue; upperLocation[i] = end; location[start].upper[i] = false; location[end].upper[i] = true; } for (int i = 0; i < 4; i++) { if (!location[end].lower[i]) continue; lowerLocation[i] = 1; location[end].lower[i] = false; } } else if (turn >= 'a') { int mal = turn - 'a'; int start = lowerLocation[mal]; int end = direction(start, move); if (end >= 32) end = 32; lowerLocation[mal] = end; location[start].lower[mal] = false; location[end].lower[mal] = true; for (int i = 0; i < 4; i++) { if (start == 1 || !location[start].lower[i]) continue; lowerLocation[i] = end; location[start].lower[i] = false; location[end].lower[i] = true; } for (int i = 0; i < 4; i++) { if (!location[end].upper[i]) continue; upperLocation[i] = 1; location[end].upper[i] = false; } } } for (int i = 1; i < location.length; i++) { for (int j = 0; j < 4; j++) { if (location[i].upper[j]) place(i, j, true); if (location[i].lower[j]) place(i, j, false); } } for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i].length; j++) bw.write(board[i][j]); bw.newLine(); } bw.close(); } private static int direction(int start, int move) { switch (start) { case 6: return 20 + move; case 11: return (move == 3) ? 23 : 25 + move; case 21: return (move == 5) ? 16 : 21 + move; case 22: return (move == 4) ? 16 : (move == 5) ? 17 : 22 + move; case 23: return 28 + move; case 26: return (move == 2) ? 23 : 26 + move; case 27: return (move == 1) ? 23 : 27 + move; case 24: return (move == 1) ? 25 : 14 + move; case 25: return (move == 1) ? 16 : 15 + move; default: return (16 <= start && start <= 20 && start + move >= 21) ? 10 + start + move : start + move; } } private static int count(String yut) { int count = 0; for (int i = 0; i < 4; i++) if (yut.charAt(i) == 'F') count++; return (count == 0) ? 5 : count; } private static void place(int loc, int mal, boolean team) { if (loc == 31) { if (mal == 0) board[30][30] = team ? 'A' : 'a'; if (mal == 1) board[30][31] = team ? 'B' : 'b'; if (mal == 2) board[31][30] = team ? 'C' : 'c'; if (mal == 3) board[31][31] = team ? 'D' : 'd'; } else if (loc == 2) { if (mal == 0) board[24][30] = team ? 'A' : 'a'; if (mal == 1) board[24][31] = team ? 'B' : 'b'; if (mal == 2) board[25][30] = team ? 'C' : 'c'; if (mal == 3) board[25][31] = team ? 'D' : 'd'; } else if (loc == 3) { if (mal == 0) board[18][30] = team ? 'A' : 'a'; if (mal == 1) board[18][31] = team ? 'B' : 'b'; if (mal == 2) board[19][30] = team ? 'C' : 'c'; if (mal == 3) board[19][31] = team ? 'D' : 'd'; } else if (loc == 4) { if (mal == 0) board[12][30] = team ? 'A' : 'a'; if (mal == 1) board[12][31] = team ? 'B' : 'b'; if (mal == 2) board[13][30] = team ? 'C' : 'c'; if (mal == 3) board[13][31] = team ? 'D' : 'd'; } else if (loc == 5) { if (mal == 0) board[6][30] = team ? 'A' : 'a'; if (mal == 1) board[6][31] = team ? 'B' : 'b'; if (mal == 2) board[7][30] = team ? 'C' : 'c'; if (mal == 3) board[7][31] = team ? 'D' : 'd'; } else if (loc == 6) { if (mal == 0) board[0][30] = team ? 'A' : 'a'; if (mal == 1) board[0][31] = team ? 'B' : 'b'; if (mal == 2) board[1][30] = team ? 'C' : 'c'; if (mal == 3) board[1][31] = team ? 'D' : 'd'; } else if (loc == 7) { if (mal == 0) board[0][24] = team ? 'A' : 'a'; if (mal == 1) board[0][25] = team ? 'B' : 'b'; if (mal == 2) board[1][24] = team ? 'C' : 'c'; if (mal == 3) board[1][25] = team ? 'D' : 'd'; } else if (loc == 8) { if (mal == 0) board[0][18] = team ? 'A' : 'a'; if (mal == 1) board[0][19] = team ? 'B' : 'b'; if (mal == 2) board[1][18] = team ? 'C' : 'c'; if (mal == 3) board[1][19] = team ? 'D' : 'd'; } else if (loc == 9) { if (mal == 0) board[0][12] = team ? 'A' : 'a'; if (mal == 1) board[0][13] = team ? 'B' : 'b'; if (mal == 2) board[1][12] = team ? 'C' : 'c'; if (mal == 3) board[1][13] = team ? 'D' : 'd'; } else if (loc == 10) { if (mal == 0) board[0][6] = team ? 'A' : 'a'; if (mal == 1) board[0][7] = team ? 'B' : 'b'; if (mal == 2) board[1][6] = team ? 'C' : 'c'; if (mal == 3) board[1][7] = team ? 'D' : 'd'; } else if (loc == 11) { if (mal == 0) board[0][0] = team ? 'A' : 'a'; if (mal == 1) board[0][1] = team ? 'B' : 'b'; if (mal == 2) board[1][0] = team ? 'C' : 'c'; if (mal == 3) board[1][1] = team ? 'D' : 'd'; } else if (loc == 12) { if (mal == 0) board[6][0] = team ? 'A' : 'a'; if (mal == 1) board[6][1] = team ? 'B' : 'b'; if (mal == 2) board[7][0] = team ? 'C' : 'c'; if (mal == 3) board[7][1] = team ? 'D' : 'd'; } else if (loc == 13) { if (mal == 0) board[12][0] = team ? 'A' : 'a'; if (mal == 1) board[12][1] = team ? 'B' : 'b'; if (mal == 2) board[13][0] = team ? 'C' : 'c'; if (mal == 3) board[13][1] = team ? 'D' : 'd'; } else if (loc == 14) { if (mal == 0) board[18][0] = team ? 'A' : 'a'; if (mal == 1) board[18][1] = team ? 'B' : 'b'; if (mal == 2) board[19][0] = team ? 'C' : 'c'; if (mal == 3) board[19][1] = team ? 'D' : 'd'; } else if (loc == 15) { if (mal == 0) board[24][0] = team ? 'A' : 'a'; if (mal == 1) board[24][1] = team ? 'B' : 'b'; if (mal == 2) board[25][0] = team ? 'C' : 'c'; if (mal == 3) board[25][1] = team ? 'D' : 'd'; } else if (loc == 16) { if (mal == 0) board[30][0] = team ? 'A' : 'a'; if (mal == 1) board[30][1] = team ? 'B' : 'b'; if (mal == 2) board[31][0] = team ? 'C' : 'c'; if (mal == 3) board[31][1] = team ? 'D' : 'd'; } else if (loc == 17) { if (mal == 0) board[30][6] = team ? 'A' : 'a'; if (mal == 1) board[30][7] = team ? 'B' : 'b'; if (mal == 2) board[31][6] = team ? 'C' : 'c'; if (mal == 3) board[31][7] = team ? 'D' : 'd'; } else if (loc == 18) { if (mal == 0) board[30][12] = team ? 'A' : 'a'; if (mal == 1) board[30][13] = team ? 'B' : 'b'; if (mal == 2) board[31][12] = team ? 'C' : 'c'; if (mal == 3) board[31][13] = team ? 'D' : 'd'; } else if (loc == 19) { if (mal == 0) board[30][18] = team ? 'A' : 'a'; if (mal == 1) board[30][19] = team ? 'B' : 'b'; if (mal == 2) board[31][18] = team ? 'C' : 'c'; if (mal == 3) board[31][19] = team ? 'D' : 'd'; } else if (loc == 20) { if (mal == 0) board[30][24] = team ? 'A' : 'a'; if (mal == 1) board[30][25] = team ? 'B' : 'b'; if (mal == 2) board[31][24] = team ? 'C' : 'c'; if (mal == 3) board[31][25] = team ? 'D' : 'd'; } else if (loc == 21) { if (mal == 0) board[5][25] = team ? 'A' : 'a'; if (mal == 1) board[5][26] = team ? 'B' : 'b'; if (mal == 2) board[6][25] = team ? 'C' : 'c'; if (mal == 3) board[6][26] = team ? 'D' : 'd'; } else if (loc == 22) { if (mal == 0) board[10][20] = team ? 'A' : 'a'; if (mal == 1) board[10][21] = team ? 'B' : 'b'; if (mal == 2) board[11][20] = team ? 'C' : 'c'; if (mal == 3) board[11][21] = team ? 'D' : 'd'; } else if (loc == 23) { if (mal == 0) board[15][15] = team ? 'A' : 'a'; if (mal == 1) board[15][16] = team ? 'B' : 'b'; if (mal == 2) board[16][15] = team ? 'C' : 'c'; if (mal == 3) board[16][16] = team ? 'D' : 'd'; } else if (loc == 24) { if (mal == 0) board[20][10] = team ? 'A' : 'a'; if (mal == 1) board[20][11] = team ? 'B' : 'b'; if (mal == 2) board[21][10] = team ? 'C' : 'c'; if (mal == 3) board[21][11] = team ? 'D' : 'd'; } else if (loc == 25) { if (mal == 0) board[25][5] = team ? 'A' : 'a'; if (mal == 1) board[25][6] = team ? 'B' : 'b'; if (mal == 2) board[26][5] = team ? 'C' : 'c'; if (mal == 3) board[26][6] = team ? 'D' : 'd'; } else if (loc == 26) { if (mal == 0) board[5][5] = team ? 'A' : 'a'; if (mal == 1) board[5][6] = team ? 'B' : 'b'; if (mal == 2) board[6][5] = team ? 'C' : 'c'; if (mal == 3) board[6][6] = team ? 'D' : 'd'; } else if (loc == 27) { if (mal == 0) board[10][10] = team ? 'A' : 'a'; if (mal == 1) board[10][11] = team ? 'B' : 'b'; if (mal == 2) board[11][10] = team ? 'C' : 'c'; if (mal == 3) board[11][11] = team ? 'D' : 'd'; } else if (loc == 29) { if (mal == 0) board[20][20] = team ? 'A' : 'a'; if (mal == 1) board[20][21] = team ? 'B' : 'b'; if (mal == 2) board[21][20] = team ? 'C' : 'c'; if (mal == 3) board[21][21] = team ? 'D' : 'd'; } else if (loc == 30) { if (mal == 0) board[25][25] = team ? 'A' : 'a'; if (mal == 1) board[25][26] = team ? 'B' : 'b'; if (mal == 2) board[26][25] = team ? 'C' : 'c'; if (mal == 3) board[26][26] = team ? 'D' : 'd'; } } private static class Location { public boolean[] upper, lower; public Location() { this.upper = new boolean[4]; this.lower = new boolean[4]; } } }
BOJ/15778/Main.java
BOJ #15778: Yut Nori
BOJ/15778/Main.java
BOJ #15778: Yut Nori
<ide><path>OJ/15778/Main.java <add>/* <add> * Author: Minho Kim (ISKU) <add> * Date: May 22, 2018 <add> * E-mail: [email protected] <add> * <add> * https://github.com/ISKU/Algorithm <add> * https://www.acmicpc.net/problem/15778 <add> */ <add> <add>import java.util.*; <add>import java.io.*; <add> <add>public class Main { <add> <add> private static char[][] board = { <add> { '.', '.', '-', '-', '-', '-', '.', '.', '-', '-', '-', '-', '.', '.', '-', '-', '-', '-', '.', '.', '-', '-', '-', '-', '.', '.', '-', '-', '-', '-', '.', '.' }, <add> { '.', '.', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', '.', '.' }, <add> { '|', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', '|' }, <add> { '|', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', '|' }, <add> { '|', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', '|' }, <add> { '|', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', '|' }, <add> { '.', '.', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', '.', '.' }, <add> { '.', '.', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', '.', '.' }, <add> { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, <add> { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, <add> { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, <add> { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, <add> { '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.' }, <add> { '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.' }, <add> { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, <add> { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, <add> { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, <add> { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, <add> { '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.' }, <add> { '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.' }, <add> { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, <add> { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, <add> { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, <add> { '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|' }, <add> { '.', '.', ' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' ', '.', '.' }, <add> { '.', '.', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', '.', '.' }, <add> { '|', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', '|' }, <add> { '|', ' ', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', ' ', '|' }, <add> { '|', ' ', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', ' ', '|' }, <add> { '|', ' ', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', ' ', '|' }, <add> { '.', '.', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', '.', '.', ' ', ' ', ' ', ' ', '.', '.' }, <add> { '.', '.', '-', '-', '-', '-', '.', '.', '-', '-', '-', '-', '.', '.', '-', '-', '-', '-', '.', '.', '-', '-', '-', '-', '.', '.', '-', '-', '-', '-', '.', '.' } <add> }; <add> <add> private static Location[] location; <add> private static int[] upperLocation, lowerLocation; <add> <add> public static void main(String... args) throws Exception { <add> BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); <add> BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); <add> int N = Integer.parseInt(br.readLine()); <add> <add> location = new Location[33]; <add> for (int i = 0; i < location.length; i++) <add> location[i] = new Location(); <add> <add> upperLocation = new int[4]; <add> lowerLocation = new int[4]; <add> for (int i = 0; i < 4; i++) { <add> upperLocation[i] = 1; <add> lowerLocation[i] = 1; <add> location[1].upper[i] = true; <add> location[1].lower[i] = true; <add> } <add> <add> while (N-- > 0) { <add> StringTokenizer st = new StringTokenizer(br.readLine()); <add> char turn = st.nextToken().charAt(0); <add> int move = count(st.nextToken()); <add> <add> if (turn <= 'Z') { <add> int mal = turn - 'A'; <add> int start = upperLocation[mal]; <add> int end = direction(start, move); <add> if (end >= 32) <add> end = 32; <add> <add> upperLocation[mal] = end; <add> location[start].upper[mal] = false; <add> location[end].upper[mal] = true; <add> <add> for (int i = 0; i < 4; i++) { <add> if (start == 1 || !location[start].upper[i]) <add> continue; <add> <add> upperLocation[i] = end; <add> location[start].upper[i] = false; <add> location[end].upper[i] = true; <add> } <add> <add> for (int i = 0; i < 4; i++) { <add> if (!location[end].lower[i]) <add> continue; <add> <add> lowerLocation[i] = 1; <add> location[end].lower[i] = false; <add> } <add> } <add> else if (turn >= 'a') { <add> int mal = turn - 'a'; <add> int start = lowerLocation[mal]; <add> int end = direction(start, move); <add> if (end >= 32) <add> end = 32; <add> <add> lowerLocation[mal] = end; <add> location[start].lower[mal] = false; <add> location[end].lower[mal] = true; <add> <add> for (int i = 0; i < 4; i++) { <add> if (start == 1 || !location[start].lower[i]) <add> continue; <add> <add> lowerLocation[i] = end; <add> location[start].lower[i] = false; <add> location[end].lower[i] = true; <add> } <add> <add> for (int i = 0; i < 4; i++) { <add> if (!location[end].upper[i]) <add> continue; <add> <add> upperLocation[i] = 1; <add> location[end].upper[i] = false; <add> } <add> } <add> } <add> <add> for (int i = 1; i < location.length; i++) { <add> for (int j = 0; j < 4; j++) { <add> if (location[i].upper[j]) <add> place(i, j, true); <add> if (location[i].lower[j]) <add> place(i, j, false); <add> } <add> } <add> <add> for (int i = 0; i < board.length; i++) { <add> for (int j = 0; j < board[i].length; j++) <add> bw.write(board[i][j]); <add> bw.newLine(); <add> } <add> <add> bw.close(); <add> } <add> <add> private static int direction(int start, int move) { <add> switch (start) { <add> case 6: <add> return 20 + move; <add> case 11: <add> return (move == 3) ? 23 : 25 + move; <add> case 21: <add> return (move == 5) ? 16 : 21 + move; <add> case 22: <add> return (move == 4) ? 16 : (move == 5) ? 17 : 22 + move; <add> case 23: <add> return 28 + move; <add> case 26: <add> return (move == 2) ? 23 : 26 + move; <add> case 27: <add> return (move == 1) ? 23 : 27 + move; <add> case 24: <add> return (move == 1) ? 25 : 14 + move; <add> case 25: <add> return (move == 1) ? 16 : 15 + move; <add> default: <add> return (16 <= start && start <= 20 && start + move >= 21) ? 10 + start + move : start + move; <add> } <add> } <add> <add> private static int count(String yut) { <add> int count = 0; <add> for (int i = 0; i < 4; i++) <add> if (yut.charAt(i) == 'F') <add> count++; <add> <add> return (count == 0) ? 5 : count; <add> } <add> <add> private static void place(int loc, int mal, boolean team) { <add> if (loc == 31) { <add> if (mal == 0) <add> board[30][30] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[30][31] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[31][30] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[31][31] = team ? 'D' : 'd'; <add> } <add> else if (loc == 2) { <add> if (mal == 0) <add> board[24][30] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[24][31] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[25][30] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[25][31] = team ? 'D' : 'd'; <add> } <add> else if (loc == 3) { <add> if (mal == 0) <add> board[18][30] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[18][31] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[19][30] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[19][31] = team ? 'D' : 'd'; <add> } <add> else if (loc == 4) { <add> if (mal == 0) <add> board[12][30] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[12][31] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[13][30] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[13][31] = team ? 'D' : 'd'; <add> } <add> else if (loc == 5) { <add> if (mal == 0) <add> board[6][30] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[6][31] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[7][30] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[7][31] = team ? 'D' : 'd'; <add> } <add> else if (loc == 6) { <add> if (mal == 0) <add> board[0][30] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[0][31] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[1][30] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[1][31] = team ? 'D' : 'd'; <add> } <add> else if (loc == 7) { <add> if (mal == 0) <add> board[0][24] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[0][25] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[1][24] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[1][25] = team ? 'D' : 'd'; <add> } <add> else if (loc == 8) { <add> if (mal == 0) <add> board[0][18] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[0][19] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[1][18] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[1][19] = team ? 'D' : 'd'; <add> } <add> else if (loc == 9) { <add> if (mal == 0) <add> board[0][12] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[0][13] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[1][12] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[1][13] = team ? 'D' : 'd'; <add> } <add> else if (loc == 10) { <add> if (mal == 0) <add> board[0][6] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[0][7] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[1][6] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[1][7] = team ? 'D' : 'd'; <add> } <add> else if (loc == 11) { <add> if (mal == 0) <add> board[0][0] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[0][1] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[1][0] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[1][1] = team ? 'D' : 'd'; <add> } <add> else if (loc == 12) { <add> if (mal == 0) <add> board[6][0] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[6][1] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[7][0] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[7][1] = team ? 'D' : 'd'; <add> } <add> else if (loc == 13) { <add> if (mal == 0) <add> board[12][0] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[12][1] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[13][0] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[13][1] = team ? 'D' : 'd'; <add> } <add> else if (loc == 14) { <add> if (mal == 0) <add> board[18][0] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[18][1] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[19][0] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[19][1] = team ? 'D' : 'd'; <add> } <add> else if (loc == 15) { <add> if (mal == 0) <add> board[24][0] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[24][1] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[25][0] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[25][1] = team ? 'D' : 'd'; <add> } <add> else if (loc == 16) { <add> if (mal == 0) <add> board[30][0] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[30][1] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[31][0] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[31][1] = team ? 'D' : 'd'; <add> } <add> else if (loc == 17) { <add> if (mal == 0) <add> board[30][6] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[30][7] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[31][6] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[31][7] = team ? 'D' : 'd'; <add> } <add> else if (loc == 18) { <add> if (mal == 0) <add> board[30][12] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[30][13] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[31][12] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[31][13] = team ? 'D' : 'd'; <add> } <add> else if (loc == 19) { <add> if (mal == 0) <add> board[30][18] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[30][19] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[31][18] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[31][19] = team ? 'D' : 'd'; <add> } <add> else if (loc == 20) { <add> if (mal == 0) <add> board[30][24] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[30][25] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[31][24] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[31][25] = team ? 'D' : 'd'; <add> } <add> else if (loc == 21) { <add> if (mal == 0) <add> board[5][25] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[5][26] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[6][25] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[6][26] = team ? 'D' : 'd'; <add> } <add> else if (loc == 22) { <add> if (mal == 0) <add> board[10][20] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[10][21] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[11][20] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[11][21] = team ? 'D' : 'd'; <add> } <add> else if (loc == 23) { <add> if (mal == 0) <add> board[15][15] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[15][16] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[16][15] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[16][16] = team ? 'D' : 'd'; <add> } <add> else if (loc == 24) { <add> if (mal == 0) <add> board[20][10] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[20][11] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[21][10] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[21][11] = team ? 'D' : 'd'; <add> } <add> else if (loc == 25) { <add> if (mal == 0) <add> board[25][5] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[25][6] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[26][5] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[26][6] = team ? 'D' : 'd'; <add> } <add> else if (loc == 26) { <add> if (mal == 0) <add> board[5][5] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[5][6] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[6][5] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[6][6] = team ? 'D' : 'd'; <add> } <add> else if (loc == 27) { <add> if (mal == 0) <add> board[10][10] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[10][11] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[11][10] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[11][11] = team ? 'D' : 'd'; <add> } <add> else if (loc == 29) { <add> if (mal == 0) <add> board[20][20] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[20][21] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[21][20] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[21][21] = team ? 'D' : 'd'; <add> } <add> else if (loc == 30) { <add> if (mal == 0) <add> board[25][25] = team ? 'A' : 'a'; <add> if (mal == 1) <add> board[25][26] = team ? 'B' : 'b'; <add> if (mal == 2) <add> board[26][25] = team ? 'C' : 'c'; <add> if (mal == 3) <add> board[26][26] = team ? 'D' : 'd'; <add> } <add> } <add> <add> private static class Location { <add> public boolean[] upper, lower; <add> <add> public Location() { <add> this.upper = new boolean[4]; <add> this.lower = new boolean[4]; <add> } <add> } <add>}
Java
unlicense
e7231a5d0c8dc58099369cc92debaae016e61275
0
harryjamesuk/Ribbit
package com.harryjamesuk.ribbit; import java.util.Locale; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { protected Context mContext; public SectionsPagerAdapter(Context context, FragmentManager fm) { super(fm); mContext = context; } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class // below). switch(position) { case 0: return new InboxFragment(); case 1: return new FriendsFragment(); } return null; } @Override public int getCount() { return 2; } @Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch (position) { case 0: return mContext.getString(R.string.title_section1).toUpperCase(l); case 1: return mContext.getString(R.string.title_section2).toUpperCase(l); } return null; } }
src/com/harryjamesuk/ribbit/SectionsPagerAdapter.java
package com.harryjamesuk.ribbit; import java.util.Locale; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { protected Context mContext; public SectionsPagerAdapter(Context context, FragmentManager fm) { super(fm); mContext = context; } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class // below). switch(position) { case 0: return new InboxFragment(); case 1: return new FriendsFragment(); } return new InboxFragment(); } @Override public int getCount() { return 2; } @Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch (position) { case 0: return mContext.getString(R.string.title_section1).toUpperCase(l); case 1: return mContext.getString(R.string.title_section2).toUpperCase(l); } return null; } }
Modified fragments bugfix Returning null instead of InboxFragment() to avoid errors. Should never return null, however.
src/com/harryjamesuk/ribbit/SectionsPagerAdapter.java
Modified fragments bugfix
<ide><path>rc/com/harryjamesuk/ribbit/SectionsPagerAdapter.java <ide> return new FriendsFragment(); <ide> } <ide> <del> return new InboxFragment(); <add> return null; <ide> } <ide> <ide> @Override